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/core/src/main/java/de/uniluebeck/itm/wsn/deviceutils/listener/DeviceListenerCLI.java b/core/src/main/java/de/uniluebeck/itm/wsn/deviceutils/listener/DeviceListenerCLI.java
index 3632f90..b4a8ee5 100755
--- a/core/src/main/java/de/uniluebeck/itm/wsn/deviceutils/listener/DeviceListenerCLI.java
+++ b/core/src/main/java/de/uniluebeck/itm/wsn/deviceutils/listener/DeviceListenerCLI.java
@@ -1,291 +1,291 @@
/**********************************************************************************************************************
* Copyright (c) 2010, Institute of Telematics, University of Luebeck *
* 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 the University of Luebeck 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 THE COPYRIGHT HOLDER 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 de.uniluebeck.itm.wsn.deviceutils.listener;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.Guice;
import de.uniluebeck.itm.nettyprotocols.*;
import de.uniluebeck.itm.util.StringUtils;
import de.uniluebeck.itm.util.Tuple;
import de.uniluebeck.itm.util.logging.LogLevel;
import de.uniluebeck.itm.util.logging.Logging;
import de.uniluebeck.itm.wsn.drivers.core.Device;
import de.uniluebeck.itm.wsn.drivers.factories.DeviceFactory;
import de.uniluebeck.itm.wsn.drivers.factories.DeviceFactoryModule;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.iostream.IOStreamAddress;
import org.jboss.netty.channel.iostream.IOStreamChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static de.uniluebeck.itm.wsn.deviceutils.CliUtils.assertParametersPresent;
import static de.uniluebeck.itm.wsn.deviceutils.CliUtils.printUsageAndExit;
import static org.jboss.netty.channel.Channels.pipeline;
public class DeviceListenerCLI {
static {
Logging.setLoggingDefaults(LogLevel.WARN);
}
private final static Logger log = LoggerFactory.getLogger(DeviceListenerCLI.class);
private static final DeviceFactory deviceFactory = Guice
.createInjector(new DeviceFactoryModule())
.getInstance(DeviceFactory.class);
public static void main(String[] args) throws InterruptedException, IOException {
CommandLineParser parser = new PosixParser();
Options options = createCommandLineOptions();
String deviceType = null;
String port = null;
Map<String, String> configuration = newHashMap();
OutputStream outStream = System.out;
WriterHandler writerHandler = null;
@Nonnull List<Tuple<String, ChannelHandler>> handlers = newArrayList();
try {
CommandLine line = parser.parse(options, args, true);
if (line.hasOption('h')) {
printUsageAndExit(DeviceListenerCLI.class, options, 0);
}
if (line.hasOption('v')) {
Logging.setLogLevel(LogLevel.DEBUG);
}
if (line.hasOption('l')) {
Logging.setLogLevel(LogLevel.toLevel(line.getOptionValue('l')));
}
if (line.hasOption('c')) {
final String configurationFileString = line.getOptionValue('c');
final File configurationFile = new File(configurationFileString);
final Properties configurationProperties = new Properties();
configurationProperties.load(new FileReader(configurationFile));
for (Map.Entry<Object, Object> entry : configurationProperties.entrySet()) {
configuration.put((String) entry.getKey(), (String) entry.getValue());
}
}
assertParametersPresent(line, 't', 'p');
deviceType = line.getOptionValue('t');
port = line.getOptionValue('p');
if (line.hasOption('o')) {
String filename = line.getOptionValue('o');
log.info("Using outfile {}", filename);
outStream = new FileOutputStream(filename);
}
if (line.hasOption('e')) {
final String handlerNamesString = line.getOptionValue('e');
final Iterable<String> handlerNames = Splitter.on(",")
.omitEmptyStrings()
.trimResults()
.split(handlerNamesString);
final HandlerFactoryMap handlerFactories = Guice
.createInjector(new NettyProtocolsModule())
.getInstance(HandlerFactoryMap.class);
for (String handlerName : handlerNames) {
final NamedChannelHandlerList channelHandlers = handlerFactories
.get(handlerName)
.create(new ChannelHandlerConfig(handlerName));
for (NamedChannelHandler channelHandler : channelHandlers) {
handlers.add(
new Tuple<String, ChannelHandler>(
channelHandler.getInstanceName(),
channelHandler.getChannelHandler()
)
);
}
}
}
if (line.hasOption('f')) {
String format = line.getOptionValue('f');
if ("csv".equals(format)) {
writerHandler = new CsvWriter(outStream);
} else if ("wiseml".equals(format)) {
writerHandler = new WiseMLWriterHandler(outStream, "node at " + line.getOptionValue('p'), true);
} else if ("hex".equals(format)) {
writerHandler = new HexWriter(outStream);
} else if ("human".equals(format)) {
writerHandler = new HumanReadableWriter(outStream);
} else if ("utf8".equals(format) || "UTF-8".equals(format)) {
writerHandler = new StringWriter(outStream, Charset.forName("UTF-8"));
} else if ("iso".equals(format) || "ISO-8859-1".equals(format)) {
writerHandler = new StringWriter(outStream, Charset.forName("ISO-8859-1"));
} else {
throw new Exception("Unknown format " + format);
}
log.info("Using format {}", format);
} else {
writerHandler = new StringWriter(outStream, Charset.forName("US-ASCII"));
}
} catch (Exception e) {
- log.error("Invalid command line: {}", e);
+ log.error("Invalid command line: {}", e.getMessage());
printUsageAndExit(DeviceListenerCLI.class, options, 1);
}
if (writerHandler == null) {
throw new RuntimeException("This should not happen!");
}
final ExecutorService executorService = Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("DeviceListener-Thread %d").build()
);
final Device device = deviceFactory.create(executorService, deviceType, configuration);
device.connect(port);
if (!device.isConnected()) {
throw new RuntimeException("Connection to device at port \"" + args[1] + "\" could not be established!");
}
final InputStream inputStream = device.getInputStream();
final OutputStream outputStream = device.getOutputStream();
final ClientBootstrap bootstrap = new ClientBootstrap(new IOStreamChannelFactory(executorService));
final WriterHandler finalWriterHandler = writerHandler;
final List<Tuple<String, ChannelHandler>> finalHandlers = handlers;
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
final ChannelPipeline pipeline = pipeline();
for (Tuple<String, ChannelHandler> handler : finalHandlers) {
pipeline.addLast(handler.getFirst(), handler.getSecond());
}
pipeline.addLast("finalWriterHandler", finalWriterHandler);
return pipeline;
}
}
);
// Make a new connection.
ChannelFuture connectFuture = bootstrap.connect(new IOStreamAddress(inputStream, outputStream));
// Wait until the connection is made successfully.
final Channel channel = connectFuture.awaitUninterruptibly().getChannel();
Runtime.getRuntime().addShutdownHook(new Thread(DeviceListenerCLI.class.getName() + "-ShutdownThread") {
@Override
public void run() {
try {
channel.close();
} catch (Exception e) {
log.error("Exception while closing channel to device: {}", e, e);
}
}
}
);
while (!Thread.interrupted()) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
final byte[] cmdBytes = in.readLine().getBytes();
final byte[] bytes = new byte[cmdBytes.length + 1];
System.arraycopy(cmdBytes, 0, bytes, 0, cmdBytes.length);
bytes[cmdBytes.length] = 0x0a; // LF
device.getOutputStream().write(bytes);
System.out.println("SENT " + bytes.length + " bytes: " + StringUtils.toHexString(bytes));
device.getOutputStream().flush();
// device.getOutputStream().write(StringUtils.fromStringToByteArray(in.readLine()));
} catch (IOException e) {
log.error("{}", e);
System.exit(1);
}
}
}
private static Options createCommandLineOptions() {
Options options = new Options();
// add all available options
options.addOption("p", "port", true, "Serial port to which the device is attached");
options.getOption("p").setRequired(true);
options.addOption("t", "type", true, "Type of the device");
options.getOption("t").setRequired(true);
options.addOption("c", "configuration", true,
"Optional: file name of a configuration file containing key value pairs to configure the device"
);
options.addOption("e", "channelpipeline", true,
"Optional: comma-separated list of channel pipeline handler names"
);
options.addOption("f", "format", true, "Optional: output format, options: csv, wiseml");
options.addOption("o", "outfile", true, "Optional: redirect output to file");
options.addOption("v", "verbose", false, "Optional: verbose logging output (equal to -l DEBUG)");
options.addOption("l", "logging", true,
"Optional: set logging level (one of [" + Joiner.on(", ").join(Logging.LOG_LEVELS) + "])"
);
options.addOption("h", "help", false, "Optional: print help");
return options;
}
}
| true | true | public static void main(String[] args) throws InterruptedException, IOException {
CommandLineParser parser = new PosixParser();
Options options = createCommandLineOptions();
String deviceType = null;
String port = null;
Map<String, String> configuration = newHashMap();
OutputStream outStream = System.out;
WriterHandler writerHandler = null;
@Nonnull List<Tuple<String, ChannelHandler>> handlers = newArrayList();
try {
CommandLine line = parser.parse(options, args, true);
if (line.hasOption('h')) {
printUsageAndExit(DeviceListenerCLI.class, options, 0);
}
if (line.hasOption('v')) {
Logging.setLogLevel(LogLevel.DEBUG);
}
if (line.hasOption('l')) {
Logging.setLogLevel(LogLevel.toLevel(line.getOptionValue('l')));
}
if (line.hasOption('c')) {
final String configurationFileString = line.getOptionValue('c');
final File configurationFile = new File(configurationFileString);
final Properties configurationProperties = new Properties();
configurationProperties.load(new FileReader(configurationFile));
for (Map.Entry<Object, Object> entry : configurationProperties.entrySet()) {
configuration.put((String) entry.getKey(), (String) entry.getValue());
}
}
assertParametersPresent(line, 't', 'p');
deviceType = line.getOptionValue('t');
port = line.getOptionValue('p');
if (line.hasOption('o')) {
String filename = line.getOptionValue('o');
log.info("Using outfile {}", filename);
outStream = new FileOutputStream(filename);
}
if (line.hasOption('e')) {
final String handlerNamesString = line.getOptionValue('e');
final Iterable<String> handlerNames = Splitter.on(",")
.omitEmptyStrings()
.trimResults()
.split(handlerNamesString);
final HandlerFactoryMap handlerFactories = Guice
.createInjector(new NettyProtocolsModule())
.getInstance(HandlerFactoryMap.class);
for (String handlerName : handlerNames) {
final NamedChannelHandlerList channelHandlers = handlerFactories
.get(handlerName)
.create(new ChannelHandlerConfig(handlerName));
for (NamedChannelHandler channelHandler : channelHandlers) {
handlers.add(
new Tuple<String, ChannelHandler>(
channelHandler.getInstanceName(),
channelHandler.getChannelHandler()
)
);
}
}
}
if (line.hasOption('f')) {
String format = line.getOptionValue('f');
if ("csv".equals(format)) {
writerHandler = new CsvWriter(outStream);
} else if ("wiseml".equals(format)) {
writerHandler = new WiseMLWriterHandler(outStream, "node at " + line.getOptionValue('p'), true);
} else if ("hex".equals(format)) {
writerHandler = new HexWriter(outStream);
} else if ("human".equals(format)) {
writerHandler = new HumanReadableWriter(outStream);
} else if ("utf8".equals(format) || "UTF-8".equals(format)) {
writerHandler = new StringWriter(outStream, Charset.forName("UTF-8"));
} else if ("iso".equals(format) || "ISO-8859-1".equals(format)) {
writerHandler = new StringWriter(outStream, Charset.forName("ISO-8859-1"));
} else {
throw new Exception("Unknown format " + format);
}
log.info("Using format {}", format);
} else {
writerHandler = new StringWriter(outStream, Charset.forName("US-ASCII"));
}
} catch (Exception e) {
log.error("Invalid command line: {}", e);
printUsageAndExit(DeviceListenerCLI.class, options, 1);
}
if (writerHandler == null) {
throw new RuntimeException("This should not happen!");
}
final ExecutorService executorService = Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("DeviceListener-Thread %d").build()
);
final Device device = deviceFactory.create(executorService, deviceType, configuration);
device.connect(port);
if (!device.isConnected()) {
throw new RuntimeException("Connection to device at port \"" + args[1] + "\" could not be established!");
}
final InputStream inputStream = device.getInputStream();
final OutputStream outputStream = device.getOutputStream();
final ClientBootstrap bootstrap = new ClientBootstrap(new IOStreamChannelFactory(executorService));
final WriterHandler finalWriterHandler = writerHandler;
final List<Tuple<String, ChannelHandler>> finalHandlers = handlers;
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
final ChannelPipeline pipeline = pipeline();
for (Tuple<String, ChannelHandler> handler : finalHandlers) {
pipeline.addLast(handler.getFirst(), handler.getSecond());
}
pipeline.addLast("finalWriterHandler", finalWriterHandler);
return pipeline;
}
}
);
// Make a new connection.
ChannelFuture connectFuture = bootstrap.connect(new IOStreamAddress(inputStream, outputStream));
// Wait until the connection is made successfully.
final Channel channel = connectFuture.awaitUninterruptibly().getChannel();
Runtime.getRuntime().addShutdownHook(new Thread(DeviceListenerCLI.class.getName() + "-ShutdownThread") {
@Override
public void run() {
try {
channel.close();
} catch (Exception e) {
log.error("Exception while closing channel to device: {}", e, e);
}
}
}
);
while (!Thread.interrupted()) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
final byte[] cmdBytes = in.readLine().getBytes();
final byte[] bytes = new byte[cmdBytes.length + 1];
System.arraycopy(cmdBytes, 0, bytes, 0, cmdBytes.length);
bytes[cmdBytes.length] = 0x0a; // LF
device.getOutputStream().write(bytes);
System.out.println("SENT " + bytes.length + " bytes: " + StringUtils.toHexString(bytes));
device.getOutputStream().flush();
// device.getOutputStream().write(StringUtils.fromStringToByteArray(in.readLine()));
} catch (IOException e) {
log.error("{}", e);
System.exit(1);
}
}
}
| public static void main(String[] args) throws InterruptedException, IOException {
CommandLineParser parser = new PosixParser();
Options options = createCommandLineOptions();
String deviceType = null;
String port = null;
Map<String, String> configuration = newHashMap();
OutputStream outStream = System.out;
WriterHandler writerHandler = null;
@Nonnull List<Tuple<String, ChannelHandler>> handlers = newArrayList();
try {
CommandLine line = parser.parse(options, args, true);
if (line.hasOption('h')) {
printUsageAndExit(DeviceListenerCLI.class, options, 0);
}
if (line.hasOption('v')) {
Logging.setLogLevel(LogLevel.DEBUG);
}
if (line.hasOption('l')) {
Logging.setLogLevel(LogLevel.toLevel(line.getOptionValue('l')));
}
if (line.hasOption('c')) {
final String configurationFileString = line.getOptionValue('c');
final File configurationFile = new File(configurationFileString);
final Properties configurationProperties = new Properties();
configurationProperties.load(new FileReader(configurationFile));
for (Map.Entry<Object, Object> entry : configurationProperties.entrySet()) {
configuration.put((String) entry.getKey(), (String) entry.getValue());
}
}
assertParametersPresent(line, 't', 'p');
deviceType = line.getOptionValue('t');
port = line.getOptionValue('p');
if (line.hasOption('o')) {
String filename = line.getOptionValue('o');
log.info("Using outfile {}", filename);
outStream = new FileOutputStream(filename);
}
if (line.hasOption('e')) {
final String handlerNamesString = line.getOptionValue('e');
final Iterable<String> handlerNames = Splitter.on(",")
.omitEmptyStrings()
.trimResults()
.split(handlerNamesString);
final HandlerFactoryMap handlerFactories = Guice
.createInjector(new NettyProtocolsModule())
.getInstance(HandlerFactoryMap.class);
for (String handlerName : handlerNames) {
final NamedChannelHandlerList channelHandlers = handlerFactories
.get(handlerName)
.create(new ChannelHandlerConfig(handlerName));
for (NamedChannelHandler channelHandler : channelHandlers) {
handlers.add(
new Tuple<String, ChannelHandler>(
channelHandler.getInstanceName(),
channelHandler.getChannelHandler()
)
);
}
}
}
if (line.hasOption('f')) {
String format = line.getOptionValue('f');
if ("csv".equals(format)) {
writerHandler = new CsvWriter(outStream);
} else if ("wiseml".equals(format)) {
writerHandler = new WiseMLWriterHandler(outStream, "node at " + line.getOptionValue('p'), true);
} else if ("hex".equals(format)) {
writerHandler = new HexWriter(outStream);
} else if ("human".equals(format)) {
writerHandler = new HumanReadableWriter(outStream);
} else if ("utf8".equals(format) || "UTF-8".equals(format)) {
writerHandler = new StringWriter(outStream, Charset.forName("UTF-8"));
} else if ("iso".equals(format) || "ISO-8859-1".equals(format)) {
writerHandler = new StringWriter(outStream, Charset.forName("ISO-8859-1"));
} else {
throw new Exception("Unknown format " + format);
}
log.info("Using format {}", format);
} else {
writerHandler = new StringWriter(outStream, Charset.forName("US-ASCII"));
}
} catch (Exception e) {
log.error("Invalid command line: {}", e.getMessage());
printUsageAndExit(DeviceListenerCLI.class, options, 1);
}
if (writerHandler == null) {
throw new RuntimeException("This should not happen!");
}
final ExecutorService executorService = Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("DeviceListener-Thread %d").build()
);
final Device device = deviceFactory.create(executorService, deviceType, configuration);
device.connect(port);
if (!device.isConnected()) {
throw new RuntimeException("Connection to device at port \"" + args[1] + "\" could not be established!");
}
final InputStream inputStream = device.getInputStream();
final OutputStream outputStream = device.getOutputStream();
final ClientBootstrap bootstrap = new ClientBootstrap(new IOStreamChannelFactory(executorService));
final WriterHandler finalWriterHandler = writerHandler;
final List<Tuple<String, ChannelHandler>> finalHandlers = handlers;
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
final ChannelPipeline pipeline = pipeline();
for (Tuple<String, ChannelHandler> handler : finalHandlers) {
pipeline.addLast(handler.getFirst(), handler.getSecond());
}
pipeline.addLast("finalWriterHandler", finalWriterHandler);
return pipeline;
}
}
);
// Make a new connection.
ChannelFuture connectFuture = bootstrap.connect(new IOStreamAddress(inputStream, outputStream));
// Wait until the connection is made successfully.
final Channel channel = connectFuture.awaitUninterruptibly().getChannel();
Runtime.getRuntime().addShutdownHook(new Thread(DeviceListenerCLI.class.getName() + "-ShutdownThread") {
@Override
public void run() {
try {
channel.close();
} catch (Exception e) {
log.error("Exception while closing channel to device: {}", e, e);
}
}
}
);
while (!Thread.interrupted()) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
final byte[] cmdBytes = in.readLine().getBytes();
final byte[] bytes = new byte[cmdBytes.length + 1];
System.arraycopy(cmdBytes, 0, bytes, 0, cmdBytes.length);
bytes[cmdBytes.length] = 0x0a; // LF
device.getOutputStream().write(bytes);
System.out.println("SENT " + bytes.length + " bytes: " + StringUtils.toHexString(bytes));
device.getOutputStream().flush();
// device.getOutputStream().write(StringUtils.fromStringToByteArray(in.readLine()));
} catch (IOException e) {
log.error("{}", e);
System.exit(1);
}
}
}
|
diff --git a/src/main/java/com/dumptruckman/chunky/permission/ChunkyPermissions.java b/src/main/java/com/dumptruckman/chunky/permission/ChunkyPermissions.java
index 885d002..a761c04 100644
--- a/src/main/java/com/dumptruckman/chunky/permission/ChunkyPermissions.java
+++ b/src/main/java/com/dumptruckman/chunky/permission/ChunkyPermissions.java
@@ -1,63 +1,64 @@
package com.dumptruckman.chunky.permission;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* @author dumptruckman, SwearWord
*/
public class ChunkyPermissions {
public enum Flags {
BUILD('b'), DESTROY('d'), ITEMUSE('i'), SWITCH('s');
private char rep;
private static final Map<Character, Flags> lookup = new HashMap<Character, Flags>();
static {
for(Flags f : EnumSet.allOf(Flags.class))
lookup.put(f.getRep(), f);
}
Flags(char rep) {
this.rep = rep;
}
private char getRep() {
return rep;
}
public static Flags get(char c) {
return lookup.get(c);
}
}
protected EnumSet<Flags> flags;
public ChunkyPermissions(Flags... flags) {
EnumSet flagSet = EnumSet.noneOf(Flags.class);
+ if (flags == null) return;
for (Flags flag : flags) {
flagSet.add(flag);
}
this.flags = flagSet;
}
public boolean contains(Flags flag) {
return flags.contains(flag);
}
public EnumSet<Flags> getFlags() {
return flags;
}
public void setFlag(Flags flag, boolean status) {
if (flags.contains(flag) && !status) {
flags.remove(flag);
} else if (!flags.contains(flag) && status) {
flags.add(flag);
}
}
}
| true | true | public ChunkyPermissions(Flags... flags) {
EnumSet flagSet = EnumSet.noneOf(Flags.class);
for (Flags flag : flags) {
flagSet.add(flag);
}
this.flags = flagSet;
}
| public ChunkyPermissions(Flags... flags) {
EnumSet flagSet = EnumSet.noneOf(Flags.class);
if (flags == null) return;
for (Flags flag : flags) {
flagSet.add(flag);
}
this.flags = flagSet;
}
|
diff --git a/src/com/nicknackhacks/dailyburn/adapters/BodyEntryWrapper.java b/src/com/nicknackhacks/dailyburn/adapters/BodyEntryWrapper.java
index 5231a45..ba2b2a2 100644
--- a/src/com/nicknackhacks/dailyburn/adapters/BodyEntryWrapper.java
+++ b/src/com/nicknackhacks/dailyburn/adapters/BodyEntryWrapper.java
@@ -1,64 +1,62 @@
package com.nicknackhacks.dailyburn.adapters;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.nicknackhacks.dailyburn.R;
import com.nicknackhacks.dailyburn.model.BodyLogEntry;
import com.nicknackhacks.dailyburn.model.FoodLogEntry;
public class BodyEntryWrapper {
TextView value;
TextView loggedOn;
TextView delta;
View row;
public BodyEntryWrapper(View row) {
this.row = row;
}
public void populateFrom(BodyLogEntry e) {
getValue().setText(String.valueOf(e.getValue()));
getLoggedOn().setText(e.getLoggedOn());
getDelta().setText("0.0");
getDelta().setTextColor(Color.WHITE);
}
public void populateWithDiff(BodyLogEntry e, BodyLogEntry past) {
getValue().setText(String.valueOf(e.getValue()));
getLoggedOn().setText(e.getLoggedOn());
float diff = e.getValue() - past.getValue();
- String diffString = String.valueOf(diff);
- diffString = diffString.substring(0, diffString.indexOf('.') + 3);
+ String diffString = String.format("%+2.2f",diff);
if(diff > 0) {
- diffString = "+" + diffString;
getDelta().setTextColor(Color.RED);
} else if(diff < 0) {
getDelta().setTextColor(Color.GREEN);
}
getDelta().setText(diffString);
}
public TextView getValue() {
if (value == null) {
value = (TextView) row.findViewById(R.id.entry_value);
}
return value;
}
public TextView getLoggedOn() {
if (loggedOn == null) {
loggedOn = (TextView) row.findViewById(R.id.entry_loggedOn);
}
return loggedOn;
}
public TextView getDelta() {
if (delta == null) {
delta = (TextView) row.findViewById(R.id.entry_delta);
}
return delta;
}
}
| false | true | public void populateWithDiff(BodyLogEntry e, BodyLogEntry past) {
getValue().setText(String.valueOf(e.getValue()));
getLoggedOn().setText(e.getLoggedOn());
float diff = e.getValue() - past.getValue();
String diffString = String.valueOf(diff);
diffString = diffString.substring(0, diffString.indexOf('.') + 3);
if(diff > 0) {
diffString = "+" + diffString;
getDelta().setTextColor(Color.RED);
} else if(diff < 0) {
getDelta().setTextColor(Color.GREEN);
}
getDelta().setText(diffString);
}
| public void populateWithDiff(BodyLogEntry e, BodyLogEntry past) {
getValue().setText(String.valueOf(e.getValue()));
getLoggedOn().setText(e.getLoggedOn());
float diff = e.getValue() - past.getValue();
String diffString = String.format("%+2.2f",diff);
if(diff > 0) {
getDelta().setTextColor(Color.RED);
} else if(diff < 0) {
getDelta().setTextColor(Color.GREEN);
}
getDelta().setText(diffString);
}
|
diff --git a/src/common/com/ForgeEssentials/permissions/ConfigGroups.java b/src/common/com/ForgeEssentials/permissions/ConfigGroups.java
index 98ff054ab..435171e05 100644
--- a/src/common/com/ForgeEssentials/permissions/ConfigGroups.java
+++ b/src/common/com/ForgeEssentials/permissions/ConfigGroups.java
@@ -1,52 +1,52 @@
package com.ForgeEssentials.permissions;
import java.io.File;
import java.util.HashSet;
import net.minecraftforge.common.ConfigCategory;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.Property;
import net.minecraftforge.event.Event.Result;
import com.ForgeEssentials.core.ForgeEssentials;
import com.ForgeEssentials.util.OutputHandler;
public class ConfigGroups
{
public static File groupsFile = new File(ModulePermissions.permsFolder, "groups.cfg");
public Configuration config;
private String defaultGroup;
public ConfigGroups()
{
config = new Configuration(groupsFile, true);
defaultGroup = GroupManager.DEFAULT.name;
// check for other groups. or generate
if (config.categories.size() == 0)
{
config.addCustomCategoryComment("members", "Generated group for your conveniance");
- config.get("members", "promoteGroup", "owners", "The group to which this group will promote to");
+ config.get("members", "promoteGroup", "owners", "The group to which this group will promote");
config.get("members", "chatPrefix", "", "text to go before the username in chat. format char: \u00a7 Only works with the Chat module installed");
config.get("members", "chatSuffix", "", "text to go after the username in chat. format char: \u00a7 Only works with the Chat module installed");
config.addCustomCategoryComment("owners", "Generated group for your conveniance");
config.get("owners", "promoteGroup", "", "The group to which this group will promote to");
config.get("owners", "chatPrefix", OutputHandler.GOLD+"[OWNER]", "text to go before the username in chat. format char: \u00a7 Only works with the Chat module installed");
config.get("owners", "chatSuffix", "", "text to go after the username in chat. format char: \u00a7 Only works with the Chat module installed");
}
// default group
{
config.addCustomCategoryComment(defaultGroup, "very default of all default groups. " + config.NEW_LINE + " This is also used for blanket permissions that are not applied to players but to zones");
String gPromote = config.get(defaultGroup, "promoteGroup", "members", "The group to which this group will promote to").value;
String gPrefix = config.get(defaultGroup, "chatPrefix", OutputHandler.GREY+"[Default]", "text to go before the username in chat. format char: \u00a7 Only works with the Chat module installed").value;
String gSuffix = config.get(defaultGroup, "chatSuffix", "", "text to go after the username in chat. format char: \u00a7 Only works with the Chat module installed").value;
}
}
}
| true | true | public ConfigGroups()
{
config = new Configuration(groupsFile, true);
defaultGroup = GroupManager.DEFAULT.name;
// check for other groups. or generate
if (config.categories.size() == 0)
{
config.addCustomCategoryComment("members", "Generated group for your conveniance");
config.get("members", "promoteGroup", "owners", "The group to which this group will promote to");
config.get("members", "chatPrefix", "", "text to go before the username in chat. format char: \u00a7 Only works with the Chat module installed");
config.get("members", "chatSuffix", "", "text to go after the username in chat. format char: \u00a7 Only works with the Chat module installed");
config.addCustomCategoryComment("owners", "Generated group for your conveniance");
config.get("owners", "promoteGroup", "", "The group to which this group will promote to");
config.get("owners", "chatPrefix", OutputHandler.GOLD+"[OWNER]", "text to go before the username in chat. format char: \u00a7 Only works with the Chat module installed");
config.get("owners", "chatSuffix", "", "text to go after the username in chat. format char: \u00a7 Only works with the Chat module installed");
}
// default group
{
config.addCustomCategoryComment(defaultGroup, "very default of all default groups. " + config.NEW_LINE + " This is also used for blanket permissions that are not applied to players but to zones");
String gPromote = config.get(defaultGroup, "promoteGroup", "members", "The group to which this group will promote to").value;
String gPrefix = config.get(defaultGroup, "chatPrefix", OutputHandler.GREY+"[Default]", "text to go before the username in chat. format char: \u00a7 Only works with the Chat module installed").value;
String gSuffix = config.get(defaultGroup, "chatSuffix", "", "text to go after the username in chat. format char: \u00a7 Only works with the Chat module installed").value;
}
}
| public ConfigGroups()
{
config = new Configuration(groupsFile, true);
defaultGroup = GroupManager.DEFAULT.name;
// check for other groups. or generate
if (config.categories.size() == 0)
{
config.addCustomCategoryComment("members", "Generated group for your conveniance");
config.get("members", "promoteGroup", "owners", "The group to which this group will promote");
config.get("members", "chatPrefix", "", "text to go before the username in chat. format char: \u00a7 Only works with the Chat module installed");
config.get("members", "chatSuffix", "", "text to go after the username in chat. format char: \u00a7 Only works with the Chat module installed");
config.addCustomCategoryComment("owners", "Generated group for your conveniance");
config.get("owners", "promoteGroup", "", "The group to which this group will promote to");
config.get("owners", "chatPrefix", OutputHandler.GOLD+"[OWNER]", "text to go before the username in chat. format char: \u00a7 Only works with the Chat module installed");
config.get("owners", "chatSuffix", "", "text to go after the username in chat. format char: \u00a7 Only works with the Chat module installed");
}
// default group
{
config.addCustomCategoryComment(defaultGroup, "very default of all default groups. " + config.NEW_LINE + " This is also used for blanket permissions that are not applied to players but to zones");
String gPromote = config.get(defaultGroup, "promoteGroup", "members", "The group to which this group will promote to").value;
String gPrefix = config.get(defaultGroup, "chatPrefix", OutputHandler.GREY+"[Default]", "text to go before the username in chat. format char: \u00a7 Only works with the Chat module installed").value;
String gSuffix = config.get(defaultGroup, "chatSuffix", "", "text to go after the username in chat. format char: \u00a7 Only works with the Chat module installed").value;
}
}
|
diff --git a/src/com/android/dialer/PhoneCallDetailsHelper.java b/src/com/android/dialer/PhoneCallDetailsHelper.java
index b51a27bce..be9cb660f 100644
--- a/src/com/android/dialer/PhoneCallDetailsHelper.java
+++ b/src/com/android/dialer/PhoneCallDetailsHelper.java
@@ -1,204 +1,205 @@
/*
* Copyright (C) 2011 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.dialer;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.PhoneNumberUtils;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;
import com.android.contacts.common.test.NeededForTesting;
import com.android.dialer.calllog.CallTypeHelper;
import com.android.dialer.calllog.ContactInfo;
import com.android.dialer.calllog.PhoneNumberHelper;
/**
* Helper class to fill in the views in {@link PhoneCallDetailsViews}.
*/
public class PhoneCallDetailsHelper {
/** The maximum number of icons will be shown to represent the call types in a group. */
private static final int MAX_CALL_TYPE_ICONS = 3;
private final Resources mResources;
/** The injected current time in milliseconds since the epoch. Used only by tests. */
private Long mCurrentTimeMillisForTest;
// Helper classes.
private final CallTypeHelper mCallTypeHelper;
private final PhoneNumberHelper mPhoneNumberHelper;
/**
* Creates a new instance of the helper.
* <p>
* Generally you should have a single instance of this helper in any context.
*
* @param resources used to look up strings
*/
public PhoneCallDetailsHelper(Resources resources, CallTypeHelper callTypeHelper,
PhoneNumberHelper phoneNumberHelper) {
mResources = resources;
mCallTypeHelper = callTypeHelper;
mPhoneNumberHelper = phoneNumberHelper;
}
/** Fills the call details views with content. */
public void setPhoneCallDetails(PhoneCallDetailsViews views, PhoneCallDetails details,
boolean isHighlighted) {
// Display up to a given number of icons.
views.callTypeIcons.clear();
int count = details.callTypes.length;
for (int index = 0; index < count && index < MAX_CALL_TYPE_ICONS; ++index) {
views.callTypeIcons.add(details.callTypes[index]);
}
+ views.callTypeIcons.requestLayout();
views.callTypeIcons.setVisibility(View.VISIBLE);
// Show the total call count only if there are more than the maximum number of icons.
final Integer callCount;
if (count > MAX_CALL_TYPE_ICONS) {
callCount = count;
} else {
callCount = null;
}
// The color to highlight the count and date in, if any. This is based on the first call.
Integer highlightColor =
isHighlighted ? mCallTypeHelper.getHighlightedColor(details.callTypes[0]) : null;
// The date of this call, relative to the current time.
CharSequence dateText =
DateUtils.getRelativeTimeSpanString(details.date,
getCurrentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
// Set the call count and date.
setCallCountAndDate(views, callCount, dateText, highlightColor);
CharSequence numberFormattedLabel = null;
// Only show a label if the number is shown and it is not a SIP address.
if (!TextUtils.isEmpty(details.number)
&& !PhoneNumberUtils.isUriNumber(details.number.toString())) {
if (details.numberLabel == ContactInfo.GEOCODE_AS_LABEL) {
numberFormattedLabel = details.geocode;
} else {
numberFormattedLabel = Phone.getTypeLabel(mResources, details.numberType,
details.numberLabel);
}
}
final CharSequence nameText;
final CharSequence numberText;
final CharSequence labelText;
final CharSequence displayNumber =
mPhoneNumberHelper.getDisplayNumber(details.number,
details.numberPresentation, details.formattedNumber);
if (TextUtils.isEmpty(details.name)) {
nameText = displayNumber;
if (TextUtils.isEmpty(details.geocode)
|| mPhoneNumberHelper.isVoicemailNumber(details.number)) {
numberText = mResources.getString(R.string.call_log_empty_gecode);
} else {
numberText = details.geocode;
}
labelText = numberText;
// We have a real phone number as "nameView" so make it always LTR
views.nameView.setTextDirection(View.TEXT_DIRECTION_LTR);
} else {
nameText = details.name;
numberText = displayNumber;
labelText = TextUtils.isEmpty(numberFormattedLabel) ? numberText :
numberFormattedLabel;
}
views.nameView.setText(nameText);
views.labelView.setText(labelText);
views.labelView.setVisibility(TextUtils.isEmpty(labelText) ? View.GONE : View.VISIBLE);
}
/** Sets the text of the header view for the details page of a phone call. */
public void setCallDetailsHeader(TextView nameView, PhoneCallDetails details) {
final CharSequence nameText;
final CharSequence displayNumber =
mPhoneNumberHelper.getDisplayNumber(details.number, details.numberPresentation,
mResources.getString(R.string.recentCalls_addToContact));
if (TextUtils.isEmpty(details.name)) {
nameText = displayNumber;
} else {
nameText = details.name;
}
nameView.setText(nameText);
}
@NeededForTesting
public void setCurrentTimeForTest(long currentTimeMillis) {
mCurrentTimeMillisForTest = currentTimeMillis;
}
/**
* Returns the current time in milliseconds since the epoch.
* <p>
* It can be injected in tests using {@link #setCurrentTimeForTest(long)}.
*/
private long getCurrentTimeMillis() {
if (mCurrentTimeMillisForTest == null) {
return System.currentTimeMillis();
} else {
return mCurrentTimeMillisForTest;
}
}
/** Sets the call count and date. */
private void setCallCountAndDate(PhoneCallDetailsViews views, Integer callCount,
CharSequence dateText, Integer highlightColor) {
// Combine the count (if present) and the date.
final CharSequence text;
if (callCount != null) {
text = mResources.getString(
R.string.call_log_item_count_and_date, callCount.intValue(), dateText);
} else {
text = dateText;
}
// Apply the highlight color if present.
final CharSequence formattedText;
if (highlightColor != null) {
formattedText = addBoldAndColor(text, highlightColor);
} else {
formattedText = text;
}
views.callTypeAndDate.setText(formattedText);
}
/** Creates a SpannableString for the given text which is bold and in the given color. */
private CharSequence addBoldAndColor(CharSequence text, int color) {
int flags = Spanned.SPAN_INCLUSIVE_INCLUSIVE;
SpannableString result = new SpannableString(text);
result.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), flags);
result.setSpan(new ForegroundColorSpan(color), 0, text.length(), flags);
return result;
}
}
| true | true | public void setPhoneCallDetails(PhoneCallDetailsViews views, PhoneCallDetails details,
boolean isHighlighted) {
// Display up to a given number of icons.
views.callTypeIcons.clear();
int count = details.callTypes.length;
for (int index = 0; index < count && index < MAX_CALL_TYPE_ICONS; ++index) {
views.callTypeIcons.add(details.callTypes[index]);
}
views.callTypeIcons.setVisibility(View.VISIBLE);
// Show the total call count only if there are more than the maximum number of icons.
final Integer callCount;
if (count > MAX_CALL_TYPE_ICONS) {
callCount = count;
} else {
callCount = null;
}
// The color to highlight the count and date in, if any. This is based on the first call.
Integer highlightColor =
isHighlighted ? mCallTypeHelper.getHighlightedColor(details.callTypes[0]) : null;
// The date of this call, relative to the current time.
CharSequence dateText =
DateUtils.getRelativeTimeSpanString(details.date,
getCurrentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
// Set the call count and date.
setCallCountAndDate(views, callCount, dateText, highlightColor);
CharSequence numberFormattedLabel = null;
// Only show a label if the number is shown and it is not a SIP address.
if (!TextUtils.isEmpty(details.number)
&& !PhoneNumberUtils.isUriNumber(details.number.toString())) {
if (details.numberLabel == ContactInfo.GEOCODE_AS_LABEL) {
numberFormattedLabel = details.geocode;
} else {
numberFormattedLabel = Phone.getTypeLabel(mResources, details.numberType,
details.numberLabel);
}
}
final CharSequence nameText;
final CharSequence numberText;
final CharSequence labelText;
final CharSequence displayNumber =
mPhoneNumberHelper.getDisplayNumber(details.number,
details.numberPresentation, details.formattedNumber);
if (TextUtils.isEmpty(details.name)) {
nameText = displayNumber;
if (TextUtils.isEmpty(details.geocode)
|| mPhoneNumberHelper.isVoicemailNumber(details.number)) {
numberText = mResources.getString(R.string.call_log_empty_gecode);
} else {
numberText = details.geocode;
}
labelText = numberText;
// We have a real phone number as "nameView" so make it always LTR
views.nameView.setTextDirection(View.TEXT_DIRECTION_LTR);
} else {
nameText = details.name;
numberText = displayNumber;
labelText = TextUtils.isEmpty(numberFormattedLabel) ? numberText :
numberFormattedLabel;
}
views.nameView.setText(nameText);
views.labelView.setText(labelText);
views.labelView.setVisibility(TextUtils.isEmpty(labelText) ? View.GONE : View.VISIBLE);
}
| public void setPhoneCallDetails(PhoneCallDetailsViews views, PhoneCallDetails details,
boolean isHighlighted) {
// Display up to a given number of icons.
views.callTypeIcons.clear();
int count = details.callTypes.length;
for (int index = 0; index < count && index < MAX_CALL_TYPE_ICONS; ++index) {
views.callTypeIcons.add(details.callTypes[index]);
}
views.callTypeIcons.requestLayout();
views.callTypeIcons.setVisibility(View.VISIBLE);
// Show the total call count only if there are more than the maximum number of icons.
final Integer callCount;
if (count > MAX_CALL_TYPE_ICONS) {
callCount = count;
} else {
callCount = null;
}
// The color to highlight the count and date in, if any. This is based on the first call.
Integer highlightColor =
isHighlighted ? mCallTypeHelper.getHighlightedColor(details.callTypes[0]) : null;
// The date of this call, relative to the current time.
CharSequence dateText =
DateUtils.getRelativeTimeSpanString(details.date,
getCurrentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
// Set the call count and date.
setCallCountAndDate(views, callCount, dateText, highlightColor);
CharSequence numberFormattedLabel = null;
// Only show a label if the number is shown and it is not a SIP address.
if (!TextUtils.isEmpty(details.number)
&& !PhoneNumberUtils.isUriNumber(details.number.toString())) {
if (details.numberLabel == ContactInfo.GEOCODE_AS_LABEL) {
numberFormattedLabel = details.geocode;
} else {
numberFormattedLabel = Phone.getTypeLabel(mResources, details.numberType,
details.numberLabel);
}
}
final CharSequence nameText;
final CharSequence numberText;
final CharSequence labelText;
final CharSequence displayNumber =
mPhoneNumberHelper.getDisplayNumber(details.number,
details.numberPresentation, details.formattedNumber);
if (TextUtils.isEmpty(details.name)) {
nameText = displayNumber;
if (TextUtils.isEmpty(details.geocode)
|| mPhoneNumberHelper.isVoicemailNumber(details.number)) {
numberText = mResources.getString(R.string.call_log_empty_gecode);
} else {
numberText = details.geocode;
}
labelText = numberText;
// We have a real phone number as "nameView" so make it always LTR
views.nameView.setTextDirection(View.TEXT_DIRECTION_LTR);
} else {
nameText = details.name;
numberText = displayNumber;
labelText = TextUtils.isEmpty(numberFormattedLabel) ? numberText :
numberFormattedLabel;
}
views.nameView.setText(nameText);
views.labelView.setText(labelText);
views.labelView.setVisibility(TextUtils.isEmpty(labelText) ? View.GONE : View.VISIBLE);
}
|
diff --git a/src/serial/RoundConfiguration.java b/src/serial/RoundConfiguration.java
index 0be5a9d..a0976ae 100644
--- a/src/serial/RoundConfiguration.java
+++ b/src/serial/RoundConfiguration.java
@@ -1,151 +1,151 @@
package serial;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Location;
import org.bukkit.block.Block;
import plugin.Stalemate;
import defense.HolyBlock;
import defense.Team;
public class RoundConfiguration {
private Map<Location, HolyBlock> holyBlocks = new ConcurrentHashMap<Location, HolyBlock>();
private List<Block> blocks = new Vector<Block>();
private Set<Team> teams = new HashSet<Team>();
private MapArea area;
public static enum RoundState {
IDLE, JOIN, BUILD, FIGHT, FINISH
}
public RoundConfiguration.RoundState state = RoundState.IDLE;
/**
* Takes a List<Team> containing all participating teams and creates a round with the center at Location center
* @param center - Center of the round
* @param list - List of the teams in the round
*/
public RoundConfiguration(Location center, List<Team> list) {
// Auto-assign positions
- String radiusStr = Stalemate.getInstance().settings.get("playradius");
+ String radiusStr = Stalemate.getInstance().getSetting("playradius", "10");
int radius;
try {
radius = Integer.parseInt(radiusStr);
- } catch (NumberFormatException|NullPointerException e) {
- throw new RuntimeException("Please set playradius in the configuration.");
+ } catch (NumberFormatException e) {
+ throw new RuntimeException("Please set playradius in the configuration properly.");
}
- MapArea a = new MapArea(center.subtract(new Location(center.getWorld(), radius, radius, radius)), center.add(new Location(center.getWorld(), radius, radius, radius)));
+ MapArea a = new MapArea(center.clone().subtract(new Location(center.getWorld(), radius, radius, radius)), center.clone().add(new Location(center.getWorld(), radius, radius, radius)));
double currentAngle = 0;
double ang = 2*Math.PI/list.size();
Map<Location, Team> t = new HashMap<Location, Team>();
for (int i = 0; i < list.size(); i++)
{
int posX = (int) Math.round(Math.cos(currentAngle));
int posZ = (int) Math.round(Math.sin(currentAngle));
Location blockLoc = new Location(center.getWorld(), center.getBlockX()+posX, center.getBlockY(), center.getBlockZ()+posZ);
t.put(blockLoc, list.get(i));
currentAngle += ang;
}
init(a, t);
}
/**
* Constructs a round from an area of the map (MapArea), and a Map of team Locations (Map<Location, Team>)
* @param area - A MapArea that defines where the round is played
* @param teams - A Map<Location, Team> that contains the teams at a given Location
*/
public RoundConfiguration(MapArea area, Map<Location, Team> teams) {
init(area, teams);
}
private void init(MapArea area, Map<Location, Team> teams) {
this.area = area;
for (Location loc : teams.keySet())
{
HolyBlock hb = new HolyBlock(loc, teams.get(loc));
holyBlocks.put(loc, hb);
hb.place();
blocks.add(loc.getWorld().getBlockAt(loc));
}
}
/**
* Gets the HolyBlock at a location
* @param loc - The location
* @return block - The HolyBlock
*/
public HolyBlock holyBlockAt(Location loc)
{
return holyBlocks.get(loc);
}
/**
* Gets the map area in which the round is taking place
* @return area - A MapArea of where the area where the round takes place
*/
public MapArea getArea()
{
return area;
}
/**
* Adds a team to the round
* @param t - The Team to be added
*/
public void addTeam(Team t)
{
teams.add(t);
}
/**
* Removes a team from the round
* @param t - The Team to be removed
*/
public void removeTeam(Team t)
{
teams.remove(t);
}
/**
* Gets the players in the round, names capitalized.
* @return players - A List<String> containing the players in the round
*/
public List<String> getParticipatingPlayers()
{
List<String> players = new Vector<String>();
for (Team t : getParticipatingTeams())
{
for (String s : t.getPlayers())
players.add(s);
}
return players;
}
/**
* Gets the teams in the round
* @return teams - A List<Team> containing the participating teams
*/
public List<Team> getParticipatingTeams()
{
return new Vector<Team>(teams);
}
/**
* Returns all of the Holy Blocks in a round
* @return blocks - A List<Block> containing all of the Holy Blocks
*/
public List<Block> getHolyBlocks()
{
return new Vector<Block>(blocks);
}
/**
* Returns the number of teams participating in a round
* @return number - The number of teams in a round, expressed as an int
*/
public int numTeams() {
return teams.size();
}
}
| false | true | public RoundConfiguration(Location center, List<Team> list) {
// Auto-assign positions
String radiusStr = Stalemate.getInstance().settings.get("playradius");
int radius;
try {
radius = Integer.parseInt(radiusStr);
} catch (NumberFormatException|NullPointerException e) {
throw new RuntimeException("Please set playradius in the configuration.");
}
MapArea a = new MapArea(center.subtract(new Location(center.getWorld(), radius, radius, radius)), center.add(new Location(center.getWorld(), radius, radius, radius)));
double currentAngle = 0;
double ang = 2*Math.PI/list.size();
Map<Location, Team> t = new HashMap<Location, Team>();
for (int i = 0; i < list.size(); i++)
{
int posX = (int) Math.round(Math.cos(currentAngle));
int posZ = (int) Math.round(Math.sin(currentAngle));
Location blockLoc = new Location(center.getWorld(), center.getBlockX()+posX, center.getBlockY(), center.getBlockZ()+posZ);
t.put(blockLoc, list.get(i));
currentAngle += ang;
}
init(a, t);
}
| public RoundConfiguration(Location center, List<Team> list) {
// Auto-assign positions
String radiusStr = Stalemate.getInstance().getSetting("playradius", "10");
int radius;
try {
radius = Integer.parseInt(radiusStr);
} catch (NumberFormatException e) {
throw new RuntimeException("Please set playradius in the configuration properly.");
}
MapArea a = new MapArea(center.clone().subtract(new Location(center.getWorld(), radius, radius, radius)), center.clone().add(new Location(center.getWorld(), radius, radius, radius)));
double currentAngle = 0;
double ang = 2*Math.PI/list.size();
Map<Location, Team> t = new HashMap<Location, Team>();
for (int i = 0; i < list.size(); i++)
{
int posX = (int) Math.round(Math.cos(currentAngle));
int posZ = (int) Math.round(Math.sin(currentAngle));
Location blockLoc = new Location(center.getWorld(), center.getBlockX()+posX, center.getBlockY(), center.getBlockZ()+posZ);
t.put(blockLoc, list.get(i));
currentAngle += ang;
}
init(a, t);
}
|
diff --git a/hidden-src/net/slreynolds/ds/util/FileUtil.java b/hidden-src/net/slreynolds/ds/util/FileUtil.java
index 4fdbcd2..e79fa0c 100644
--- a/hidden-src/net/slreynolds/ds/util/FileUtil.java
+++ b/hidden-src/net/slreynolds/ds/util/FileUtil.java
@@ -1,35 +1,35 @@
package net.slreynolds.ds.util;
import java.io.File;
import java.io.IOException;
/**
* Some utility methods on files
*/
public class FileUtil {
public static File createEmptyWritableFile(String path) throws IOException {
File out = new File(path);
if (out.exists()) {
if (!out.isFile()) {
throw new IOException(path + " is not a file");
}
if (!out.delete()) {
throw new IOException("Unable to delete existing file: "+path);
}
}
// invariant: file does not exist
- File parent = new File(out.getParent());
- if (!parent.exists()) {
+ File parent = out.getParentFile();
+ if (parent != null && !parent.exists()) {
parent.mkdirs();
}
out.createNewFile();
if (!out.canWrite()) {
throw new IOException("Cannot write to file " + path);
}
return out;
}
}
| true | true | public static File createEmptyWritableFile(String path) throws IOException {
File out = new File(path);
if (out.exists()) {
if (!out.isFile()) {
throw new IOException(path + " is not a file");
}
if (!out.delete()) {
throw new IOException("Unable to delete existing file: "+path);
}
}
// invariant: file does not exist
File parent = new File(out.getParent());
if (!parent.exists()) {
parent.mkdirs();
}
out.createNewFile();
if (!out.canWrite()) {
throw new IOException("Cannot write to file " + path);
}
return out;
}
| public static File createEmptyWritableFile(String path) throws IOException {
File out = new File(path);
if (out.exists()) {
if (!out.isFile()) {
throw new IOException(path + " is not a file");
}
if (!out.delete()) {
throw new IOException("Unable to delete existing file: "+path);
}
}
// invariant: file does not exist
File parent = out.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
out.createNewFile();
if (!out.canWrite()) {
throw new IOException("Cannot write to file " + path);
}
return out;
}
|
diff --git a/srcj/com/sun/electric/tool/io/input/ScalarEpicAnalysis.java b/srcj/com/sun/electric/tool/io/input/ScalarEpicAnalysis.java
index 9c6cdc673..3c7a5eb6b 100644
--- a/srcj/com/sun/electric/tool/io/input/ScalarEpicAnalysis.java
+++ b/srcj/com/sun/electric/tool/io/input/ScalarEpicAnalysis.java
@@ -1,962 +1,962 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: ScalarEpicAnalysis.java
*
* Copyright (c) 2009 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.io.input;
import com.sun.electric.database.geometry.GenMath;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.tool.simulation.AnalogAnalysis;
import com.sun.electric.tool.simulation.AnalogSignal;
import com.sun.electric.tool.simulation.Stimuli;
import com.sun.electric.tool.simulation.Waveform;
import com.sun.electric.tool.simulation.WaveformImpl;
import com.sun.electric.tool.user.ActivityLogger;
import com.sun.electric.tool.simulation.Signal;
import com.sun.electric.tool.simulation.NewSignal;
import com.sun.electric.tool.simulation.ScalarSample;
import com.sun.electric.tool.simulation.NewSignalSimpleImpl;
import com.sun.electric.tool.btree.*;
import com.sun.electric.tool.btree.unboxed.*;
import com.sun.electric.tool.btree.*;
import com.sun.electric.tool.btree.unboxed.*;
import com.sun.electric.tool.btree.*;
import com.sun.electric.tool.btree.unboxed.*;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Vector;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
/**
* Class to define a set of simulation data producet by Epic
* simulators, using the new disk-indexed format.
* This class differs from Anylisis base class by less memory consumption.
* Waveforms are stored in a file in packed form. They are loaded to memory by
* denand. Hierarchical structure is reconstructed from Epic flat names into Context objects.
* EpicSignals don't store signalContex strings, ScalarEpicAnalysis don't have signalNames hash map.
* Elements of Context are EpicTreeNodes. They partially implements interface javax.swing.tree.TreeNode .
*/
public class ScalarEpicAnalysis extends AnalogAnalysis {
/** Separator in Epic signal names. */ static final char separator = '.';
/** Type of voltage signal. */ static final byte VOLTAGE_TYPE = 1;
/** Type of current signal. */ static final byte CURRENT_TYPE = 2;
/** Fake context which denotes voltage signal. */ static final Context VOLTAGE_CONTEXT = new Context(VOLTAGE_TYPE);
/** Fake context which denotes current signal. */ static final Context CURRENT_CONTEXT = new Context(CURRENT_TYPE);
/** File name of File with waveforms. */ private File waveFileName;
/** Opened file with waveforms. */ private RandomAccessFile waveFile;
/** Offsets of packed waveforms in the file. */ int[] waveStarts;
/** Lengths of packed waveforms in the file. */ int[] waveLengths;
/** Time resolution of integer time unit. */ private double timeResolution;
/** Voltage resolution of integer voltage unit. */ private double voltageResolution;
/** Current resolution of integer current unit. */ private double currentResolution;
/** Simulation time. */ private double maxTime;
/** Unmodifieable view of signals list. */ private List<AnalogSignal> signalsUnmodifiable;
/** a set of voltage signals. */ private BitSet voltageSignals = new BitSet();
/** Top-most context. */ private Context rootContext;
/** Hash of all contexts. */ private Context[] contextHash = new Context[1];
/** Count of contexts in the hash. */ private int numContexts = 0;
/*
private final BTree<SimulationKey,SimulationValue> btree;
*/
private static class SimulationKey implements Comparable<SimulationKey>, Externalizable {
public String signalName;
public int index;
public SimulationKey() { }
public SimulationKey(String signalName, int index) {
this.signalName = signalName;
this.index = index;
}
public int compareTo(SimulationKey sp) {
int ret = signalName.compareTo(sp.signalName);
if (ret!=0) return ret;
ret = index - sp.index;
if (ret!=0) return ret;
return 0;
}
public boolean equals(Object o) {
if (!(o instanceof SimulationKey)) return false;
SimulationKey sp = (SimulationKey)o;
return sp.signalName.equals(signalName) && index==sp.index;
}
public int hashCode() {
return signalName.hashCode() ^ index;
}
public void readExternal(ObjectInput in) throws IOException {
signalName = in.readUTF();
index = in.readInt();
}
public void writeExternal(ObjectOutput out) throws IOException{
out.writeUTF(signalName);
out.writeInt(index);
}
}
private static class SimulationValue implements Externalizable {
public double time;
public double value;
public SimulationValue() { }
public SimulationValue(double time, double value) {
this.time = time;
this.value = value;
}
public void readExternal(ObjectInput in) throws IOException {
this.time = in.readDouble();
this.value = in.readDouble();
}
public void writeExternal(ObjectOutput out) throws IOException{
out.writeDouble(time);
out.writeDouble(value);
}
}
/**
* Package-private constructor.
* @param sd Stimuli.
*/
ScalarEpicAnalysis(Stimuli sd) {
super(sd, AnalogAnalysis.ANALYSIS_TRANS, false);
signalsUnmodifiable = Collections.unmodifiableList(super.getSignals());
}
/**
* Set time resolution of this ScalarEpicAnalysis.
* @param timeResolution time resolution in nanoseconds.
*/
void setTimeResolution(double timeResolution) { this.timeResolution = timeResolution; }
/**
* Set voltage resolution of this EpicAnalysys.
* @param voltageResolution voltage resolution in volts.
*/
void setVoltageResolution(double voltageResolution) { this.voltageResolution = voltageResolution; }
/**
* Set current resolution of this EpicAnalysys.
* @param currentResolution in amperes ( milliamperes? ).
*/
void setCurrentResolution(double currentResolution) { this.currentResolution = currentResolution; }
double getValueResolution(int signalIndex) {
return voltageSignals.get(signalIndex) ? voltageResolution : currentResolution;
}
/**
* Set simulation time of this ScalarEpicAnalysis.
* @param maxTime simulation time in nanoseconds.
*/
void setMaxTime(double maxTime) { this.maxTime = maxTime; }
/**
* Set root context of this EpicAnalysys.
* @param context root context.
*/
void setRootContext(Context context) { rootContext = context; }
/**
* Set waveform file of this ScalarEpicAnalysis.
* @param waveFileName File object with name of waveform file.
*/
void setWaveFile(File waveFileName) throws FileNotFoundException {
this.waveFileName = waveFileName;
waveFileName.deleteOnExit();
waveFile = new RandomAccessFile(waveFileName, "r");
}
/**
* Free allocated resources before closing.
*/
@Override
public void finished() {
try {
waveFile.close();
waveFileName.delete();
} catch (IOException e) {
}
}
/**
* Method to quickly return the signal that corresponds to a given Network name.
* This method overrides the m,ethod from Analysis class.
* It doesn't use signalNames hash map.
* @param netName the Network name to find.
* @return the Signal that corresponds with the Network.
* Returns null if none can be found.
*/
@Override
public AnalogSignal findSignalForNetworkQuickly(String netName) {
AnalogSignal old = super.findSignalForNetworkQuickly(netName);
String lookupName = TextUtils.canonicString(netName);
int index = searchName(lookupName);
if (index < 0) {
assert old == null;
return null;
}
AnalogSignal sig = signalsUnmodifiable.get(index);
return sig;
}
public List<AnalogSignal> getSignalsFromExtractedNet(Signal ws) {
ArrayList<AnalogSignal> ret = new ArrayList<AnalogSignal>();
ret.add((AnalogSignal)ws);
return ret;
}
/**
* Public method to build tree of EpicTreeNodes.
* Root of the tree us EpicRootTreeNode objects.
* Deeper nodes are EpicTreeNode objects.
* @param analysis name of root DefaultMutableTreeNode.
* @return root EpicRootTreeNode of the tree.
*/
public DefaultMutableTreeNode getSignalsForExplorer(String analysis) {
DefaultMutableTreeNode signalsExplorerTree = new EpicRootTreeNode(this, analysis);
return signalsExplorerTree;
}
/**
* Returns EpicSignal by its TreePath.
* @param treePath specified TreePath.
* @return EpicSignal or null.
*/
public static EpicSignal getSignal(TreePath treePath) {
Object[] path = treePath.getPath();
int i = 0;
while (i < path.length && !(path[i] instanceof EpicRootTreeNode))
i++;
if (i >= path.length) return null;
ScalarEpicAnalysis an = ((EpicRootTreeNode)path[i]).an;
i++;
int index = 0;
for (; i < path.length; i++) {
EpicTreeNode tn = (EpicTreeNode)path[i];
index += tn.nodeOffset;
if (tn.isLeaf())
return (EpicSignal)an.signalsUnmodifiable.get(index);
}
return null;
}
/**
* Method to get the list of signals in this Simulation Data object.
* List is unmodifieable.
* @return a List of signals.
*/
@Override
public List<AnalogSignal> getSignals() { return signalsUnmodifiable; }
/**
* This methods overrides Analysis.nameSignal.
* It doesn't use Analisys.signalNames to use less memory.
*/
@Override
public void nameSignal(AnalogSignal ws, String sigName) {}
/**
* Finds signal index of AnalogSignal with given full name.
* @param name full name.
* @return signal index of AnalogSignal in unmodifiable list of signals or -1.
*/
int searchName(String name) {
Context context = rootContext;
for (int pos = 0, index = 0;;) {
int indexOfSep = name.indexOf(separator, pos);
if (indexOfSep < 0) {
EpicTreeNode sig = context.sigs.get(name.substring(pos));
return sig != null ? index + sig.nodeOffset : -1;
}
EpicTreeNode sub = context.subs.get(name.substring(pos, indexOfSep));
if (sub == null) return -1;
context = sub.context;
pos = indexOfSep + 1;
index += sub.nodeOffset;
}
}
/**
* Makes fullName or signalContext of signal with specified index.
* @param index signal index.
* @param full true to request full name.
*/
String makeName(int index, boolean full) {
StringBuilder sb = new StringBuilder();
Context context = rootContext;
if (context == null) return null;
if (index < 0 || index >= context.treeSize)
throw new IndexOutOfBoundsException();
for (;;) {
int localIndex = context.localSearch(index);
EpicTreeNode tn = context.nodes[localIndex];
Context subContext = tn.context;
if (subContext.isLeaf()) {
if (full)
sb.append(tn.name);
else if (sb.length() == 0)
return null;
else
sb.setLength(sb.length() - 1);
return sb.toString();
}
sb.append(tn.name);
sb.append(separator);
index -= tn.nodeOffset;
context = subContext;
}
}
/**
* Method to get Fake context of AnalogSignal.
* @param byte physical type of AnalogSignal.
* @return Fake context.
*/
static Context getContext(byte type) {
switch (type) {
case VOLTAGE_TYPE:
return VOLTAGE_CONTEXT;
case CURRENT_TYPE:
return CURRENT_CONTEXT;
}
throw new IllegalArgumentException();
}
/**
* Method to get Context by list of names and list of contexts.
* @param strings list of names.
* @param contexts list of contexts.
*/
Context getContext(ArrayList<String> strings, ArrayList<Context> contexts) {
assert strings.size() == contexts.size();
int hashCode = Context.hashValue(strings, contexts);
int i = hashCode & 0x7FFFFFFF;
i %= contextHash.length;
for (int j = 1; contextHash[i] != null; j += 2) {
Context c = contextHash[i];
if (c.hashCode == hashCode && c.equals(strings, contexts)) return c;
i += j;
if (i >= contextHash.length) i -= contextHash.length;
}
// Need to create new context.
if (numContexts*2 <= contextHash.length - 3) {
// create a new CellUsage, if enough space in the hash
Context c = new Context(strings, contexts, hashCode);
contextHash[i] = c;
numContexts++;
return c;
}
// enlarge hash if not
rehash();
return getContext(strings, contexts);
}
/**
* Rehash the context hash.
* @throws IndexOutOfBoundsException on hash overflow.
*/
private void rehash() {
int newSize = numContexts*2 + 3;
if (newSize < 0) throw new IndexOutOfBoundsException();
Context[] newHash = new Context[GenMath.primeSince(newSize)];
for (int k = 0; k < contextHash.length; k++) {
Context c = contextHash[k];
if (c == null) continue;
int i = c.hashCode & 0x7FFFFFFF;
i %= newHash.length;
for (int j = 1; newHash[i] != null; j += 2) {
i += j;
if (i >= newHash.length) i -= newHash.length;
}
newHash[i] = c;
}
contextHash = newHash;
}
private HashMap<String,BTree<Integer,Double>> timetrees = new HashMap<String,BTree<Integer,Double>>();
private HashMap<String,BTree<Integer,Double>> valtrees = new HashMap<String,BTree<Integer,Double>>();
private PageStorage ps = null;
@Override
protected Waveform[] loadWaveforms(AnalogSignal signal) {
int index = signal.getIndexInAnalysis();
double valueResolution = getValueResolution(index);
int start = waveStarts[index];
int len = waveLengths[index];
byte[] packedWaveform = new byte[len];
try {
waveFile.seek(start);
waveFile.readFully(packedWaveform);
} catch (IOException e) {
ActivityLogger.logException(e);
return new Waveform[] { new WaveformImpl(new double[0], new double[0]) };
}
int count = 0;
int t = 0;
int v = 0;
double minValue = Double.MAX_VALUE;
double maxValue = Double.MIN_VALUE;
int evmin = 0;
int evmax = 0;
String sigName = signal.getFullName();
BTree<Integer,Double> timetree = timetrees.get(sigName);
BTree<Integer,Double> valtree = valtrees.get(sigName);
if (ps==null)
try {
ps = new CachingPageStorage(FilePageStorage.create(), 16 * 1024);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (timetree==null)
timetrees.put(sigName, timetree =
new com.sun.electric.tool.btree.BTree<Integer,Double,Integer>(ps, UnboxedInt.instance, null, UnboxedHalfDouble.instance));
if (valtree==null)
valtrees.put(sigName, valtree =
new com.sun.electric.tool.btree.BTree<Integer,Double,Integer>(ps, UnboxedInt.instance, null, UnboxedHalfDouble.instance));
long now = System.currentTimeMillis();
System.err.println("filling btree for signal " + sigName);
long last = 0;
for (int i = 0; i < len; count++) {
int l;
int b = packedWaveform[i++] & 0xff;
if (b < 0xC0) { l = 0; } else if (b < 0xFF) { l = 1; b -= 0xC0; } else { l = 4; }
while (l > 0) {
b = (b << 8) | packedWaveform[i++] & 0xff;
l--;
}
t = t + b;
b = packedWaveform[i++] & 0xff;
if (b < 0xC0) { l = 0; b -= 0x60; } else if (b < 0xFF) { l = 1; b -= 0xDF; } else { l = 4; }
while (l > 0) {
b = (b << 8) | packedWaveform[i++] & 0xff;
l--;
}
v = v + b;
double value = v * valueResolution;
if (value < minValue) { minValue = value; evmin = count; }
if (value > maxValue) { maxValue = value; evmax = count; }
timetree.put(count, t*timeResolution);
valtree.put(count, value);
- long now = System.currentTimeMillis();
- if (now-last > 500) {
- last = now;
+ long now1 = System.currentTimeMillis();
+ if (now1-last > 500) {
+ last = now1;
System.err.print("\r " + i + "/" + len + " = " + ((int)Math.round(((float)i*100)/len)) +"% ");
}
}
System.err.println(" done filling btree for signal " + sigName + "; took " + (System.currentTimeMillis()-now) +"ms");
return new Waveform[] { new ScalarWaveformImpl(sigName, count, evmin, evmax, timetree, valtree) };
}
private class ScalarWaveformImpl extends NewSignalSimpleImpl implements Waveform {
private final String signal;
private final int numEvents;
private final int eventWithMinValue;
private final int eventWithMaxValue;
private NewSignal.Approximation<ScalarSample> preferredApproximation = null;
private final BTree<Integer,Double> timetree;
private final BTree<Integer,Double> valtree;
public ScalarWaveformImpl(String signal, int numEvents, int eventWithMinValue, int eventWithMaxValue,
BTree<Integer,Double> timetree,
BTree<Integer,Double> valtree
) {
this.signal = signal;
this.numEvents = numEvents;
this.eventWithMinValue = eventWithMinValue;
this.eventWithMaxValue = eventWithMaxValue;
if (timetree==null) throw new RuntimeException();
if (valtree==null) throw new RuntimeException();
this.timetree = timetree;
this.valtree = valtree;
this.preferredApproximation = new ScalarWaveformImplApproximation();
}
public synchronized NewSignal.Approximation<ScalarSample> getPreferredApproximation() {
return preferredApproximation;
}
public int getNumEvents() { return numEvents; }
public void getEvent(int index, double[] result) {
result[0] = getPreferredApproximation().getTime(index);
result[1] = result[2] = getPreferredApproximation().getSample(index).getValue();
}
private class ScalarWaveformImplApproximation implements NewSignal.Approximation<ScalarSample> {
public int getNumEvents() { return numEvents; }
public double getTime(int index) {
Double d = timetree.get(index);
if (d==null) throw new RuntimeException("index out of bounds");
return d.doubleValue();
}
public ScalarSample getSample(int index) {
Double d = valtree.get(index);
if (d==null) throw new RuntimeException("index out of bounds");
return new ScalarSample(d.doubleValue());
}
public int getTimeNumerator(int index) { throw new RuntimeException("not implemented"); }
public int getTimeDenominator() { throw new RuntimeException("not implemented"); }
public int getEventWithMaxValue() { return eventWithMaxValue; }
public int getEventWithMinValue() { return eventWithMinValue; }
}
}
/************************* EpicRootTreeNode *********************************************
* This class is for root node of EpicTreeNode tree.
* It contains children from rootContext of specified ScalarEpicAnalysis.
*/
private static class EpicRootTreeNode extends DefaultMutableTreeNode {
/** ScalarEpicAnalysis which owns the tree. */ private ScalarEpicAnalysis an;
/**
* Private constructor.
* @param an specified EpicAnalysy.
* @paran name name of bwq EpicRootTreeNode
*/
private EpicRootTreeNode(ScalarEpicAnalysis an, String name) {
super(name);
this.an = an;
Vector<EpicTreeNode> children = new Vector<EpicTreeNode>();
// // make a list of signal names with "#" in them
// Map<String,DefaultMutableTreeNode> sharpMap = new HashMap<String,DefaultMutableTreeNode>();
// for (EpicTreeNode tn: an.rootContext.sortedNodes)
// {
// String sigName = tn.name;
// int hashPos = sigName.indexOf('#');
// if (hashPos <= 0) continue;
// String sharpName = sigName.substring(0, hashPos);
// DefaultMutableTreeNode parent = sharpMap.get(sharpName);
// if (parent == null)
// {
// parent = new DefaultMutableTreeNode(sharpName + "#");
// sharpMap.put(sharpName, parent);
// this.add(parent);
// }
// }
//
// // add all signals to the tree
// for (EpicTreeNode tn: an.rootContext.sortedNodes)
// {
// String nodeName = null;
// String sigName = tn.name;
// int hashPos = sigName.indexOf('#');
// if (hashPos > 0)
// {
// // force a branch with the proper name
// nodeName = sigName.substring(0, hashPos);
// } else
// {
// // if this is the pure name of a hash set, force a branch
// String pureSharpName = sigName;
// if (sharpMap.get(pureSharpName) != null)
// nodeName = pureSharpName;
// }
// if (nodeName != null)
// {
// DefaultMutableTreeNode parent = sharpMap.get(nodeName);
// parent.add(new DefaultMutableTreeNode(tn));
// } else
// {
// children.add(tn);
// }
// }
for (EpicTreeNode tn: an.rootContext.sortedNodes)
children.add(tn);
this.children = children;
}
/**
* Returns the index of the specified child in this node's child array.
* If the specified node is not a child of this node, returns
* <code>-1</code>. This method performs a linear search and is O(n)
* where n is the number of children.
*
* @param aChild the TreeNode to search for among this node's children
* @exception IllegalArgumentException if <code>aChild</code>
* is null
* @return an int giving the index of the node in this node's child
* array, or <code>-1</code> if the specified node is a not
* a child of this node
*/
public int getIndex(TreeNode aChild) {
try {
EpicTreeNode tn = (EpicTreeNode)aChild;
if (getChildAt(tn.sortedIndex) == tn)
return tn.sortedIndex;
} catch (Exception e) {
if (aChild == null)
throw new IllegalArgumentException("argument is null");
}
return -1;
}
}
/************************* Context *********************************************
* This class denotes a group of siignals. It may have a few instance in signal tree.
*/
static class Context {
/**
* Type of context.
* it is nonzero for leaf context and it is zero for non-leaf contexts.
*/
private final byte type;
/**
* Hash code of this Context
*/
private final int hashCode;
/**
* Nodes of this Context in chronological order.
*/
private final EpicTreeNode[] nodes;
/**
* Nodes of this Context sorted by type and name.
*/
private final EpicTreeNode[] sortedNodes;
/**
* Flat number of signals in tree whose root is this context.
*/
private final int treeSize;
/**
* Map from name of subcontext to EpicTreeNode.
*/
private final HashMap<String,EpicTreeNode> subs = new HashMap<String,EpicTreeNode>();
/**
* Map from name of leaf npde to EpicTreeNode.
*/
private final HashMap<String,EpicTreeNode> sigs = new HashMap<String,EpicTreeNode>();
/**
* Constructor of leaf fake context.
*/
private Context(byte type) {
assert type != 0;
this.type = type;
assert isLeaf();
hashCode = type;
nodes = null;
sortedNodes = null;
treeSize = 1;
}
/**
* Constructor of real context.
* @param names list of names.
* @param contexts list of contexts.
* @param hashCode precalculated hash code of new Context.
*/
private Context(ArrayList<String> names, ArrayList<Context> contexts, int hashCode) {
assert names.size() == contexts.size();
type = 0;
this.hashCode = hashCode;
nodes = new EpicTreeNode[names.size()];
int treeSize = 0;
for (int i = 0; i < nodes.length; i++) {
String name = names.get(i);
Context subContext = contexts.get(i);
EpicTreeNode tn = new EpicTreeNode(i, name, subContext,treeSize);
nodes[i] = tn;
String canonicName = TextUtils.canonicString(name);
if (subContext.isLeaf())
sigs.put(canonicName, tn);
else
subs.put(canonicName, tn);
treeSize += subContext.treeSize;
}
sortedNodes = nodes.clone();
Arrays.sort(sortedNodes, TREE_NODE_ORDER);
for (int i = 0; i < sortedNodes.length; i++)
sortedNodes[i].sortedIndex = i;
this.treeSize = treeSize;
}
/**
* Returns true if this context is fake leaf context.
* @return true if this context is fake leaf context.
*/
boolean isLeaf() { return type != 0; }
/**
* Returns true if contenst of this Context is equal to specified lists.
* @returns true if contenst of this Context is equal to specified lists.
*/
private boolean equals(ArrayList<String> names, ArrayList<Context> contexts) {
int len = nodes.length;
if (names.size() != len || contexts.size() != len) return false;
for (int i = 0; i < len; i++) {
EpicTreeNode tn = nodes[i];
if (names.get(i) != tn.name || contexts.get(i) != tn.context) return false;
}
return true;
}
/**
* Returns hash code of this Context.
* @return hash code of this Context.
*/
public int hashCode() { return hashCode; }
/**
* Private method to calculate hash code.
* @param names list of names.
* @param contexts list of contexts.
* @return hash code
*/
private static int hashValue(ArrayList<String> names, ArrayList<Context> contexts) {
assert names.size() == contexts.size();
int hash = 0;
for (int i = 0; i < names.size(); i++)
hash = hash * 19 + names.get(i).hashCode()^contexts.get(i).hashCode();
return hash;
}
/**
* Searches an EpicTreeNode in this context where signal with specified flat offset lives.
* @param offset flat offset of EpicSignal.
* @return index of EpicTreeNode in this Context or -1.
*/
private int localSearch(int offset) {
assert offset >= 0 && offset < treeSize;
assert nodes.length > 0;
int l = 1;
int h = nodes.length - 1;
while (l <= h) {
int m = (l + h) >> 1;
if (nodes[m].nodeOffset <= offset)
l = m + 1;
else
h = m - 1;
}
return h;
}
}
/************************* EpicTreeNode *********************************************
* This class denotes an element of a Context.
* It partially implements TreeNode (without getParent).
*/
public static class EpicTreeNode implements TreeNode {
// private final int chronIndex;
private final String name;
private final Context context;
private final int nodeOffset;
private int sortedIndex;
/**
* Private constructor.
*/
private EpicTreeNode(int chronIndex, String name, Context context, int nodeOffset) {
// this.chronIndex = chronIndex;
this.name = name;
this.context = context;
this.nodeOffset = nodeOffset;
}
/**
* Returns the child <code>TreeNode</code> at index
* <code>childIndex</code>.
*/
public TreeNode getChildAt(int childIndex) {
try {
return context.sortedNodes[childIndex];
} catch (NullPointerException e) {
throw new ArrayIndexOutOfBoundsException("node has no children");
}
}
/**
* Returns the number of children <code>TreeNode</code>s the receiver
* contains.
*/
public int getChildCount() {
return isLeaf() ? 0 : context.sortedNodes.length;
}
/**
* Returns the parent <code>TreeNode</code> of the receiver.
*/
public TreeNode getParent() {
throw new UnsupportedOperationException();
}
/**
* Returns the index of <code>node</code> in the receivers children.
* If the receiver does not contain <code>node</code>, -1 will be
* returned.
*/
public int getIndex(TreeNode node) {
try {
EpicTreeNode tn = (EpicTreeNode)node;
if (context.nodes[tn.sortedIndex] == tn)
return tn.sortedIndex;
} catch (Exception e) {
if (node == null)
throw new IllegalArgumentException("argument is null");
}
return -1;
}
/**
* Returns true if the receiver allows children.
*/
public boolean getAllowsChildren() { return !isLeaf(); }
/**
* Returns true if the receiver is a leaf.
*/
public boolean isLeaf() { return context.type != 0; }
/**
* Returns the children of the receiver as an <code>Enumeration</code>.
*/
public Enumeration children() {
if (isLeaf())
return DefaultMutableTreeNode.EMPTY_ENUMERATION;
return new Enumeration<EpicTreeNode>() {
int count = 0;
public boolean hasMoreElements() {
return count < context.nodes.length;
}
public EpicTreeNode nextElement() {
if (count < context.nodes.length)
return context.nodes[count++];
throw new NoSuchElementException("Vector Enumeration");
}
};
}
public String toString() { return name; }
}
/**
* Comparator which compares EpicTreeNodes by type and by name.
*/
private static Comparator<EpicTreeNode> TREE_NODE_ORDER = new Comparator<EpicTreeNode>() {
public int compare(EpicTreeNode tn1, EpicTreeNode tn2) {
int cmp = tn1.context.type - tn2.context.type;
if (cmp != 0) return cmp;
return TextUtils.STRING_NUMBER_ORDER.compare(tn1.name, tn2.name);
}
};
/************************* EpicSignal *********************************************
* Class which represents Epic AnalogSignal.
*/
static class EpicSignal extends AnalogSignal {
int sigNum;
EpicSignal(ScalarEpicAnalysis an, byte type, int index, int sigNum) {
super(an);
assert getIndexInAnalysis() == index;
if (type == VOLTAGE_TYPE)
an.voltageSignals.set(index);
else
assert type == CURRENT_TYPE;
this.sigNum = sigNum;
}
/**
* Method to return the context of this simulation signal.
* The context is the hierarchical path to the signal, and it usually contains
* instance names of cells farther up the hierarchy, all separated by dots.
* @param signalContext the context of this simulation signal.
*/
@Override
public void setSignalContext(String signalContext) { throw new UnsupportedOperationException(); }
/**
* Method to return the context of this simulation signal.
* The context is the hierarchical path to the signal, and it usually contains
* instance names of cells farther up the hierarchy, all separated by dots.
* @return the context of this simulation signal.
* If there is no context, this returns null.
*/
@Override
public String getSignalContext() {
return ((ScalarEpicAnalysis)getAnalysis()).makeName(getIndexInAnalysis(), false);
}
/**
* Method to return the full name of this simulation signal.
* The full name includes the context, if any.
* @return the full name of this simulation signal.
*/
@Override
public String getFullName() {
return ((ScalarEpicAnalysis)getAnalysis()).makeName(getIndexInAnalysis(), true);
}
void setBounds(int minV, int maxV) {
ScalarEpicAnalysis an = (ScalarEpicAnalysis)getAnalysis();
double resolution = an.getValueResolution(getIndexInAnalysis());
bounds = new Rectangle2D.Double(0, minV*resolution, an.maxTime, (maxV - minV)*resolution);
leftEdge = 0;
rightEdge = an.maxTime;
// rightEdge = minV*resolution;
}
}
}
| true | true | protected Waveform[] loadWaveforms(AnalogSignal signal) {
int index = signal.getIndexInAnalysis();
double valueResolution = getValueResolution(index);
int start = waveStarts[index];
int len = waveLengths[index];
byte[] packedWaveform = new byte[len];
try {
waveFile.seek(start);
waveFile.readFully(packedWaveform);
} catch (IOException e) {
ActivityLogger.logException(e);
return new Waveform[] { new WaveformImpl(new double[0], new double[0]) };
}
int count = 0;
int t = 0;
int v = 0;
double minValue = Double.MAX_VALUE;
double maxValue = Double.MIN_VALUE;
int evmin = 0;
int evmax = 0;
String sigName = signal.getFullName();
BTree<Integer,Double> timetree = timetrees.get(sigName);
BTree<Integer,Double> valtree = valtrees.get(sigName);
if (ps==null)
try {
ps = new CachingPageStorage(FilePageStorage.create(), 16 * 1024);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (timetree==null)
timetrees.put(sigName, timetree =
new com.sun.electric.tool.btree.BTree<Integer,Double,Integer>(ps, UnboxedInt.instance, null, UnboxedHalfDouble.instance));
if (valtree==null)
valtrees.put(sigName, valtree =
new com.sun.electric.tool.btree.BTree<Integer,Double,Integer>(ps, UnboxedInt.instance, null, UnboxedHalfDouble.instance));
long now = System.currentTimeMillis();
System.err.println("filling btree for signal " + sigName);
long last = 0;
for (int i = 0; i < len; count++) {
int l;
int b = packedWaveform[i++] & 0xff;
if (b < 0xC0) { l = 0; } else if (b < 0xFF) { l = 1; b -= 0xC0; } else { l = 4; }
while (l > 0) {
b = (b << 8) | packedWaveform[i++] & 0xff;
l--;
}
t = t + b;
b = packedWaveform[i++] & 0xff;
if (b < 0xC0) { l = 0; b -= 0x60; } else if (b < 0xFF) { l = 1; b -= 0xDF; } else { l = 4; }
while (l > 0) {
b = (b << 8) | packedWaveform[i++] & 0xff;
l--;
}
v = v + b;
double value = v * valueResolution;
if (value < minValue) { minValue = value; evmin = count; }
if (value > maxValue) { maxValue = value; evmax = count; }
timetree.put(count, t*timeResolution);
valtree.put(count, value);
long now = System.currentTimeMillis();
if (now-last > 500) {
last = now;
System.err.print("\r " + i + "/" + len + " = " + ((int)Math.round(((float)i*100)/len)) +"% ");
}
}
System.err.println(" done filling btree for signal " + sigName + "; took " + (System.currentTimeMillis()-now) +"ms");
return new Waveform[] { new ScalarWaveformImpl(sigName, count, evmin, evmax, timetree, valtree) };
}
| protected Waveform[] loadWaveforms(AnalogSignal signal) {
int index = signal.getIndexInAnalysis();
double valueResolution = getValueResolution(index);
int start = waveStarts[index];
int len = waveLengths[index];
byte[] packedWaveform = new byte[len];
try {
waveFile.seek(start);
waveFile.readFully(packedWaveform);
} catch (IOException e) {
ActivityLogger.logException(e);
return new Waveform[] { new WaveformImpl(new double[0], new double[0]) };
}
int count = 0;
int t = 0;
int v = 0;
double minValue = Double.MAX_VALUE;
double maxValue = Double.MIN_VALUE;
int evmin = 0;
int evmax = 0;
String sigName = signal.getFullName();
BTree<Integer,Double> timetree = timetrees.get(sigName);
BTree<Integer,Double> valtree = valtrees.get(sigName);
if (ps==null)
try {
ps = new CachingPageStorage(FilePageStorage.create(), 16 * 1024);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (timetree==null)
timetrees.put(sigName, timetree =
new com.sun.electric.tool.btree.BTree<Integer,Double,Integer>(ps, UnboxedInt.instance, null, UnboxedHalfDouble.instance));
if (valtree==null)
valtrees.put(sigName, valtree =
new com.sun.electric.tool.btree.BTree<Integer,Double,Integer>(ps, UnboxedInt.instance, null, UnboxedHalfDouble.instance));
long now = System.currentTimeMillis();
System.err.println("filling btree for signal " + sigName);
long last = 0;
for (int i = 0; i < len; count++) {
int l;
int b = packedWaveform[i++] & 0xff;
if (b < 0xC0) { l = 0; } else if (b < 0xFF) { l = 1; b -= 0xC0; } else { l = 4; }
while (l > 0) {
b = (b << 8) | packedWaveform[i++] & 0xff;
l--;
}
t = t + b;
b = packedWaveform[i++] & 0xff;
if (b < 0xC0) { l = 0; b -= 0x60; } else if (b < 0xFF) { l = 1; b -= 0xDF; } else { l = 4; }
while (l > 0) {
b = (b << 8) | packedWaveform[i++] & 0xff;
l--;
}
v = v + b;
double value = v * valueResolution;
if (value < minValue) { minValue = value; evmin = count; }
if (value > maxValue) { maxValue = value; evmax = count; }
timetree.put(count, t*timeResolution);
valtree.put(count, value);
long now1 = System.currentTimeMillis();
if (now1-last > 500) {
last = now1;
System.err.print("\r " + i + "/" + len + " = " + ((int)Math.round(((float)i*100)/len)) +"% ");
}
}
System.err.println(" done filling btree for signal " + sigName + "; took " + (System.currentTimeMillis()-now) +"ms");
return new Waveform[] { new ScalarWaveformImpl(sigName, count, evmin, evmax, timetree, valtree) };
}
|
diff --git a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/CreateRuntimeFromESB.java b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/CreateRuntimeFromESB.java
index 8636a53..1a670cf 100644
--- a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/CreateRuntimeFromESB.java
+++ b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/CreateRuntimeFromESB.java
@@ -1,39 +1,39 @@
package org.jboss.tools.esb.ui.bot.tests;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.jboss.tools.ui.bot.ext.SWTTestExt;
import org.jboss.tools.ui.bot.ext.config.TestConfigurator;
import org.jboss.tools.ui.bot.ext.config.Annotations.*;
import org.jboss.tools.ui.bot.ext.gen.ActionItem;
import org.jboss.tools.ui.bot.ext.types.IDELabel;
import org.junit.Test;
@Require(esb=@ESB())
public class CreateRuntimeFromESB extends SWTTestExt {
@Test
public void createESBRuntime() {
SWTBot wiz = open.preferenceOpen(ActionItem.Preference.JBossToolsJBossESBRuntimes.LABEL);
wiz.button("Add").click();
bot.shell(IDELabel.Shell.NEW_ESB_RUNTIME).activate();
assertFalse("Finish button must not be enabled when no home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
bot.text(1).setText(TestConfigurator.currentConfig.getEsb().runtimeHome);
bot.sleep (3000l, "3 sleeping - " + TestConfigurator.currentConfig.getEsb().runtimeHome + " " + TestConfigurator.currentConfig.getEsb().version + " " + bot.comboBox().selection().toString());
/* ldimaggi - Oct 2011 - https://issues.jboss.org/browse/JBDS-1886 - this test fails for ESB 4.10 */
- //assertTrue("JBDS-1886 - Version was not automatically selected by setting ESB home dir",bot.comboBox().selection().equals(TestConfigurator.currentConfig.getEsb().version));
+ assertTrue("JBDS-1886 - Version was not automatically selected by setting ESB home dir",bot.comboBox().selection().equals(TestConfigurator.currentConfig.getEsb().version));
/* ldimaggi - Oct 2011 */
bot.text(0).setText("123_TheName");
//System.out.println ("[" + bot.textWithLabel("JBoss ESB Runtime").getText() +"]");
assertTrue ("Runtime name cannot start with a number", bot.textWithLabel("JBoss ESB Runtime").getText().equals(" Runtime name is not correct") );
bot.text(0).setText("runtime");
String name = bot.text(0).getText();
assertFalse("Runtime name was not automaticly set by setting ESB home dir",name.equals(""));
assertTrue("Finish button must be enabled when valid home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
open.finish(bot.activeShell().bot());
open.finish(wiz, IDELabel.Button.OK);
eclipse.removeESBRuntime(name);
}
}
| true | true | public void createESBRuntime() {
SWTBot wiz = open.preferenceOpen(ActionItem.Preference.JBossToolsJBossESBRuntimes.LABEL);
wiz.button("Add").click();
bot.shell(IDELabel.Shell.NEW_ESB_RUNTIME).activate();
assertFalse("Finish button must not be enabled when no home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
bot.text(1).setText(TestConfigurator.currentConfig.getEsb().runtimeHome);
bot.sleep (3000l, "3 sleeping - " + TestConfigurator.currentConfig.getEsb().runtimeHome + " " + TestConfigurator.currentConfig.getEsb().version + " " + bot.comboBox().selection().toString());
/* ldimaggi - Oct 2011 - https://issues.jboss.org/browse/JBDS-1886 - this test fails for ESB 4.10 */
//assertTrue("JBDS-1886 - Version was not automatically selected by setting ESB home dir",bot.comboBox().selection().equals(TestConfigurator.currentConfig.getEsb().version));
/* ldimaggi - Oct 2011 */
bot.text(0).setText("123_TheName");
//System.out.println ("[" + bot.textWithLabel("JBoss ESB Runtime").getText() +"]");
assertTrue ("Runtime name cannot start with a number", bot.textWithLabel("JBoss ESB Runtime").getText().equals(" Runtime name is not correct") );
bot.text(0).setText("runtime");
String name = bot.text(0).getText();
assertFalse("Runtime name was not automaticly set by setting ESB home dir",name.equals(""));
assertTrue("Finish button must be enabled when valid home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
open.finish(bot.activeShell().bot());
open.finish(wiz, IDELabel.Button.OK);
eclipse.removeESBRuntime(name);
}
| public void createESBRuntime() {
SWTBot wiz = open.preferenceOpen(ActionItem.Preference.JBossToolsJBossESBRuntimes.LABEL);
wiz.button("Add").click();
bot.shell(IDELabel.Shell.NEW_ESB_RUNTIME).activate();
assertFalse("Finish button must not be enabled when no home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
bot.text(1).setText(TestConfigurator.currentConfig.getEsb().runtimeHome);
bot.sleep (3000l, "3 sleeping - " + TestConfigurator.currentConfig.getEsb().runtimeHome + " " + TestConfigurator.currentConfig.getEsb().version + " " + bot.comboBox().selection().toString());
/* ldimaggi - Oct 2011 - https://issues.jboss.org/browse/JBDS-1886 - this test fails for ESB 4.10 */
assertTrue("JBDS-1886 - Version was not automatically selected by setting ESB home dir",bot.comboBox().selection().equals(TestConfigurator.currentConfig.getEsb().version));
/* ldimaggi - Oct 2011 */
bot.text(0).setText("123_TheName");
//System.out.println ("[" + bot.textWithLabel("JBoss ESB Runtime").getText() +"]");
assertTrue ("Runtime name cannot start with a number", bot.textWithLabel("JBoss ESB Runtime").getText().equals(" Runtime name is not correct") );
bot.text(0).setText("runtime");
String name = bot.text(0).getText();
assertFalse("Runtime name was not automaticly set by setting ESB home dir",name.equals(""));
assertTrue("Finish button must be enabled when valid home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
open.finish(bot.activeShell().bot());
open.finish(wiz, IDELabel.Button.OK);
eclipse.removeESBRuntime(name);
}
|
diff --git a/src/ca/couchware/wezzle2d/tile/ItemTileEntity.java b/src/ca/couchware/wezzle2d/tile/ItemTileEntity.java
index 9942e10..3043dac 100644
--- a/src/ca/couchware/wezzle2d/tile/ItemTileEntity.java
+++ b/src/ca/couchware/wezzle2d/tile/ItemTileEntity.java
@@ -1,77 +1,79 @@
package ca.couchware.wezzle2d.tile;
import ca.couchware.wezzle2d.manager.BoardManager;
import ca.couchware.wezzle2d.graphics.ISprite;
import ca.couchware.wezzle2d.*;
import ca.couchware.wezzle2d.graphics.GraphicEntity;
/**
* An abstract class for making item tiles like bombs and rockets.
*
* @author cdmckay
*/
public abstract class ItemTileEntity extends TileEntity
{
/**
* The sprite representing the bomb graphic.
*/
final protected ISprite itemGraphic;
/**
* The rotation of the item.
*/
protected double itemTheta;
/**
* The constructor.
* @param boardMan
* @param color
* @param x
* @param y
*/
public ItemTileEntity(final String path,
final BoardManager boardMan, final TileColor color,
final int x, final int y)
{
// Invoke super.
super(boardMan, color, x, y);
// Load bomb sprite.
itemGraphic = ResourceFactory.get().getSprite(path);
// Initialize the item theta.
itemTheta = 0;
}
/**
* Override that draw muthafucka.
*/
@Override
public boolean draw()
{
if (isVisible() == false)
return false;
// Invoke super draw.
super.draw();
// Draw bomb on top of it.
//itemSprite.draw((int) x2, (int) y2, width, height, itemTheta, opacity);
- itemGraphic.draw(x, y).width(width).height(height).theta(itemTheta).opacity(opacity).end();
+ itemGraphic.draw(x, y).width(width).height(height)
+ .theta(itemTheta, width / 2, height /2)
+ .opacity(opacity).end();
return true;
}
public double getItemTheta()
{
return itemTheta;
}
public void setItemTheta(double itemTheta)
{
this.itemTheta = itemTheta;
}
}
| true | true | public boolean draw()
{
if (isVisible() == false)
return false;
// Invoke super draw.
super.draw();
// Draw bomb on top of it.
//itemSprite.draw((int) x2, (int) y2, width, height, itemTheta, opacity);
itemGraphic.draw(x, y).width(width).height(height).theta(itemTheta).opacity(opacity).end();
return true;
}
| public boolean draw()
{
if (isVisible() == false)
return false;
// Invoke super draw.
super.draw();
// Draw bomb on top of it.
//itemSprite.draw((int) x2, (int) y2, width, height, itemTheta, opacity);
itemGraphic.draw(x, y).width(width).height(height)
.theta(itemTheta, width / 2, height /2)
.opacity(opacity).end();
return true;
}
|
diff --git a/hama/hybrid/kmeans/src/at/illecker/hama/hybrid/examples/kmeans/KMeansHybridKernel.java b/hama/hybrid/kmeans/src/at/illecker/hama/hybrid/examples/kmeans/KMeansHybridKernel.java
index 1ab8c9e..e590611 100644
--- a/hama/hybrid/kmeans/src/at/illecker/hama/hybrid/examples/kmeans/KMeansHybridKernel.java
+++ b/hama/hybrid/kmeans/src/at/illecker/hama/hybrid/examples/kmeans/KMeansHybridKernel.java
@@ -1,654 +1,655 @@
/**
* 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 at.illecker.hama.hybrid.examples.kmeans;
import edu.syr.pcpratts.rootbeer.runtime.HamaPeer;
import edu.syr.pcpratts.rootbeer.runtime.Kernel;
import edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu;
public class KMeansHybridKernel implements Kernel {
private long m_superstepCount;
private long m_converged;
public double[][] m_inputs; // input
public double[][] m_centers; // input
public int m_maxIterations; // input
public KMeansHybridKernel(double[][] inputs, double[][] centers,
int maxIterations) {
m_inputs = inputs;
m_centers = centers;
m_maxIterations = maxIterations;
}
public void gpuMethod() {
// Check maxIterations
if (m_maxIterations <= 0) {
return;
}
int blockSize = RootbeerGpu.getBlockDimx();
int gridSize = RootbeerGpu.getGridDimx();
int block_idxx = RootbeerGpu.getBlockIdxx();
int thread_idxx = RootbeerGpu.getThreadIdxx();
// globalThreadId = blockIdx.x * blockDim.x + threadIdx.x;
int globalThreadId = RootbeerGpu.getThreadId();
int centerCount = m_centers.length;
int centerDim = m_centers[0].length;
int inputCount = m_inputs.length;
int blockInputSize = divup(inputCount, gridSize);
// System.out.print("blockInputSize: ");
// System.out.println(blockInputSize);
// SharedMemory per block
// centerCount x centerDim x Doubles (centerCount x centerDim * 8 bytes)
int sharedMemoryCenterSize = centerCount * centerDim * 8;
// centerCount x centerDim x Doubles (centerCount x centerDim * 8 bytes)
int sharedMemoryNewCentersStartPos = sharedMemoryCenterSize;
// centerCount x Integers (centerCount * 4 bytes)
int sharedMemorySummationCountStartPos = sharedMemoryNewCentersStartPos
+ sharedMemoryCenterSize;
// blockSize x centerDim x Doubles (blockSize x centerDim * 8 bytes)
int sharedMemoryInputVectorsStartPos = sharedMemorySummationCountStartPos
+ (centerCount * 4);
// blockSize x Integers (blockSize * 4 bytes)
int sharedMemoryLowestDistantCenterStartPos = sharedMemoryInputVectorsStartPos
+ (blockSize * centerDim * 8);
// 1 x Integer (4 bytes)
int sharedMemoryInputIndex = sharedMemoryLowestDistantCenterStartPos
+ (blockSize * 4);
// 1 x Integer (4 bytes)
int sharedMemoryInputStartIndex = sharedMemoryInputIndex + 4;
// 1 x Boolean (1 byte)
int sharedMemoryInputHasMoreBoolean = sharedMemoryInputStartIndex + 4;
// 1 x Long (8 bytes)
int sharedMemorySuperstepCount = sharedMemoryInputHasMoreBoolean + 1;
// 1 x Long (8 bytes)
int sharedMemoryConverged = sharedMemorySuperstepCount + 8;
// int sharedMemoryEndPos = sharedMemoryConverged + 8;
// if (globalThreadId == 0) {
// System.out.print("SharedMemorySize: ");
// System.out.print(sharedMemoryEndPos);
// System.out.println(" bytes");
// }
// Start KMeans clustering algorithm
do {
// Thread 0 of each block
// Setup SharedMemory
// Load centers into SharedMemory
// Init newCenters and summationCount in SharedMemory
if (thread_idxx == 0) {
for (int i = 0; i < centerCount; i++) {
for (int j = 0; j < centerDim; j++) {
// Init centers[][]
int centerIndex = ((i * centerDim) + j) * 8;
RootbeerGpu.setSharedDouble(centerIndex, m_centers[i][j]);
// Init newCenters[][]
int newCenterIndex = sharedMemoryNewCentersStartPos + centerIndex;
RootbeerGpu.setSharedDouble(newCenterIndex, 0);
}
// Init summationCount[]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
RootbeerGpu.setSharedInteger(summationCountIndex, 0);
}
// boolean inputHasMore = true;
RootbeerGpu.setSharedBoolean(sharedMemoryInputHasMoreBoolean, true);
// int startIndex = 0; // used by thread 0 of each block
RootbeerGpu.setSharedInteger(sharedMemoryInputStartIndex, 0);
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
// **********************************************************************
// assignCenters ********************************************************
// **********************************************************************
// loop until input is empty
// while (inputHasMore == true)
while (RootbeerGpu.getSharedBoolean(sharedMemoryInputHasMoreBoolean)) {
// Sync all threads within a block
RootbeerGpu.syncthreads();
// Thread 0 of each block
// Setup inputs for thread block
if (thread_idxx == 0) {
// int i = 0; // amount of threads in block
RootbeerGpu.setSharedInteger(sharedMemoryInputIndex, 0);
// check if block has some input
if ((block_idxx * blockInputSize) < inputCount) {
int j = RootbeerGpu.getSharedInteger(sharedMemoryInputStartIndex);
while (RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) < blockSize) {
// System.out.print("get from cache j: ");
// System.out.println((block_idxx * blockInputSize) + j);
// Update inputs on SharedMemory
for (int k = 0; k < centerDim; k++) {
// Init inputs[][]
int inputIndex = sharedMemoryInputVectorsStartPos
+ ((RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) * centerDim) + k)
* 8;
RootbeerGpu.setSharedDouble(inputIndex,
m_inputs[(block_idxx * blockInputSize) + j][k]);
}
// i++;
RootbeerGpu.setSharedInteger(sharedMemoryInputIndex,
RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) + 1);
j++;
if ((j == blockInputSize)
|| ((block_idxx * blockInputSize) + j == inputCount)) {
- // update inputHasMore
+ // Set inputHasMore to false
RootbeerGpu.setSharedBoolean(sharedMemoryInputHasMoreBoolean,
false);
break;
}
}
RootbeerGpu.setSharedInteger(sharedMemoryInputStartIndex, j);
} else { // block has no inputs
// System.out.println(block_idxx);
+ // Set inputHasMore to false
RootbeerGpu
.setSharedBoolean(sharedMemoryInputHasMoreBoolean, false);
}
// System.out.println("SharedMemory init finished.");
}
// Sync all threads within a block
// input[][] was updated
RootbeerGpu.syncthreads();
// System.out.println(RootbeerGpu.getSharedInteger(sharedMemoryIndex));
// System.out.println(thread_idxx);
// #################
// Parallelism Start
// #################
if (thread_idxx < RootbeerGpu.getSharedInteger(sharedMemoryInputIndex)) {
// System.out.println(thread_idxx);
// getNearestCenter
int lowestDistantCenter = 0;
double lowestDistance = Double.MAX_VALUE;
for (int i = 0; i < centerCount; i++) {
// measureEuclidianDistance
double sum = 0;
for (int j = 0; j < centerDim; j++) {
int inputIdxx = sharedMemoryInputVectorsStartPos
+ ((thread_idxx * centerDim) + j) * 8;
int centerIdxx = ((i * centerDim) + j) * 8;
// double diff = vector2[i] - vector1[i];
double diff = RootbeerGpu.getSharedDouble(inputIdxx)
- RootbeerGpu.getSharedDouble(centerIdxx);
// multiplication is faster than Math.pow() for ^2.
sum += (diff * diff);
}
double estimatedDistance = Math.sqrt(sum);
// System.out.print("estimatedDistance: ");
// System.out.println(estimatedDistance);
// check if we have a can assign a new center, because we
// got a lower distance
if (estimatedDistance < lowestDistance) {
lowestDistance = estimatedDistance;
lowestDistantCenter = i;
}
}
int lowestDistantCenterIdxx = sharedMemoryLowestDistantCenterStartPos
+ (thread_idxx * 4);
RootbeerGpu.setSharedInteger(lowestDistantCenterIdxx,
lowestDistantCenter);
// System.out.print("lowestDistantCenter: ");
// System.out.println(lowestDistantCenter);
}
// #################
// Parallelism End
// #################
// Sync all threads within a block
RootbeerGpu.syncthreads();
// assignCenters
// synchronized because it has to write into SharedMemory
if ((thread_idxx == 0)
&& (RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) > 0)) {
// for each thread in block assignCenters
for (int i = 0; i < RootbeerGpu
.getSharedInteger(sharedMemoryInputIndex); i++) {
int lowestDistantCenterIdxx = sharedMemoryLowestDistantCenterStartPos
+ (i * 4);
int lowestDistantCenter = RootbeerGpu
.getSharedInteger(lowestDistantCenterIdxx);
// TODO if summationCount == 0 no addition is needed!
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((lowestDistantCenter * centerDim) + j) * 8);
int inputIndex = sharedMemoryInputVectorsStartPos
+ ((i * centerDim) + j) * 8;
// newCenters[lowestDistantCenter][j] += vector[j];
RootbeerGpu.setSharedDouble(
newCenterIndex,
RootbeerGpu.getSharedDouble(newCenterIndex)
+ RootbeerGpu.getSharedDouble(inputIndex));
}
// Update newCenter counter
// summationCount[lowestDistantCenter]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (lowestDistantCenter * 4);
// summationCount[lowestDistantCenter]++;
RootbeerGpu.setSharedInteger(summationCountIndex,
RootbeerGpu.getSharedInteger(summationCountIndex) + 1);
}
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
// System.out.println(thread_idxx);
// **********************************************************************
// sendMessages *********************************************************
// **********************************************************************
// Thread 0 of each block
// Sends messages about the local updates to each other peer
if ((thread_idxx == 0)
&& (RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) > 0)) {
// TODO fetch allPeerNames only once
String[] allPeerNames = HamaPeer.getAllPeerNames();
for (int i = 0; i < centerCount; i++) {
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
if (summationCount > 0) {
// centerIndex:incrementCounter:VectorValue1,VectorValue2,VectorValue3
String message = "";
message += Integer.toString(i);
message += ":";
message += Integer.toString(summationCount);
message += ":";
// centerDim = m_newCenters[i].length
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// newCenters[i][j]
message += Double.toString(RootbeerGpu
.getSharedDouble(newCenterIndex));
// add ", " if not last element
if (j < centerDim - 1) {
message += ", ";
}
}
// System.out.println(message);
for (String peerName : allPeerNames) {
HamaPeer.send(peerName, message);
}
}
}
}
// Sync all blocks Inter-Block Synchronization
RootbeerGpu.syncblocks(1);
// Global Thread 0 of each blocks
if (globalThreadId == 0) {
// Sync all peers
HamaPeer.sync();
// ********************************************************************
// updateCenters ******************************************************
// ********************************************************************
// Fetch messages
// Reinit SharedMemory
// use newCenters for msgCenters
// use summationCount for msgIncrementSum
for (int i = 0; i < centerCount; i++) {
for (int j = 0; j < centerDim; j++) {
// Reinit newCenters[][]
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
RootbeerGpu.setSharedDouble(newCenterIndex, 0);
}
// Reinit summationCount[]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
RootbeerGpu.setSharedInteger(summationCountIndex, 0);
}
// Fetch messages
int msgCount = HamaPeer.getNumCurrentMessages();
for (int i = 0; i < msgCount; i++) {
// centerIndex:incrementCounter:VectorValue1,VectorValue2,VectorValue3
String message = HamaPeer.getCurrentStringMessage();
- // System.out.println(message);
+ System.out.println(message);
// parse message
String[] values = message.split(":", 3);
int centerIndex = Integer.parseInt(values[0]);
int incrementCounter = Integer.parseInt(values[1]);
String[] vectorStr = values[2].split(",");
int len = vectorStr.length;
double[] messageVector = new double[len];
for (int j = 0; j < len; j++) {
messageVector[j] = Double.parseDouble(vectorStr[j]);
}
// msgIncrementSum[centerIndex]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (centerIndex * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
// Update
if (summationCount == 0) {
// Set messageVector to msgCenters
// msgCenters[centerIndex] = messageVector;
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((centerIndex * centerDim) + j) * 8);
RootbeerGpu.setSharedDouble(newCenterIndex, messageVector[j]);
}
} else {
// VectorAdd
// msgCenters[centerIndex] =
// addVector(msgCenters[centerIndex],msgVector);
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((centerIndex * centerDim) + j) * 8);
// msgCenters[centerIndex][j] += messageVector[j];
RootbeerGpu.setSharedDouble(newCenterIndex,
RootbeerGpu.getSharedDouble(newCenterIndex)
+ messageVector[j]);
}
}
// msgIncrementSum[centerIndex] += incrementCounter;
RootbeerGpu.setSharedInteger(summationCountIndex, summationCount
+ incrementCounter);
}
// ********************************************************************
// divide by how often we globally summed vectors
// ********************************************************************
for (int i = 0; i < centerCount; i++) {
// msgIncrementSum[i]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
// and only if we really have an update for center
if (summationCount > 0) {
// msgCenters[i] = divideVector(msgCenters[i], msgIncrementSum[i]);
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// msgCenters[i][j] /= msgIncrementSum[i];
RootbeerGpu.setSharedDouble(newCenterIndex,
RootbeerGpu.getSharedDouble(newCenterIndex) / summationCount);
}
}
}
// ********************************************************************
// finally check for convergence by the absolute difference
// ********************************************************************
long convergedCounter = 0L;
for (int i = 0; i < centerCount; i++) {
// msgIncrementSum[i]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
if (summationCount > 0) {
double calculateError = 0;
for (int j = 0; j < centerDim; j++) {
// msgCenters[i][j]
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// TODO m_centers is in global GPU memory
calculateError += Math.abs(m_centers[i][j]
- RootbeerGpu.getSharedDouble(newCenterIndex));
}
// System.out.print("calculateError: ");
// System.out.println(calculateError);
// Update center if calculateError > 0
if (calculateError > 0.0d) {
// m_centers[i] = msgCenters[i];
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// TODO m_centers is in global GPU memory
m_centers[i][j] = RootbeerGpu.getSharedDouble(newCenterIndex);
}
convergedCounter++;
}
}
}
// m_converged and m_superstepCount are stored in global GPU memory
m_converged = convergedCounter;
m_superstepCount = HamaPeer.getSuperstepCount();
// RootbeerGpu.threadfenceSystem();
}
// Sync all blocks Inter-Block Synchronization
RootbeerGpu.syncblocks(2);
// Thread 0 of each block
// Update SharedMemory superstepCount and converged
if (thread_idxx == 0) {
RootbeerGpu.setSharedLong(sharedMemorySuperstepCount, m_superstepCount);
RootbeerGpu.setSharedLong(sharedMemoryConverged, m_converged);
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
} while ((RootbeerGpu.getSharedLong(sharedMemoryConverged) != 0)
&& (RootbeerGpu.getSharedLong(sharedMemorySuperstepCount) <= m_maxIterations));
// ************************************************************************
// recalculateAssignmentsAndWrite *****************************************
// ************************************************************************
/*
int startIndex = 0;
if (thread_idxx == 0) {
// boolean inputHasMore = true;
RootbeerGpu.setSharedBoolean(sharedMemoryInputHasMoreBoolean, true);
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
// loop until input is empty
// while (inputHasMore == true)
while (RootbeerGpu.getSharedBoolean(sharedMemoryInputHasMoreBoolean)) {
int i = 0; // amount of threads in block
// Thread 0 of each block
// Setup inputs for thread block
if (thread_idxx == 0) {
int j = startIndex;
while (i < blockSize) {
// System.out.print("get from cache j: ");
// System.out.println(j);
DenseDoubleVector vector = m_cache.get(j);
// TODO skip toArray (vector.get(j))
double[] inputs = vector.toArray(); // vectorDim = centerDim
// Update inputs on SharedMemory
for (int k = 0; k < centerDim; k++) {
// Init inputs[][]
int inputIndex = sharedMemoryInputVectorsStartPos
+ ((i * centerDim) + k) * 8;
RootbeerGpu.setSharedDouble(inputIndex, inputs[k]);
}
i++;
j++;
if (j == m_cache.getLength()) {
// update inputHasMore
RootbeerGpu
.setSharedBoolean(sharedMemoryInputHasMoreBoolean, false);
break;
}
}
startIndex = j;
}
// Sync all threads within a block
// input[][] was updated
RootbeerGpu.syncthreads();
// #################
// Parallelism Start
// #################
if (thread_idxx < i) {
int lowestDistantCenter = getNearestCenter(centerCount, centerDim,
sharedMemoryInputVectorsStartPos);
// TODO Performance issue
// Write out own vector and corresponding lowestDistantCenter
String vectorStr = "";
for (int k = 0; k < centerDim; k++) {
int inputIdxx = sharedMemoryInputVectorsStartPos
+ ((thread_idxx * centerDim) + k) * 8;
vectorStr += Double.toString(RootbeerGpu.getSharedDouble(inputIdxx));
if (k < centerDim - 1) {
vectorStr += ", ";
}
}
// TODO Performance issue
HamaPeer.write(new Integer(lowestDistantCenter), vectorStr);
}
// #################
// Parallelism End
// #################
// Sync all threads within a block
RootbeerGpu.syncthreads();
}
*/
}
private int divup(int x, int y) {
if (x % y != 0) {
return ((x + y - 1) / y); // round up
} else {
return x / y;
}
}
public static void main(String[] args) {
// Dummy constructor invocation
// to keep kernel constructor in
// rootbeer transformation
new KMeansHybridKernel(null, null, 0);
}
}
| false | true | public void gpuMethod() {
// Check maxIterations
if (m_maxIterations <= 0) {
return;
}
int blockSize = RootbeerGpu.getBlockDimx();
int gridSize = RootbeerGpu.getGridDimx();
int block_idxx = RootbeerGpu.getBlockIdxx();
int thread_idxx = RootbeerGpu.getThreadIdxx();
// globalThreadId = blockIdx.x * blockDim.x + threadIdx.x;
int globalThreadId = RootbeerGpu.getThreadId();
int centerCount = m_centers.length;
int centerDim = m_centers[0].length;
int inputCount = m_inputs.length;
int blockInputSize = divup(inputCount, gridSize);
// System.out.print("blockInputSize: ");
// System.out.println(blockInputSize);
// SharedMemory per block
// centerCount x centerDim x Doubles (centerCount x centerDim * 8 bytes)
int sharedMemoryCenterSize = centerCount * centerDim * 8;
// centerCount x centerDim x Doubles (centerCount x centerDim * 8 bytes)
int sharedMemoryNewCentersStartPos = sharedMemoryCenterSize;
// centerCount x Integers (centerCount * 4 bytes)
int sharedMemorySummationCountStartPos = sharedMemoryNewCentersStartPos
+ sharedMemoryCenterSize;
// blockSize x centerDim x Doubles (blockSize x centerDim * 8 bytes)
int sharedMemoryInputVectorsStartPos = sharedMemorySummationCountStartPos
+ (centerCount * 4);
// blockSize x Integers (blockSize * 4 bytes)
int sharedMemoryLowestDistantCenterStartPos = sharedMemoryInputVectorsStartPos
+ (blockSize * centerDim * 8);
// 1 x Integer (4 bytes)
int sharedMemoryInputIndex = sharedMemoryLowestDistantCenterStartPos
+ (blockSize * 4);
// 1 x Integer (4 bytes)
int sharedMemoryInputStartIndex = sharedMemoryInputIndex + 4;
// 1 x Boolean (1 byte)
int sharedMemoryInputHasMoreBoolean = sharedMemoryInputStartIndex + 4;
// 1 x Long (8 bytes)
int sharedMemorySuperstepCount = sharedMemoryInputHasMoreBoolean + 1;
// 1 x Long (8 bytes)
int sharedMemoryConverged = sharedMemorySuperstepCount + 8;
// int sharedMemoryEndPos = sharedMemoryConverged + 8;
// if (globalThreadId == 0) {
// System.out.print("SharedMemorySize: ");
// System.out.print(sharedMemoryEndPos);
// System.out.println(" bytes");
// }
// Start KMeans clustering algorithm
do {
// Thread 0 of each block
// Setup SharedMemory
// Load centers into SharedMemory
// Init newCenters and summationCount in SharedMemory
if (thread_idxx == 0) {
for (int i = 0; i < centerCount; i++) {
for (int j = 0; j < centerDim; j++) {
// Init centers[][]
int centerIndex = ((i * centerDim) + j) * 8;
RootbeerGpu.setSharedDouble(centerIndex, m_centers[i][j]);
// Init newCenters[][]
int newCenterIndex = sharedMemoryNewCentersStartPos + centerIndex;
RootbeerGpu.setSharedDouble(newCenterIndex, 0);
}
// Init summationCount[]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
RootbeerGpu.setSharedInteger(summationCountIndex, 0);
}
// boolean inputHasMore = true;
RootbeerGpu.setSharedBoolean(sharedMemoryInputHasMoreBoolean, true);
// int startIndex = 0; // used by thread 0 of each block
RootbeerGpu.setSharedInteger(sharedMemoryInputStartIndex, 0);
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
// **********************************************************************
// assignCenters ********************************************************
// **********************************************************************
// loop until input is empty
// while (inputHasMore == true)
while (RootbeerGpu.getSharedBoolean(sharedMemoryInputHasMoreBoolean)) {
// Sync all threads within a block
RootbeerGpu.syncthreads();
// Thread 0 of each block
// Setup inputs for thread block
if (thread_idxx == 0) {
// int i = 0; // amount of threads in block
RootbeerGpu.setSharedInteger(sharedMemoryInputIndex, 0);
// check if block has some input
if ((block_idxx * blockInputSize) < inputCount) {
int j = RootbeerGpu.getSharedInteger(sharedMemoryInputStartIndex);
while (RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) < blockSize) {
// System.out.print("get from cache j: ");
// System.out.println((block_idxx * blockInputSize) + j);
// Update inputs on SharedMemory
for (int k = 0; k < centerDim; k++) {
// Init inputs[][]
int inputIndex = sharedMemoryInputVectorsStartPos
+ ((RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) * centerDim) + k)
* 8;
RootbeerGpu.setSharedDouble(inputIndex,
m_inputs[(block_idxx * blockInputSize) + j][k]);
}
// i++;
RootbeerGpu.setSharedInteger(sharedMemoryInputIndex,
RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) + 1);
j++;
if ((j == blockInputSize)
|| ((block_idxx * blockInputSize) + j == inputCount)) {
// update inputHasMore
RootbeerGpu.setSharedBoolean(sharedMemoryInputHasMoreBoolean,
false);
break;
}
}
RootbeerGpu.setSharedInteger(sharedMemoryInputStartIndex, j);
} else { // block has no inputs
// System.out.println(block_idxx);
RootbeerGpu
.setSharedBoolean(sharedMemoryInputHasMoreBoolean, false);
}
// System.out.println("SharedMemory init finished.");
}
// Sync all threads within a block
// input[][] was updated
RootbeerGpu.syncthreads();
// System.out.println(RootbeerGpu.getSharedInteger(sharedMemoryIndex));
// System.out.println(thread_idxx);
// #################
// Parallelism Start
// #################
if (thread_idxx < RootbeerGpu.getSharedInteger(sharedMemoryInputIndex)) {
// System.out.println(thread_idxx);
// getNearestCenter
int lowestDistantCenter = 0;
double lowestDistance = Double.MAX_VALUE;
for (int i = 0; i < centerCount; i++) {
// measureEuclidianDistance
double sum = 0;
for (int j = 0; j < centerDim; j++) {
int inputIdxx = sharedMemoryInputVectorsStartPos
+ ((thread_idxx * centerDim) + j) * 8;
int centerIdxx = ((i * centerDim) + j) * 8;
// double diff = vector2[i] - vector1[i];
double diff = RootbeerGpu.getSharedDouble(inputIdxx)
- RootbeerGpu.getSharedDouble(centerIdxx);
// multiplication is faster than Math.pow() for ^2.
sum += (diff * diff);
}
double estimatedDistance = Math.sqrt(sum);
// System.out.print("estimatedDistance: ");
// System.out.println(estimatedDistance);
// check if we have a can assign a new center, because we
// got a lower distance
if (estimatedDistance < lowestDistance) {
lowestDistance = estimatedDistance;
lowestDistantCenter = i;
}
}
int lowestDistantCenterIdxx = sharedMemoryLowestDistantCenterStartPos
+ (thread_idxx * 4);
RootbeerGpu.setSharedInteger(lowestDistantCenterIdxx,
lowestDistantCenter);
// System.out.print("lowestDistantCenter: ");
// System.out.println(lowestDistantCenter);
}
// #################
// Parallelism End
// #################
// Sync all threads within a block
RootbeerGpu.syncthreads();
// assignCenters
// synchronized because it has to write into SharedMemory
if ((thread_idxx == 0)
&& (RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) > 0)) {
// for each thread in block assignCenters
for (int i = 0; i < RootbeerGpu
.getSharedInteger(sharedMemoryInputIndex); i++) {
int lowestDistantCenterIdxx = sharedMemoryLowestDistantCenterStartPos
+ (i * 4);
int lowestDistantCenter = RootbeerGpu
.getSharedInteger(lowestDistantCenterIdxx);
// TODO if summationCount == 0 no addition is needed!
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((lowestDistantCenter * centerDim) + j) * 8);
int inputIndex = sharedMemoryInputVectorsStartPos
+ ((i * centerDim) + j) * 8;
// newCenters[lowestDistantCenter][j] += vector[j];
RootbeerGpu.setSharedDouble(
newCenterIndex,
RootbeerGpu.getSharedDouble(newCenterIndex)
+ RootbeerGpu.getSharedDouble(inputIndex));
}
// Update newCenter counter
// summationCount[lowestDistantCenter]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (lowestDistantCenter * 4);
// summationCount[lowestDistantCenter]++;
RootbeerGpu.setSharedInteger(summationCountIndex,
RootbeerGpu.getSharedInteger(summationCountIndex) + 1);
}
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
// System.out.println(thread_idxx);
// **********************************************************************
// sendMessages *********************************************************
// **********************************************************************
// Thread 0 of each block
// Sends messages about the local updates to each other peer
if ((thread_idxx == 0)
&& (RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) > 0)) {
// TODO fetch allPeerNames only once
String[] allPeerNames = HamaPeer.getAllPeerNames();
for (int i = 0; i < centerCount; i++) {
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
if (summationCount > 0) {
// centerIndex:incrementCounter:VectorValue1,VectorValue2,VectorValue3
String message = "";
message += Integer.toString(i);
message += ":";
message += Integer.toString(summationCount);
message += ":";
// centerDim = m_newCenters[i].length
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// newCenters[i][j]
message += Double.toString(RootbeerGpu
.getSharedDouble(newCenterIndex));
// add ", " if not last element
if (j < centerDim - 1) {
message += ", ";
}
}
// System.out.println(message);
for (String peerName : allPeerNames) {
HamaPeer.send(peerName, message);
}
}
}
}
// Sync all blocks Inter-Block Synchronization
RootbeerGpu.syncblocks(1);
// Global Thread 0 of each blocks
if (globalThreadId == 0) {
// Sync all peers
HamaPeer.sync();
// ********************************************************************
// updateCenters ******************************************************
// ********************************************************************
// Fetch messages
// Reinit SharedMemory
// use newCenters for msgCenters
// use summationCount for msgIncrementSum
for (int i = 0; i < centerCount; i++) {
for (int j = 0; j < centerDim; j++) {
// Reinit newCenters[][]
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
RootbeerGpu.setSharedDouble(newCenterIndex, 0);
}
// Reinit summationCount[]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
RootbeerGpu.setSharedInteger(summationCountIndex, 0);
}
// Fetch messages
int msgCount = HamaPeer.getNumCurrentMessages();
for (int i = 0; i < msgCount; i++) {
// centerIndex:incrementCounter:VectorValue1,VectorValue2,VectorValue3
String message = HamaPeer.getCurrentStringMessage();
// System.out.println(message);
// parse message
String[] values = message.split(":", 3);
int centerIndex = Integer.parseInt(values[0]);
int incrementCounter = Integer.parseInt(values[1]);
String[] vectorStr = values[2].split(",");
int len = vectorStr.length;
double[] messageVector = new double[len];
for (int j = 0; j < len; j++) {
messageVector[j] = Double.parseDouble(vectorStr[j]);
}
// msgIncrementSum[centerIndex]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (centerIndex * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
// Update
if (summationCount == 0) {
// Set messageVector to msgCenters
// msgCenters[centerIndex] = messageVector;
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((centerIndex * centerDim) + j) * 8);
RootbeerGpu.setSharedDouble(newCenterIndex, messageVector[j]);
}
} else {
// VectorAdd
// msgCenters[centerIndex] =
// addVector(msgCenters[centerIndex],msgVector);
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((centerIndex * centerDim) + j) * 8);
// msgCenters[centerIndex][j] += messageVector[j];
RootbeerGpu.setSharedDouble(newCenterIndex,
RootbeerGpu.getSharedDouble(newCenterIndex)
+ messageVector[j]);
}
}
// msgIncrementSum[centerIndex] += incrementCounter;
RootbeerGpu.setSharedInteger(summationCountIndex, summationCount
+ incrementCounter);
}
// ********************************************************************
// divide by how often we globally summed vectors
// ********************************************************************
for (int i = 0; i < centerCount; i++) {
// msgIncrementSum[i]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
// and only if we really have an update for center
if (summationCount > 0) {
// msgCenters[i] = divideVector(msgCenters[i], msgIncrementSum[i]);
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// msgCenters[i][j] /= msgIncrementSum[i];
RootbeerGpu.setSharedDouble(newCenterIndex,
RootbeerGpu.getSharedDouble(newCenterIndex) / summationCount);
}
}
}
// ********************************************************************
// finally check for convergence by the absolute difference
// ********************************************************************
long convergedCounter = 0L;
for (int i = 0; i < centerCount; i++) {
// msgIncrementSum[i]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
if (summationCount > 0) {
double calculateError = 0;
for (int j = 0; j < centerDim; j++) {
// msgCenters[i][j]
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// TODO m_centers is in global GPU memory
calculateError += Math.abs(m_centers[i][j]
- RootbeerGpu.getSharedDouble(newCenterIndex));
}
// System.out.print("calculateError: ");
// System.out.println(calculateError);
// Update center if calculateError > 0
if (calculateError > 0.0d) {
// m_centers[i] = msgCenters[i];
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// TODO m_centers is in global GPU memory
m_centers[i][j] = RootbeerGpu.getSharedDouble(newCenterIndex);
}
convergedCounter++;
}
}
}
// m_converged and m_superstepCount are stored in global GPU memory
m_converged = convergedCounter;
m_superstepCount = HamaPeer.getSuperstepCount();
// RootbeerGpu.threadfenceSystem();
}
// Sync all blocks Inter-Block Synchronization
RootbeerGpu.syncblocks(2);
// Thread 0 of each block
// Update SharedMemory superstepCount and converged
if (thread_idxx == 0) {
RootbeerGpu.setSharedLong(sharedMemorySuperstepCount, m_superstepCount);
RootbeerGpu.setSharedLong(sharedMemoryConverged, m_converged);
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
} while ((RootbeerGpu.getSharedLong(sharedMemoryConverged) != 0)
&& (RootbeerGpu.getSharedLong(sharedMemorySuperstepCount) <= m_maxIterations));
// ************************************************************************
// recalculateAssignmentsAndWrite *****************************************
// ************************************************************************
/*
int startIndex = 0;
if (thread_idxx == 0) {
// boolean inputHasMore = true;
RootbeerGpu.setSharedBoolean(sharedMemoryInputHasMoreBoolean, true);
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
// loop until input is empty
// while (inputHasMore == true)
while (RootbeerGpu.getSharedBoolean(sharedMemoryInputHasMoreBoolean)) {
int i = 0; // amount of threads in block
// Thread 0 of each block
// Setup inputs for thread block
if (thread_idxx == 0) {
int j = startIndex;
while (i < blockSize) {
// System.out.print("get from cache j: ");
// System.out.println(j);
DenseDoubleVector vector = m_cache.get(j);
// TODO skip toArray (vector.get(j))
double[] inputs = vector.toArray(); // vectorDim = centerDim
// Update inputs on SharedMemory
for (int k = 0; k < centerDim; k++) {
// Init inputs[][]
int inputIndex = sharedMemoryInputVectorsStartPos
+ ((i * centerDim) + k) * 8;
RootbeerGpu.setSharedDouble(inputIndex, inputs[k]);
}
i++;
j++;
if (j == m_cache.getLength()) {
// update inputHasMore
RootbeerGpu
.setSharedBoolean(sharedMemoryInputHasMoreBoolean, false);
break;
}
}
startIndex = j;
}
// Sync all threads within a block
// input[][] was updated
RootbeerGpu.syncthreads();
// #################
// Parallelism Start
// #################
if (thread_idxx < i) {
int lowestDistantCenter = getNearestCenter(centerCount, centerDim,
sharedMemoryInputVectorsStartPos);
// TODO Performance issue
// Write out own vector and corresponding lowestDistantCenter
String vectorStr = "";
for (int k = 0; k < centerDim; k++) {
int inputIdxx = sharedMemoryInputVectorsStartPos
+ ((thread_idxx * centerDim) + k) * 8;
vectorStr += Double.toString(RootbeerGpu.getSharedDouble(inputIdxx));
if (k < centerDim - 1) {
vectorStr += ", ";
}
}
// TODO Performance issue
HamaPeer.write(new Integer(lowestDistantCenter), vectorStr);
}
// #################
// Parallelism End
// #################
// Sync all threads within a block
RootbeerGpu.syncthreads();
}
*/
}
| public void gpuMethod() {
// Check maxIterations
if (m_maxIterations <= 0) {
return;
}
int blockSize = RootbeerGpu.getBlockDimx();
int gridSize = RootbeerGpu.getGridDimx();
int block_idxx = RootbeerGpu.getBlockIdxx();
int thread_idxx = RootbeerGpu.getThreadIdxx();
// globalThreadId = blockIdx.x * blockDim.x + threadIdx.x;
int globalThreadId = RootbeerGpu.getThreadId();
int centerCount = m_centers.length;
int centerDim = m_centers[0].length;
int inputCount = m_inputs.length;
int blockInputSize = divup(inputCount, gridSize);
// System.out.print("blockInputSize: ");
// System.out.println(blockInputSize);
// SharedMemory per block
// centerCount x centerDim x Doubles (centerCount x centerDim * 8 bytes)
int sharedMemoryCenterSize = centerCount * centerDim * 8;
// centerCount x centerDim x Doubles (centerCount x centerDim * 8 bytes)
int sharedMemoryNewCentersStartPos = sharedMemoryCenterSize;
// centerCount x Integers (centerCount * 4 bytes)
int sharedMemorySummationCountStartPos = sharedMemoryNewCentersStartPos
+ sharedMemoryCenterSize;
// blockSize x centerDim x Doubles (blockSize x centerDim * 8 bytes)
int sharedMemoryInputVectorsStartPos = sharedMemorySummationCountStartPos
+ (centerCount * 4);
// blockSize x Integers (blockSize * 4 bytes)
int sharedMemoryLowestDistantCenterStartPos = sharedMemoryInputVectorsStartPos
+ (blockSize * centerDim * 8);
// 1 x Integer (4 bytes)
int sharedMemoryInputIndex = sharedMemoryLowestDistantCenterStartPos
+ (blockSize * 4);
// 1 x Integer (4 bytes)
int sharedMemoryInputStartIndex = sharedMemoryInputIndex + 4;
// 1 x Boolean (1 byte)
int sharedMemoryInputHasMoreBoolean = sharedMemoryInputStartIndex + 4;
// 1 x Long (8 bytes)
int sharedMemorySuperstepCount = sharedMemoryInputHasMoreBoolean + 1;
// 1 x Long (8 bytes)
int sharedMemoryConverged = sharedMemorySuperstepCount + 8;
// int sharedMemoryEndPos = sharedMemoryConverged + 8;
// if (globalThreadId == 0) {
// System.out.print("SharedMemorySize: ");
// System.out.print(sharedMemoryEndPos);
// System.out.println(" bytes");
// }
// Start KMeans clustering algorithm
do {
// Thread 0 of each block
// Setup SharedMemory
// Load centers into SharedMemory
// Init newCenters and summationCount in SharedMemory
if (thread_idxx == 0) {
for (int i = 0; i < centerCount; i++) {
for (int j = 0; j < centerDim; j++) {
// Init centers[][]
int centerIndex = ((i * centerDim) + j) * 8;
RootbeerGpu.setSharedDouble(centerIndex, m_centers[i][j]);
// Init newCenters[][]
int newCenterIndex = sharedMemoryNewCentersStartPos + centerIndex;
RootbeerGpu.setSharedDouble(newCenterIndex, 0);
}
// Init summationCount[]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
RootbeerGpu.setSharedInteger(summationCountIndex, 0);
}
// boolean inputHasMore = true;
RootbeerGpu.setSharedBoolean(sharedMemoryInputHasMoreBoolean, true);
// int startIndex = 0; // used by thread 0 of each block
RootbeerGpu.setSharedInteger(sharedMemoryInputStartIndex, 0);
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
// **********************************************************************
// assignCenters ********************************************************
// **********************************************************************
// loop until input is empty
// while (inputHasMore == true)
while (RootbeerGpu.getSharedBoolean(sharedMemoryInputHasMoreBoolean)) {
// Sync all threads within a block
RootbeerGpu.syncthreads();
// Thread 0 of each block
// Setup inputs for thread block
if (thread_idxx == 0) {
// int i = 0; // amount of threads in block
RootbeerGpu.setSharedInteger(sharedMemoryInputIndex, 0);
// check if block has some input
if ((block_idxx * blockInputSize) < inputCount) {
int j = RootbeerGpu.getSharedInteger(sharedMemoryInputStartIndex);
while (RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) < blockSize) {
// System.out.print("get from cache j: ");
// System.out.println((block_idxx * blockInputSize) + j);
// Update inputs on SharedMemory
for (int k = 0; k < centerDim; k++) {
// Init inputs[][]
int inputIndex = sharedMemoryInputVectorsStartPos
+ ((RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) * centerDim) + k)
* 8;
RootbeerGpu.setSharedDouble(inputIndex,
m_inputs[(block_idxx * blockInputSize) + j][k]);
}
// i++;
RootbeerGpu.setSharedInteger(sharedMemoryInputIndex,
RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) + 1);
j++;
if ((j == blockInputSize)
|| ((block_idxx * blockInputSize) + j == inputCount)) {
// Set inputHasMore to false
RootbeerGpu.setSharedBoolean(sharedMemoryInputHasMoreBoolean,
false);
break;
}
}
RootbeerGpu.setSharedInteger(sharedMemoryInputStartIndex, j);
} else { // block has no inputs
// System.out.println(block_idxx);
// Set inputHasMore to false
RootbeerGpu
.setSharedBoolean(sharedMemoryInputHasMoreBoolean, false);
}
// System.out.println("SharedMemory init finished.");
}
// Sync all threads within a block
// input[][] was updated
RootbeerGpu.syncthreads();
// System.out.println(RootbeerGpu.getSharedInteger(sharedMemoryIndex));
// System.out.println(thread_idxx);
// #################
// Parallelism Start
// #################
if (thread_idxx < RootbeerGpu.getSharedInteger(sharedMemoryInputIndex)) {
// System.out.println(thread_idxx);
// getNearestCenter
int lowestDistantCenter = 0;
double lowestDistance = Double.MAX_VALUE;
for (int i = 0; i < centerCount; i++) {
// measureEuclidianDistance
double sum = 0;
for (int j = 0; j < centerDim; j++) {
int inputIdxx = sharedMemoryInputVectorsStartPos
+ ((thread_idxx * centerDim) + j) * 8;
int centerIdxx = ((i * centerDim) + j) * 8;
// double diff = vector2[i] - vector1[i];
double diff = RootbeerGpu.getSharedDouble(inputIdxx)
- RootbeerGpu.getSharedDouble(centerIdxx);
// multiplication is faster than Math.pow() for ^2.
sum += (diff * diff);
}
double estimatedDistance = Math.sqrt(sum);
// System.out.print("estimatedDistance: ");
// System.out.println(estimatedDistance);
// check if we have a can assign a new center, because we
// got a lower distance
if (estimatedDistance < lowestDistance) {
lowestDistance = estimatedDistance;
lowestDistantCenter = i;
}
}
int lowestDistantCenterIdxx = sharedMemoryLowestDistantCenterStartPos
+ (thread_idxx * 4);
RootbeerGpu.setSharedInteger(lowestDistantCenterIdxx,
lowestDistantCenter);
// System.out.print("lowestDistantCenter: ");
// System.out.println(lowestDistantCenter);
}
// #################
// Parallelism End
// #################
// Sync all threads within a block
RootbeerGpu.syncthreads();
// assignCenters
// synchronized because it has to write into SharedMemory
if ((thread_idxx == 0)
&& (RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) > 0)) {
// for each thread in block assignCenters
for (int i = 0; i < RootbeerGpu
.getSharedInteger(sharedMemoryInputIndex); i++) {
int lowestDistantCenterIdxx = sharedMemoryLowestDistantCenterStartPos
+ (i * 4);
int lowestDistantCenter = RootbeerGpu
.getSharedInteger(lowestDistantCenterIdxx);
// TODO if summationCount == 0 no addition is needed!
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((lowestDistantCenter * centerDim) + j) * 8);
int inputIndex = sharedMemoryInputVectorsStartPos
+ ((i * centerDim) + j) * 8;
// newCenters[lowestDistantCenter][j] += vector[j];
RootbeerGpu.setSharedDouble(
newCenterIndex,
RootbeerGpu.getSharedDouble(newCenterIndex)
+ RootbeerGpu.getSharedDouble(inputIndex));
}
// Update newCenter counter
// summationCount[lowestDistantCenter]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (lowestDistantCenter * 4);
// summationCount[lowestDistantCenter]++;
RootbeerGpu.setSharedInteger(summationCountIndex,
RootbeerGpu.getSharedInteger(summationCountIndex) + 1);
}
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
// System.out.println(thread_idxx);
// **********************************************************************
// sendMessages *********************************************************
// **********************************************************************
// Thread 0 of each block
// Sends messages about the local updates to each other peer
if ((thread_idxx == 0)
&& (RootbeerGpu.getSharedInteger(sharedMemoryInputIndex) > 0)) {
// TODO fetch allPeerNames only once
String[] allPeerNames = HamaPeer.getAllPeerNames();
for (int i = 0; i < centerCount; i++) {
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
if (summationCount > 0) {
// centerIndex:incrementCounter:VectorValue1,VectorValue2,VectorValue3
String message = "";
message += Integer.toString(i);
message += ":";
message += Integer.toString(summationCount);
message += ":";
// centerDim = m_newCenters[i].length
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// newCenters[i][j]
message += Double.toString(RootbeerGpu
.getSharedDouble(newCenterIndex));
// add ", " if not last element
if (j < centerDim - 1) {
message += ", ";
}
}
// System.out.println(message);
for (String peerName : allPeerNames) {
HamaPeer.send(peerName, message);
}
}
}
}
// Sync all blocks Inter-Block Synchronization
RootbeerGpu.syncblocks(1);
// Global Thread 0 of each blocks
if (globalThreadId == 0) {
// Sync all peers
HamaPeer.sync();
// ********************************************************************
// updateCenters ******************************************************
// ********************************************************************
// Fetch messages
// Reinit SharedMemory
// use newCenters for msgCenters
// use summationCount for msgIncrementSum
for (int i = 0; i < centerCount; i++) {
for (int j = 0; j < centerDim; j++) {
// Reinit newCenters[][]
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
RootbeerGpu.setSharedDouble(newCenterIndex, 0);
}
// Reinit summationCount[]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
RootbeerGpu.setSharedInteger(summationCountIndex, 0);
}
// Fetch messages
int msgCount = HamaPeer.getNumCurrentMessages();
for (int i = 0; i < msgCount; i++) {
// centerIndex:incrementCounter:VectorValue1,VectorValue2,VectorValue3
String message = HamaPeer.getCurrentStringMessage();
System.out.println(message);
// parse message
String[] values = message.split(":", 3);
int centerIndex = Integer.parseInt(values[0]);
int incrementCounter = Integer.parseInt(values[1]);
String[] vectorStr = values[2].split(",");
int len = vectorStr.length;
double[] messageVector = new double[len];
for (int j = 0; j < len; j++) {
messageVector[j] = Double.parseDouble(vectorStr[j]);
}
// msgIncrementSum[centerIndex]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (centerIndex * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
// Update
if (summationCount == 0) {
// Set messageVector to msgCenters
// msgCenters[centerIndex] = messageVector;
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((centerIndex * centerDim) + j) * 8);
RootbeerGpu.setSharedDouble(newCenterIndex, messageVector[j]);
}
} else {
// VectorAdd
// msgCenters[centerIndex] =
// addVector(msgCenters[centerIndex],msgVector);
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((centerIndex * centerDim) + j) * 8);
// msgCenters[centerIndex][j] += messageVector[j];
RootbeerGpu.setSharedDouble(newCenterIndex,
RootbeerGpu.getSharedDouble(newCenterIndex)
+ messageVector[j]);
}
}
// msgIncrementSum[centerIndex] += incrementCounter;
RootbeerGpu.setSharedInteger(summationCountIndex, summationCount
+ incrementCounter);
}
// ********************************************************************
// divide by how often we globally summed vectors
// ********************************************************************
for (int i = 0; i < centerCount; i++) {
// msgIncrementSum[i]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
// and only if we really have an update for center
if (summationCount > 0) {
// msgCenters[i] = divideVector(msgCenters[i], msgIncrementSum[i]);
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// msgCenters[i][j] /= msgIncrementSum[i];
RootbeerGpu.setSharedDouble(newCenterIndex,
RootbeerGpu.getSharedDouble(newCenterIndex) / summationCount);
}
}
}
// ********************************************************************
// finally check for convergence by the absolute difference
// ********************************************************************
long convergedCounter = 0L;
for (int i = 0; i < centerCount; i++) {
// msgIncrementSum[i]
int summationCountIndex = sharedMemorySummationCountStartPos
+ (i * 4);
int summationCount = RootbeerGpu
.getSharedInteger(summationCountIndex);
if (summationCount > 0) {
double calculateError = 0;
for (int j = 0; j < centerDim; j++) {
// msgCenters[i][j]
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// TODO m_centers is in global GPU memory
calculateError += Math.abs(m_centers[i][j]
- RootbeerGpu.getSharedDouble(newCenterIndex));
}
// System.out.print("calculateError: ");
// System.out.println(calculateError);
// Update center if calculateError > 0
if (calculateError > 0.0d) {
// m_centers[i] = msgCenters[i];
for (int j = 0; j < centerDim; j++) {
int newCenterIndex = sharedMemoryNewCentersStartPos
+ (((i * centerDim) + j) * 8);
// TODO m_centers is in global GPU memory
m_centers[i][j] = RootbeerGpu.getSharedDouble(newCenterIndex);
}
convergedCounter++;
}
}
}
// m_converged and m_superstepCount are stored in global GPU memory
m_converged = convergedCounter;
m_superstepCount = HamaPeer.getSuperstepCount();
// RootbeerGpu.threadfenceSystem();
}
// Sync all blocks Inter-Block Synchronization
RootbeerGpu.syncblocks(2);
// Thread 0 of each block
// Update SharedMemory superstepCount and converged
if (thread_idxx == 0) {
RootbeerGpu.setSharedLong(sharedMemorySuperstepCount, m_superstepCount);
RootbeerGpu.setSharedLong(sharedMemoryConverged, m_converged);
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
} while ((RootbeerGpu.getSharedLong(sharedMemoryConverged) != 0)
&& (RootbeerGpu.getSharedLong(sharedMemorySuperstepCount) <= m_maxIterations));
// ************************************************************************
// recalculateAssignmentsAndWrite *****************************************
// ************************************************************************
/*
int startIndex = 0;
if (thread_idxx == 0) {
// boolean inputHasMore = true;
RootbeerGpu.setSharedBoolean(sharedMemoryInputHasMoreBoolean, true);
}
// Sync all threads within a block
RootbeerGpu.syncthreads();
// loop until input is empty
// while (inputHasMore == true)
while (RootbeerGpu.getSharedBoolean(sharedMemoryInputHasMoreBoolean)) {
int i = 0; // amount of threads in block
// Thread 0 of each block
// Setup inputs for thread block
if (thread_idxx == 0) {
int j = startIndex;
while (i < blockSize) {
// System.out.print("get from cache j: ");
// System.out.println(j);
DenseDoubleVector vector = m_cache.get(j);
// TODO skip toArray (vector.get(j))
double[] inputs = vector.toArray(); // vectorDim = centerDim
// Update inputs on SharedMemory
for (int k = 0; k < centerDim; k++) {
// Init inputs[][]
int inputIndex = sharedMemoryInputVectorsStartPos
+ ((i * centerDim) + k) * 8;
RootbeerGpu.setSharedDouble(inputIndex, inputs[k]);
}
i++;
j++;
if (j == m_cache.getLength()) {
// update inputHasMore
RootbeerGpu
.setSharedBoolean(sharedMemoryInputHasMoreBoolean, false);
break;
}
}
startIndex = j;
}
// Sync all threads within a block
// input[][] was updated
RootbeerGpu.syncthreads();
// #################
// Parallelism Start
// #################
if (thread_idxx < i) {
int lowestDistantCenter = getNearestCenter(centerCount, centerDim,
sharedMemoryInputVectorsStartPos);
// TODO Performance issue
// Write out own vector and corresponding lowestDistantCenter
String vectorStr = "";
for (int k = 0; k < centerDim; k++) {
int inputIdxx = sharedMemoryInputVectorsStartPos
+ ((thread_idxx * centerDim) + k) * 8;
vectorStr += Double.toString(RootbeerGpu.getSharedDouble(inputIdxx));
if (k < centerDim - 1) {
vectorStr += ", ";
}
}
// TODO Performance issue
HamaPeer.write(new Integer(lowestDistantCenter), vectorStr);
}
// #################
// Parallelism End
// #################
// Sync all threads within a block
RootbeerGpu.syncthreads();
}
*/
}
|
diff --git a/rds-manager/src/main/java/com/stationmillenium/rdsmanager/services/rs232/RDSDisplayManagerService.java b/rds-manager/src/main/java/com/stationmillenium/rdsmanager/services/rs232/RDSDisplayManagerService.java
index 0534932..ace8af5 100644
--- a/rds-manager/src/main/java/com/stationmillenium/rdsmanager/services/rs232/RDSDisplayManagerService.java
+++ b/rds-manager/src/main/java/com/stationmillenium/rdsmanager/services/rs232/RDSDisplayManagerService.java
@@ -1,269 +1,269 @@
package com.stationmillenium.rdsmanager.services.rs232;
import java.io.IOException;
import java.util.Calendar;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Service;
import com.stationmillenium.rdsmanager.beans.rs232.RDSDisplayManagerProperties;
import com.stationmillenium.rdsmanager.beans.rs232.RS232Properties;
import com.stationmillenium.rdsmanager.dto.documents.RDSDisplay;
import com.stationmillenium.rdsmanager.dto.documents.subs.RS232Commands;
import com.stationmillenium.rdsmanager.dto.title.BroadcastableTitle;
import com.stationmillenium.rdsmanager.exceptions.rs232.RS232RDSCoderException;
import com.stationmillenium.rdsmanager.repositories.MongoDBRepository;
import com.stationmillenium.rdsmanager.services.alertmails.AlertMailService;
/**
* Service to manager text displayed on RDS
* @author vincent
*
*/
@Service
public class RDSDisplayManagerService implements ApplicationContextAware {
/**
* Available command type
* @author vincent
*
*/
private enum CommandType {
INIT,
PS,
RADIOTEXT;
}
//logger
private static final Logger LOGGER = LoggerFactory.getLogger(RDSDisplayManagerService.class);
//config for rs232
@Autowired
private RS232Properties rs232Config;
//configuration
@Autowired
private RDSDisplayManagerProperties rdsDisplayManagerProperties;
//db repository to log commands
@Autowired
private MongoDBRepository mongoDBRepository;
//rs232 wire service to send command
@Autowired
private RS232WireService rs232WireService;
//alerts mail service
@Autowired
private AlertMailService alertMailService;
//app context to shutdown app if com port init error
private ApplicationContext context;
/**
* Display a title on PS and RadioText
* @param titleToDisplay the title to display
*/
public void displayTitle(BroadcastableTitle titleToDisplay) {
LOGGER.debug("Display title on RDS : " + titleToDisplay);
String psCommandToSend = preparePSTitleCommand(titleToDisplay);
String rtCommandToSend = prepareRTTitleCommand(titleToDisplay);
//send ps command
sendCommandsToRDS(psCommandToSend, rtCommandToSend, titleToDisplay);
}
/**
* Prepapre the RT title command to display title on RDS
* @param titleToDisplay the title
* @return the command as string
*/
private String prepareRTTitleCommand(BroadcastableTitle titleToDisplay) {
String rtText = titleToDisplay.getArtist() + " " + rdsDisplayManagerProperties.getRtSeparator() + " " + titleToDisplay.getTitle();
if (rtText.length() > rdsDisplayManagerProperties.getMaxLength())
rtText = rtText.substring(0, rdsDisplayManagerProperties.getMaxLength() - 1);
String rtCommandToSend = rdsDisplayManagerProperties.getRtCommandPrefix() + rtText + rdsDisplayManagerProperties.getCommandTerminaison();
return rtCommandToSend;
}
/**
* Prepare the PS command to display title on RDS
* @param titleToDisplay the title
* @return the command as string
*/
private String preparePSTitleCommand(BroadcastableTitle titleToDisplay) {
String psText = titleToDisplay.getArtist() + " " + titleToDisplay.getTitle();
if (psText.length() > rdsDisplayManagerProperties.getMaxLength())
psText = psText.substring(0, rdsDisplayManagerProperties.getMaxLength() - 1);
String psCommandToSend = rdsDisplayManagerProperties.getPsCommandPrefix() + psText + rdsDisplayManagerProperties.getCommandTerminaison();
return psCommandToSend;
}
/**
* Display the idle text
*/
public void displayIdleText() {
LOGGER.debug("Display the idle text");
String psCommandToSend = rdsDisplayManagerProperties.getPsCommandPrefix() + rdsDisplayManagerProperties.getPsIdle() + rdsDisplayManagerProperties.getCommandTerminaison();
String rtCommandToSend = rdsDisplayManagerProperties.getRtCommandPrefix() + rdsDisplayManagerProperties.getRtIdle() + rdsDisplayManagerProperties.getCommandTerminaison();
//send command
sendCommandsToRDS(psCommandToSend, rtCommandToSend, null);
}
/**
* Send command to the RDS
* @param psCommand the PS command as string
* @param rtCommand the RT command as String
* @param title title to log
*/
private void sendCommandsToRDS(String psCommand, String rtCommand, BroadcastableTitle title) {
LOGGER.debug("Command to send for PS : " + psCommand);
LOGGER.debug("Command to send for RT : " + rtCommand);
//send PS command
String psCommandReturn = null;
try {
psCommandReturn = rs232WireService.sendCommand(psCommand);
psCommandReturn = processCommandReturnAndVirtualMode(CommandType.PS, psCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending PS command", e);
alertMailService.sendRDSCoderErrorAlert(e);
}
//send RT command
String rtCommandReturn = null;
try {
rtCommandReturn = rs232WireService.sendCommand(rtCommand);
rtCommandReturn = processCommandReturnAndVirtualMode(CommandType.RADIOTEXT, rtCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending RT command", e);
alertMailService.sendRDSCoderErrorAlert(e);
}
//db log
logCommandsIntoDB(psCommand, psCommandReturn, rtCommand, rtCommandReturn, title);
}
/**
* Log the commands into db
* @param psCommand the PS command sent
* @param psCommandReturn the PS command return
* @param rtCommand the RT command sent
* @param rtCommandReturn the RT command return
* @param title title to display
*/
private void logCommandsIntoDB(String psCommand, String psCommandReturn, String rtCommand, String rtCommandReturn, BroadcastableTitle title) {
//log into db
RDSDisplay rdsDisplayDocument = new RDSDisplay();
rdsDisplayDocument.setBroadcastableTitle(title);
rdsDisplayDocument.setDate(Calendar.getInstance().getTime());
rdsDisplayDocument.setRs232Commands(new RS232Commands());
rdsDisplayDocument.getRs232Commands().setPsCommand(psCommand);
rdsDisplayDocument.getRs232Commands().setPsCommandReturn(psCommandReturn);
rdsDisplayDocument.getRs232Commands().setRtCommand(rtCommand);
rdsDisplayDocument.getRs232Commands().setRtCommandReturn(rtCommandReturn);
mongoDBRepository.insertRDSDisplay(rdsDisplayDocument);
}
/**
* Process the return text
* @param commandType the sent command type
* @param returnedText the returned text
* @return the returned text if OK
* @throws RS232RDSCoderException if not the expected text
*/
private String processCommandReturnAndVirtualMode(CommandType commandType, String returnedText) throws RS232RDSCoderException {
if (!rs232Config.isVirtualMode()) {
String expectedText = null;
switch (commandType) {
case INIT:
expectedText = rs232Config.getInitCommandReturn();
break;
case PS:
expectedText = rdsDisplayManagerProperties.getPsCommandReturn();
break;
case RADIOTEXT:
expectedText = rdsDisplayManagerProperties.getRtCommandReturn();
break;
}
if (expectedText.equals(returnedText))
return returnedText;
else {
String message = "Bad return text on " + commandType.toString() + " : " + returnedText;
LOGGER.error(message);
throw new RS232RDSCoderException(message);
}
} else { //we are in virtual mode
LOGGER.debug("Virtual mode enabled - using defaut return text");
return rdsDisplayManagerProperties.getVirtualModeReturnText();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
/**
* Send the init commands to RDS
*/
@PostConstruct
public void initRDS() {
- String initCommand = rs232Config.getInitCommand();
+ String initCommand = rs232Config.getInitCommand() + rdsDisplayManagerProperties.getCommandTerminaison();
String psCommand = rdsDisplayManagerProperties.getPsCommandPrefix() + rdsDisplayManagerProperties.getPsInitCommand() + rdsDisplayManagerProperties.getCommandTerminaison();
String rtCommand = rdsDisplayManagerProperties.getRtCommandPrefix() + rdsDisplayManagerProperties.getRtInitCommand() + rdsDisplayManagerProperties.getCommandTerminaison();
LOGGER.debug("Command to send for RDS init : " + initCommand);
LOGGER.debug("Command to send for PS : " + psCommand);
LOGGER.debug("Command to send for RT : " + rtCommand);
//send PS command
String initCommandReturn = null;
try {
initCommandReturn = rs232WireService.sendCommand(initCommand);
initCommandReturn = processCommandReturnAndVirtualMode(CommandType.INIT, initCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending RDS port init command - stop context", e);
alertMailService.sendCOMPortErrorAlert(e);
((AbstractApplicationContext) context).close(); //unload context (stop starting)
}
//send PS command
String psCommandReturn = null;
try {
psCommandReturn = rs232WireService.sendCommand(psCommand);
psCommandReturn = processCommandReturnAndVirtualMode(CommandType.PS, psCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending PS init command - stop context", e);
alertMailService.sendCOMPortErrorAlert(e);
((AbstractApplicationContext) context).close(); //unload context (stop starting)
}
//send RT command
String rtCommandReturn = null;
try {
rtCommandReturn = rs232WireService.sendCommand(rtCommand);
rtCommandReturn = processCommandReturnAndVirtualMode(CommandType.RADIOTEXT, rtCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending RT init command - stop context", e);
alertMailService.sendCOMPortErrorAlert(e);
((AbstractApplicationContext) context).close(); //unload context (stop starting)
}
//db log
logCommandsIntoDB(psCommand, psCommandReturn, rtCommand, rtCommandReturn, null);
}
}
| true | true | public void initRDS() {
String initCommand = rs232Config.getInitCommand();
String psCommand = rdsDisplayManagerProperties.getPsCommandPrefix() + rdsDisplayManagerProperties.getPsInitCommand() + rdsDisplayManagerProperties.getCommandTerminaison();
String rtCommand = rdsDisplayManagerProperties.getRtCommandPrefix() + rdsDisplayManagerProperties.getRtInitCommand() + rdsDisplayManagerProperties.getCommandTerminaison();
LOGGER.debug("Command to send for RDS init : " + initCommand);
LOGGER.debug("Command to send for PS : " + psCommand);
LOGGER.debug("Command to send for RT : " + rtCommand);
//send PS command
String initCommandReturn = null;
try {
initCommandReturn = rs232WireService.sendCommand(initCommand);
initCommandReturn = processCommandReturnAndVirtualMode(CommandType.INIT, initCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending RDS port init command - stop context", e);
alertMailService.sendCOMPortErrorAlert(e);
((AbstractApplicationContext) context).close(); //unload context (stop starting)
}
//send PS command
String psCommandReturn = null;
try {
psCommandReturn = rs232WireService.sendCommand(psCommand);
psCommandReturn = processCommandReturnAndVirtualMode(CommandType.PS, psCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending PS init command - stop context", e);
alertMailService.sendCOMPortErrorAlert(e);
((AbstractApplicationContext) context).close(); //unload context (stop starting)
}
//send RT command
String rtCommandReturn = null;
try {
rtCommandReturn = rs232WireService.sendCommand(rtCommand);
rtCommandReturn = processCommandReturnAndVirtualMode(CommandType.RADIOTEXT, rtCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending RT init command - stop context", e);
alertMailService.sendCOMPortErrorAlert(e);
((AbstractApplicationContext) context).close(); //unload context (stop starting)
}
//db log
logCommandsIntoDB(psCommand, psCommandReturn, rtCommand, rtCommandReturn, null);
}
| public void initRDS() {
String initCommand = rs232Config.getInitCommand() + rdsDisplayManagerProperties.getCommandTerminaison();
String psCommand = rdsDisplayManagerProperties.getPsCommandPrefix() + rdsDisplayManagerProperties.getPsInitCommand() + rdsDisplayManagerProperties.getCommandTerminaison();
String rtCommand = rdsDisplayManagerProperties.getRtCommandPrefix() + rdsDisplayManagerProperties.getRtInitCommand() + rdsDisplayManagerProperties.getCommandTerminaison();
LOGGER.debug("Command to send for RDS init : " + initCommand);
LOGGER.debug("Command to send for PS : " + psCommand);
LOGGER.debug("Command to send for RT : " + rtCommand);
//send PS command
String initCommandReturn = null;
try {
initCommandReturn = rs232WireService.sendCommand(initCommand);
initCommandReturn = processCommandReturnAndVirtualMode(CommandType.INIT, initCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending RDS port init command - stop context", e);
alertMailService.sendCOMPortErrorAlert(e);
((AbstractApplicationContext) context).close(); //unload context (stop starting)
}
//send PS command
String psCommandReturn = null;
try {
psCommandReturn = rs232WireService.sendCommand(psCommand);
psCommandReturn = processCommandReturnAndVirtualMode(CommandType.PS, psCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending PS init command - stop context", e);
alertMailService.sendCOMPortErrorAlert(e);
((AbstractApplicationContext) context).close(); //unload context (stop starting)
}
//send RT command
String rtCommandReturn = null;
try {
rtCommandReturn = rs232WireService.sendCommand(rtCommand);
rtCommandReturn = processCommandReturnAndVirtualMode(CommandType.RADIOTEXT, rtCommandReturn);
} catch (IOException | RS232RDSCoderException e) {
LOGGER.error("Error while sending RT init command - stop context", e);
alertMailService.sendCOMPortErrorAlert(e);
((AbstractApplicationContext) context).close(); //unload context (stop starting)
}
//db log
logCommandsIntoDB(psCommand, psCommandReturn, rtCommand, rtCommandReturn, null);
}
|
diff --git a/src/confdb/db/CfgDatabase.java b/src/confdb/db/CfgDatabase.java
index 24e543c9..d282d37b 100644
--- a/src/confdb/db/CfgDatabase.java
+++ b/src/confdb/db/CfgDatabase.java
@@ -1,2356 +1,2356 @@
package confdb.db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import confdb.data.Directory;
import confdb.data.ConfigInfo;
import confdb.data.Configuration;
import confdb.data.TemplateFactory;
import confdb.data.Template;
import confdb.data.Instance;
import confdb.data.Reference;
import confdb.data.ParameterFactory;
import confdb.data.Parameter;
import confdb.data.ScalarParameter;
import confdb.data.VectorParameter;
import confdb.data.PSetParameter;
import confdb.data.VPSetParameter;
import confdb.data.EDSourceInstance;
import confdb.data.ESSourceInstance;
import confdb.data.ServiceInstance;
import confdb.data.Referencable;
import confdb.data.ModuleInstance;
import confdb.data.Path;
import confdb.data.Sequence;
import confdb.data.PathReference;
import confdb.data.SequenceReference;
import confdb.data.ModuleReference;
/**
* CfgDatabase
* -----------
* @author Philipp Schieferdecker
*
* Handle database access operations.
*/
public class CfgDatabase
{
//
// member data
//
/** define database arch types */
public static final String dbTypeMySQL = "mysql";
public static final String dbTypeOracle = "oracle";
/** define database table names */
public static final String tableModuleTemplates = "ModuleTemplates";
public static final String tableServiceTemplates = "ServiceTemplates";
public static final String tableEDSourceTemplates = "EDSourceTemplates";
public static final String tableESSourceTemplates = "ESSourceTemplates";
/** database connector object, handles access to various DBMSs */
private IDatabaseConnector dbConnector = null;
/** database type */
private String dbType = null;
/** template table name hash map */
private HashMap<String,String> templateTableNameHashMap = null;
/** module type id hash map */
private HashMap<String,Integer> moduleTypeIdHashMap = null;
/** parameter type id hash map */
private HashMap<String,Integer> paramTypeIdHashMap = null;
/** vector/scalar parameter hash map */
private HashMap<Integer,Boolean> isVectorParamHashMap = null;
/** 'insert parameter' sql statement hash map */
private HashMap<String,PreparedStatement> insertParameterHashMap = null;
/** 'select parameter' sql statement hash map, by parameter type */
private HashMap<String,PreparedStatement> selectParameterHashMap = null;
/** 'selevt parameter' sql statement hash map, by parameter id */
private HashMap<Integer,PreparedStatement> selectParameterIdHashMap = null;
/** service template-name hash map */
private HashMap<Integer,String> serviceTemplateNameHashMap = null;
/** edsource template-name hash map */
private HashMap<Integer,String> edsourceTemplateNameHashMap = null;
/** essource template-name hash map */
private HashMap<Integer,String> essourceTemplateNameHashMap = null;
/** module template-name hash map */
private HashMap<Integer,String> moduleTemplateNameHashMap = null;
/** prepared sql statements */
private PreparedStatement psSelectModuleTypes = null;
private PreparedStatement psSelectParameterTypes = null;
private PreparedStatement psSelectDirectories = null;
private PreparedStatement psSelectConfigurationsByDir = null;
private PreparedStatement psSelectConfigNames = null;
private PreparedStatement psSelectConfiguration = null;
private PreparedStatement psSelectReleaseTags = null;
private PreparedStatement psSelectReleaseTag = null;
private PreparedStatement psSelectSuperIdReleaseAssoc = null;
private PreparedStatement psSelectServiceTemplate = null;
private PreparedStatement psSelectServiceTemplatesByRelease = null;
private PreparedStatement psSelectEDSourceTemplate = null;
private PreparedStatement psSelectEDSourceTemplatesByRelease = null;
private PreparedStatement psSelectESSourceTemplate = null;
private PreparedStatement psSelectESSourceTemplatesByRelease = null;
private PreparedStatement psSelectModuleTemplate = null;
private PreparedStatement psSelectModuleTemplatesByRelease = null;
private PreparedStatement psSelectServices = null;
private PreparedStatement psSelectEDSources = null;
private PreparedStatement psSelectESSources = null;
private PreparedStatement psSelectPaths = null;
private PreparedStatement psSelectSequences = null;
private PreparedStatement psSelectModulesFromPaths = null;
private PreparedStatement psSelectModulesFromSequences = null;
private PreparedStatement psSelectSequenceModuleAssoc = null;
private PreparedStatement psSelectPathPathAssoc = null;
private PreparedStatement psSelectPathSequenceAssoc = null;
private PreparedStatement psSelectPathModuleAssoc = null;
private PreparedStatement psSelectParameters = null;
private PreparedStatement psSelectParameterSets = null;
private PreparedStatement psSelectVecParameterSets = null;
private PreparedStatement psSelectBoolParamValue = null;
private PreparedStatement psSelectInt32ParamValue = null;
private PreparedStatement psSelectUInt32ParamValue = null;
private PreparedStatement psSelectDoubleParamValue = null;
private PreparedStatement psSelectStringParamValue = null;
private PreparedStatement psSelectEventIDParamValue = null;
private PreparedStatement psSelectInputTagParamValue = null;
private PreparedStatement psSelectVInt32ParamValues = null;
private PreparedStatement psSelectVUInt32ParamValues = null;
private PreparedStatement psSelectVDoubleParamValues = null;
private PreparedStatement psSelectVStringParamValues = null;
private PreparedStatement psSelectVEventIDParamValues = null;
private PreparedStatement psSelectVInputTagParamValues = null;
private PreparedStatement psInsertDirectory = null;
private PreparedStatement psInsertConfiguration = null;
private PreparedStatement psInsertConfigReleaseAssoc = null;
private PreparedStatement psInsertSuperId = null;
private PreparedStatement psInsertService = null;
private PreparedStatement psInsertEDSource = null;
private PreparedStatement psInsertESSource = null;
private PreparedStatement psInsertPath = null;
private PreparedStatement psInsertSequence = null;
private PreparedStatement psInsertModule = null;
private PreparedStatement psInsertSequenceModuleAssoc = null;
private PreparedStatement psInsertPathPathAssoc = null;
private PreparedStatement psInsertPathSequenceAssoc = null;
private PreparedStatement psInsertPathModuleAssoc = null;
private PreparedStatement psInsertSuperIdReleaseAssoc = null;
private PreparedStatement psInsertServiceTemplate = null;
private PreparedStatement psInsertEDSourceTemplate = null;
private PreparedStatement psInsertESSourceTemplate = null;
private PreparedStatement psInsertModuleTemplate = null;
private PreparedStatement psInsertParameter = null;
private PreparedStatement psInsertParameterSet = null;
private PreparedStatement psInsertVecParameterSet = null;
private PreparedStatement psInsertSuperIdParamAssoc = null;
private PreparedStatement psInsertSuperIdParamSetAssoc = null;
private PreparedStatement psInsertSuperIdVecParamSetAssoc = null;
private PreparedStatement psInsertBoolParamValue = null;
private PreparedStatement psInsertInt32ParamValue = null;
private PreparedStatement psInsertUInt32ParamValue = null;
private PreparedStatement psInsertDoubleParamValue = null;
private PreparedStatement psInsertStringParamValue = null;
private PreparedStatement psInsertEventIDParamValue = null;
private PreparedStatement psInsertInputTagParamValue = null;
private PreparedStatement psInsertVInt32ParamValue = null;
private PreparedStatement psInsertVUInt32ParamValue = null;
private PreparedStatement psInsertVDoubleParamValue = null;
private PreparedStatement psInsertVStringParamValue = null;
private PreparedStatement psInsertVEventIDParamValue = null;
private PreparedStatement psInsertVInputTagParamValue = null;
//
// construction
//
/** standard constructor */
public CfgDatabase()
{
// template table name hash map
templateTableNameHashMap = new HashMap<String,String>();
templateTableNameHashMap.put("Service", tableServiceTemplates);
templateTableNameHashMap.put("EDSource", tableEDSourceTemplates);
templateTableNameHashMap.put("ESSource", tableESSourceTemplates);
// template name hash maps
serviceTemplateNameHashMap = new HashMap<Integer,String>();
edsourceTemplateNameHashMap = new HashMap<Integer,String>();
essourceTemplateNameHashMap = new HashMap<Integer,String>();
moduleTemplateNameHashMap = new HashMap<Integer,String>();
}
//
// member functions
//
/** prepare database transaction statements */
public boolean prepareStatements()
{
int[] keyColumn = { 1 };
try {
psSelectModuleTypes =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ModuleTypes.typeId," +
" ModuleTypes.type " +
"FROM ModuleTypes");
psSelectParameterTypes =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ParameterTypes.paramTypeId," +
" ParameterTypes.paramType " +
"FROM ParameterTypes");
psSelectDirectories =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Directories.dirId," +
" Directories.parentDirId," +
" Directories.dirName," +
" Directories.created " +
"FROM Directories " +
"ORDER BY Directories.created ASC");
psSelectConfigurationsByDir =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Configurations.configId," +
" Configurations.config," +
" Configurations.version," +
" Configurations.created," +
" SoftwareReleases.releaseTag " +
"FROM Configurations " +
"JOIN ConfigurationReleaseAssoc " +
"ON ConfigurationReleaseAssoc.configId = Configurations.configId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId = ConfigurationReleaseAssoc.releaseId " +
"WHERE Configurations.parentDirId = ? " +
"ORDER BY Configurations.created DESC");
psSelectConfigNames =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Configurations.configId," +
" Configurations.config " +
"FROM Configurations " +
"WHERE version=1 " +
"ORDER BY created DESC");
psSelectConfiguration =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Configurations.created " +
"FROM Configurations " +
"WHERE Configurations.configId = ?");
psSelectReleaseTags =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SoftwareReleases.releaseId," +
" SoftwareReleases.releaseTag " +
"FROM SoftwareReleases " +
"ORDER BY releaseId DESC");
psSelectReleaseTag =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SoftwareReleases.releaseId," +
" SoftwareReleases.releaseTag " +
"FROM SoftwareReleases " +
"WHERE releaseTag = ?");
psSelectSuperIdReleaseAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SuperIdReleaseAssoc.superId," +
" SuperIdReleaseAssoc.releaseId " +
"FROM SuperIdReleaseAssoc " +
"WHERE superId =? AND releaseId = ?");
psSelectServiceTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ServiceTemplates.superId," +
" ServiceTemplates.name," +
" ServiceTemplates.cvstag " +
"FROM ServiceTemplates " +
"WHERE name=? AND cvstag=?");
psSelectServiceTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ServiceTemplates.superId," +
" ServiceTemplates.name," +
" ServiceTemplates.cvstag " +
"FROM ServiceTemplates " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = ServiceTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY ServiceTemplates.name ASC");
psSelectEDSourceTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EDSourceTemplates.superId," +
" EDSourceTemplates.name," +
" EDSourceTemplates.cvstag " +
"FROM EDSourceTemplates " +
"WHERE name=? AND cvstag=?");
psSelectEDSourceTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EDSourceTemplates.superId," +
" EDSourceTemplates.name," +
" EDSourceTemplates.cvstag " +
"FROM EDSourceTemplates " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = EDSourceTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY EDSourceTemplates.name ASC");
psSelectESSourceTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ESSourceTemplates.superId," +
" ESSourceTemplates.name," +
" ESSourceTemplates.cvstag " +
"FROM ESSourceTemplates " +
"WHERE name=? AND cvstag=?");
psSelectESSourceTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ESSourceTemplates.superId," +
" ESSourceTemplates.name," +
" ESSourceTemplates.cvstag " +
"FROM ESSourceTemplates " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = ESSourceTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY ESSourceTemplates.name ASC");
psSelectModuleTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ModuleTemplates.superId," +
" ModuleTemplates.typeId," +
" ModuleTemplates.name," +
" ModuleTemplates.cvstag " +
"FROM ModuleTemplates " +
"WHERE name=? AND cvstag=?");
psSelectModuleTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ModuleTemplates.superId," +
" ModuleTypes.type," +
" ModuleTemplates.name," +
" ModuleTemplates.cvstag " +
"FROM ModuleTemplates " +
"JOIN ModuleTypes " +
"ON ModuleTypes.typeId = ModuleTemplates.typeId " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = ModuleTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY ModuleTemplates.name ASC");
psSelectServices =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Services.superId," +
" Services.templateId," +
" Services.configId," +
" Services.sequenceNb " +
"FROM Services " +
"WHERE configId=? "+
"ORDER BY Services.sequenceNb ASC");
psSelectEDSources =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EDSources.superId," +
" EDSources.templateId," +
" EDSources.configId," +
" EDSources.sequenceNb " +
"FROM EDSources " +
"WHERE configId=? " +
"ORDER BY EDSources.sequenceNb ASC");
psSelectESSources =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ESSources.superId," +
" ESSources.templateId," +
" ESSources.configId," +
" ESSources.name," +
" ESSources.sequenceNb " +
"FROM ESSources " +
- "WHERE configId=?" +
+ "WHERE configId=? " +
"ORDER BY ESSources.sequenceNb ASC");
psSelectPaths =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Paths.pathId," +
" Paths.configId," +
" Paths.name," +
" Paths.sequenceNb, " +
" Paths.isEndPath " +
"FROM Paths " +
"WHERE Paths.configId=? " +
"ORDER BY sequenceNb ASC");
psSelectSequences =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Sequences.sequenceId," +
" Sequences.configId," +
" Sequences.name " +
"FROM Sequences " +
"WHERE Sequences.configId=?");
psSelectModulesFromPaths=
dbConnector.getConnection().prepareStatement
("SELECT" +
" Modules.superId," +
" Modules.templateId," +
" Modules.name," +
" Paths.configId " +
"FROM Modules " +
"JOIN PathModuleAssoc " +
"ON PathModuleAssoc.moduleId = Modules.superId " +
"JOIN Paths " +
"ON Paths.pathId = PathModuleAssoc.pathId " +
"WHERE Paths.configId=?");
psSelectModulesFromSequences=
dbConnector.getConnection().prepareStatement
("SELECT" +
" Modules.superId," +
" Modules.templateId," +
" Modules.name," +
" Paths.configId " +
"FROM Modules " +
"JOIN SequenceModuleAssoc " +
"ON SequenceModuleAssoc.moduleId = Modules.superId " +
"JOIN Sequences " +
"ON Sequences.sequenceId = SequenceModuleAssoc.sequenceId " +
"JOIN PathSequenceAssoc " +
"ON PathSequenceAssoc.sequenceId = Sequences.sequenceId " +
"JOIN Paths " +
"ON Paths.pathId = PathSequenceAssoc.pathId " +
"WHERE Paths.configId=?");
psSelectSequenceModuleAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SequenceModuleAssoc.sequenceId," +
" SequenceModuleAssoc.moduleId," +
" SequenceModuleAssoc.sequenceNb " +
"FROM SequenceModuleAssoc " +
"WHERE SequenceModuleAssoc.sequenceId = ?");
psSelectPathPathAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" PathInPathAssoc.parentPathId," +
" PathInPathAssoc.childPathId," +
" PathInPathAssoc.sequenceNb " +
"FROM PathInPathAssoc " +
"WHERE PathInPathAssoc.parentPathId = ?");
psSelectPathSequenceAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" PathSequenceAssoc.pathId," +
" PathSequenceAssoc.sequenceId," +
" PathSequenceAssoc.sequenceNb " +
"FROM PathSequenceAssoc " +
"WHERE PathSequenceAssoc.pathId = ?");
psSelectPathModuleAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" PathModuleAssoc.pathId," +
" PathModuleAssoc.moduleId," +
" PathModuleAssoc.sequenceNb " +
"FROM PathModuleAssoc " +
"WHERE PathModuleAssoc.pathId = ?");
psSelectParameters =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Parameters.paramId," +
" Parameters.name," +
" Parameters.tracked," +
" Parameters.paramTypeId," +
" ParameterTypes.paramType," +
" SuperIdParameterAssoc.superId," +
" SuperIdParameterAssoc.sequenceNb " +
"FROM Parameters " +
"JOIN SuperIdParameterAssoc " +
"ON SuperIdParameterAssoc.paramId = Parameters.paramId " +
"JOIN ParameterTypes " +
"ON Parameters.paramTypeId = ParameterTypes.paramTypeId " +
"WHERE SuperIdParameterAssoc.superId = ? " +
"ORDER BY SuperIdParameterAssoc.sequenceNb ASC");
psSelectParameterSets =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ParameterSets.superId," +
" ParameterSets.name," +
" ParameterSets.tracked," +
" SuperIdParamSetAssoc.superId," +
" SuperIdParamSetAssoc.sequenceNb " +
"FROM ParameterSets " +
"JOIN SuperIdParamSetAssoc " +
"ON SuperIdParamSetAssoc.paramSetId = ParameterSets.superId " +
"WHERE SuperIdParamSetAssoc.superId = ? " +
"ORDER BY SuperIdParamSetAssoc.sequenceNb ASC");
psSelectVecParameterSets =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VecParameterSets.superId," +
" VecParameterSets.name," +
" VecParameterSets.tracked," +
" SuperIdVecParamSetAssoc.superId," +
" SuperIdVecParamSetAssoc.sequenceNb " +
"FROM VecParameterSets " +
"JOIN SuperIdVecParamSetAssoc " +
"ON SuperIdVecParamSetAssoc.vecParamSetId=VecParameterSets.superId "+
"WHERE SuperIdVecParamSetAssoc.superId = ? "+
"ORDER BY SuperIdVecParamSetAssoc.sequenceNb ASC");
psSelectBoolParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" BoolParamValues.paramId," +
" BoolParamValues.value " +
"FROM BoolParamValues " +
"WHERE paramId = ?");
psSelectInt32ParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Int32ParamValues.paramId," +
" Int32ParamValues.value " +
"FROM Int32ParamValues " +
"WHERE paramId = ?");
psSelectUInt32ParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" UInt32ParamValues.paramId," +
" UInt32ParamValues.value " +
"FROM UInt32ParamValues " +
"WHERE paramId = ?");
psSelectDoubleParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" DoubleParamValues.paramId," +
" DoubleParamValues.value " +
"FROM DoubleParamValues " +
"WHERE paramId = ?");
psSelectStringParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" StringParamValues.paramId," +
" StringParamValues.value " +
"FROM StringParamValues " +
"WHERE paramId = ?");
psSelectEventIDParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EventIDParamValues.paramId," +
" EventIDParamValues.value " +
"FROM EventIDParamValues " +
"WHERE paramId = ?");
psSelectInputTagParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" InputTagParamValues.paramId," +
" InputTagParamValues.value " +
"FROM InputTagParamValues " +
"WHERE paramId = ?");
psSelectVInt32ParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VInt32ParamValues.paramId," +
" VInt32ParamValues.sequenceNb," +
" VInt32ParamValues.value " +
"FROM VInt32ParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVUInt32ParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VUInt32ParamValues.paramId," +
" VUInt32ParamValues.sequenceNb," +
" VUInt32ParamValues.value " +
"FROM VUInt32ParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVDoubleParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VDoubleParamValues.paramId," +
" VDoubleParamValues.sequenceNb," +
" VDoubleParamValues.value " +
"FROM VDoubleParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVStringParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VStringParamValues.paramId," +
" VStringParamValues.sequenceNb," +
" VStringParamValues.value " +
"FROM VStringParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVEventIDParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VEventIDParamValues.paramId," +
" VEventIDParamValues.sequenceNb," +
" VEventIDParamValues.value " +
"FROM VEventIDParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVInputTagParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VInputTagParamValues.paramId," +
" VInputTagParamValues.sequenceNb," +
" VInputTagParamValues.value " +
"FROM VInputTagParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
if (dbType.equals(dbTypeMySQL))
psInsertDirectory =
dbConnector.getConnection().prepareStatement
("INSERT INTO Directories " +
"(parentDirId,dirName,created) " +
"VALUES (?, ?, NOW())",keyColumn);
else if (dbType.equals(dbTypeOracle))
psInsertConfiguration =
dbConnector.getConnection().prepareStatement
("INSERT INTO Directories " +
"(parentDirId,dirName,created) " +
"VALUES (?, ?, SYSDATE)",keyColumn);
if (dbType.equals(dbTypeMySQL))
psInsertConfiguration =
dbConnector.getConnection().prepareStatement
("INSERT INTO Configurations " +
"(config,parentDirId,version,created) " +
"VALUES (?, ?, ?, NOW())",keyColumn);
else if (dbType.equals(dbTypeOracle))
psInsertConfiguration =
dbConnector.getConnection().prepareStatement
("INSERT INTO Configurations " +
"(config,parentDirId,version,created) " +
"VALUES (?, ?, ?, SYSDATE)",keyColumn);
psInsertConfigReleaseAssoc = dbConnector.getConnection().prepareStatement
("INSERT INTO ConfigurationReleaseAssoc (configId,releaseId) " +
"VALUES(?, ?)");
if (dbType.equals(dbTypeMySQL))
psInsertSuperId = dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIds VALUES()",keyColumn);
else if (dbType.equals(dbTypeOracle))
psInsertSuperId = dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIds VALUES('')",keyColumn);
psInsertService =
dbConnector.getConnection().prepareStatement
("INSERT INTO Services (superId,templateId,configId,sequenceNb) " +
"VALUES(?, ?, ?, ?)");
psInsertEDSource =
dbConnector.getConnection().prepareStatement
("INSERT INTO EDSources (superId,templateId,configId,sequenceNb) " +
"VALUES(?, ?, ?, ?)");
psInsertESSource =
dbConnector.getConnection().prepareStatement
("INSERT INTO " +
"ESSources (superId,templateId,configId,name,sequenceNb) " +
"VALUES(?, ?, ?, ?, ?)");
psInsertPath =
dbConnector.getConnection().prepareStatement
("INSERT INTO Paths (configId,name,sequenceNb) " +
"VALUES(?, ?, ?)",keyColumn);
psInsertSequence =
dbConnector.getConnection().prepareStatement
("INSERT INTO Sequences (configId,name) " +
"VALUES(?, ?)",keyColumn);
psInsertModule =
dbConnector.getConnection().prepareStatement
("INSERT INTO Modules (superId,templateId,name) " +
"VALUES(?, ?, ?)");
psInsertSequenceModuleAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SequenceModuleAssoc (sequenceId,moduleId,sequenceNb) "+
"VALUES(?, ?, ?)");
psInsertPathPathAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO PathInPathAssoc(parentPathId,childPathId,sequenceNb) "+
"VALUES(?, ?, ?)");
psInsertPathSequenceAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO PathSequenceAssoc (pathId,sequenceId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertPathModuleAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO PathModuleAssoc (pathId,moduleId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertSuperIdReleaseAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIdReleaseAssoc (superId,releaseId) " +
"VALUES(?, ?)");
psInsertServiceTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO ServiceTemplates (superId,name,cvstag) " +
"VALUES (?, ?, ?)");
psInsertEDSourceTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO EDSourceTemplates (superId,name,cvstag) " +
"VALUES (?, ?, ?)");
psInsertESSourceTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO ESSourceTemplates (superId,name,cvstag) " +
"VALUES (?, ?, ?)");
psInsertModuleTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO ModuleTemplates (superId,typeId,name,cvstag) " +
"VALUES (?, ?, ?, ?)");
psInsertParameterSet =
dbConnector.getConnection().prepareStatement
("INSERT INTO ParameterSets(superId,name,tracked) " +
"VALUES(?, ?, ?)");
psInsertVecParameterSet =
dbConnector.getConnection().prepareStatement
("INSERT INTO VecParameterSets(superId,name,tracked) " +
"VALUES(?, ?, ?)");
psInsertParameter =
dbConnector.getConnection().prepareStatement
("INSERT INTO Parameters (paramTypeId,name,tracked) " +
"VALUES(?, ?, ?)",keyColumn);
psInsertSuperIdParamSetAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIdParamSetAssoc (superId,paramSetId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertSuperIdVecParamSetAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO " +
"SuperIdVecParamSetAssoc (superId,vecParamSetId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertSuperIdParamAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIdParameterAssoc (superId,paramId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertBoolParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO BoolParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertInt32ParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO Int32ParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertUInt32ParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO UInt32ParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertDoubleParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO DoubleParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertStringParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO StringParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertEventIDParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO EventIDParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertInputTagParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO InputTagParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertVInt32ParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VInt32ParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVUInt32ParamValue
= dbConnector.getConnection().prepareStatement
("INSERT INTO VUInt32ParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVDoubleParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VDoubleParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVStringParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VStringParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVEventIDParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VEventIDParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVInputTagParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VInputTagParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
// create hash maps
moduleTypeIdHashMap = new HashMap<String,Integer>();
paramTypeIdHashMap = new HashMap<String,Integer>();
isVectorParamHashMap = new HashMap<Integer,Boolean>();
insertParameterHashMap = new HashMap<String,PreparedStatement>();
selectParameterHashMap = new HashMap<String,PreparedStatement>();
selectParameterIdHashMap = new HashMap<Integer,PreparedStatement>();
insertParameterHashMap.put("bool", psInsertBoolParamValue);
insertParameterHashMap.put("int32", psInsertInt32ParamValue);
insertParameterHashMap.put("vint32", psInsertVInt32ParamValue);
insertParameterHashMap.put("uint32", psInsertUInt32ParamValue);
insertParameterHashMap.put("vuint32", psInsertVUInt32ParamValue);
insertParameterHashMap.put("double", psInsertDoubleParamValue);
insertParameterHashMap.put("vdouble", psInsertVDoubleParamValue);
insertParameterHashMap.put("string", psInsertStringParamValue);
insertParameterHashMap.put("vstring", psInsertVStringParamValue);
insertParameterHashMap.put("EventID", psInsertEventIDParamValue);
insertParameterHashMap.put("VEventID", psInsertVEventIDParamValue);
insertParameterHashMap.put("InputTag", psInsertInputTagParamValue);
insertParameterHashMap.put("VInputTag",psInsertVInputTagParamValue);
selectParameterHashMap.put("bool", psSelectBoolParamValue);
selectParameterHashMap.put("int32", psSelectInt32ParamValue);
selectParameterHashMap.put("vint32", psSelectVInt32ParamValues);
selectParameterHashMap.put("uint32", psSelectUInt32ParamValue);
selectParameterHashMap.put("vuint32", psSelectVUInt32ParamValues);
selectParameterHashMap.put("double", psSelectDoubleParamValue);
selectParameterHashMap.put("vdouble", psSelectVDoubleParamValues);
selectParameterHashMap.put("string", psSelectStringParamValue);
selectParameterHashMap.put("vstring", psSelectVStringParamValues);
selectParameterHashMap.put("EventID", psSelectEventIDParamValue);
selectParameterHashMap.put("VEventID", psSelectVEventIDParamValues);
selectParameterHashMap.put("InputTag", psSelectInputTagParamValue);
selectParameterHashMap.put("VInputTag",psSelectVInputTagParamValues);
ResultSet rs = null;
try {
rs = psSelectModuleTypes.executeQuery();
while (rs.next()) {
int typeId = rs.getInt(1);
String type = rs.getString(2);
moduleTypeIdHashMap.put(type,typeId);
templateTableNameHashMap.put(type,tableModuleTemplates);
}
rs = psSelectParameterTypes.executeQuery();
while (rs.next()) {
int typeId = rs.getInt(1);
String type = rs.getString(2);
PreparedStatement ps = selectParameterHashMap.get(type);
paramTypeIdHashMap.put(type,typeId);
selectParameterIdHashMap.put(typeId,ps);
if (type.startsWith("v")||type.startsWith("V"))
isVectorParamHashMap.put(typeId,true);
else
isVectorParamHashMap.put(typeId,false);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return true;
}
/** connect to the database */
public boolean connect(String dbType,String dbUrl,String dbUser,String dbPwrd)
throws DatabaseException
{
if (dbType.equals(dbTypeMySQL))
dbConnector = new MySQLDatabaseConnector(dbUrl,dbUser,dbPwrd);
else if (dbType.equals(dbTypeOracle))
dbConnector = new OracleDatabaseConnector(dbUrl,dbUser,dbPwrd);
dbConnector.openConnection();
this.dbType = dbType;
return prepareStatements();
}
/** disconnect from database */
public boolean disconnect() throws DatabaseException
{
if (dbConnector==null) return false;
dbConnector.closeConnection();
dbConnector = null;
return true;
}
/** load information about all stored configurations */
public Directory loadConfigurationTree()
{
Directory rootDir = null;
ResultSet rs = null;
try {
// retrieve all directories
ArrayList<Directory> directoryList = new ArrayList<Directory>();
HashMap<Integer,Directory> directoryHashMap = new HashMap<Integer,Directory>();
rs = psSelectDirectories.executeQuery();
while (rs.next()) {
int dirId = rs.getInt(1);
int parentDirId = rs.getInt(2);
String dirName = rs.getString(3);
String dirCreated = rs.getObject(4).toString();
if (directoryList.size()==0) {
rootDir = new Directory(dirId,dirName,dirCreated,null);
directoryList.add(rootDir);
directoryHashMap.put(dirId,rootDir);
}
else {
if (!directoryHashMap.containsKey(parentDirId))
throw new DatabaseException("parent dir not found in DB!");
Directory parentDir = directoryHashMap.get(parentDirId);
Directory newDir = new Directory(dirId,dirName,dirCreated,parentDir);
parentDir.addChildDir(newDir);
directoryList.add(newDir);
directoryHashMap.put(dirId,newDir);
}
}
// retrieve list of configurations for all directories
HashMap<String,ConfigInfo> configHashMap =
new HashMap<String,ConfigInfo>();
for (Directory dir : directoryList) {
psSelectConfigurationsByDir.setInt(1,dir.dbId());
rs = psSelectConfigurationsByDir.executeQuery();
while (rs.next()) {
int configId = rs.getInt(1);
String configName = rs.getString(2);
int configVersion = rs.getInt(3);
String configCreated = rs.getObject(4).toString();
String configReleaseTag = rs.getString(5);
String configPathAndName = dir.name()+"/"+configName;
if (configHashMap.containsKey(configPathAndName)) {
ConfigInfo configInfo = configHashMap.get(configPathAndName);
configInfo.addVersion(configId,
configVersion,
configCreated,
configReleaseTag);
}
else {
ConfigInfo configInfo = new ConfigInfo(configName,
dir,
configId,
configVersion,
configCreated,
configReleaseTag);
configHashMap.put(configPathAndName,configInfo);
dir.addConfigInfo(configInfo);
}
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
catch (DatabaseException e) {
System.out.println("DatabaseException: " + e.getMessage());
}
finally {
dbConnector.release(rs);
}
return rootDir;
}
/** load service templates */
public int loadServiceTemplates(String releaseTag,
ArrayList<Template> templateList)
{
try {
psSelectServiceTemplatesByRelease.setString(1,releaseTag);
loadTemplates(psSelectServiceTemplatesByRelease,"Service",templateList);
}
catch (SQLException e) {
e.printStackTrace();
}
return templateList.size();
}
/** load edsource templates */
public int loadEDSourceTemplates(String releaseTag,
ArrayList<Template> templateList)
{
try {
psSelectEDSourceTemplatesByRelease.setString(1,releaseTag);
loadTemplates(psSelectEDSourceTemplatesByRelease,"EDSource",templateList);
}
catch (SQLException e) {
e.printStackTrace();
}
return templateList.size();
}
/** load essource templates */
public int loadESSourceTemplates(String releaseTag,
ArrayList<Template> templateList)
{
try {
psSelectESSourceTemplatesByRelease.setString(1,releaseTag);
loadTemplates(psSelectESSourceTemplatesByRelease,"ESSource",templateList);
}
catch (SQLException e) {
e.printStackTrace();
}
return templateList.size();
}
/** load module templates */
public int loadModuleTemplates(String releaseTag,
ArrayList<Template> templateList)
{
try {
psSelectModuleTemplatesByRelease.setString(1,releaseTag);
loadTemplates(psSelectModuleTemplatesByRelease,"Module",templateList);
}
catch (SQLException e) {
e.printStackTrace();
}
return templateList.size();
}
/** load templates, given the already prepared statement */
public void loadTemplates(PreparedStatement psSelectTemplates,
String templateType,
ArrayList<Template> templateList)
{
templateList.clear();
ResultSet rs = null;
try {
rs = psSelectTemplates.executeQuery();
while (rs.next()) {
int superId = rs.getInt(1);
String type;
String name;
String cvsTag;
if (templateType.equals("Module")) {
type = rs.getString(2);
name = rs.getString(3);
cvsTag = rs.getString(4);
}
else {
type = templateType;
name = rs.getString(2);
cvsTag = rs.getString(3);
}
ArrayList<Parameter> parameters = new ArrayList<Parameter>();
loadParameters(superId,parameters);
loadParameterSets(superId,parameters);
loadVecParameterSets(superId,parameters);
boolean paramIsNull = false;
for (Parameter p : parameters) if (p==null) paramIsNull=true;
if (paramIsNull) {
System.out.println("ERROR: " + type + " '" + name +
" has 'null' parameter, can't load template.");
}
else {
templateList.add(TemplateFactory
.create(type,name,cvsTag,superId,parameters));
}
}
}
catch (SQLException e) { e.printStackTrace(); }
catch (Exception e) { System.out.println(e.getMessage()); }
finally {
dbConnector.release(rs);
}
}
/** load a configuration from the database */
public Configuration loadConfiguration(ConfigInfo configInfo,
ArrayList<Template> edsourceTemplateList,
ArrayList<Template> essourceTemplateList,
ArrayList<Template> serviceTemplateList,
ArrayList<Template> moduleTemplateList)
{
Configuration config = null;
String releaseTag = configInfo.releaseTag();
loadEDSourceTemplates(releaseTag,edsourceTemplateList);
loadESSourceTemplates(releaseTag,essourceTemplateList);
loadServiceTemplates(releaseTag,serviceTemplateList);
loadModuleTemplates(releaseTag,moduleTemplateList);
edsourceTemplateNameHashMap.clear();
essourceTemplateNameHashMap.clear();
serviceTemplateNameHashMap.clear();
moduleTemplateNameHashMap.clear();
for (Template t : edsourceTemplateList)
edsourceTemplateNameHashMap.put(t.dbSuperId(),t.name());
for (Template t : essourceTemplateList)
essourceTemplateNameHashMap.put(t.dbSuperId(),t.name());
for (Template t : serviceTemplateList)
serviceTemplateNameHashMap.put(t.dbSuperId(),t.name());
for (Template t : moduleTemplateList)
moduleTemplateNameHashMap.put(t.dbSuperId(),t.name());
config = new Configuration(configInfo,
edsourceTemplateList,
essourceTemplateList,
serviceTemplateList,
moduleTemplateList);
int configId = configInfo.dbId();
ResultSet rs = null;
try {
// load EDSource
psSelectEDSources.setInt(1,configId);
rs = psSelectEDSources.executeQuery();
if (rs.next()) {
int edsourceId = rs.getInt(1);
int templateId = rs.getInt(2);
String templateName = edsourceTemplateNameHashMap.get(templateId);
Instance edsource = config.insertEDSource(templateName);
loadInstanceParameters(edsourceId,edsource);
loadInstanceParameterSets(edsourceId,edsource);
loadInstanceVecParameterSets(edsourceId,edsource);
}
// load ESSources
psSelectESSources.setInt(1,configId);
rs = psSelectESSources.executeQuery();
int insertIndex = 0;
while (rs.next()) {
int essourceId = rs.getInt(1);
int templateId = rs.getInt(2);
String instanceName = rs.getString(4);
String templateName = essourceTemplateNameHashMap.get(templateId);
Instance essource = config.insertESSource(insertIndex,
templateName,
instanceName);
loadInstanceParameters(essourceId,essource);
loadInstanceParameterSets(essourceId,essource);
loadInstanceVecParameterSets(essourceId,essource);
insertIndex++;
}
// load Services
psSelectServices.setInt(1,configId);
rs = psSelectServices.executeQuery();
insertIndex = 0;
while (rs.next()) {
int serviceId = rs.getInt(1);
int templateId = rs.getInt(2);
String templateName = serviceTemplateNameHashMap.get(templateId);
Instance service = config.insertService(insertIndex,
templateName);
loadInstanceParameters(serviceId,service);
loadInstanceParameterSets(serviceId,service);
loadInstanceVecParameterSets(serviceId,service);
insertIndex++;
}
// load all Paths
HashMap<Integer,Path> pathHashMap =
new HashMap<Integer,Path>();
psSelectPaths.setInt(1,configId);
rs = psSelectPaths.executeQuery();
while (rs.next()) {
int pathId = rs.getInt(1);
String pathName = rs.getString(3);
int pathIndex = rs.getInt(4);
boolean pathIsEndPath = rs.getBoolean(5);
Path path = config.insertPath(pathIndex,pathName);
pathHashMap.put(pathId,path);
}
// load all Sequences
HashMap<Integer,Sequence> sequenceHashMap =
new HashMap<Integer,Sequence>();
psSelectSequences.setInt(1,configId);
rs = psSelectSequences.executeQuery();
while (rs.next()) {
int seqId = rs.getInt(1);
if (!sequenceHashMap.containsKey(seqId)) {
String seqName = rs.getString(3);
Sequence sequence = config.insertSequence(config.sequenceCount(),
seqName);
sequenceHashMap.put(seqId,sequence);
}
}
// load all Modules
HashMap<Integer,ModuleInstance> moduleHashMap =
new HashMap<Integer,ModuleInstance>();
// from paths
psSelectModulesFromPaths.setInt(1,configId);
rs = psSelectModulesFromPaths.executeQuery();
while (rs.next()) {
int moduleId = rs.getInt(1);
if (!moduleHashMap.containsKey(moduleId)) {
int templateId = rs.getInt(2);
String instanceName = rs.getString(3);
String templateName = moduleTemplateNameHashMap.get(templateId);
ModuleInstance module = config.insertModule(templateName,
instanceName);
loadInstanceParameters(moduleId,module);
loadInstanceParameterSets(moduleId,module);
loadInstanceVecParameterSets(moduleId,module);
moduleHashMap.put(moduleId,module);
}
}
// from sequences
psSelectModulesFromSequences.setInt(1,configId);
rs = psSelectModulesFromSequences.executeQuery();
while (rs.next()) {
int moduleId = rs.getInt(1);
if (!moduleHashMap.containsKey(moduleId)) {
int templateId = rs.getInt(2);
String instanceName = rs.getString(3);
String templateName = moduleTemplateNameHashMap.get(templateId);
ModuleInstance module = config.insertModule(templateName,
instanceName);
loadInstanceParameters(moduleId,module);
loadInstanceParameterSets(moduleId,module);
loadInstanceVecParameterSets(moduleId,module);
moduleHashMap.put(moduleId,module);
}
}
// loop over all Sequences and insert all Module References
for (Map.Entry<Integer,Sequence> e : sequenceHashMap.entrySet()) {
int sequenceId = e.getKey();
Sequence sequence = e.getValue();
psSelectSequenceModuleAssoc.setInt(1,sequenceId);
rs = psSelectSequenceModuleAssoc.executeQuery();
while (rs.next()) {
int moduleId = rs.getInt(2);
int sequenceNb = rs.getInt(3);
ModuleInstance module = moduleHashMap.get(moduleId);
config.insertModuleReference(sequence,sequenceNb,module);
}
}
// loop over Paths and insert references
for (Map.Entry<Integer,Path> e : pathHashMap.entrySet()) {
int pathId = e.getKey();
Path path = e.getValue();
HashMap<Integer,Referencable> refHashMap=
new HashMap<Integer,Referencable>();
// paths to be referenced
psSelectPathPathAssoc.setInt(1,pathId);
rs = psSelectPathPathAssoc.executeQuery();
while (rs.next()) {
int childPathId = rs.getInt(2);
int sequenceNb = rs.getInt(3);
Path childPath = pathHashMap.get(childPathId);
refHashMap.put(sequenceNb,childPath);
}
// sequences to be referenced
psSelectPathSequenceAssoc.setInt(1,pathId);
rs = psSelectPathSequenceAssoc.executeQuery();
while (rs.next()) {
int sequenceId = rs.getInt(2);
int sequenceNb = rs.getInt(3);
Sequence sequence = sequenceHashMap.get(sequenceId);
refHashMap.put(sequenceNb,sequence);
}
// modules to be referenced
psSelectPathModuleAssoc.setInt(1,pathId);
rs = psSelectPathModuleAssoc.executeQuery();
while (rs.next()) {
int moduleId = rs.getInt(2);
int sequenceNb = rs.getInt(3);
ModuleInstance module = moduleHashMap.get(moduleId);
refHashMap.put(sequenceNb,module);
}
// check that the keys are 0...size-1
Set<Integer> keys = refHashMap.keySet();
Set<Integer> requiredKeys = new HashSet<Integer>();
for (int i=0;i<refHashMap.size();i++)
requiredKeys.add(new Integer(i));
if (!keys.containsAll(requiredKeys))
System.out.println("CfgDatabase.loadConfiguration ERROR:" +
"path '"+path.name()+"' has invalid " +
"key set!");
// add references to path
for (int i=0;i<refHashMap.size();i++) {
Referencable r = refHashMap.get(i);
if (r instanceof Path) {
Path p = (Path)r;
config.insertPathReference(path,i,p);
}
else if (r instanceof Sequence) {
Sequence s = (Sequence)r;
config.insertSequenceReference(path,i,s);
}
else if (r instanceof ModuleInstance) {
ModuleInstance m = (ModuleInstance)r;
config.insertModuleReference(path,i,m);
}
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
// set 'hasChanged' flag
config.setHasChanged(false);
return config;
}
/** load parameters */
public boolean loadParameters(int superId,ArrayList<Parameter> parameters)
{
ResultSet rs = null;
try {
psSelectParameters.setInt(1,superId);
rs = psSelectParameters.executeQuery();
while (rs.next()) {
int paramId = rs.getInt(1);
String paramName = rs.getString(2);
boolean paramIsTrkd = rs.getBoolean(3);
int paramTypeId = rs.getInt(4);
String paramType = rs.getString(5);
int sequenceNb = rs.getInt(7);
String paramValue = loadParamValue(paramId,paramTypeId);
Parameter p = ParameterFactory.create(paramType,
paramName,
paramValue,
paramIsTrkd,
true);
while (parameters.size()<sequenceNb) parameters.add(null);
parameters.set(sequenceNb-1,p);
}
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
finally {
dbConnector.release(rs);
}
return true;
}
/** load ParameterSets */
public boolean loadParameterSets(int superId,ArrayList<Parameter> parameters)
{
ResultSet rs = null;
try {
psSelectParameterSets.setInt(1,superId);
rs = psSelectParameterSets.executeQuery();
while (rs.next()) {
int psetId = rs.getInt(1);
String psetName = rs.getString(2);
boolean psetIsTrkd = rs.getBoolean(3);
int sequenceNb = rs.getInt(5);
PSetParameter pset =
(PSetParameter)ParameterFactory
.create("PSet",psetName,"",psetIsTrkd,true);
ArrayList<Parameter> psetParameters = new ArrayList<Parameter>();
loadParameters(psetId,psetParameters);
for (Parameter p : psetParameters) pset.addParameter(p);
while (parameters.size()<sequenceNb) parameters.add(null);
parameters.set(sequenceNb-1,pset);
}
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
finally {
dbConnector.release(rs);
}
return true;
}
/** load vector<ParameterSet>s */
public boolean loadVecParameterSets(int superId,ArrayList<Parameter> parameters)
{
ResultSet rs = null;
try {
psSelectVecParameterSets.setInt(1,superId);
rs = psSelectVecParameterSets.executeQuery();
while (rs.next()) {
int vpsetId = rs.getInt(1);
String vpsetName = rs.getString(2);
boolean vpsetIsTrkd = rs.getBoolean(3);
int sequenceNb = rs.getInt(5);
VPSetParameter vpset =
(VPSetParameter)ParameterFactory
.create("VPSet",vpsetName,"",vpsetIsTrkd,true);
ArrayList<Parameter> vpsetParameters = new ArrayList<Parameter>();
loadParameterSets(vpsetId,vpsetParameters);
for (Parameter p : vpsetParameters) {
PSetParameter pset = (PSetParameter)p;
vpset.addParameterSet(pset);
}
while (parameters.size()<sequenceNb) parameters.add(null);
parameters.set(sequenceNb-1,vpset);
}
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
finally {
dbConnector.release(rs);
}
return true;
}
/** load *instance* (overwritten) parameters */
public boolean loadInstanceParameters(int instanceId,Instance instance)
{
ResultSet rs = null;
try {
psSelectParameters.setInt(1,instanceId);
rs = psSelectParameters.executeQuery();
while (rs.next()) {
int paramId = rs.getInt(1);
String paramName = rs.getString(2);
int paramTypeId = rs.getInt(4);
String paramValue = loadParamValue(paramId,paramTypeId);
instance.updateParameter(paramName,paramValue);
}
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
finally {
dbConnector.release(rs);
}
return true;
}
/** load *instance* (overwritten) ParameterSets */
public boolean loadInstanceParameterSets(int instanceId,Instance instance)
{
ArrayList<Parameter> psets = new ArrayList<Parameter>();
loadParameterSets(instanceId,psets);
for (Parameter p : psets)
instance.updateParameter(p.name(),p.valueAsString());
return true;
}
/** load *instance* (overwritten) vector<ParameterSet>s */
public boolean loadInstanceVecParameterSets(int instanceId,Instance instance)
{
ArrayList<Parameter> vpsets = new ArrayList<Parameter>();
loadVecParameterSets(instanceId,vpsets);
for (Parameter p : vpsets)
instance.updateParameter(p.name(),p.valueAsString());
return true;
}
/** insert a new directory */
public boolean insertDirectory(Directory dir)
{
boolean result = false;
ResultSet rs = null;
try {
psInsertDirectory.setInt(1,dir.parentDir().dbId());
psInsertDirectory.setString(2,dir.name());
psInsertDirectory.executeUpdate();
rs = psInsertDirectory.getGeneratedKeys();
rs.next();
dir.setDbId(rs.getInt(1));
result = true;
}
catch (SQLException e) {
System.out.println("insertDirectory FAILED: " + e.getMessage());
}
finally {
dbConnector.release(rs);
}
return result;
}
/** insert a new configuration */
public boolean insertConfiguration(Configuration config)
{
boolean result = true;
int configId = 0;
String releaseTag = config.releaseTag();
int releaseId = getReleaseId(releaseTag);
if (releaseId==0) return false;
ResultSet rs = null;
try {
psInsertConfiguration.setString(1,config.name());
psInsertConfiguration.setInt(2,config.parentDirId());
psInsertConfiguration.setInt(3,config.nextVersion());
psInsertConfiguration.executeUpdate();
rs = psInsertConfiguration.getGeneratedKeys();
rs.next();
configId = rs.getInt(1);
psSelectConfiguration.setInt(1,configId);
rs = psSelectConfiguration.executeQuery();
rs.next();
String created = rs.getString(1);
config.addNextVersion(configId,created,releaseTag);
psInsertConfigReleaseAssoc.setInt(1,configId);
psInsertConfigReleaseAssoc.setInt(2,releaseId);
psInsertConfigReleaseAssoc.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
result = false;
}
finally {
dbConnector.release(rs);
}
if (result) {
// insert services
insertServices(configId,config);
// insert edsource
insertEDSources(configId,config);
// insert essources
insertESSources(configId,config);
// insert paths
HashMap<String,Integer> pathHashMap=insertPaths(configId,config);
// insert sequences
HashMap<String,Integer> sequenceHashMap=insertSequences(configId,config);
// insert modules
HashMap<String,Integer> moduleHashMap=insertModules(config);
// insert references regarding paths and sequences
insertReferences(config,pathHashMap,sequenceHashMap,moduleHashMap);
}
return result;
}
/** insert a new super id, return its value */
private int insertSuperId()
{
int result = 0;
ResultSet rs = null;
try {
psInsertSuperId.executeUpdate();
rs = psInsertSuperId.getGeneratedKeys();
rs.next();
result = rs.getInt(1);
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return result;
}
/** insert configuration's services */
private boolean insertServices(int configId,Configuration config)
{
for (int sequenceNb=0;sequenceNb<config.serviceCount();sequenceNb++) {
ServiceInstance service = config.service(sequenceNb);
int superId = insertSuperId();
int templateId = service.template().dbSuperId();
try {
psInsertService.setInt(1,superId);
psInsertService.setInt(2,templateId);
psInsertService.setInt(3,configId);
psInsertService.setInt(4,sequenceNb);
psInsertService.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
if (!insertInstanceParameters(superId,service)) return false;
}
return true;
}
/** insert configuration's edsoures */
private boolean insertEDSources(int configId,Configuration config)
{
for (int sequenceNb=0;sequenceNb<config.edsourceCount();sequenceNb++) {
EDSourceInstance edsource = config.edsource(sequenceNb);
int superId = insertSuperId();
int templateId = edsource.template().dbSuperId();
try {
psInsertEDSource.setInt(1,superId);
psInsertEDSource.setInt(2,templateId);
psInsertEDSource.setInt(3,configId);
psInsertEDSource.setInt(4,sequenceNb);
psInsertEDSource.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
if (!insertInstanceParameters(superId,edsource)) return false;
}
return true;
}
/** insert configuration's essources */
private boolean insertESSources(int configId,Configuration config)
{
for (int sequenceNb=0;sequenceNb<config.essourceCount();sequenceNb++) {
ESSourceInstance essource = config.essource(sequenceNb);
int superId = insertSuperId();
int templateId = essource.template().dbSuperId();
try {
psInsertESSource.setInt(1,superId);
psInsertESSource.setInt(2,templateId);
psInsertESSource.setInt(3,configId);
psInsertESSource.setString(4,essource.name());
psInsertESSource.setInt(5,sequenceNb);
psInsertESSource.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
if (!insertInstanceParameters(superId,essource)) return false;
}
return true;
}
/** insert configuration's paths */
private HashMap<String,Integer> insertPaths(int configId,Configuration config)
{
HashMap<String,Integer> result = new HashMap<String,Integer>();
ResultSet rs = null;
try {
for (int i=0;i<config.pathCount();i++) {
Path path = config.path(i);
psInsertPath.setInt(1,configId);
psInsertPath.setString(2,path.name());
psInsertPath.setInt(3,i);
psInsertPath.executeUpdate();
rs = psInsertPath.getGeneratedKeys();
rs.next();
result.put(path.name(),rs.getInt(1));
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return result;
}
/** insert configuration's sequences */
private HashMap<String,Integer> insertSequences(int configId,Configuration config)
{
HashMap<String,Integer> result = new HashMap<String,Integer>();
ResultSet rs = null;
try {
for (int i=0;i<config.sequenceCount();i++) {
Sequence sequence = config.sequence(i);
psInsertSequence.setInt(1,configId);
psInsertSequence.setString(2,sequence.name());
psInsertSequence.executeUpdate();
rs = psInsertSequence.getGeneratedKeys();
rs.next();
result.put(sequence.name(),rs.getInt(1));
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return result;
}
/** insert configuration's modules */
private HashMap<String,Integer> insertModules(Configuration config)
{
HashMap<String,Integer> result = new HashMap<String,Integer>();
for (int i=0;i<config.moduleCount();i++) {
ModuleInstance module = config.module(i);
int superId = insertSuperId();
int templateId = module.template().dbSuperId();
try {
psInsertModule.setInt(1,superId);
psInsertModule.setInt(2,templateId);
psInsertModule.setString(3,module.name());
psInsertModule.executeUpdate();
result.put(module.name(),superId);
}
catch (SQLException e) {
e.printStackTrace();
}
if (!insertInstanceParameters(superId,module))
System.out.println("CfgDatabase.insertModules ERROR: " +
"failed to insert instance parameters "+
"for module '"+module.name()+"'");
}
return result;
}
/** insert all references, regarding paths and sequences */
private boolean insertReferences(Configuration config,
HashMap<String,Integer> pathHashMap,
HashMap<String,Integer> sequenceHashMap,
HashMap<String,Integer> moduleHashMap)
{
// paths
for (int i=0;i<config.pathCount();i++) {
Path path = config.path(i);
int pathId = pathHashMap.get(path.name());
for (int sequenceNb=0;sequenceNb<path.entryCount();sequenceNb++) {
Reference r = path.entry(sequenceNb);
if (r instanceof PathReference) {
int childPathId = pathHashMap.get(r.name());
try {
psInsertPathPathAssoc.setInt(1,pathId);
psInsertPathPathAssoc.setInt(2,childPathId);
psInsertPathPathAssoc.setInt(3,sequenceNb);
psInsertPathPathAssoc.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
}
else if (r instanceof SequenceReference) {
int sequenceId = sequenceHashMap.get(r.name());
try {
psInsertPathSequenceAssoc.setInt(1,pathId);
psInsertPathSequenceAssoc.setInt(2,sequenceId);
psInsertPathSequenceAssoc.setInt(3,sequenceNb);
psInsertPathSequenceAssoc.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
}
else if (r instanceof ModuleReference) {
int moduleId = moduleHashMap.get(r.name());
try {
psInsertPathModuleAssoc.setInt(1,pathId);
psInsertPathModuleAssoc.setInt(2,moduleId);
psInsertPathModuleAssoc.setInt(3,sequenceNb);
psInsertPathModuleAssoc.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
// sequences
for (int i=0;i<config.sequenceCount();i++) {
Sequence sequence = config.sequence(i);
int sequenceId = sequenceHashMap.get(sequence.name());
for (int sequenceNb=0;sequenceNb<sequence.entryCount();sequenceNb++) {
ModuleReference m = (ModuleReference)sequence.entry(sequenceNb);
int moduleId = moduleHashMap.get(m.name());
try {
psInsertSequenceModuleAssoc.setInt(1,sequenceId);
psInsertSequenceModuleAssoc.setInt(2,moduleId);
psInsertSequenceModuleAssoc.setInt(3,sequenceNb);
psInsertSequenceModuleAssoc.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
return true;
}
/** insert all instance parameters */
private boolean insertInstanceParameters(int superId,Instance instance)
{
for (int sequenceNb=0;sequenceNb<instance.parameterCount();sequenceNb++) {
Parameter p = instance.parameter(sequenceNb);
if (!p.isDefault()) {
if (p instanceof VPSetParameter) {
VPSetParameter vpset = (VPSetParameter)p;
if (!insertVecParameterSet(superId,sequenceNb,vpset))
return false;
}
else if (p instanceof PSetParameter) {
PSetParameter pset = (PSetParameter)p;
if (!insertParameterSet(superId,sequenceNb,pset)) return false;
}
else {
if (!insertParameter(superId,sequenceNb,p)) return false;
}
}
}
return true;
}
/** add a template for a service, edsource, essource, or module */
public boolean insertTemplate(Template template,String releaseTag)
{
// check if the template already exists
String templateTable = templateTableNameHashMap.get(template.type());
int sid = tableHasEntry(templateTable,template);
if (sid>0) {
if (!areAssociated(sid,releaseTag)) {
insertSuperIdReleaseAssoc(sid,releaseTag);
return true;
}
return false;
}
// insert a new template
int superId = insertSuperId();
PreparedStatement psInsertTemplate = null;
if (templateTable.equals(tableServiceTemplates))
psInsertTemplate = psInsertServiceTemplate;
else if (templateTable.equals(tableEDSourceTemplates))
psInsertTemplate = psInsertEDSourceTemplate;
else if (templateTable.equals(tableESSourceTemplates))
psInsertTemplate = psInsertESSourceTemplate;
else if (templateTable.equals(tableModuleTemplates))
psInsertTemplate = psInsertModuleTemplate;
try {
psInsertTemplate.setInt(1,superId);
if (templateTable.equals(tableModuleTemplates)) {
psInsertTemplate.setInt(2,moduleTypeIdHashMap.get(template.type()));
psInsertTemplate.setString(3,template.name());
psInsertTemplate.setString(4,template.cvsTag());
}
else {
psInsertTemplate.setString(2,template.name());
psInsertTemplate.setString(3,template.cvsTag());
}
psInsertTemplate.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
// insert the template parameters
for (int sequenceNb=0;sequenceNb<template.parameterCount();sequenceNb++) {
Parameter p = template.parameter(sequenceNb);
if (p instanceof VPSetParameter) {
VPSetParameter vpset = (VPSetParameter)p;
if (!insertVecParameterSet(superId,sequenceNb,vpset)) return false;
}
else if (p instanceof PSetParameter) {
PSetParameter pset = (PSetParameter)p;
if (!insertParameterSet(superId,sequenceNb,pset)) return false;
}
else {
if (!insertParameter(superId,sequenceNb,p)) return false;
}
}
insertSuperIdReleaseAssoc(superId,releaseTag);
template.setDbSuperId(superId);
return true;
}
/** get all configuration names */
public String[] getConfigNames()
{
ArrayList<String> listOfNames = new ArrayList<String>();
ResultSet rs = null;
try {
rs = psSelectConfigNames.executeQuery();
while (rs.next()) listOfNames.add(rs.getString(2));
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return listOfNames.toArray(new String[listOfNames.size()]);
}
/** get list of software release tags */
public String[] getReleaseTags()
{
ArrayList<String> listOfTags = new ArrayList<String>();
listOfTags.add(new String());
ResultSet rs = null;
try {
rs = psSelectReleaseTags.executeQuery();
while (rs.next()) {
String releaseTag = rs.getString(2);
if (!listOfTags.contains(releaseTag)) listOfTags.add(releaseTag);
}
}
catch (SQLException e) { e.printStackTrace(); }
return listOfTags.toArray(new String[listOfTags.size()]);
}
//
// private member functions
//
/** load parameter value */
private String loadParamValue(int paramId,int paramTypeId)
{
String valueAsString = new String();
PreparedStatement psSelectParameterValue =
selectParameterIdHashMap.get(paramTypeId);
ResultSet rs = null;
try {
psSelectParameterValue.setInt(1,paramId);
rs = psSelectParameterValue.executeQuery();
if (isVectorParamHashMap.get(paramTypeId)) {
while (rs.next()) valueAsString += rs.getObject(3).toString() + ", ";
int length = valueAsString.length();
if (length>0) valueAsString = valueAsString.substring(0,length-2);
}
else {
if (rs.next()) valueAsString = rs.getObject(2).toString();
}
}
catch (Exception e) { /* ignore */ }
finally {
dbConnector.release(rs);
}
return valueAsString;
}
/** insert parameter-set into ParameterSets table */
private boolean insertVecParameterSet(int superId,
int sequenceNb,
VPSetParameter vpset)
{
boolean result = false;
int vecParamSetId = insertSuperId();
ResultSet rs = null;
try {
psInsertVecParameterSet.setInt(1,vecParamSetId);
psInsertVecParameterSet.setString(2,vpset.name());
psInsertVecParameterSet.setBoolean(3,vpset.isTracked());
psInsertVecParameterSet.executeUpdate();
for (int i=0;i<vpset.parameterSetCount();i++) {
PSetParameter pset = vpset.parameterSet(i);
insertParameterSet(vecParamSetId,i,pset);
}
result=true;
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
if (result)
if (!insertSuperIdVecParamSetAssoc(superId,vecParamSetId,sequenceNb))
return false;
return result;
}
/** insert parameter-set into ParameterSets table */
private boolean insertParameterSet(int superId,
int sequenceNb,
PSetParameter pset)
{
boolean result = false;
int paramSetId = insertSuperId();
ResultSet rs = null;
try {
psInsertParameterSet.setInt(1,paramSetId);
psInsertParameterSet.setString(2,pset.name());
psInsertParameterSet.setBoolean(3,pset.isTracked());
psInsertParameterSet.executeUpdate();
for (int i=0;i<pset.parameterCount();i++) {
Parameter p = pset.parameter(i);
if (p instanceof PSetParameter) {
PSetParameter ps = (PSetParameter)p;
insertParameterSet(paramSetId,i,ps);
}
else if (p instanceof VPSetParameter) {
VPSetParameter vps = (VPSetParameter)p;
insertVecParameterSet(paramSetId,i,vps);
}
else insertParameter(paramSetId,i,p);
}
result = true;
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
if (result)
if (!insertSuperIdParamSetAssoc(superId,paramSetId,sequenceNb))
return false;
return result;
}
/** insert parameter into Parameters table */
private boolean insertParameter(int superId,
int sequenceNb,
Parameter parameter)
{
boolean result = false;
int paramId = 0;
ResultSet rs = null;
try {
psInsertParameter.setInt(1,paramTypeIdHashMap.get(parameter.type()));
psInsertParameter.setString(2,parameter.name());
psInsertParameter.setBoolean(3,parameter.isTracked());
psInsertParameter.executeUpdate();
rs = psInsertParameter.getGeneratedKeys();
rs.next();
paramId = rs.getInt(1);
result = true;
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
if (result) {
if (!insertSuperIdParamAssoc(superId,paramId,sequenceNb)) return false;
if (!insertParameterValue(paramId,parameter)) return false;
}
return result;
}
/** associate parameter with the service/module superid */
private boolean insertSuperIdParamAssoc(int superId,int paramId,int sequenceNb)
{
boolean result = true;
ResultSet rs = null;
try {
psInsertSuperIdParamAssoc.setInt(1,superId);
psInsertSuperIdParamAssoc.setInt(2,paramId);
psInsertSuperIdParamAssoc.setInt(3,sequenceNb);
psInsertSuperIdParamAssoc.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
result = false;
}
finally {
dbConnector.release(rs);
}
return result;
}
/** associate parameterset with the service/module superid */
private boolean insertSuperIdParamSetAssoc(int superId,int paramSetId,
int sequenceNb)
{
boolean result = true;
ResultSet rs = null;
try {
psInsertSuperIdParamSetAssoc.setInt(1,superId);
psInsertSuperIdParamSetAssoc.setInt(2,paramSetId);
psInsertSuperIdParamSetAssoc.setInt(3,sequenceNb);
psInsertSuperIdParamSetAssoc.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
result = false;
}
finally {
dbConnector.release(rs);
}
return result;
}
/** associate vector<parameterset> with the service/module superid */
private boolean insertSuperIdVecParamSetAssoc(int superId,int vecParamSetId,
int sequenceNb)
{
boolean result = true;
ResultSet rs = null;
try {
psInsertSuperIdVecParamSetAssoc.setInt(1,superId);
psInsertSuperIdVecParamSetAssoc.setInt(2,vecParamSetId);
psInsertSuperIdVecParamSetAssoc.setInt(3,sequenceNb);
psInsertSuperIdVecParamSetAssoc.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
result = false;
}
finally {
dbConnector.release(rs);
}
return result;
}
/** insert a parameter value in the table corresponding to the parameter type */
private boolean insertParameterValue(int paramId,Parameter parameter)
{
if (!parameter.isValueSet()) return (parameter.isTracked()) ? false : true;
PreparedStatement psInsertParameterValue =
insertParameterHashMap.get(parameter.type());
try {
if (parameter instanceof VectorParameter) {
VectorParameter vp = (VectorParameter)parameter;
for (int i=0;i<vp.vectorSize();i++) {
psInsertParameterValue.setInt(1,paramId);
psInsertParameterValue.setInt(2,i);
psInsertParameterValue.setObject(3,vp.value(i));
psInsertParameterValue.executeUpdate();
}
}
else {
ScalarParameter sp = (ScalarParameter)parameter;
psInsertParameterValue.setInt(1,paramId);
psInsertParameterValue.setObject(2,sp.value());
psInsertParameterValue.executeUpdate();
}
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
catch (NullPointerException e) {
System.out.println(e.getMessage());
}
return true;
}
/** associate a template super id with a software release */
private boolean insertSuperIdReleaseAssoc(int superId, String releaseTag)
{
int releaseId = getReleaseId(releaseTag);
if (releaseId==0) return false;
try {
psInsertSuperIdReleaseAssoc.setInt(1,superId);
psInsertSuperIdReleaseAssoc.setInt(2,releaseId);
psInsertSuperIdReleaseAssoc.executeUpdate();;
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
/** get the release id for a release tag */
private int getReleaseId(String releaseTag)
{
int result = 0;
ResultSet rs = null;
try {
psSelectReleaseTag.setString(1,releaseTag);
rs = psSelectReleaseTag.executeQuery();
if (rs.next()) result = rs.getInt(1);
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return result;
}
/** check if a superId is associate with a release Tag */
private boolean areAssociated(int superId, String releaseTag)
{
int releaseId = getReleaseId(releaseTag);
if (releaseId==0) return false;
boolean result = false;
ResultSet rs = null;
try {
psSelectSuperIdReleaseAssoc.setInt(1,superId);
psSelectSuperIdReleaseAssoc.setInt(2,releaseId);
rs = psSelectSuperIdReleaseAssoc.executeQuery();
if (rs.next()) result = true;
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return result;
}
/** check if a template table has an entry for the template already */
private int tableHasEntry(String table, Template template)
{
PreparedStatement psSelectTemplate = null;
if (table.equals(tableServiceTemplates))
psSelectTemplate = psSelectServiceTemplate;
if (table.equals(tableEDSourceTemplates))
psSelectTemplate = psSelectEDSourceTemplate;
if (table.equals(tableESSourceTemplates))
psSelectTemplate = psSelectESSourceTemplate;
if (table.equals(tableModuleTemplates))
psSelectTemplate = psSelectModuleTemplate;
int result = 0;
ResultSet rs = null;
try {
psSelectTemplate.setString(1,template.name());
psSelectTemplate.setString(2,template.cvsTag());
rs = psSelectTemplate.executeQuery();
if (rs.next()) { result = rs.getInt(1); }
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return result;
}
}
| true | true | public boolean prepareStatements()
{
int[] keyColumn = { 1 };
try {
psSelectModuleTypes =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ModuleTypes.typeId," +
" ModuleTypes.type " +
"FROM ModuleTypes");
psSelectParameterTypes =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ParameterTypes.paramTypeId," +
" ParameterTypes.paramType " +
"FROM ParameterTypes");
psSelectDirectories =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Directories.dirId," +
" Directories.parentDirId," +
" Directories.dirName," +
" Directories.created " +
"FROM Directories " +
"ORDER BY Directories.created ASC");
psSelectConfigurationsByDir =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Configurations.configId," +
" Configurations.config," +
" Configurations.version," +
" Configurations.created," +
" SoftwareReleases.releaseTag " +
"FROM Configurations " +
"JOIN ConfigurationReleaseAssoc " +
"ON ConfigurationReleaseAssoc.configId = Configurations.configId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId = ConfigurationReleaseAssoc.releaseId " +
"WHERE Configurations.parentDirId = ? " +
"ORDER BY Configurations.created DESC");
psSelectConfigNames =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Configurations.configId," +
" Configurations.config " +
"FROM Configurations " +
"WHERE version=1 " +
"ORDER BY created DESC");
psSelectConfiguration =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Configurations.created " +
"FROM Configurations " +
"WHERE Configurations.configId = ?");
psSelectReleaseTags =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SoftwareReleases.releaseId," +
" SoftwareReleases.releaseTag " +
"FROM SoftwareReleases " +
"ORDER BY releaseId DESC");
psSelectReleaseTag =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SoftwareReleases.releaseId," +
" SoftwareReleases.releaseTag " +
"FROM SoftwareReleases " +
"WHERE releaseTag = ?");
psSelectSuperIdReleaseAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SuperIdReleaseAssoc.superId," +
" SuperIdReleaseAssoc.releaseId " +
"FROM SuperIdReleaseAssoc " +
"WHERE superId =? AND releaseId = ?");
psSelectServiceTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ServiceTemplates.superId," +
" ServiceTemplates.name," +
" ServiceTemplates.cvstag " +
"FROM ServiceTemplates " +
"WHERE name=? AND cvstag=?");
psSelectServiceTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ServiceTemplates.superId," +
" ServiceTemplates.name," +
" ServiceTemplates.cvstag " +
"FROM ServiceTemplates " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = ServiceTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY ServiceTemplates.name ASC");
psSelectEDSourceTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EDSourceTemplates.superId," +
" EDSourceTemplates.name," +
" EDSourceTemplates.cvstag " +
"FROM EDSourceTemplates " +
"WHERE name=? AND cvstag=?");
psSelectEDSourceTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EDSourceTemplates.superId," +
" EDSourceTemplates.name," +
" EDSourceTemplates.cvstag " +
"FROM EDSourceTemplates " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = EDSourceTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY EDSourceTemplates.name ASC");
psSelectESSourceTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ESSourceTemplates.superId," +
" ESSourceTemplates.name," +
" ESSourceTemplates.cvstag " +
"FROM ESSourceTemplates " +
"WHERE name=? AND cvstag=?");
psSelectESSourceTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ESSourceTemplates.superId," +
" ESSourceTemplates.name," +
" ESSourceTemplates.cvstag " +
"FROM ESSourceTemplates " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = ESSourceTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY ESSourceTemplates.name ASC");
psSelectModuleTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ModuleTemplates.superId," +
" ModuleTemplates.typeId," +
" ModuleTemplates.name," +
" ModuleTemplates.cvstag " +
"FROM ModuleTemplates " +
"WHERE name=? AND cvstag=?");
psSelectModuleTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ModuleTemplates.superId," +
" ModuleTypes.type," +
" ModuleTemplates.name," +
" ModuleTemplates.cvstag " +
"FROM ModuleTemplates " +
"JOIN ModuleTypes " +
"ON ModuleTypes.typeId = ModuleTemplates.typeId " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = ModuleTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY ModuleTemplates.name ASC");
psSelectServices =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Services.superId," +
" Services.templateId," +
" Services.configId," +
" Services.sequenceNb " +
"FROM Services " +
"WHERE configId=? "+
"ORDER BY Services.sequenceNb ASC");
psSelectEDSources =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EDSources.superId," +
" EDSources.templateId," +
" EDSources.configId," +
" EDSources.sequenceNb " +
"FROM EDSources " +
"WHERE configId=? " +
"ORDER BY EDSources.sequenceNb ASC");
psSelectESSources =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ESSources.superId," +
" ESSources.templateId," +
" ESSources.configId," +
" ESSources.name," +
" ESSources.sequenceNb " +
"FROM ESSources " +
"WHERE configId=?" +
"ORDER BY ESSources.sequenceNb ASC");
psSelectPaths =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Paths.pathId," +
" Paths.configId," +
" Paths.name," +
" Paths.sequenceNb, " +
" Paths.isEndPath " +
"FROM Paths " +
"WHERE Paths.configId=? " +
"ORDER BY sequenceNb ASC");
psSelectSequences =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Sequences.sequenceId," +
" Sequences.configId," +
" Sequences.name " +
"FROM Sequences " +
"WHERE Sequences.configId=?");
psSelectModulesFromPaths=
dbConnector.getConnection().prepareStatement
("SELECT" +
" Modules.superId," +
" Modules.templateId," +
" Modules.name," +
" Paths.configId " +
"FROM Modules " +
"JOIN PathModuleAssoc " +
"ON PathModuleAssoc.moduleId = Modules.superId " +
"JOIN Paths " +
"ON Paths.pathId = PathModuleAssoc.pathId " +
"WHERE Paths.configId=?");
psSelectModulesFromSequences=
dbConnector.getConnection().prepareStatement
("SELECT" +
" Modules.superId," +
" Modules.templateId," +
" Modules.name," +
" Paths.configId " +
"FROM Modules " +
"JOIN SequenceModuleAssoc " +
"ON SequenceModuleAssoc.moduleId = Modules.superId " +
"JOIN Sequences " +
"ON Sequences.sequenceId = SequenceModuleAssoc.sequenceId " +
"JOIN PathSequenceAssoc " +
"ON PathSequenceAssoc.sequenceId = Sequences.sequenceId " +
"JOIN Paths " +
"ON Paths.pathId = PathSequenceAssoc.pathId " +
"WHERE Paths.configId=?");
psSelectSequenceModuleAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SequenceModuleAssoc.sequenceId," +
" SequenceModuleAssoc.moduleId," +
" SequenceModuleAssoc.sequenceNb " +
"FROM SequenceModuleAssoc " +
"WHERE SequenceModuleAssoc.sequenceId = ?");
psSelectPathPathAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" PathInPathAssoc.parentPathId," +
" PathInPathAssoc.childPathId," +
" PathInPathAssoc.sequenceNb " +
"FROM PathInPathAssoc " +
"WHERE PathInPathAssoc.parentPathId = ?");
psSelectPathSequenceAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" PathSequenceAssoc.pathId," +
" PathSequenceAssoc.sequenceId," +
" PathSequenceAssoc.sequenceNb " +
"FROM PathSequenceAssoc " +
"WHERE PathSequenceAssoc.pathId = ?");
psSelectPathModuleAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" PathModuleAssoc.pathId," +
" PathModuleAssoc.moduleId," +
" PathModuleAssoc.sequenceNb " +
"FROM PathModuleAssoc " +
"WHERE PathModuleAssoc.pathId = ?");
psSelectParameters =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Parameters.paramId," +
" Parameters.name," +
" Parameters.tracked," +
" Parameters.paramTypeId," +
" ParameterTypes.paramType," +
" SuperIdParameterAssoc.superId," +
" SuperIdParameterAssoc.sequenceNb " +
"FROM Parameters " +
"JOIN SuperIdParameterAssoc " +
"ON SuperIdParameterAssoc.paramId = Parameters.paramId " +
"JOIN ParameterTypes " +
"ON Parameters.paramTypeId = ParameterTypes.paramTypeId " +
"WHERE SuperIdParameterAssoc.superId = ? " +
"ORDER BY SuperIdParameterAssoc.sequenceNb ASC");
psSelectParameterSets =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ParameterSets.superId," +
" ParameterSets.name," +
" ParameterSets.tracked," +
" SuperIdParamSetAssoc.superId," +
" SuperIdParamSetAssoc.sequenceNb " +
"FROM ParameterSets " +
"JOIN SuperIdParamSetAssoc " +
"ON SuperIdParamSetAssoc.paramSetId = ParameterSets.superId " +
"WHERE SuperIdParamSetAssoc.superId = ? " +
"ORDER BY SuperIdParamSetAssoc.sequenceNb ASC");
psSelectVecParameterSets =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VecParameterSets.superId," +
" VecParameterSets.name," +
" VecParameterSets.tracked," +
" SuperIdVecParamSetAssoc.superId," +
" SuperIdVecParamSetAssoc.sequenceNb " +
"FROM VecParameterSets " +
"JOIN SuperIdVecParamSetAssoc " +
"ON SuperIdVecParamSetAssoc.vecParamSetId=VecParameterSets.superId "+
"WHERE SuperIdVecParamSetAssoc.superId = ? "+
"ORDER BY SuperIdVecParamSetAssoc.sequenceNb ASC");
psSelectBoolParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" BoolParamValues.paramId," +
" BoolParamValues.value " +
"FROM BoolParamValues " +
"WHERE paramId = ?");
psSelectInt32ParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Int32ParamValues.paramId," +
" Int32ParamValues.value " +
"FROM Int32ParamValues " +
"WHERE paramId = ?");
psSelectUInt32ParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" UInt32ParamValues.paramId," +
" UInt32ParamValues.value " +
"FROM UInt32ParamValues " +
"WHERE paramId = ?");
psSelectDoubleParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" DoubleParamValues.paramId," +
" DoubleParamValues.value " +
"FROM DoubleParamValues " +
"WHERE paramId = ?");
psSelectStringParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" StringParamValues.paramId," +
" StringParamValues.value " +
"FROM StringParamValues " +
"WHERE paramId = ?");
psSelectEventIDParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EventIDParamValues.paramId," +
" EventIDParamValues.value " +
"FROM EventIDParamValues " +
"WHERE paramId = ?");
psSelectInputTagParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" InputTagParamValues.paramId," +
" InputTagParamValues.value " +
"FROM InputTagParamValues " +
"WHERE paramId = ?");
psSelectVInt32ParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VInt32ParamValues.paramId," +
" VInt32ParamValues.sequenceNb," +
" VInt32ParamValues.value " +
"FROM VInt32ParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVUInt32ParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VUInt32ParamValues.paramId," +
" VUInt32ParamValues.sequenceNb," +
" VUInt32ParamValues.value " +
"FROM VUInt32ParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVDoubleParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VDoubleParamValues.paramId," +
" VDoubleParamValues.sequenceNb," +
" VDoubleParamValues.value " +
"FROM VDoubleParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVStringParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VStringParamValues.paramId," +
" VStringParamValues.sequenceNb," +
" VStringParamValues.value " +
"FROM VStringParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVEventIDParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VEventIDParamValues.paramId," +
" VEventIDParamValues.sequenceNb," +
" VEventIDParamValues.value " +
"FROM VEventIDParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVInputTagParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VInputTagParamValues.paramId," +
" VInputTagParamValues.sequenceNb," +
" VInputTagParamValues.value " +
"FROM VInputTagParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
if (dbType.equals(dbTypeMySQL))
psInsertDirectory =
dbConnector.getConnection().prepareStatement
("INSERT INTO Directories " +
"(parentDirId,dirName,created) " +
"VALUES (?, ?, NOW())",keyColumn);
else if (dbType.equals(dbTypeOracle))
psInsertConfiguration =
dbConnector.getConnection().prepareStatement
("INSERT INTO Directories " +
"(parentDirId,dirName,created) " +
"VALUES (?, ?, SYSDATE)",keyColumn);
if (dbType.equals(dbTypeMySQL))
psInsertConfiguration =
dbConnector.getConnection().prepareStatement
("INSERT INTO Configurations " +
"(config,parentDirId,version,created) " +
"VALUES (?, ?, ?, NOW())",keyColumn);
else if (dbType.equals(dbTypeOracle))
psInsertConfiguration =
dbConnector.getConnection().prepareStatement
("INSERT INTO Configurations " +
"(config,parentDirId,version,created) " +
"VALUES (?, ?, ?, SYSDATE)",keyColumn);
psInsertConfigReleaseAssoc = dbConnector.getConnection().prepareStatement
("INSERT INTO ConfigurationReleaseAssoc (configId,releaseId) " +
"VALUES(?, ?)");
if (dbType.equals(dbTypeMySQL))
psInsertSuperId = dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIds VALUES()",keyColumn);
else if (dbType.equals(dbTypeOracle))
psInsertSuperId = dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIds VALUES('')",keyColumn);
psInsertService =
dbConnector.getConnection().prepareStatement
("INSERT INTO Services (superId,templateId,configId,sequenceNb) " +
"VALUES(?, ?, ?, ?)");
psInsertEDSource =
dbConnector.getConnection().prepareStatement
("INSERT INTO EDSources (superId,templateId,configId,sequenceNb) " +
"VALUES(?, ?, ?, ?)");
psInsertESSource =
dbConnector.getConnection().prepareStatement
("INSERT INTO " +
"ESSources (superId,templateId,configId,name,sequenceNb) " +
"VALUES(?, ?, ?, ?, ?)");
psInsertPath =
dbConnector.getConnection().prepareStatement
("INSERT INTO Paths (configId,name,sequenceNb) " +
"VALUES(?, ?, ?)",keyColumn);
psInsertSequence =
dbConnector.getConnection().prepareStatement
("INSERT INTO Sequences (configId,name) " +
"VALUES(?, ?)",keyColumn);
psInsertModule =
dbConnector.getConnection().prepareStatement
("INSERT INTO Modules (superId,templateId,name) " +
"VALUES(?, ?, ?)");
psInsertSequenceModuleAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SequenceModuleAssoc (sequenceId,moduleId,sequenceNb) "+
"VALUES(?, ?, ?)");
psInsertPathPathAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO PathInPathAssoc(parentPathId,childPathId,sequenceNb) "+
"VALUES(?, ?, ?)");
psInsertPathSequenceAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO PathSequenceAssoc (pathId,sequenceId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertPathModuleAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO PathModuleAssoc (pathId,moduleId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertSuperIdReleaseAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIdReleaseAssoc (superId,releaseId) " +
"VALUES(?, ?)");
psInsertServiceTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO ServiceTemplates (superId,name,cvstag) " +
"VALUES (?, ?, ?)");
psInsertEDSourceTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO EDSourceTemplates (superId,name,cvstag) " +
"VALUES (?, ?, ?)");
psInsertESSourceTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO ESSourceTemplates (superId,name,cvstag) " +
"VALUES (?, ?, ?)");
psInsertModuleTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO ModuleTemplates (superId,typeId,name,cvstag) " +
"VALUES (?, ?, ?, ?)");
psInsertParameterSet =
dbConnector.getConnection().prepareStatement
("INSERT INTO ParameterSets(superId,name,tracked) " +
"VALUES(?, ?, ?)");
psInsertVecParameterSet =
dbConnector.getConnection().prepareStatement
("INSERT INTO VecParameterSets(superId,name,tracked) " +
"VALUES(?, ?, ?)");
psInsertParameter =
dbConnector.getConnection().prepareStatement
("INSERT INTO Parameters (paramTypeId,name,tracked) " +
"VALUES(?, ?, ?)",keyColumn);
psInsertSuperIdParamSetAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIdParamSetAssoc (superId,paramSetId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertSuperIdVecParamSetAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO " +
"SuperIdVecParamSetAssoc (superId,vecParamSetId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertSuperIdParamAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIdParameterAssoc (superId,paramId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertBoolParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO BoolParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertInt32ParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO Int32ParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertUInt32ParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO UInt32ParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertDoubleParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO DoubleParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertStringParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO StringParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertEventIDParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO EventIDParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertInputTagParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO InputTagParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertVInt32ParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VInt32ParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVUInt32ParamValue
= dbConnector.getConnection().prepareStatement
("INSERT INTO VUInt32ParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVDoubleParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VDoubleParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVStringParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VStringParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVEventIDParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VEventIDParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVInputTagParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VInputTagParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
// create hash maps
moduleTypeIdHashMap = new HashMap<String,Integer>();
paramTypeIdHashMap = new HashMap<String,Integer>();
isVectorParamHashMap = new HashMap<Integer,Boolean>();
insertParameterHashMap = new HashMap<String,PreparedStatement>();
selectParameterHashMap = new HashMap<String,PreparedStatement>();
selectParameterIdHashMap = new HashMap<Integer,PreparedStatement>();
insertParameterHashMap.put("bool", psInsertBoolParamValue);
insertParameterHashMap.put("int32", psInsertInt32ParamValue);
insertParameterHashMap.put("vint32", psInsertVInt32ParamValue);
insertParameterHashMap.put("uint32", psInsertUInt32ParamValue);
insertParameterHashMap.put("vuint32", psInsertVUInt32ParamValue);
insertParameterHashMap.put("double", psInsertDoubleParamValue);
insertParameterHashMap.put("vdouble", psInsertVDoubleParamValue);
insertParameterHashMap.put("string", psInsertStringParamValue);
insertParameterHashMap.put("vstring", psInsertVStringParamValue);
insertParameterHashMap.put("EventID", psInsertEventIDParamValue);
insertParameterHashMap.put("VEventID", psInsertVEventIDParamValue);
insertParameterHashMap.put("InputTag", psInsertInputTagParamValue);
insertParameterHashMap.put("VInputTag",psInsertVInputTagParamValue);
selectParameterHashMap.put("bool", psSelectBoolParamValue);
selectParameterHashMap.put("int32", psSelectInt32ParamValue);
selectParameterHashMap.put("vint32", psSelectVInt32ParamValues);
selectParameterHashMap.put("uint32", psSelectUInt32ParamValue);
selectParameterHashMap.put("vuint32", psSelectVUInt32ParamValues);
selectParameterHashMap.put("double", psSelectDoubleParamValue);
selectParameterHashMap.put("vdouble", psSelectVDoubleParamValues);
selectParameterHashMap.put("string", psSelectStringParamValue);
selectParameterHashMap.put("vstring", psSelectVStringParamValues);
selectParameterHashMap.put("EventID", psSelectEventIDParamValue);
selectParameterHashMap.put("VEventID", psSelectVEventIDParamValues);
selectParameterHashMap.put("InputTag", psSelectInputTagParamValue);
selectParameterHashMap.put("VInputTag",psSelectVInputTagParamValues);
ResultSet rs = null;
try {
rs = psSelectModuleTypes.executeQuery();
while (rs.next()) {
int typeId = rs.getInt(1);
String type = rs.getString(2);
moduleTypeIdHashMap.put(type,typeId);
templateTableNameHashMap.put(type,tableModuleTemplates);
}
rs = psSelectParameterTypes.executeQuery();
while (rs.next()) {
int typeId = rs.getInt(1);
String type = rs.getString(2);
PreparedStatement ps = selectParameterHashMap.get(type);
paramTypeIdHashMap.put(type,typeId);
selectParameterIdHashMap.put(typeId,ps);
if (type.startsWith("v")||type.startsWith("V"))
isVectorParamHashMap.put(typeId,true);
else
isVectorParamHashMap.put(typeId,false);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return true;
}
| public boolean prepareStatements()
{
int[] keyColumn = { 1 };
try {
psSelectModuleTypes =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ModuleTypes.typeId," +
" ModuleTypes.type " +
"FROM ModuleTypes");
psSelectParameterTypes =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ParameterTypes.paramTypeId," +
" ParameterTypes.paramType " +
"FROM ParameterTypes");
psSelectDirectories =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Directories.dirId," +
" Directories.parentDirId," +
" Directories.dirName," +
" Directories.created " +
"FROM Directories " +
"ORDER BY Directories.created ASC");
psSelectConfigurationsByDir =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Configurations.configId," +
" Configurations.config," +
" Configurations.version," +
" Configurations.created," +
" SoftwareReleases.releaseTag " +
"FROM Configurations " +
"JOIN ConfigurationReleaseAssoc " +
"ON ConfigurationReleaseAssoc.configId = Configurations.configId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId = ConfigurationReleaseAssoc.releaseId " +
"WHERE Configurations.parentDirId = ? " +
"ORDER BY Configurations.created DESC");
psSelectConfigNames =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Configurations.configId," +
" Configurations.config " +
"FROM Configurations " +
"WHERE version=1 " +
"ORDER BY created DESC");
psSelectConfiguration =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Configurations.created " +
"FROM Configurations " +
"WHERE Configurations.configId = ?");
psSelectReleaseTags =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SoftwareReleases.releaseId," +
" SoftwareReleases.releaseTag " +
"FROM SoftwareReleases " +
"ORDER BY releaseId DESC");
psSelectReleaseTag =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SoftwareReleases.releaseId," +
" SoftwareReleases.releaseTag " +
"FROM SoftwareReleases " +
"WHERE releaseTag = ?");
psSelectSuperIdReleaseAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SuperIdReleaseAssoc.superId," +
" SuperIdReleaseAssoc.releaseId " +
"FROM SuperIdReleaseAssoc " +
"WHERE superId =? AND releaseId = ?");
psSelectServiceTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ServiceTemplates.superId," +
" ServiceTemplates.name," +
" ServiceTemplates.cvstag " +
"FROM ServiceTemplates " +
"WHERE name=? AND cvstag=?");
psSelectServiceTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ServiceTemplates.superId," +
" ServiceTemplates.name," +
" ServiceTemplates.cvstag " +
"FROM ServiceTemplates " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = ServiceTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY ServiceTemplates.name ASC");
psSelectEDSourceTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EDSourceTemplates.superId," +
" EDSourceTemplates.name," +
" EDSourceTemplates.cvstag " +
"FROM EDSourceTemplates " +
"WHERE name=? AND cvstag=?");
psSelectEDSourceTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EDSourceTemplates.superId," +
" EDSourceTemplates.name," +
" EDSourceTemplates.cvstag " +
"FROM EDSourceTemplates " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = EDSourceTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY EDSourceTemplates.name ASC");
psSelectESSourceTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ESSourceTemplates.superId," +
" ESSourceTemplates.name," +
" ESSourceTemplates.cvstag " +
"FROM ESSourceTemplates " +
"WHERE name=? AND cvstag=?");
psSelectESSourceTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ESSourceTemplates.superId," +
" ESSourceTemplates.name," +
" ESSourceTemplates.cvstag " +
"FROM ESSourceTemplates " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = ESSourceTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY ESSourceTemplates.name ASC");
psSelectModuleTemplate =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ModuleTemplates.superId," +
" ModuleTemplates.typeId," +
" ModuleTemplates.name," +
" ModuleTemplates.cvstag " +
"FROM ModuleTemplates " +
"WHERE name=? AND cvstag=?");
psSelectModuleTemplatesByRelease =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ModuleTemplates.superId," +
" ModuleTypes.type," +
" ModuleTemplates.name," +
" ModuleTemplates.cvstag " +
"FROM ModuleTemplates " +
"JOIN ModuleTypes " +
"ON ModuleTypes.typeId = ModuleTemplates.typeId " +
"JOIN SuperIdReleaseAssoc " +
"ON SuperIdReleaseAssoc.superId = ModuleTemplates.superId " +
"JOIN SoftwareReleases " +
"ON SoftwareReleases.releaseId=SuperIdReleaseAssoc.releaseId " +
"WHERE SoftwareReleases.releaseTag = ? " +
"ORDER BY ModuleTemplates.name ASC");
psSelectServices =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Services.superId," +
" Services.templateId," +
" Services.configId," +
" Services.sequenceNb " +
"FROM Services " +
"WHERE configId=? "+
"ORDER BY Services.sequenceNb ASC");
psSelectEDSources =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EDSources.superId," +
" EDSources.templateId," +
" EDSources.configId," +
" EDSources.sequenceNb " +
"FROM EDSources " +
"WHERE configId=? " +
"ORDER BY EDSources.sequenceNb ASC");
psSelectESSources =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ESSources.superId," +
" ESSources.templateId," +
" ESSources.configId," +
" ESSources.name," +
" ESSources.sequenceNb " +
"FROM ESSources " +
"WHERE configId=? " +
"ORDER BY ESSources.sequenceNb ASC");
psSelectPaths =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Paths.pathId," +
" Paths.configId," +
" Paths.name," +
" Paths.sequenceNb, " +
" Paths.isEndPath " +
"FROM Paths " +
"WHERE Paths.configId=? " +
"ORDER BY sequenceNb ASC");
psSelectSequences =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Sequences.sequenceId," +
" Sequences.configId," +
" Sequences.name " +
"FROM Sequences " +
"WHERE Sequences.configId=?");
psSelectModulesFromPaths=
dbConnector.getConnection().prepareStatement
("SELECT" +
" Modules.superId," +
" Modules.templateId," +
" Modules.name," +
" Paths.configId " +
"FROM Modules " +
"JOIN PathModuleAssoc " +
"ON PathModuleAssoc.moduleId = Modules.superId " +
"JOIN Paths " +
"ON Paths.pathId = PathModuleAssoc.pathId " +
"WHERE Paths.configId=?");
psSelectModulesFromSequences=
dbConnector.getConnection().prepareStatement
("SELECT" +
" Modules.superId," +
" Modules.templateId," +
" Modules.name," +
" Paths.configId " +
"FROM Modules " +
"JOIN SequenceModuleAssoc " +
"ON SequenceModuleAssoc.moduleId = Modules.superId " +
"JOIN Sequences " +
"ON Sequences.sequenceId = SequenceModuleAssoc.sequenceId " +
"JOIN PathSequenceAssoc " +
"ON PathSequenceAssoc.sequenceId = Sequences.sequenceId " +
"JOIN Paths " +
"ON Paths.pathId = PathSequenceAssoc.pathId " +
"WHERE Paths.configId=?");
psSelectSequenceModuleAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" SequenceModuleAssoc.sequenceId," +
" SequenceModuleAssoc.moduleId," +
" SequenceModuleAssoc.sequenceNb " +
"FROM SequenceModuleAssoc " +
"WHERE SequenceModuleAssoc.sequenceId = ?");
psSelectPathPathAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" PathInPathAssoc.parentPathId," +
" PathInPathAssoc.childPathId," +
" PathInPathAssoc.sequenceNb " +
"FROM PathInPathAssoc " +
"WHERE PathInPathAssoc.parentPathId = ?");
psSelectPathSequenceAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" PathSequenceAssoc.pathId," +
" PathSequenceAssoc.sequenceId," +
" PathSequenceAssoc.sequenceNb " +
"FROM PathSequenceAssoc " +
"WHERE PathSequenceAssoc.pathId = ?");
psSelectPathModuleAssoc =
dbConnector.getConnection().prepareStatement
("SELECT" +
" PathModuleAssoc.pathId," +
" PathModuleAssoc.moduleId," +
" PathModuleAssoc.sequenceNb " +
"FROM PathModuleAssoc " +
"WHERE PathModuleAssoc.pathId = ?");
psSelectParameters =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Parameters.paramId," +
" Parameters.name," +
" Parameters.tracked," +
" Parameters.paramTypeId," +
" ParameterTypes.paramType," +
" SuperIdParameterAssoc.superId," +
" SuperIdParameterAssoc.sequenceNb " +
"FROM Parameters " +
"JOIN SuperIdParameterAssoc " +
"ON SuperIdParameterAssoc.paramId = Parameters.paramId " +
"JOIN ParameterTypes " +
"ON Parameters.paramTypeId = ParameterTypes.paramTypeId " +
"WHERE SuperIdParameterAssoc.superId = ? " +
"ORDER BY SuperIdParameterAssoc.sequenceNb ASC");
psSelectParameterSets =
dbConnector.getConnection().prepareStatement
("SELECT" +
" ParameterSets.superId," +
" ParameterSets.name," +
" ParameterSets.tracked," +
" SuperIdParamSetAssoc.superId," +
" SuperIdParamSetAssoc.sequenceNb " +
"FROM ParameterSets " +
"JOIN SuperIdParamSetAssoc " +
"ON SuperIdParamSetAssoc.paramSetId = ParameterSets.superId " +
"WHERE SuperIdParamSetAssoc.superId = ? " +
"ORDER BY SuperIdParamSetAssoc.sequenceNb ASC");
psSelectVecParameterSets =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VecParameterSets.superId," +
" VecParameterSets.name," +
" VecParameterSets.tracked," +
" SuperIdVecParamSetAssoc.superId," +
" SuperIdVecParamSetAssoc.sequenceNb " +
"FROM VecParameterSets " +
"JOIN SuperIdVecParamSetAssoc " +
"ON SuperIdVecParamSetAssoc.vecParamSetId=VecParameterSets.superId "+
"WHERE SuperIdVecParamSetAssoc.superId = ? "+
"ORDER BY SuperIdVecParamSetAssoc.sequenceNb ASC");
psSelectBoolParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" BoolParamValues.paramId," +
" BoolParamValues.value " +
"FROM BoolParamValues " +
"WHERE paramId = ?");
psSelectInt32ParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" Int32ParamValues.paramId," +
" Int32ParamValues.value " +
"FROM Int32ParamValues " +
"WHERE paramId = ?");
psSelectUInt32ParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" UInt32ParamValues.paramId," +
" UInt32ParamValues.value " +
"FROM UInt32ParamValues " +
"WHERE paramId = ?");
psSelectDoubleParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" DoubleParamValues.paramId," +
" DoubleParamValues.value " +
"FROM DoubleParamValues " +
"WHERE paramId = ?");
psSelectStringParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" StringParamValues.paramId," +
" StringParamValues.value " +
"FROM StringParamValues " +
"WHERE paramId = ?");
psSelectEventIDParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" EventIDParamValues.paramId," +
" EventIDParamValues.value " +
"FROM EventIDParamValues " +
"WHERE paramId = ?");
psSelectInputTagParamValue =
dbConnector.getConnection().prepareStatement
("SELECT" +
" InputTagParamValues.paramId," +
" InputTagParamValues.value " +
"FROM InputTagParamValues " +
"WHERE paramId = ?");
psSelectVInt32ParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VInt32ParamValues.paramId," +
" VInt32ParamValues.sequenceNb," +
" VInt32ParamValues.value " +
"FROM VInt32ParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVUInt32ParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VUInt32ParamValues.paramId," +
" VUInt32ParamValues.sequenceNb," +
" VUInt32ParamValues.value " +
"FROM VUInt32ParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVDoubleParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VDoubleParamValues.paramId," +
" VDoubleParamValues.sequenceNb," +
" VDoubleParamValues.value " +
"FROM VDoubleParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVStringParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VStringParamValues.paramId," +
" VStringParamValues.sequenceNb," +
" VStringParamValues.value " +
"FROM VStringParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVEventIDParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VEventIDParamValues.paramId," +
" VEventIDParamValues.sequenceNb," +
" VEventIDParamValues.value " +
"FROM VEventIDParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
psSelectVInputTagParamValues =
dbConnector.getConnection().prepareStatement
("SELECT" +
" VInputTagParamValues.paramId," +
" VInputTagParamValues.sequenceNb," +
" VInputTagParamValues.value " +
"FROM VInputTagParamValues " +
"WHERE paramId = ? " +
"ORDER BY sequenceNb ASC");
if (dbType.equals(dbTypeMySQL))
psInsertDirectory =
dbConnector.getConnection().prepareStatement
("INSERT INTO Directories " +
"(parentDirId,dirName,created) " +
"VALUES (?, ?, NOW())",keyColumn);
else if (dbType.equals(dbTypeOracle))
psInsertConfiguration =
dbConnector.getConnection().prepareStatement
("INSERT INTO Directories " +
"(parentDirId,dirName,created) " +
"VALUES (?, ?, SYSDATE)",keyColumn);
if (dbType.equals(dbTypeMySQL))
psInsertConfiguration =
dbConnector.getConnection().prepareStatement
("INSERT INTO Configurations " +
"(config,parentDirId,version,created) " +
"VALUES (?, ?, ?, NOW())",keyColumn);
else if (dbType.equals(dbTypeOracle))
psInsertConfiguration =
dbConnector.getConnection().prepareStatement
("INSERT INTO Configurations " +
"(config,parentDirId,version,created) " +
"VALUES (?, ?, ?, SYSDATE)",keyColumn);
psInsertConfigReleaseAssoc = dbConnector.getConnection().prepareStatement
("INSERT INTO ConfigurationReleaseAssoc (configId,releaseId) " +
"VALUES(?, ?)");
if (dbType.equals(dbTypeMySQL))
psInsertSuperId = dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIds VALUES()",keyColumn);
else if (dbType.equals(dbTypeOracle))
psInsertSuperId = dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIds VALUES('')",keyColumn);
psInsertService =
dbConnector.getConnection().prepareStatement
("INSERT INTO Services (superId,templateId,configId,sequenceNb) " +
"VALUES(?, ?, ?, ?)");
psInsertEDSource =
dbConnector.getConnection().prepareStatement
("INSERT INTO EDSources (superId,templateId,configId,sequenceNb) " +
"VALUES(?, ?, ?, ?)");
psInsertESSource =
dbConnector.getConnection().prepareStatement
("INSERT INTO " +
"ESSources (superId,templateId,configId,name,sequenceNb) " +
"VALUES(?, ?, ?, ?, ?)");
psInsertPath =
dbConnector.getConnection().prepareStatement
("INSERT INTO Paths (configId,name,sequenceNb) " +
"VALUES(?, ?, ?)",keyColumn);
psInsertSequence =
dbConnector.getConnection().prepareStatement
("INSERT INTO Sequences (configId,name) " +
"VALUES(?, ?)",keyColumn);
psInsertModule =
dbConnector.getConnection().prepareStatement
("INSERT INTO Modules (superId,templateId,name) " +
"VALUES(?, ?, ?)");
psInsertSequenceModuleAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SequenceModuleAssoc (sequenceId,moduleId,sequenceNb) "+
"VALUES(?, ?, ?)");
psInsertPathPathAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO PathInPathAssoc(parentPathId,childPathId,sequenceNb) "+
"VALUES(?, ?, ?)");
psInsertPathSequenceAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO PathSequenceAssoc (pathId,sequenceId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertPathModuleAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO PathModuleAssoc (pathId,moduleId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertSuperIdReleaseAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIdReleaseAssoc (superId,releaseId) " +
"VALUES(?, ?)");
psInsertServiceTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO ServiceTemplates (superId,name,cvstag) " +
"VALUES (?, ?, ?)");
psInsertEDSourceTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO EDSourceTemplates (superId,name,cvstag) " +
"VALUES (?, ?, ?)");
psInsertESSourceTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO ESSourceTemplates (superId,name,cvstag) " +
"VALUES (?, ?, ?)");
psInsertModuleTemplate =
dbConnector.getConnection().prepareStatement
("INSERT INTO ModuleTemplates (superId,typeId,name,cvstag) " +
"VALUES (?, ?, ?, ?)");
psInsertParameterSet =
dbConnector.getConnection().prepareStatement
("INSERT INTO ParameterSets(superId,name,tracked) " +
"VALUES(?, ?, ?)");
psInsertVecParameterSet =
dbConnector.getConnection().prepareStatement
("INSERT INTO VecParameterSets(superId,name,tracked) " +
"VALUES(?, ?, ?)");
psInsertParameter =
dbConnector.getConnection().prepareStatement
("INSERT INTO Parameters (paramTypeId,name,tracked) " +
"VALUES(?, ?, ?)",keyColumn);
psInsertSuperIdParamSetAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIdParamSetAssoc (superId,paramSetId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertSuperIdVecParamSetAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO " +
"SuperIdVecParamSetAssoc (superId,vecParamSetId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertSuperIdParamAssoc =
dbConnector.getConnection().prepareStatement
("INSERT INTO SuperIdParameterAssoc (superId,paramId,sequenceNb) " +
"VALUES(?, ?, ?)");
psInsertBoolParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO BoolParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertInt32ParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO Int32ParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertUInt32ParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO UInt32ParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertDoubleParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO DoubleParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertStringParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO StringParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertEventIDParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO EventIDParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertInputTagParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO InputTagParamValues (paramId,value) " +
"VALUES (?, ?)");
psInsertVInt32ParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VInt32ParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVUInt32ParamValue
= dbConnector.getConnection().prepareStatement
("INSERT INTO VUInt32ParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVDoubleParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VDoubleParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVStringParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VStringParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVEventIDParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VEventIDParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
psInsertVInputTagParamValue =
dbConnector.getConnection().prepareStatement
("INSERT INTO VInputTagParamValues (paramId,sequenceNb,value) " +
"VALUES (?, ?, ?)");
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
// create hash maps
moduleTypeIdHashMap = new HashMap<String,Integer>();
paramTypeIdHashMap = new HashMap<String,Integer>();
isVectorParamHashMap = new HashMap<Integer,Boolean>();
insertParameterHashMap = new HashMap<String,PreparedStatement>();
selectParameterHashMap = new HashMap<String,PreparedStatement>();
selectParameterIdHashMap = new HashMap<Integer,PreparedStatement>();
insertParameterHashMap.put("bool", psInsertBoolParamValue);
insertParameterHashMap.put("int32", psInsertInt32ParamValue);
insertParameterHashMap.put("vint32", psInsertVInt32ParamValue);
insertParameterHashMap.put("uint32", psInsertUInt32ParamValue);
insertParameterHashMap.put("vuint32", psInsertVUInt32ParamValue);
insertParameterHashMap.put("double", psInsertDoubleParamValue);
insertParameterHashMap.put("vdouble", psInsertVDoubleParamValue);
insertParameterHashMap.put("string", psInsertStringParamValue);
insertParameterHashMap.put("vstring", psInsertVStringParamValue);
insertParameterHashMap.put("EventID", psInsertEventIDParamValue);
insertParameterHashMap.put("VEventID", psInsertVEventIDParamValue);
insertParameterHashMap.put("InputTag", psInsertInputTagParamValue);
insertParameterHashMap.put("VInputTag",psInsertVInputTagParamValue);
selectParameterHashMap.put("bool", psSelectBoolParamValue);
selectParameterHashMap.put("int32", psSelectInt32ParamValue);
selectParameterHashMap.put("vint32", psSelectVInt32ParamValues);
selectParameterHashMap.put("uint32", psSelectUInt32ParamValue);
selectParameterHashMap.put("vuint32", psSelectVUInt32ParamValues);
selectParameterHashMap.put("double", psSelectDoubleParamValue);
selectParameterHashMap.put("vdouble", psSelectVDoubleParamValues);
selectParameterHashMap.put("string", psSelectStringParamValue);
selectParameterHashMap.put("vstring", psSelectVStringParamValues);
selectParameterHashMap.put("EventID", psSelectEventIDParamValue);
selectParameterHashMap.put("VEventID", psSelectVEventIDParamValues);
selectParameterHashMap.put("InputTag", psSelectInputTagParamValue);
selectParameterHashMap.put("VInputTag",psSelectVInputTagParamValues);
ResultSet rs = null;
try {
rs = psSelectModuleTypes.executeQuery();
while (rs.next()) {
int typeId = rs.getInt(1);
String type = rs.getString(2);
moduleTypeIdHashMap.put(type,typeId);
templateTableNameHashMap.put(type,tableModuleTemplates);
}
rs = psSelectParameterTypes.executeQuery();
while (rs.next()) {
int typeId = rs.getInt(1);
String type = rs.getString(2);
PreparedStatement ps = selectParameterHashMap.get(type);
paramTypeIdHashMap.put(type,typeId);
selectParameterIdHashMap.put(typeId,ps);
if (type.startsWith("v")||type.startsWith("V"))
isVectorParamHashMap.put(typeId,true);
else
isVectorParamHashMap.put(typeId,false);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
dbConnector.release(rs);
}
return true;
}
|
diff --git a/common/logisticspipes/logic/BaseLogicCrafting.java b/common/logisticspipes/logic/BaseLogicCrafting.java
index 1c111c82..99760287 100644
--- a/common/logisticspipes/logic/BaseLogicCrafting.java
+++ b/common/logisticspipes/logic/BaseLogicCrafting.java
@@ -1,316 +1,317 @@
package logisticspipes.logic;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import logisticspipes.LogisticsPipes;
import logisticspipes.interfaces.routing.IRequireReliableTransport;
import logisticspipes.network.GuiIDs;
import logisticspipes.network.NetworkConstants;
import logisticspipes.network.packets.PacketCoordinates;
import logisticspipes.network.packets.PacketInventoryChange;
import logisticspipes.network.packets.PacketPipeInteger;
import logisticspipes.pipes.basic.RoutedPipe;
import logisticspipes.proxy.MainProxy;
import logisticspipes.proxy.SimpleServiceLocator;
import logisticspipes.proxy.interfaces.ICraftingRecipeProvider;
import logisticspipes.request.RequestManager;
import logisticspipes.routing.IRouter;
import logisticspipes.utils.AdjacentTile;
import logisticspipes.utils.ItemIdentifier;
import logisticspipes.utils.SimpleInventory;
import logisticspipes.utils.WorldUtil;
import net.minecraft.src.Block;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.IInventory;
import net.minecraft.src.ItemStack;
import net.minecraft.src.NBTTagCompound;
import buildcraft.api.core.Orientations;
import buildcraft.core.network.TileNetworkData;
import buildcraft.transport.TileGenericPipe;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;
public class BaseLogicCrafting extends BaseRoutingLogic implements IRequireReliableTransport {
protected SimpleInventory _dummyInventory = new SimpleInventory(10, "Requested items", 127);
@TileNetworkData
public int signEntityX = 0;
@TileNetworkData
public int signEntityY = 0;
@TileNetworkData
public int signEntityZ = 0;
//public LogisticsTileEntiy signEntity;
protected final LinkedList<ItemIdentifier> _lostItems = new LinkedList<ItemIdentifier>();
@TileNetworkData
public int satelliteId = 0;
@TileNetworkData
public int priority = 0;
public BaseLogicCrafting() {
throttleTime = 40;
}
/* ** SATELLITE CODE ** */
protected int getNextConnectSatelliteId(boolean prev) {
final HashMap<IRouter, Orientations> routes = getRouter().getRouteTable();
int closestIdFound = prev ? 0 : Integer.MAX_VALUE;
for (final BaseLogicSatellite satellite : BaseLogicSatellite.AllSatellites) {
if (routes.containsKey(satellite.getRouter())) {
if (!prev && satellite.satelliteId > satelliteId && satellite.satelliteId < closestIdFound) {
closestIdFound = satellite.satelliteId;
} else if (prev && satellite.satelliteId < satelliteId && satellite.satelliteId > closestIdFound) {
closestIdFound = satellite.satelliteId;
}
}
}
if (closestIdFound == Integer.MAX_VALUE) {
return satelliteId;
}
return closestIdFound;
}
public void setNextSatellite(EntityPlayer player) {
satelliteId = getNextConnectSatelliteId(false);
if (MainProxy.isClient(player.worldObj)) {
final PacketCoordinates packet = new PacketCoordinates(NetworkConstants.CRAFTING_PIPE_NEXT_SATELLITE, xCoord, yCoord, zCoord);
PacketDispatcher.sendPacketToServer(packet.getPacket());
} else {
final PacketPipeInteger packet = new PacketPipeInteger(NetworkConstants.CRAFTING_PIPE_SATELLITE_ID, xCoord, yCoord, zCoord, satelliteId);
PacketDispatcher.sendPacketToPlayer(packet.getPacket(), (Player)player);
}
}
// This is called by the packet PacketCraftingPipeSatelliteId
public void setSatelliteId(int satelliteId) {
this.satelliteId = satelliteId;
}
public void setPrevSatellite(EntityPlayer player) {
satelliteId = getNextConnectSatelliteId(true);
if (MainProxy.isClient(player.worldObj)) {
final PacketCoordinates packet = new PacketCoordinates(NetworkConstants.CRAFTING_PIPE_PREV_SATELLITE, xCoord, yCoord, zCoord);
PacketDispatcher.sendPacketToServer(packet.getPacket());
} else {
final PacketPipeInteger packet = new PacketPipeInteger(NetworkConstants.CRAFTING_PIPE_SATELLITE_ID, xCoord, yCoord, zCoord, satelliteId);
PacketDispatcher.sendPacketToPlayer(packet.getPacket(), (Player)player);
}
}
public boolean isSatelliteConnected() {
for (final BaseLogicSatellite satellite : BaseLogicSatellite.AllSatellites) {
if (satellite.satelliteId == satelliteId) {
if (getRouter().getRouteTable().containsKey(satellite.getRouter())) {
return true;
}
}
}
return false;
}
public IRouter getSatelliteRouter() {
for (final BaseLogicSatellite satellite : BaseLogicSatellite.AllSatellites) {
if (satellite.satelliteId == satelliteId) {
return satellite.getRouter();
}
}
return null;
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound) {
super.readFromNBT(nbttagcompound);
_dummyInventory.readFromNBT(nbttagcompound, "");
satelliteId = nbttagcompound.getInteger("satelliteid");
signEntityX = nbttagcompound.getInteger("CraftingSignEntityX");
signEntityY = nbttagcompound.getInteger("CraftingSignEntityY");
signEntityZ = nbttagcompound.getInteger("CraftingSignEntityZ");
priority = nbttagcompound.getInteger("priority");
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound) {
super.writeToNBT(nbttagcompound);
_dummyInventory.writeToNBT(nbttagcompound, "");
nbttagcompound.setInteger("satelliteid", satelliteId);
nbttagcompound.setInteger("CraftingSignEntityX", signEntityX);
nbttagcompound.setInteger("CraftingSignEntityY", signEntityY);
nbttagcompound.setInteger("CraftingSignEntityZ", signEntityZ);
nbttagcompound.setInteger("priority", priority);
}
@Override
public void destroy() {
if(signEntityX != 0 && signEntityY != 0 && signEntityZ != 0) {
worldObj.setBlockWithNotify(signEntityX, signEntityY, signEntityZ, 0);
signEntityX = 0;
signEntityY = 0;
signEntityZ = 0;
}
}
@Override
public void onWrenchClicked(EntityPlayer entityplayer) {
if (MainProxy.isServer(entityplayer.worldObj)) {
entityplayer.openGui(LogisticsPipes.instance, GuiIDs.GUI_CRAFTINGPIPE_ID, worldObj, xCoord, yCoord, zCoord);
}
}
@Override
public void throttledUpdateEntity() {
super.throttledUpdateEntity();
if (_lostItems.isEmpty()) {
return;
}
final Iterator<ItemIdentifier> iterator = _lostItems.iterator();
while (iterator.hasNext()) {
if (RequestManager.request(iterator.next().makeStack(1), ((RoutedPipe) container.pipe), ((RoutedPipe) container.pipe).getRouter().getIRoutersByCost(), null)) {
iterator.remove();
}
}
}
@Override
public void itemArrived(ItemIdentifier item) {
}
@Override
public void itemLost(ItemIdentifier item) {
_lostItems.add(item);
}
public void openAttachedGui(EntityPlayer player) {
if (MainProxy.isClient(player.worldObj)) {
+ player.closeScreen();
final PacketCoordinates packet = new PacketCoordinates(NetworkConstants.CRAFTING_PIPE_OPEN_CONNECTED_GUI, xCoord, yCoord, zCoord);
PacketDispatcher.sendPacketToServer(packet.getPacket());
return;
}
final WorldUtil worldUtil = new WorldUtil(worldObj, xCoord, yCoord, zCoord);
boolean found = false;
for (final AdjacentTile tile : worldUtil.getAdjacentTileEntities()) {
for (ICraftingRecipeProvider provider : SimpleServiceLocator.craftingRecipeProviders) {
if (provider.canOpenGui(tile.tile)) {
found = true;
break;
}
}
if (!found)
found = (tile.tile instanceof IInventory && !(tile.tile instanceof TileGenericPipe));
if (found) {
Block block = worldObj.getBlockId(tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord) < Block.blocksList.length ? Block.blocksList[worldObj.getBlockId(tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord)] : null;
if(block != null) {
if(block.onBlockActivated(worldObj, tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord, player, 0, 0, 0, 0)){
break;
}
}
}
}
}
public void importFromCraftingTable(EntityPlayer player) {
final WorldUtil worldUtil = new WorldUtil(worldObj, xCoord, yCoord, zCoord);
for (final AdjacentTile tile : worldUtil.getAdjacentTileEntities()) {
for (ICraftingRecipeProvider provider : SimpleServiceLocator.craftingRecipeProviders) {
if (provider.importRecipe(tile.tile, _dummyInventory))
break;
}
}
if (MainProxy.isClient(player.worldObj)) {
// Send packet asking for import
final PacketCoordinates packet = new PacketCoordinates(NetworkConstants.CRAFTING_PIPE_IMPORT, xCoord, yCoord, zCoord);
PacketDispatcher.sendPacketToServer(packet.getPacket());
} else{
// Send inventory as packet
final PacketInventoryChange packet = new PacketInventoryChange(NetworkConstants.CRAFTING_PIPE_IMPORT_BACK, xCoord, yCoord, zCoord, _dummyInventory);
PacketDispatcher.sendPacketToPlayer(packet.getPacket(), (Player)player);
}
}
public void handleStackMove(int number) {
if(MainProxy.isClient()) {
PacketDispatcher.sendPacketToServer(new PacketPipeInteger(NetworkConstants.CRAFTING_PIPE_STACK_MOVE,xCoord,yCoord,zCoord,number).getPacket());
}
ItemStack stack = _dummyInventory.getStackInSlot(number);
if(stack == null ) return;
for(int i = 6;i < 9;i++) {
ItemStack stackb = _dummyInventory.getStackInSlot(i);
if(stackb == null) {
_dummyInventory.setInventorySlotContents(i, stack);
_dummyInventory.setInventorySlotContents(number, null);
break;
}
}
}
public void priorityUp(EntityPlayer player) {
priority++;
if(MainProxy.isClient()) {
PacketDispatcher.sendPacketToServer(new PacketCoordinates(NetworkConstants.CRAFTING_PIPE_PRIORITY_UP, xCoord, yCoord, zCoord).getPacket());
} else if(MainProxy.isServer() && player != null) {
PacketDispatcher.sendPacketToPlayer(new PacketPipeInteger(NetworkConstants.CRAFTING_PIPE_PRIORITY, xCoord, yCoord, zCoord, priority).getPacket(), (Player)player);
}
}
public void priorityDown(EntityPlayer player) {
priority--;
if(MainProxy.isClient()) {
PacketDispatcher.sendPacketToServer(new PacketCoordinates(NetworkConstants.CRAFTING_PIPE_PRIORITY_DOWN, xCoord, yCoord, zCoord).getPacket());
} else if(MainProxy.isServer() && player != null) {
PacketDispatcher.sendPacketToPlayer(new PacketPipeInteger(NetworkConstants.CRAFTING_PIPE_PRIORITY, xCoord, yCoord, zCoord, priority).getPacket(), (Player)player);
}
}
public void setPriority(int amount) {
priority = amount;
}
/* ** INTERFACE TO PIPE ** */
public ItemStack getCraftedItem() {
return _dummyInventory.getStackInSlot(9);
}
public ItemStack getMaterials(int slotnr) {
return _dummyInventory.getStackInSlot(slotnr);
}
/**
* Simply get the dummy inventory
*
* @return the dummy inventory
*/
public SimpleInventory getDummyInventory() {
return _dummyInventory;
}
public void setDummyInventorySlot(int slot, ItemStack itemstack) {
_dummyInventory.setInventorySlotContents(slot, itemstack);
}
/* ** NON NETWORKING ** */
public void paintPathToSatellite() {
final IRouter satelliteRouter = getSatelliteRouter();
if (satelliteRouter == null) {
return;
}
getRouter().displayRouteTo(satelliteRouter);
}
}
| true | true | public void openAttachedGui(EntityPlayer player) {
if (MainProxy.isClient(player.worldObj)) {
final PacketCoordinates packet = new PacketCoordinates(NetworkConstants.CRAFTING_PIPE_OPEN_CONNECTED_GUI, xCoord, yCoord, zCoord);
PacketDispatcher.sendPacketToServer(packet.getPacket());
return;
}
final WorldUtil worldUtil = new WorldUtil(worldObj, xCoord, yCoord, zCoord);
boolean found = false;
for (final AdjacentTile tile : worldUtil.getAdjacentTileEntities()) {
for (ICraftingRecipeProvider provider : SimpleServiceLocator.craftingRecipeProviders) {
if (provider.canOpenGui(tile.tile)) {
found = true;
break;
}
}
if (!found)
found = (tile.tile instanceof IInventory && !(tile.tile instanceof TileGenericPipe));
if (found) {
Block block = worldObj.getBlockId(tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord) < Block.blocksList.length ? Block.blocksList[worldObj.getBlockId(tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord)] : null;
if(block != null) {
if(block.onBlockActivated(worldObj, tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord, player, 0, 0, 0, 0)){
break;
}
}
}
}
}
| public void openAttachedGui(EntityPlayer player) {
if (MainProxy.isClient(player.worldObj)) {
player.closeScreen();
final PacketCoordinates packet = new PacketCoordinates(NetworkConstants.CRAFTING_PIPE_OPEN_CONNECTED_GUI, xCoord, yCoord, zCoord);
PacketDispatcher.sendPacketToServer(packet.getPacket());
return;
}
final WorldUtil worldUtil = new WorldUtil(worldObj, xCoord, yCoord, zCoord);
boolean found = false;
for (final AdjacentTile tile : worldUtil.getAdjacentTileEntities()) {
for (ICraftingRecipeProvider provider : SimpleServiceLocator.craftingRecipeProviders) {
if (provider.canOpenGui(tile.tile)) {
found = true;
break;
}
}
if (!found)
found = (tile.tile instanceof IInventory && !(tile.tile instanceof TileGenericPipe));
if (found) {
Block block = worldObj.getBlockId(tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord) < Block.blocksList.length ? Block.blocksList[worldObj.getBlockId(tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord)] : null;
if(block != null) {
if(block.onBlockActivated(worldObj, tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord, player, 0, 0, 0, 0)){
break;
}
}
}
}
}
|
diff --git a/application/app/controllers/schools/SchoolController.java b/application/app/controllers/schools/SchoolController.java
index 27a0cbe7..07b41da8 100644
--- a/application/app/controllers/schools/SchoolController.java
+++ b/application/app/controllers/schools/SchoolController.java
@@ -1,229 +1,229 @@
/**
*
*/
package controllers.schools;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.PersistenceException;
import com.avaje.ebean.Ebean;
import models.EMessages;
import models.data.Link;
import models.dbentities.SchoolModel;
import models.management.ModelState;
import models.user.AuthenticationManager;
import models.user.Role;
import models.user.Teacher;
import models.user.UserType;
import models.util.OperationResultInfo;
import play.data.Form;
import play.mvc.Result;
import play.mvc.Results;
import views.html.commons.noaccess;
import views.html.schools.addschool;
import views.html.schools.editSchool;
import views.html.schools.schools;
import controllers.EController;
/**
* @author Jens N. Rammant
*/
public class SchoolController extends EController {
/**
*
* @return a page of all the schools the teacher is somehow associated with.
* No Access page if user is not teacher.
*/
public static Result viewSchools(int page, String orderBy, String order, String filter) {
// Generate breadcrumbs & template arguments
ArrayList<Link> breadcrumbs = getBreadcrumbs();
if (!isAuthorized())
return ok(noaccess.render(breadcrumbs));
OperationResultInfo ori = new OperationResultInfo();
String teacherID = (getTeacher()==null)?"!!NoTeacher!!":getTeacher().getID();
//Configure the manager
SchoolManager sm = new SchoolManager(ModelState.READ, teacherID);
sm.setFilter(filter);
sm.setOrder(order);
sm.setOrderBy(orderBy);
//Try to render list
try{
return ok(schools.render(sm.page(page), sm, orderBy, order,filter, breadcrumbs, ori));
}catch(PersistenceException pe){
ori.add(EMessages.get("schools.list.error"),OperationResultInfo.Type.ERROR);
return ok(schools.render(null, sm, orderBy, order,filter, breadcrumbs, ori));
}
}
/**
*
* @return a page for creating a new school. No Access page if user is not a
* teacher
*/
public static Result create() {
// Generate breadcrumbs
List<Link> breadcrumbs = getBreadcrumbs();
breadcrumbs.add(new Link(EMessages.get("schools.add"), "/schools/new"));
OperationResultInfo ori = new OperationResultInfo();
// Check if authorized
if (!isAuthorized())
return ok(noaccess.render(breadcrumbs));
// Create & render form
Form<SchoolModel> form = new Form<SchoolModel>(SchoolModel.class);
return ok(addschool.render(form, breadcrumbs, ori));
}
/**
* Saves the data from the form
*
* @return the list page if succesfull. Otherwise the form page with an
* error
*/
public static Result save() {
// Generate breadcrumbs
List<Link> breadcrumbs = getBreadcrumbs();
breadcrumbs.add(new Link(EMessages.get("schools.add"), "/schools/new"));
if (!isAuthorized())
return ok(noaccess.render(breadcrumbs)); // Check if authorized
// Retrieve the form
Form<SchoolModel> form = form(SchoolModel.class).bindFromRequest();
if (form.hasErrors()) {
// Form was not complete --> return form with a warning
OperationResultInfo ori = new OperationResultInfo();
ori.add(EMessages.get("schools.error.notcomplete"),
OperationResultInfo.Type.WARNING);
return badRequest(addschool.render(form, breadcrumbs, ori));
}
// Try to save the info
SchoolModel m = form.get();
try {
String teacherID = (getTeacher()==null)?"!!NoTeacher!!":getTeacher().getID();
m.orig = teacherID; // Add teacher's id as 'originator'
m.save();
} catch (Exception p) {
// Something went wrong in the saving. Redirect back to the create
// page with an error alert
OperationResultInfo ori = new OperationResultInfo();
ori.add(EMessages.get("schools.error.savefail"),
OperationResultInfo.Type.ERROR);
return badRequest(addschool.render(form, breadcrumbs, ori));
}
// Redirect back to the list
- flash("success", Integer.toString(m.id)); // Show id of newly created
+ flash("succes", Integer.toString(m.id)); // Show id of newly created
// school in message
return Results.redirect(controllers.schools.routes.SchoolController
.viewSchools(0,"name","asc",""));
}
/**
*
* @param id of the school
* @return edit page for the school
*/
public static Result edit(int id){
//Initialize template arguments
OperationResultInfo ori = new OperationResultInfo();
List<Link> bc = getBreadcrumbs();
bc.add(new Link(EMessages.get("schools.edit"), "/schools/"+id));
//Try to show edit page for school
try{
//Check if authorized
if(!isAuthorized(id))return ok(noaccess.render(bc));
SchoolModel sm = Ebean.find(SchoolModel.class, id);
@SuppressWarnings("unused")
int temp = sm.id; //will throw exception if null
Form<SchoolModel> f = form(SchoolModel.class).bindFromRequest().fill(sm);
return ok(editSchool.render(id, f, bc, ori));
}catch(Exception e){
ori.add(EMessages.get("schools.error"),OperationResultInfo.Type.ERROR);
return ok(editSchool.render(id, null, bc, ori));
}
}
/**
* saves the updated school
* @param id of the school
* @return list of schools page
*/
public static Result update(int id){
//Initialize template arguments
OperationResultInfo ori = new OperationResultInfo();
List<Link> bc = getBreadcrumbs();
bc.add(new Link(EMessages.get("schools.edit"), "/schools/"+id));
Form<SchoolModel> f = form(SchoolModel.class).bindFromRequest();
//Update the database with the updated schoolmodel
try{
//Check if authorized
if(!isAuthorized(id))return ok(noaccess.render(bc));
//check if form is valid
if(f.hasErrors()){
ori.add(EMessages.get("schools.error.notcomplete"), OperationResultInfo.Type.WARNING);
return badRequest(editSchool.render(id, f, bc, ori));
}
SchoolModel old = Ebean.find(SchoolModel.class, id);
SchoolModel neww = f.get();
neww.id = id;
neww.orig = old.orig;
neww.update();
return redirect(routes.SchoolController.viewSchools(0,"name","asc",""));
}catch(Exception e){
ori.add(EMessages.get("schools.error.savefail"), OperationResultInfo.Type.ERROR);
return badRequest(editSchool.render(id, f, bc, ori));
}
}
/**
*
* @return the standard breadcrumbs for school management
*/
public static ArrayList<Link> getBreadcrumbs() {
ArrayList<Link> res = new ArrayList<Link>();
res.add(new Link("Home", "/"));
res.add(new Link(EMessages.get("schools.title"), "/schools"));
return res;
}
/**
*
* @return whether the user is authorized to view a School Management page
*/
private static boolean isAuthorized() {
return AuthenticationManager.getInstance().getUser().hasRole(Role.MANAGESCHOOLS);
}
/**
*
* @param id of the school
* @return whether the user is authorized to edit the class
* @throws PersistenceException
*/
public static boolean isAuthorized(int id) throws PersistenceException{
if(!isAuthorized())return false;
if(AuthenticationManager.getInstance().getUser().getType()==UserType.TEACHER){
SchoolModel sm = Ebean.find(SchoolModel.class,id);
return sm.orig.equals(AuthenticationManager.getInstance().getUser().getID());
}
return false;
}
/**
*
* @return the currently logged in Teacher. null if it's not a teacher
*
*/
private static Teacher getTeacher() {
try{
return (Teacher) AuthenticationManager.getInstance().getUser();
}catch(Exception e){
return null;
}
}
}
| true | true | public static Result save() {
// Generate breadcrumbs
List<Link> breadcrumbs = getBreadcrumbs();
breadcrumbs.add(new Link(EMessages.get("schools.add"), "/schools/new"));
if (!isAuthorized())
return ok(noaccess.render(breadcrumbs)); // Check if authorized
// Retrieve the form
Form<SchoolModel> form = form(SchoolModel.class).bindFromRequest();
if (form.hasErrors()) {
// Form was not complete --> return form with a warning
OperationResultInfo ori = new OperationResultInfo();
ori.add(EMessages.get("schools.error.notcomplete"),
OperationResultInfo.Type.WARNING);
return badRequest(addschool.render(form, breadcrumbs, ori));
}
// Try to save the info
SchoolModel m = form.get();
try {
String teacherID = (getTeacher()==null)?"!!NoTeacher!!":getTeacher().getID();
m.orig = teacherID; // Add teacher's id as 'originator'
m.save();
} catch (Exception p) {
// Something went wrong in the saving. Redirect back to the create
// page with an error alert
OperationResultInfo ori = new OperationResultInfo();
ori.add(EMessages.get("schools.error.savefail"),
OperationResultInfo.Type.ERROR);
return badRequest(addschool.render(form, breadcrumbs, ori));
}
// Redirect back to the list
flash("success", Integer.toString(m.id)); // Show id of newly created
// school in message
return Results.redirect(controllers.schools.routes.SchoolController
.viewSchools(0,"name","asc",""));
}
| public static Result save() {
// Generate breadcrumbs
List<Link> breadcrumbs = getBreadcrumbs();
breadcrumbs.add(new Link(EMessages.get("schools.add"), "/schools/new"));
if (!isAuthorized())
return ok(noaccess.render(breadcrumbs)); // Check if authorized
// Retrieve the form
Form<SchoolModel> form = form(SchoolModel.class).bindFromRequest();
if (form.hasErrors()) {
// Form was not complete --> return form with a warning
OperationResultInfo ori = new OperationResultInfo();
ori.add(EMessages.get("schools.error.notcomplete"),
OperationResultInfo.Type.WARNING);
return badRequest(addschool.render(form, breadcrumbs, ori));
}
// Try to save the info
SchoolModel m = form.get();
try {
String teacherID = (getTeacher()==null)?"!!NoTeacher!!":getTeacher().getID();
m.orig = teacherID; // Add teacher's id as 'originator'
m.save();
} catch (Exception p) {
// Something went wrong in the saving. Redirect back to the create
// page with an error alert
OperationResultInfo ori = new OperationResultInfo();
ori.add(EMessages.get("schools.error.savefail"),
OperationResultInfo.Type.ERROR);
return badRequest(addschool.render(form, breadcrumbs, ori));
}
// Redirect back to the list
flash("succes", Integer.toString(m.id)); // Show id of newly created
// school in message
return Results.redirect(controllers.schools.routes.SchoolController
.viewSchools(0,"name","asc",""));
}
|
diff --git a/src/java/com/eviware/soapui/impl/wsdl/submit/filters/HttpRequestFilter.java b/src/java/com/eviware/soapui/impl/wsdl/submit/filters/HttpRequestFilter.java
index f3d863f30..8942de0d6 100644
--- a/src/java/com/eviware/soapui/impl/wsdl/submit/filters/HttpRequestFilter.java
+++ b/src/java/com/eviware/soapui/impl/wsdl/submit/filters/HttpRequestFilter.java
@@ -1,460 +1,461 @@
/*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI 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 at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.submit.filters;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.PreencodedMimeBodyPart;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.xmlbeans.XmlBoolean;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.impl.rest.RestRequest;
import com.eviware.soapui.impl.rest.support.RestParamProperty;
import com.eviware.soapui.impl.rest.support.RestParamsPropertyHolder;
import com.eviware.soapui.impl.rest.support.RestParamsPropertyHolder.ParameterStyle;
import com.eviware.soapui.impl.rest.support.RestUtils;
import com.eviware.soapui.impl.support.http.HttpRequestInterface;
import com.eviware.soapui.impl.wsdl.submit.transports.http.BaseHttpRequestTransport;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentDataSource;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.RestRequestDataSource;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.RestRequestMimeMessageRequestEntity;
import com.eviware.soapui.impl.wsdl.support.FileAttachment;
import com.eviware.soapui.impl.wsdl.support.PathUtils;
import com.eviware.soapui.impl.wsdl.teststeps.HttpTestRequest;
import com.eviware.soapui.model.iface.Attachment;
import com.eviware.soapui.model.iface.SubmitContext;
import com.eviware.soapui.model.propertyexpansion.PropertyExpander;
import com.eviware.soapui.settings.HttpSettings;
import com.eviware.soapui.support.StringUtils;
import com.eviware.soapui.support.editor.inspectors.attachments.ContentTypeHandler;
import com.eviware.soapui.support.types.StringToStringMap;
import com.eviware.soapui.support.uri.URI;
/**
* RequestFilter that adds SOAP specific headers
*
* @author Ole.Matzura
*/
public class HttpRequestFilter extends AbstractRequestFilter
{
@SuppressWarnings( "deprecation" )
@Override
public void filterHttpRequest( SubmitContext context, HttpRequestInterface<?> request )
{
HttpRequestBase httpMethod = ( HttpRequestBase )context.getProperty( BaseHttpRequestTransport.HTTP_METHOD );
String path = PropertyExpander.expandProperties( context, request.getPath() );
StringBuffer query = new StringBuffer();
StringToStringMap responseProperties = ( StringToStringMap )context
.getProperty( BaseHttpRequestTransport.RESPONSE_PROPERTIES );
MimeMultipart formMp = "multipart/form-data".equals( request.getMediaType() )
&& httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;
RestParamsPropertyHolder params = request.getParams();
for( int c = 0; c < params.getPropertyCount(); c++ )
{
RestParamProperty param = params.getPropertyAt( c );
String value = PropertyExpander.expandProperties( context, param.getValue() );
responseProperties.put( param.getName(), value );
List<String> valueParts = sendEmptyParameters( request )
|| ( !StringUtils.hasContent( value ) && param.getRequired() ) ? RestUtils
.splitMultipleParametersEmptyIncluded( value, request.getMultiValueDelimiter() ) : RestUtils
.splitMultipleParameters( value, request.getMultiValueDelimiter() );
// skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
// the URI handling further down)
if( value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE
&& !param.isDisableUrlEncoding() )
{
try
{
String encoding = System.getProperty( "soapui.request.encoding", request.getEncoding() );
if( StringUtils.hasContent( encoding ) )
{
value = URLEncoder.encode( value, encoding );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ), encoding ) );
}
else
{
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
}
catch( UnsupportedEncodingException e1 )
{
SoapUI.logError( e1 );
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
// URLEncoder replaces space with "+", but we want "%20".
value = value.replaceAll( "\\+", "%20" );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, valueParts.get( i ).replaceAll( "\\+", "%20" ) );
}
if( param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters( request ) )
{
if( !StringUtils.hasContent( value ) && !param.getRequired() )
continue;
}
switch( param.getStyle() )
{
case HEADER :
for( String valuePart : valueParts )
httpMethod.addHeader( param.getName(), valuePart );
break;
case QUERY :
if( formMp == null || !request.isPostQueryString() )
{
for( String valuePart : valueParts )
{
if( query.length() > 0 )
query.append( '&' );
query.append( URLEncoder.encode( param.getName() ) );
query.append( '=' );
if( StringUtils.hasContent( valuePart ) )
query.append( valuePart );
}
}
else
{
try
{
addFormMultipart( request, formMp, param.getName(), responseProperties.get( param.getName() ) );
}
catch( MessagingException e )
{
SoapUI.logError( e );
}
}
break;
case TEMPLATE :
path = path.replaceAll( "\\{" + param.getName() + "\\}", value == null ? "" : value );
break;
case MATRIX :
if( param.getType().equals( XmlBoolean.type.getName() ) )
{
if( value.toUpperCase().equals( "TRUE" ) || value.equals( "1" ) )
{
path += ";" + param.getName();
}
}
else
{
path += ";" + param.getName();
if( StringUtils.hasContent( value ) )
{
path += "=" + value;
}
}
case PLAIN :
break;
}
}
if( request.getSettings().getBoolean( HttpSettings.FORWARD_SLASHES ) )
path = PathUtils.fixForwardSlashesInPath( path );
if( PathUtils.isHttpPath( path ) )
{
try
{
// URI(String) automatically URLencodes the input, so we need to
// decode it first...
URI uri = new URI( path, request.getSettings().getBoolean( HttpSettings.ENCODED_URLS ) );
context.setProperty( BaseHttpRequestTransport.REQUEST_URI, uri );
httpMethod.setURI( new java.net.URI( uri.toString() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
else if( StringUtils.hasContent( path ) )
{
try
{
java.net.URI oldUri = httpMethod.getURI();
- String pathToSet = StringUtils.hasContent( oldUri.getPath() ) ? oldUri.getPath() + path : path;
+ String pathToSet = StringUtils.hasContent( oldUri.getPath() ) && !"/".equals( oldUri.getPath() ) ? oldUri
+ .getPath() + path : path;
java.net.URI newUri = URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
pathToSet, oldUri.getQuery(), oldUri.getFragment() );
httpMethod.setURI( newUri );
context.setProperty( BaseHttpRequestTransport.REQUEST_URI, new URI( newUri.toString(), request
.getSettings().getBoolean( HttpSettings.ENCODED_URLS ) ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( query.length() > 0 && !request.isPostQueryString() )
{
try
{
java.net.URI oldUri = httpMethod.getURI();
httpMethod.setURI( URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
oldUri.getPath(), query.toString(), oldUri.getFragment() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( request instanceof RestRequest )
{
String acceptEncoding = ( ( RestRequest )request ).getAccept();
if( StringUtils.hasContent( acceptEncoding ) )
{
httpMethod.setHeader( "Accept", acceptEncoding );
}
}
String encoding = System.getProperty( "soapui.request.encoding", StringUtils.unquote( request.getEncoding() ) );
if( formMp != null )
{
// create request message
try
{
if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
if( StringUtils.hasContent( requestContent ) )
{
initRootPart( request, requestContent, formMp );
}
}
for( Attachment attachment : request.getAttachments() )
{
MimeBodyPart part = new PreencodedMimeBodyPart( "binary" );
if( attachment instanceof FileAttachment<?> )
{
String name = attachment.getName();
if( StringUtils.hasContent( attachment.getContentID() ) && !name.equals( attachment.getContentID() ) )
name = attachment.getContentID();
part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"" );
}
else
part.setDisposition( "form-data; name=\"" + attachment.getName() + "\"" );
part.setDataHandler( new DataHandler( new AttachmentDataSource( attachment ) ) );
formMp.addBodyPart( part );
}
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( formMp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type", mimeMessageRequestEntity.getContentType().getValue() );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
catch( Throwable e )
{
SoapUI.logError( e );
}
}
else if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
if( StringUtils.hasContent( request.getMediaType() ) )
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
if( request.isPostQueryString() )
{
try
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new StringEntity( query.toString() ) );
}
catch( UnsupportedEncodingException e )
{
SoapUI.logError( e );
}
}
else
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
List<Attachment> attachments = new ArrayList<Attachment>();
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getContentType().equals( request.getMediaType() ) )
{
attachments.add( attachment );
}
}
if( StringUtils.hasContent( requestContent ) && attachments.isEmpty() )
{
try
{
byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes( encoding );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( content ) );
}
catch( UnsupportedEncodingException e )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( requestContent
.getBytes() ) );
}
}
else if( attachments.size() > 0 )
{
try
{
MimeMultipart mp = null;
if( StringUtils.hasContent( requestContent ) )
{
mp = new MimeMultipart();
initRootPart( request, requestContent, mp );
}
else if( attachments.size() == 1 )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new InputStreamEntity( attachments.get( 0 )
.getInputStream(), -1 ) );
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
}
if( ( ( HttpEntityEnclosingRequest )httpMethod ).getEntity() == null )
{
if( mp == null )
mp = new MimeMultipart();
// init mimeparts
AttachmentUtils.addMimeParts( request, attachments, mp, new StringToStringMap() );
// create request message
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( mp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type",
getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding ) );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
}
}
}
private boolean sendEmptyParameters( HttpRequestInterface<?> request )
{
return request instanceof HttpTestRequest && ( ( HttpTestRequest )request ).isSendEmptyParameters();
}
private String getContentTypeHeader( String contentType, String encoding )
{
return ( encoding == null || encoding.trim().length() == 0 ) ? contentType : contentType + ";charset=" + encoding;
}
private void addFormMultipart( HttpRequestInterface<?> request, MimeMultipart formMp, String name, String value )
throws MessagingException
{
MimeBodyPart part = new MimeBodyPart();
if( value.startsWith( "file:" ) )
{
String fileName = value.substring( 5 );
File file = new File( fileName );
part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"" );
if( file.exists() )
{
part.setDataHandler( new DataHandler( new FileDataSource( file ) ) );
}
else
{
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getName().equals( fileName ) )
{
part.setDataHandler( new DataHandler( new AttachmentDataSource( attachment ) ) );
break;
}
}
}
part.setHeader( "Content-Type", ContentTypeHandler.getContentTypeFromFilename( file.getName() ) );
part.setHeader( "Content-Transfer-Encoding", "binary" );
}
else
{
part.setDisposition( "form-data; name=\"" + name + "\"" );
part.setText( value, System.getProperty( "soapui.request.encoding", request.getEncoding() ) );
}
if( part != null )
{
formMp.addBodyPart( part );
}
}
protected void initRootPart( HttpRequestInterface<?> wsdlRequest, String requestContent, MimeMultipart mp )
throws MessagingException
{
MimeBodyPart rootPart = new PreencodedMimeBodyPart( "8bit" );
// rootPart.setContentID( AttachmentUtils.ROOTPART_SOAPUI_ORG );
mp.addBodyPart( rootPart, 0 );
DataHandler dataHandler = new DataHandler( new RestRequestDataSource( wsdlRequest, requestContent ) );
rootPart.setDataHandler( dataHandler );
}
}
| true | true | public void filterHttpRequest( SubmitContext context, HttpRequestInterface<?> request )
{
HttpRequestBase httpMethod = ( HttpRequestBase )context.getProperty( BaseHttpRequestTransport.HTTP_METHOD );
String path = PropertyExpander.expandProperties( context, request.getPath() );
StringBuffer query = new StringBuffer();
StringToStringMap responseProperties = ( StringToStringMap )context
.getProperty( BaseHttpRequestTransport.RESPONSE_PROPERTIES );
MimeMultipart formMp = "multipart/form-data".equals( request.getMediaType() )
&& httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;
RestParamsPropertyHolder params = request.getParams();
for( int c = 0; c < params.getPropertyCount(); c++ )
{
RestParamProperty param = params.getPropertyAt( c );
String value = PropertyExpander.expandProperties( context, param.getValue() );
responseProperties.put( param.getName(), value );
List<String> valueParts = sendEmptyParameters( request )
|| ( !StringUtils.hasContent( value ) && param.getRequired() ) ? RestUtils
.splitMultipleParametersEmptyIncluded( value, request.getMultiValueDelimiter() ) : RestUtils
.splitMultipleParameters( value, request.getMultiValueDelimiter() );
// skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
// the URI handling further down)
if( value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE
&& !param.isDisableUrlEncoding() )
{
try
{
String encoding = System.getProperty( "soapui.request.encoding", request.getEncoding() );
if( StringUtils.hasContent( encoding ) )
{
value = URLEncoder.encode( value, encoding );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ), encoding ) );
}
else
{
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
}
catch( UnsupportedEncodingException e1 )
{
SoapUI.logError( e1 );
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
// URLEncoder replaces space with "+", but we want "%20".
value = value.replaceAll( "\\+", "%20" );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, valueParts.get( i ).replaceAll( "\\+", "%20" ) );
}
if( param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters( request ) )
{
if( !StringUtils.hasContent( value ) && !param.getRequired() )
continue;
}
switch( param.getStyle() )
{
case HEADER :
for( String valuePart : valueParts )
httpMethod.addHeader( param.getName(), valuePart );
break;
case QUERY :
if( formMp == null || !request.isPostQueryString() )
{
for( String valuePart : valueParts )
{
if( query.length() > 0 )
query.append( '&' );
query.append( URLEncoder.encode( param.getName() ) );
query.append( '=' );
if( StringUtils.hasContent( valuePart ) )
query.append( valuePart );
}
}
else
{
try
{
addFormMultipart( request, formMp, param.getName(), responseProperties.get( param.getName() ) );
}
catch( MessagingException e )
{
SoapUI.logError( e );
}
}
break;
case TEMPLATE :
path = path.replaceAll( "\\{" + param.getName() + "\\}", value == null ? "" : value );
break;
case MATRIX :
if( param.getType().equals( XmlBoolean.type.getName() ) )
{
if( value.toUpperCase().equals( "TRUE" ) || value.equals( "1" ) )
{
path += ";" + param.getName();
}
}
else
{
path += ";" + param.getName();
if( StringUtils.hasContent( value ) )
{
path += "=" + value;
}
}
case PLAIN :
break;
}
}
if( request.getSettings().getBoolean( HttpSettings.FORWARD_SLASHES ) )
path = PathUtils.fixForwardSlashesInPath( path );
if( PathUtils.isHttpPath( path ) )
{
try
{
// URI(String) automatically URLencodes the input, so we need to
// decode it first...
URI uri = new URI( path, request.getSettings().getBoolean( HttpSettings.ENCODED_URLS ) );
context.setProperty( BaseHttpRequestTransport.REQUEST_URI, uri );
httpMethod.setURI( new java.net.URI( uri.toString() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
else if( StringUtils.hasContent( path ) )
{
try
{
java.net.URI oldUri = httpMethod.getURI();
String pathToSet = StringUtils.hasContent( oldUri.getPath() ) ? oldUri.getPath() + path : path;
java.net.URI newUri = URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
pathToSet, oldUri.getQuery(), oldUri.getFragment() );
httpMethod.setURI( newUri );
context.setProperty( BaseHttpRequestTransport.REQUEST_URI, new URI( newUri.toString(), request
.getSettings().getBoolean( HttpSettings.ENCODED_URLS ) ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( query.length() > 0 && !request.isPostQueryString() )
{
try
{
java.net.URI oldUri = httpMethod.getURI();
httpMethod.setURI( URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
oldUri.getPath(), query.toString(), oldUri.getFragment() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( request instanceof RestRequest )
{
String acceptEncoding = ( ( RestRequest )request ).getAccept();
if( StringUtils.hasContent( acceptEncoding ) )
{
httpMethod.setHeader( "Accept", acceptEncoding );
}
}
String encoding = System.getProperty( "soapui.request.encoding", StringUtils.unquote( request.getEncoding() ) );
if( formMp != null )
{
// create request message
try
{
if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
if( StringUtils.hasContent( requestContent ) )
{
initRootPart( request, requestContent, formMp );
}
}
for( Attachment attachment : request.getAttachments() )
{
MimeBodyPart part = new PreencodedMimeBodyPart( "binary" );
if( attachment instanceof FileAttachment<?> )
{
String name = attachment.getName();
if( StringUtils.hasContent( attachment.getContentID() ) && !name.equals( attachment.getContentID() ) )
name = attachment.getContentID();
part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"" );
}
else
part.setDisposition( "form-data; name=\"" + attachment.getName() + "\"" );
part.setDataHandler( new DataHandler( new AttachmentDataSource( attachment ) ) );
formMp.addBodyPart( part );
}
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( formMp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type", mimeMessageRequestEntity.getContentType().getValue() );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
catch( Throwable e )
{
SoapUI.logError( e );
}
}
else if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
if( StringUtils.hasContent( request.getMediaType() ) )
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
if( request.isPostQueryString() )
{
try
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new StringEntity( query.toString() ) );
}
catch( UnsupportedEncodingException e )
{
SoapUI.logError( e );
}
}
else
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
List<Attachment> attachments = new ArrayList<Attachment>();
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getContentType().equals( request.getMediaType() ) )
{
attachments.add( attachment );
}
}
if( StringUtils.hasContent( requestContent ) && attachments.isEmpty() )
{
try
{
byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes( encoding );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( content ) );
}
catch( UnsupportedEncodingException e )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( requestContent
.getBytes() ) );
}
}
else if( attachments.size() > 0 )
{
try
{
MimeMultipart mp = null;
if( StringUtils.hasContent( requestContent ) )
{
mp = new MimeMultipart();
initRootPart( request, requestContent, mp );
}
else if( attachments.size() == 1 )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new InputStreamEntity( attachments.get( 0 )
.getInputStream(), -1 ) );
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
}
if( ( ( HttpEntityEnclosingRequest )httpMethod ).getEntity() == null )
{
if( mp == null )
mp = new MimeMultipart();
// init mimeparts
AttachmentUtils.addMimeParts( request, attachments, mp, new StringToStringMap() );
// create request message
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( mp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type",
getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding ) );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
}
}
}
| public void filterHttpRequest( SubmitContext context, HttpRequestInterface<?> request )
{
HttpRequestBase httpMethod = ( HttpRequestBase )context.getProperty( BaseHttpRequestTransport.HTTP_METHOD );
String path = PropertyExpander.expandProperties( context, request.getPath() );
StringBuffer query = new StringBuffer();
StringToStringMap responseProperties = ( StringToStringMap )context
.getProperty( BaseHttpRequestTransport.RESPONSE_PROPERTIES );
MimeMultipart formMp = "multipart/form-data".equals( request.getMediaType() )
&& httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;
RestParamsPropertyHolder params = request.getParams();
for( int c = 0; c < params.getPropertyCount(); c++ )
{
RestParamProperty param = params.getPropertyAt( c );
String value = PropertyExpander.expandProperties( context, param.getValue() );
responseProperties.put( param.getName(), value );
List<String> valueParts = sendEmptyParameters( request )
|| ( !StringUtils.hasContent( value ) && param.getRequired() ) ? RestUtils
.splitMultipleParametersEmptyIncluded( value, request.getMultiValueDelimiter() ) : RestUtils
.splitMultipleParameters( value, request.getMultiValueDelimiter() );
// skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
// the URI handling further down)
if( value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE
&& !param.isDisableUrlEncoding() )
{
try
{
String encoding = System.getProperty( "soapui.request.encoding", request.getEncoding() );
if( StringUtils.hasContent( encoding ) )
{
value = URLEncoder.encode( value, encoding );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ), encoding ) );
}
else
{
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
}
catch( UnsupportedEncodingException e1 )
{
SoapUI.logError( e1 );
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
// URLEncoder replaces space with "+", but we want "%20".
value = value.replaceAll( "\\+", "%20" );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, valueParts.get( i ).replaceAll( "\\+", "%20" ) );
}
if( param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters( request ) )
{
if( !StringUtils.hasContent( value ) && !param.getRequired() )
continue;
}
switch( param.getStyle() )
{
case HEADER :
for( String valuePart : valueParts )
httpMethod.addHeader( param.getName(), valuePart );
break;
case QUERY :
if( formMp == null || !request.isPostQueryString() )
{
for( String valuePart : valueParts )
{
if( query.length() > 0 )
query.append( '&' );
query.append( URLEncoder.encode( param.getName() ) );
query.append( '=' );
if( StringUtils.hasContent( valuePart ) )
query.append( valuePart );
}
}
else
{
try
{
addFormMultipart( request, formMp, param.getName(), responseProperties.get( param.getName() ) );
}
catch( MessagingException e )
{
SoapUI.logError( e );
}
}
break;
case TEMPLATE :
path = path.replaceAll( "\\{" + param.getName() + "\\}", value == null ? "" : value );
break;
case MATRIX :
if( param.getType().equals( XmlBoolean.type.getName() ) )
{
if( value.toUpperCase().equals( "TRUE" ) || value.equals( "1" ) )
{
path += ";" + param.getName();
}
}
else
{
path += ";" + param.getName();
if( StringUtils.hasContent( value ) )
{
path += "=" + value;
}
}
case PLAIN :
break;
}
}
if( request.getSettings().getBoolean( HttpSettings.FORWARD_SLASHES ) )
path = PathUtils.fixForwardSlashesInPath( path );
if( PathUtils.isHttpPath( path ) )
{
try
{
// URI(String) automatically URLencodes the input, so we need to
// decode it first...
URI uri = new URI( path, request.getSettings().getBoolean( HttpSettings.ENCODED_URLS ) );
context.setProperty( BaseHttpRequestTransport.REQUEST_URI, uri );
httpMethod.setURI( new java.net.URI( uri.toString() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
else if( StringUtils.hasContent( path ) )
{
try
{
java.net.URI oldUri = httpMethod.getURI();
String pathToSet = StringUtils.hasContent( oldUri.getPath() ) && !"/".equals( oldUri.getPath() ) ? oldUri
.getPath() + path : path;
java.net.URI newUri = URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
pathToSet, oldUri.getQuery(), oldUri.getFragment() );
httpMethod.setURI( newUri );
context.setProperty( BaseHttpRequestTransport.REQUEST_URI, new URI( newUri.toString(), request
.getSettings().getBoolean( HttpSettings.ENCODED_URLS ) ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( query.length() > 0 && !request.isPostQueryString() )
{
try
{
java.net.URI oldUri = httpMethod.getURI();
httpMethod.setURI( URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
oldUri.getPath(), query.toString(), oldUri.getFragment() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( request instanceof RestRequest )
{
String acceptEncoding = ( ( RestRequest )request ).getAccept();
if( StringUtils.hasContent( acceptEncoding ) )
{
httpMethod.setHeader( "Accept", acceptEncoding );
}
}
String encoding = System.getProperty( "soapui.request.encoding", StringUtils.unquote( request.getEncoding() ) );
if( formMp != null )
{
// create request message
try
{
if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
if( StringUtils.hasContent( requestContent ) )
{
initRootPart( request, requestContent, formMp );
}
}
for( Attachment attachment : request.getAttachments() )
{
MimeBodyPart part = new PreencodedMimeBodyPart( "binary" );
if( attachment instanceof FileAttachment<?> )
{
String name = attachment.getName();
if( StringUtils.hasContent( attachment.getContentID() ) && !name.equals( attachment.getContentID() ) )
name = attachment.getContentID();
part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"" );
}
else
part.setDisposition( "form-data; name=\"" + attachment.getName() + "\"" );
part.setDataHandler( new DataHandler( new AttachmentDataSource( attachment ) ) );
formMp.addBodyPart( part );
}
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( formMp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type", mimeMessageRequestEntity.getContentType().getValue() );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
catch( Throwable e )
{
SoapUI.logError( e );
}
}
else if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
if( StringUtils.hasContent( request.getMediaType() ) )
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
if( request.isPostQueryString() )
{
try
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new StringEntity( query.toString() ) );
}
catch( UnsupportedEncodingException e )
{
SoapUI.logError( e );
}
}
else
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
List<Attachment> attachments = new ArrayList<Attachment>();
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getContentType().equals( request.getMediaType() ) )
{
attachments.add( attachment );
}
}
if( StringUtils.hasContent( requestContent ) && attachments.isEmpty() )
{
try
{
byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes( encoding );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( content ) );
}
catch( UnsupportedEncodingException e )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( requestContent
.getBytes() ) );
}
}
else if( attachments.size() > 0 )
{
try
{
MimeMultipart mp = null;
if( StringUtils.hasContent( requestContent ) )
{
mp = new MimeMultipart();
initRootPart( request, requestContent, mp );
}
else if( attachments.size() == 1 )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new InputStreamEntity( attachments.get( 0 )
.getInputStream(), -1 ) );
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
}
if( ( ( HttpEntityEnclosingRequest )httpMethod ).getEntity() == null )
{
if( mp == null )
mp = new MimeMultipart();
// init mimeparts
AttachmentUtils.addMimeParts( request, attachments, mp, new StringToStringMap() );
// create request message
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( mp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type",
getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding ) );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
}
}
}
|
diff --git a/src/main/java/com/araeosia/ArcherGames/ScheduledTasks.java b/src/main/java/com/araeosia/ArcherGames/ScheduledTasks.java
index a9b9849..8f40f83 100644
--- a/src/main/java/com/araeosia/ArcherGames/ScheduledTasks.java
+++ b/src/main/java/com/araeosia/ArcherGames/ScheduledTasks.java
@@ -1,189 +1,189 @@
package com.araeosia.ArcherGames;
import com.araeosia.ArcherGames.utils.Archer;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class ScheduledTasks {
public ArcherGames plugin;
public static int gameStatus = 1;
public int currentLoop; // In loops
public int preGameCountdown; // Time before anything starts. Players choose kits.
public int gameInvincibleCountdown; // Time while players are invincible.
public int gameOvertimeCountdown; // Time until overtime starts.
public int shutdownTimer; // Time after the game ends until the server shuts down.
public int minPlayersToStart;
public int schedulerTaskID;
public long nagTime;
public ScheduledTasks(ArcherGames plugin) {
this.plugin = plugin;
}
/**
* This will do the action every second (20 TPS)
*/
public void everySecondCheck() {
if (schedulerTaskID != -1) {
schedulerTaskID = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
public void run() {
switch (gameStatus) {
case 1:
if (plugin.debug) {
plugin.log.info((preGameCountdown - currentLoop) + " seconds until game starts.");
}
// Pre-game
if(preGameCountdown - currentLoop % 3600 == 0 || preGameCountdown - currentLoop % 60 == 0 || preGameCountdown - currentLoop < 60) {
plugin.serverwide.sendMessageToAllPlayers(String.format(plugin.strings.get("starttimeleft"), ((preGameCountdown - currentLoop) % 60 == 0 ? (preGameCountdown - currentLoop) / 60 + " minute" + (((preGameCountdown - currentLoop) / 60) == 1 ? "" : "s") : (preGameCountdown-currentLoop)+ " second" + ((preGameCountdown-currentLoop != 1) ? "s" : ""))));
}
if (currentLoop >= preGameCountdown) {
if (plugin.debug) {
plugin.log.info("Attempting to start...");
}
// Time to start.
- if (plugin.serverwide.livingPlayers.size() >= minPlayersToStart) { // There aren't enough players.
+ if (plugin.serverwide.livingPlayers.size() < minPlayersToStart) { // There aren't enough players.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("startnotenoughplayers"));
} else { // There's enough players, let's start!
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("starting"));
gameStatus = 2;
for(Archer a : plugin.serverwide.livingPlayers){
for(ItemStack is : plugin.kits.get(a.getKitName())){
plugin.serverwide.getPlayer(a).getInventory().addItem(is);
}
}
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (plugin.serverwide.getArcher(p).isReady) {
p.teleport(plugin.startPosition);
}
}
}
currentLoop = -1;
}
currentLoop++;
break;
case 2:
// Invincibility
if (plugin.debug) {
plugin.log.info((gameInvincibleCountdown - currentLoop) + " seconds until invincibility ends.");
}
if (currentLoop >= gameInvincibleCountdown) {
if (plugin.debug) {
plugin.log.info("Invincibility has ended.");
}
// Invincibility is over.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("invincibilityend"));
gameStatus = 3;
currentLoop = -1;
}
currentLoop++;
break;
case 3:
// Game time
if (plugin.debug) {
plugin.log.info((gameOvertimeCountdown - currentLoop) + " seconds until overtime starts.");
}
if (currentLoop >= gameOvertimeCountdown) {
if (plugin.debug) {
plugin.log.info("Overtime has started.");
}
// Game time is up.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("overtimestart"));
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (plugin.serverwide.getArcher(p).isReady) {
p.teleport(plugin.startPosition);
}
}
gameStatus = 4;
currentLoop = -1;
// TODO: World border shrinking.
}
currentLoop++;
break;
case 4:
// Overtime
if (plugin.serverwide.livingPlayers.size() <= 1) {
if (plugin.debug) {
plugin.log.info("Game has ended.");
}
// Game is finally over. We have a winner.
plugin.serverwide.handleGameEnd();
gameStatus = 5;
currentLoop = -1;
}
currentLoop++;
break;
case 5:
// Game finished, waiting for reset to pre-game
if (plugin.debug) {
plugin.log.info((shutdownTimer - currentLoop) + " seconds until server reboots.");
}
if (currentLoop >= shutdownTimer) {
if (plugin.debug) {
plugin.log.info("Kicking all players, then shutting down.");
}
for (Player p : plugin.getServer().getOnlinePlayers()) {
p.kickPlayer(plugin.strings.get("serverclosekick"));
}
plugin.getServer().shutdown();
}
break;
}
}
}, 20L, 20L);
if (plugin.debug) {
plugin.log.info("Task ID is " + schedulerTaskID);
}
} else {
plugin.log.severe("Scheduler task start was attempted, but scheduler task already running!");
}
}
public void startGame(boolean force) {
if (force) {
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("starting"));
gameStatus = 2;
currentLoop = 0;
// for(Archer a : plugin.getArchers) for(ItemStack is : plugin.kits.get(Archer.getKit())) plugin.serverwide.getPlayer(a).getInventory().add(is);
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (plugin.serverwide.getArcher(p).isReady) {
p.teleport(plugin.startPosition);
}
}
} else {
if (plugin.debug) {
plugin.log.info("Attempting to start early...");
}
// Time to start.
if (plugin.serverwide.livingPlayers.size() < minPlayersToStart) { // There aren't enough players.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("startnotenoughplayers"));
} else { // There's enough players, let's start!
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("starting"));
gameStatus = 2;
currentLoop = 0;
// for(Archer a : plugin.getArchers) for(ItemStack is : plugin.kits.get(Archer.getKit())) plugin.serverwide.getPlayer(a).getInventory().add(is);
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (plugin.serverwide.getArcher(p).isReady) {
p.teleport(plugin.startPosition);
}
}
}
}
}
public int nagPlayerKit(final String playerName){
plugin.getServer().getPlayer(playerName).sendMessage(plugin.strings.get("kitnag"));
return plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable(){
public void run(){
plugin.getServer().getPlayer(playerName).sendMessage(plugin.strings.get("kitnag"));
}
}, new Long(nagTime*20), new Long(nagTime*20));
}
public void endGame(){
plugin.serverwide.handleGameEnd();
gameStatus = 5;
currentLoop = 0;
}
}
| true | true | public void everySecondCheck() {
if (schedulerTaskID != -1) {
schedulerTaskID = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
public void run() {
switch (gameStatus) {
case 1:
if (plugin.debug) {
plugin.log.info((preGameCountdown - currentLoop) + " seconds until game starts.");
}
// Pre-game
if(preGameCountdown - currentLoop % 3600 == 0 || preGameCountdown - currentLoop % 60 == 0 || preGameCountdown - currentLoop < 60) {
plugin.serverwide.sendMessageToAllPlayers(String.format(plugin.strings.get("starttimeleft"), ((preGameCountdown - currentLoop) % 60 == 0 ? (preGameCountdown - currentLoop) / 60 + " minute" + (((preGameCountdown - currentLoop) / 60) == 1 ? "" : "s") : (preGameCountdown-currentLoop)+ " second" + ((preGameCountdown-currentLoop != 1) ? "s" : ""))));
}
if (currentLoop >= preGameCountdown) {
if (plugin.debug) {
plugin.log.info("Attempting to start...");
}
// Time to start.
if (plugin.serverwide.livingPlayers.size() >= minPlayersToStart) { // There aren't enough players.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("startnotenoughplayers"));
} else { // There's enough players, let's start!
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("starting"));
gameStatus = 2;
for(Archer a : plugin.serverwide.livingPlayers){
for(ItemStack is : plugin.kits.get(a.getKitName())){
plugin.serverwide.getPlayer(a).getInventory().addItem(is);
}
}
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (plugin.serverwide.getArcher(p).isReady) {
p.teleport(plugin.startPosition);
}
}
}
currentLoop = -1;
}
currentLoop++;
break;
case 2:
// Invincibility
if (plugin.debug) {
plugin.log.info((gameInvincibleCountdown - currentLoop) + " seconds until invincibility ends.");
}
if (currentLoop >= gameInvincibleCountdown) {
if (plugin.debug) {
plugin.log.info("Invincibility has ended.");
}
// Invincibility is over.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("invincibilityend"));
gameStatus = 3;
currentLoop = -1;
}
currentLoop++;
break;
case 3:
// Game time
if (plugin.debug) {
plugin.log.info((gameOvertimeCountdown - currentLoop) + " seconds until overtime starts.");
}
if (currentLoop >= gameOvertimeCountdown) {
if (plugin.debug) {
plugin.log.info("Overtime has started.");
}
// Game time is up.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("overtimestart"));
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (plugin.serverwide.getArcher(p).isReady) {
p.teleport(plugin.startPosition);
}
}
gameStatus = 4;
currentLoop = -1;
// TODO: World border shrinking.
}
currentLoop++;
break;
case 4:
// Overtime
if (plugin.serverwide.livingPlayers.size() <= 1) {
if (plugin.debug) {
plugin.log.info("Game has ended.");
}
// Game is finally over. We have a winner.
plugin.serverwide.handleGameEnd();
gameStatus = 5;
currentLoop = -1;
}
currentLoop++;
break;
case 5:
// Game finished, waiting for reset to pre-game
if (plugin.debug) {
plugin.log.info((shutdownTimer - currentLoop) + " seconds until server reboots.");
}
if (currentLoop >= shutdownTimer) {
if (plugin.debug) {
plugin.log.info("Kicking all players, then shutting down.");
}
for (Player p : plugin.getServer().getOnlinePlayers()) {
p.kickPlayer(plugin.strings.get("serverclosekick"));
}
plugin.getServer().shutdown();
}
break;
}
}
}, 20L, 20L);
if (plugin.debug) {
plugin.log.info("Task ID is " + schedulerTaskID);
}
} else {
plugin.log.severe("Scheduler task start was attempted, but scheduler task already running!");
}
}
| public void everySecondCheck() {
if (schedulerTaskID != -1) {
schedulerTaskID = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
public void run() {
switch (gameStatus) {
case 1:
if (plugin.debug) {
plugin.log.info((preGameCountdown - currentLoop) + " seconds until game starts.");
}
// Pre-game
if(preGameCountdown - currentLoop % 3600 == 0 || preGameCountdown - currentLoop % 60 == 0 || preGameCountdown - currentLoop < 60) {
plugin.serverwide.sendMessageToAllPlayers(String.format(plugin.strings.get("starttimeleft"), ((preGameCountdown - currentLoop) % 60 == 0 ? (preGameCountdown - currentLoop) / 60 + " minute" + (((preGameCountdown - currentLoop) / 60) == 1 ? "" : "s") : (preGameCountdown-currentLoop)+ " second" + ((preGameCountdown-currentLoop != 1) ? "s" : ""))));
}
if (currentLoop >= preGameCountdown) {
if (plugin.debug) {
plugin.log.info("Attempting to start...");
}
// Time to start.
if (plugin.serverwide.livingPlayers.size() < minPlayersToStart) { // There aren't enough players.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("startnotenoughplayers"));
} else { // There's enough players, let's start!
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("starting"));
gameStatus = 2;
for(Archer a : plugin.serverwide.livingPlayers){
for(ItemStack is : plugin.kits.get(a.getKitName())){
plugin.serverwide.getPlayer(a).getInventory().addItem(is);
}
}
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (plugin.serverwide.getArcher(p).isReady) {
p.teleport(plugin.startPosition);
}
}
}
currentLoop = -1;
}
currentLoop++;
break;
case 2:
// Invincibility
if (plugin.debug) {
plugin.log.info((gameInvincibleCountdown - currentLoop) + " seconds until invincibility ends.");
}
if (currentLoop >= gameInvincibleCountdown) {
if (plugin.debug) {
plugin.log.info("Invincibility has ended.");
}
// Invincibility is over.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("invincibilityend"));
gameStatus = 3;
currentLoop = -1;
}
currentLoop++;
break;
case 3:
// Game time
if (plugin.debug) {
plugin.log.info((gameOvertimeCountdown - currentLoop) + " seconds until overtime starts.");
}
if (currentLoop >= gameOvertimeCountdown) {
if (plugin.debug) {
plugin.log.info("Overtime has started.");
}
// Game time is up.
plugin.serverwide.sendMessageToAllPlayers(plugin.strings.get("overtimestart"));
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (plugin.serverwide.getArcher(p).isReady) {
p.teleport(plugin.startPosition);
}
}
gameStatus = 4;
currentLoop = -1;
// TODO: World border shrinking.
}
currentLoop++;
break;
case 4:
// Overtime
if (plugin.serverwide.livingPlayers.size() <= 1) {
if (plugin.debug) {
plugin.log.info("Game has ended.");
}
// Game is finally over. We have a winner.
plugin.serverwide.handleGameEnd();
gameStatus = 5;
currentLoop = -1;
}
currentLoop++;
break;
case 5:
// Game finished, waiting for reset to pre-game
if (plugin.debug) {
plugin.log.info((shutdownTimer - currentLoop) + " seconds until server reboots.");
}
if (currentLoop >= shutdownTimer) {
if (plugin.debug) {
plugin.log.info("Kicking all players, then shutting down.");
}
for (Player p : plugin.getServer().getOnlinePlayers()) {
p.kickPlayer(plugin.strings.get("serverclosekick"));
}
plugin.getServer().shutdown();
}
break;
}
}
}, 20L, 20L);
if (plugin.debug) {
plugin.log.info("Task ID is " + schedulerTaskID);
}
} else {
plugin.log.severe("Scheduler task start was attempted, but scheduler task already running!");
}
}
|
diff --git a/activemq-broker/src/main/java/org/apache/activemq/broker/BrokerService.java b/activemq-broker/src/main/java/org/apache/activemq/broker/BrokerService.java
index eecab9de3..575e31312 100644
--- a/activemq-broker/src/main/java/org/apache/activemq/broker/BrokerService.java
+++ b/activemq-broker/src/main/java/org/apache/activemq/broker/BrokerService.java
@@ -1,2938 +1,2940 @@
/**
* 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.activemq.broker;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.security.Provider;
import java.security.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.activemq.ActiveMQConnectionMetaData;
import org.apache.activemq.ConfigurationException;
import org.apache.activemq.Service;
import org.apache.activemq.advisory.AdvisoryBroker;
import org.apache.activemq.broker.cluster.ConnectionSplitBroker;
import org.apache.activemq.broker.jmx.*;
import org.apache.activemq.broker.region.CompositeDestinationInterceptor;
import org.apache.activemq.broker.region.Destination;
import org.apache.activemq.broker.region.DestinationFactory;
import org.apache.activemq.broker.region.DestinationFactoryImpl;
import org.apache.activemq.broker.region.DestinationInterceptor;
import org.apache.activemq.broker.region.RegionBroker;
import org.apache.activemq.broker.region.policy.PolicyMap;
import org.apache.activemq.broker.region.virtual.MirroredQueue;
import org.apache.activemq.broker.region.virtual.VirtualDestination;
import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor;
import org.apache.activemq.broker.region.virtual.VirtualTopic;
import org.apache.activemq.broker.scheduler.JobSchedulerStore;
import org.apache.activemq.broker.scheduler.SchedulerBroker;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.BrokerId;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.filter.DestinationFilter;
import org.apache.activemq.network.ConnectionFilter;
import org.apache.activemq.network.DiscoveryNetworkConnector;
import org.apache.activemq.network.NetworkConnector;
import org.apache.activemq.network.jms.JmsConnector;
import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.activemq.proxy.ProxyConnector;
import org.apache.activemq.security.MessageAuthorizationPolicy;
import org.apache.activemq.selector.SelectorParser;
import org.apache.activemq.store.JournaledStore;
import org.apache.activemq.store.PListStore;
import org.apache.activemq.store.PersistenceAdapter;
import org.apache.activemq.store.PersistenceAdapterFactory;
import org.apache.activemq.store.memory.MemoryPersistenceAdapter;
import org.apache.activemq.thread.Scheduler;
import org.apache.activemq.thread.TaskRunnerFactory;
import org.apache.activemq.transport.TransportFactorySupport;
import org.apache.activemq.transport.TransportServer;
import org.apache.activemq.transport.vm.VMTransportFactory;
import org.apache.activemq.usage.SystemUsage;
import org.apache.activemq.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
/**
* Manages the life-cycle of an ActiveMQ Broker. A BrokerService consists of a
* number of transport connectors, network connectors and a bunch of properties
* which can be used to configure the broker as its lazily created.
*
* @org.apache.xbean.XBean
*/
public class BrokerService implements Service {
public static final String DEFAULT_PORT = "61616";
public static final String LOCAL_HOST_NAME;
public static final String BROKER_VERSION;
public static final String DEFAULT_BROKER_NAME = "localhost";
public static final int DEFAULT_MAX_FILE_LENGTH = 1024 * 1024 * 32;
private static final Logger LOG = LoggerFactory.getLogger(BrokerService.class);
@SuppressWarnings("unused")
private static final long serialVersionUID = 7353129142305630237L;
private boolean useJmx = true;
private boolean enableStatistics = true;
private boolean persistent = true;
private boolean populateJMSXUserID;
private boolean useAuthenticatedPrincipalForJMSXUserID;
private boolean populateUserNameInMBeans;
private long mbeanInvocationTimeout = 0;
private boolean useShutdownHook = true;
private boolean useLoggingForShutdownErrors;
private boolean shutdownOnMasterFailure;
private boolean shutdownOnSlaveFailure;
private boolean waitForSlave;
private long waitForSlaveTimeout = 600000L;
private boolean passiveSlave;
private String brokerName = DEFAULT_BROKER_NAME;
private File dataDirectoryFile;
private File tmpDataDirectory;
private Broker broker;
private BrokerView adminView;
private ManagementContext managementContext;
private ObjectName brokerObjectName;
private TaskRunnerFactory taskRunnerFactory;
private TaskRunnerFactory persistenceTaskRunnerFactory;
private SystemUsage systemUsage;
private SystemUsage producerSystemUsage;
private SystemUsage consumerSystemUsaage;
private PersistenceAdapter persistenceAdapter;
private PersistenceAdapterFactory persistenceFactory;
protected DestinationFactory destinationFactory;
private MessageAuthorizationPolicy messageAuthorizationPolicy;
private final List<TransportConnector> transportConnectors = new CopyOnWriteArrayList<TransportConnector>();
private final List<NetworkConnector> networkConnectors = new CopyOnWriteArrayList<NetworkConnector>();
private final List<ProxyConnector> proxyConnectors = new CopyOnWriteArrayList<ProxyConnector>();
private final List<JmsConnector> jmsConnectors = new CopyOnWriteArrayList<JmsConnector>();
private final List<Service> services = new ArrayList<Service>();
private transient Thread shutdownHook;
private String[] transportConnectorURIs;
private String[] networkConnectorURIs;
private JmsConnector[] jmsBridgeConnectors; // these are Jms to Jms bridges
// to other jms messaging systems
private boolean deleteAllMessagesOnStartup;
private boolean advisorySupport = true;
private URI vmConnectorURI;
private String defaultSocketURIString;
private PolicyMap destinationPolicy;
private final AtomicBoolean started = new AtomicBoolean(false);
private final AtomicBoolean stopped = new AtomicBoolean(false);
private final AtomicBoolean stopping = new AtomicBoolean(false);
private BrokerPlugin[] plugins;
private boolean keepDurableSubsActive = true;
private boolean useVirtualTopics = true;
private boolean useMirroredQueues = false;
private boolean useTempMirroredQueues = true;
private BrokerId brokerId;
private volatile DestinationInterceptor[] destinationInterceptors;
private ActiveMQDestination[] destinations;
private PListStore tempDataStore;
private int persistenceThreadPriority = Thread.MAX_PRIORITY;
private boolean useLocalHostBrokerName;
private final CountDownLatch stoppedLatch = new CountDownLatch(1);
private final CountDownLatch startedLatch = new CountDownLatch(1);
private boolean supportFailOver;
private Broker regionBroker;
private int producerSystemUsagePortion = 60;
private int consumerSystemUsagePortion = 40;
private boolean splitSystemUsageForProducersConsumers;
private boolean monitorConnectionSplits = false;
private int taskRunnerPriority = Thread.NORM_PRIORITY;
private boolean dedicatedTaskRunner;
private boolean cacheTempDestinations = false;// useful for failover
private int timeBeforePurgeTempDestinations = 5000;
private final List<Runnable> shutdownHooks = new ArrayList<Runnable>();
private boolean systemExitOnShutdown;
private int systemExitOnShutdownExitCode;
private SslContext sslContext;
private boolean forceStart = false;
private IOExceptionHandler ioExceptionHandler;
private boolean schedulerSupport = false;
private File schedulerDirectoryFile;
private Scheduler scheduler;
private ThreadPoolExecutor executor;
private int schedulePeriodForDestinationPurge= 0;
private int maxPurgedDestinationsPerSweep = 0;
private BrokerContext brokerContext;
private boolean networkConnectorStartAsync = false;
private boolean allowTempAutoCreationOnSend;
private JobSchedulerStore jobSchedulerStore;
private long offlineDurableSubscriberTimeout = -1;
private long offlineDurableSubscriberTaskSchedule = 300000;
private DestinationFilter virtualConsumerDestinationFilter;
private final Object persistenceAdapterLock = new Object();
private Throwable startException = null;
private boolean startAsync = false;
private Date startDate;
private boolean slave = true;
private boolean restartAllowed = true;
private boolean restartRequested = false;
private int storeOpenWireVersion = OpenWireFormat.DEFAULT_VERSION;
private String configurationUrl;
static {
try {
ClassLoader loader = BrokerService.class.getClassLoader();
Class<?> clazz = loader.loadClass("org.bouncycastle.jce.provider.BouncyCastleProvider");
Provider bouncycastle = (Provider) clazz.newInstance();
Security.insertProviderAt(bouncycastle, 2);
LOG.info("Loaded the Bouncy Castle security provider.");
} catch(Throwable e) {
// No BouncyCastle found so we use the default Java Security Provider
}
String localHostName = "localhost";
try {
localHostName = InetAddressUtil.getLocalHostName();
} catch (UnknownHostException e) {
LOG.error("Failed to resolve localhost");
}
LOCAL_HOST_NAME = localHostName;
InputStream in = null;
String version = null;
if ((in = BrokerService.class.getResourceAsStream("/org/apache/activemq/version.txt")) != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
version = reader.readLine();
} catch(Exception e) {
}
}
BROKER_VERSION = version;
}
@Override
public String toString() {
return "BrokerService[" + getBrokerName() + "]";
}
private String getBrokerVersion() {
String version = ActiveMQConnectionMetaData.PROVIDER_VERSION;
if (version == null) {
version = BROKER_VERSION;
}
return version;
}
/**
* Adds a new transport connector for the given bind address
*
* @return the newly created and added transport connector
* @throws Exception
*/
public TransportConnector addConnector(String bindAddress) throws Exception {
return addConnector(new URI(bindAddress));
}
/**
* Adds a new transport connector for the given bind address
*
* @return the newly created and added transport connector
* @throws Exception
*/
public TransportConnector addConnector(URI bindAddress) throws Exception {
return addConnector(createTransportConnector(bindAddress));
}
/**
* Adds a new transport connector for the given TransportServer transport
*
* @return the newly created and added transport connector
* @throws Exception
*/
public TransportConnector addConnector(TransportServer transport) throws Exception {
return addConnector(new TransportConnector(transport));
}
/**
* Adds a new transport connector
*
* @return the transport connector
* @throws Exception
*/
public TransportConnector addConnector(TransportConnector connector) throws Exception {
transportConnectors.add(connector);
return connector;
}
/**
* Stops and removes a transport connector from the broker.
*
* @param connector
* @return true if the connector has been previously added to the broker
* @throws Exception
*/
public boolean removeConnector(TransportConnector connector) throws Exception {
boolean rc = transportConnectors.remove(connector);
if (rc) {
unregisterConnectorMBean(connector);
}
return rc;
}
/**
* Adds a new network connector using the given discovery address
*
* @return the newly created and added network connector
* @throws Exception
*/
public NetworkConnector addNetworkConnector(String discoveryAddress) throws Exception {
return addNetworkConnector(new URI(discoveryAddress));
}
/**
* Adds a new proxy connector using the given bind address
*
* @return the newly created and added network connector
* @throws Exception
*/
public ProxyConnector addProxyConnector(String bindAddress) throws Exception {
return addProxyConnector(new URI(bindAddress));
}
/**
* Adds a new network connector using the given discovery address
*
* @return the newly created and added network connector
* @throws Exception
*/
public NetworkConnector addNetworkConnector(URI discoveryAddress) throws Exception {
NetworkConnector connector = new DiscoveryNetworkConnector(discoveryAddress);
return addNetworkConnector(connector);
}
/**
* Adds a new proxy connector using the given bind address
*
* @return the newly created and added network connector
* @throws Exception
*/
public ProxyConnector addProxyConnector(URI bindAddress) throws Exception {
ProxyConnector connector = new ProxyConnector();
connector.setBind(bindAddress);
connector.setRemote(new URI("fanout:multicast://default"));
return addProxyConnector(connector);
}
/**
* Adds a new network connector to connect this broker to a federated
* network
*/
public NetworkConnector addNetworkConnector(NetworkConnector connector) throws Exception {
connector.setBrokerService(this);
URI uri = getVmConnectorURI();
Map<String, String> map = new HashMap<String, String>(URISupport.parseParameters(uri));
map.put("network", "true");
uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map));
connector.setLocalUri(uri);
// Set a connection filter so that the connector does not establish loop
// back connections.
connector.setConnectionFilter(new ConnectionFilter() {
@Override
public boolean connectTo(URI location) {
List<TransportConnector> transportConnectors = getTransportConnectors();
for (Iterator<TransportConnector> iter = transportConnectors.iterator(); iter.hasNext();) {
try {
TransportConnector tc = iter.next();
if (location.equals(tc.getConnectUri())) {
return false;
}
} catch (Throwable e) {
}
}
return true;
}
});
networkConnectors.add(connector);
return connector;
}
/**
* Removes the given network connector without stopping it. The caller
* should call {@link NetworkConnector#stop()} to close the connector
*/
public boolean removeNetworkConnector(NetworkConnector connector) {
boolean answer = networkConnectors.remove(connector);
if (answer) {
unregisterNetworkConnectorMBean(connector);
}
return answer;
}
public ProxyConnector addProxyConnector(ProxyConnector connector) throws Exception {
URI uri = getVmConnectorURI();
connector.setLocalUri(uri);
proxyConnectors.add(connector);
if (isUseJmx()) {
registerProxyConnectorMBean(connector);
}
return connector;
}
public JmsConnector addJmsConnector(JmsConnector connector) throws Exception {
connector.setBrokerService(this);
jmsConnectors.add(connector);
if (isUseJmx()) {
registerJmsConnectorMBean(connector);
}
return connector;
}
public JmsConnector removeJmsConnector(JmsConnector connector) {
if (jmsConnectors.remove(connector)) {
return connector;
}
return null;
}
public void masterFailed() {
if (shutdownOnMasterFailure) {
LOG.error("The Master has failed ... shutting down");
try {
stop();
} catch (Exception e) {
LOG.error("Failed to stop for master failure", e);
}
} else {
LOG.warn("Master Failed - starting all connectors");
try {
startAllConnectors();
broker.nowMasterBroker();
} catch (Exception e) {
LOG.error("Failed to startAllConnectors", e);
}
}
}
public String getUptime() {
// compute and log uptime
if (startDate == null) {
return "not started";
}
long delta = new Date().getTime() - startDate.getTime();
return TimeUtils.printDuration(delta);
}
public boolean isStarted() {
return started.get() && startedLatch.getCount() == 0;
}
/**
* Forces a start of the broker.
* By default a BrokerService instance that was
* previously stopped using BrokerService.stop() cannot be restarted
* using BrokerService.start().
* This method enforces a restart.
* It is not recommended to force a restart of the broker and will not work
* for most but some very trivial broker configurations.
* For restarting a broker instance we recommend to first call stop() on
* the old instance and then recreate a new BrokerService instance.
*
* @param force - if true enforces a restart.
* @throws Exception
*/
public void start(boolean force) throws Exception {
forceStart = force;
stopped.set(false);
started.set(false);
start();
}
// Service interface
// -------------------------------------------------------------------------
protected boolean shouldAutostart() {
return true;
}
/**
* JSR-250 callback wrapper; converts checked exceptions to runtime exceptions
*
* delegates to autoStart, done to prevent backwards incompatible signature change
*/
@PostConstruct
private void postConstruct() {
try {
autoStart();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
*
* @throws Exception
* @org. apache.xbean.InitMethod
*/
public void autoStart() throws Exception {
if(shouldAutostart()) {
start();
}
}
@Override
public void start() throws Exception {
if (stopped.get() || !started.compareAndSet(false, true)) {
// lets just ignore redundant start() calls
// as its way too easy to not be completely sure if start() has been
// called or not with the gazillion of different configuration
// mechanisms
// throw new IllegalStateException("Already started.");
return;
}
stopping.set(false);
startDate = new Date();
MDC.put("activemq.broker", brokerName);
try {
if (systemExitOnShutdown && useShutdownHook) {
throw new ConfigurationException("'useShutdownHook' property cannot be be used with 'systemExitOnShutdown', please turn it off (useShutdownHook=false)");
}
processHelperProperties();
if (isUseJmx()) {
// need to remove MDC during starting JMX, as that would otherwise causes leaks, as spawned threads inheirt the MDC and
// we cannot cleanup clear that during shutdown of the broker.
MDC.remove("activemq.broker");
try {
startManagementContext();
for (NetworkConnector connector : getNetworkConnectors()) {
registerNetworkConnectorMBean(connector);
}
} finally {
MDC.put("activemq.broker", brokerName);
}
}
// in jvm master slave, lets not publish over existing broker till we get the lock
final BrokerRegistry brokerRegistry = BrokerRegistry.getInstance();
if (brokerRegistry.lookup(getBrokerName()) == null) {
brokerRegistry.bind(getBrokerName(), BrokerService.this);
}
startPersistenceAdapter(startAsync);
startBroker(startAsync);
brokerRegistry.bind(getBrokerName(), BrokerService.this);
} catch (Exception e) {
LOG.error("Failed to start Apache ActiveMQ ({}, {})", new Object[]{ getBrokerName(), brokerId }, e);
try {
if (!stopped.get()) {
stop();
}
} catch (Exception ex) {
LOG.warn("Failed to stop broker after failure in start. This exception will be ignored.", ex);
}
throw e;
} finally {
MDC.remove("activemq.broker");
}
}
private void startPersistenceAdapter(boolean async) throws Exception {
if (async) {
new Thread("Persistence Adapter Starting Thread") {
@Override
public void run() {
try {
doStartPersistenceAdapter();
} catch (Throwable e) {
startException = e;
} finally {
synchronized (persistenceAdapterLock) {
persistenceAdapterLock.notifyAll();
}
}
}
}.start();
} else {
doStartPersistenceAdapter();
}
}
private void doStartPersistenceAdapter() throws Exception {
getPersistenceAdapter().setUsageManager(getProducerSystemUsage());
getPersistenceAdapter().setBrokerName(getBrokerName());
LOG.info("Using Persistence Adapter: {}", getPersistenceAdapter());
if (deleteAllMessagesOnStartup) {
deleteAllMessages();
}
getPersistenceAdapter().start();
}
private void startBroker(boolean async) throws Exception {
if (async) {
new Thread("Broker Starting Thread") {
@Override
public void run() {
try {
synchronized (persistenceAdapterLock) {
persistenceAdapterLock.wait();
}
doStartBroker();
} catch (Throwable t) {
startException = t;
}
}
}.start();
} else {
doStartBroker();
}
}
private void doStartBroker() throws Exception {
if (startException != null) {
return;
}
startDestinations();
addShutdownHook();
broker = getBroker();
brokerId = broker.getBrokerId();
// need to log this after creating the broker so we have its id and name
LOG.info("Apache ActiveMQ {} ({}, {}) is starting", new Object[]{ getBrokerVersion(), getBrokerName(), brokerId });
broker.start();
if (isUseJmx()) {
if (getManagementContext().isCreateConnector() && !getManagementContext().isConnectorStarted()) {
// try to restart management context
// typical for slaves that use the same ports as master
managementContext.stop();
startManagementContext();
}
ManagedRegionBroker managedBroker = (ManagedRegionBroker) regionBroker;
managedBroker.setContextBroker(broker);
adminView.setBroker(managedBroker);
}
if (ioExceptionHandler == null) {
setIoExceptionHandler(new DefaultIOExceptionHandler());
}
startAllConnectors();
LOG.info("Apache ActiveMQ {} ({}, {}) started", new Object[]{ getBrokerVersion(), getBrokerName(), brokerId});
LOG.info("For help or more information please see: http://activemq.apache.org");
getBroker().brokerServiceStarted();
checkSystemUsageLimits();
startedLatch.countDown();
getBroker().nowMasterBroker();
}
/**
* JSR-250 callback wrapper; converts checked exceptions to runtime exceptions
*
* delegates to stop, done to prevent backwards incompatible signature change
*/
@PreDestroy
private void preDestroy () {
try {
stop();
} catch (Exception ex) {
throw new RuntimeException();
}
}
/**
*
* @throws Exception
* @org.apache .xbean.DestroyMethod
*/
@Override
public void stop() throws Exception {
if (!stopping.compareAndSet(false, true)) {
LOG.trace("Broker already stopping/stopped");
return;
}
MDC.put("activemq.broker", brokerName);
if (systemExitOnShutdown) {
new Thread() {
@Override
public void run() {
System.exit(systemExitOnShutdownExitCode);
}
}.start();
}
LOG.info("Apache ActiveMQ {} ({}, {}) is shutting down", new Object[]{ getBrokerVersion(), getBrokerName(), brokerId} );
removeShutdownHook();
if (this.scheduler != null) {
this.scheduler.stop();
this.scheduler = null;
}
ServiceStopper stopper = new ServiceStopper();
if (services != null) {
for (Service service : services) {
stopper.stop(service);
}
}
stopAllConnectors(stopper);
this.slave = true;
// remove any VMTransports connected
// this has to be done after services are stopped,
// to avoid timing issue with discovery (spinning up a new instance)
BrokerRegistry.getInstance().unbind(getBrokerName());
VMTransportFactory.stopped(getBrokerName());
if (broker != null) {
stopper.stop(broker);
broker = null;
}
if (jobSchedulerStore != null) {
jobSchedulerStore.stop();
jobSchedulerStore = null;
}
if (tempDataStore != null) {
tempDataStore.stop();
tempDataStore = null;
}
try {
stopper.stop(persistenceAdapter);
persistenceAdapter = null;
if (isUseJmx()) {
stopper.stop(getManagementContext());
managementContext = null;
}
// Clear SelectorParser cache to free memory
SelectorParser.clearCache();
} finally {
started.set(false);
stopped.set(true);
stoppedLatch.countDown();
}
if (this.taskRunnerFactory != null) {
this.taskRunnerFactory.shutdown();
this.taskRunnerFactory = null;
}
if (this.executor != null) {
ThreadPoolUtils.shutdownNow(executor);
this.executor = null;
}
this.destinationInterceptors = null;
this.destinationFactory = null;
if (startDate != null) {
LOG.info("Apache ActiveMQ {} ({}, {}) uptime {}", new Object[]{ getBrokerVersion(), getBrokerName(), brokerId, getUptime()});
}
LOG.info("Apache ActiveMQ {} ({}, {}) is shutdown", new Object[]{ getBrokerVersion(), getBrokerName(), brokerId});
synchronized (shutdownHooks) {
for (Runnable hook : shutdownHooks) {
try {
hook.run();
} catch (Throwable e) {
stopper.onException(hook, e);
}
}
}
MDC.remove("activemq.broker");
// and clear start date
startDate = null;
stopper.throwFirstException();
}
public boolean checkQueueSize(String queueName) {
long count = 0;
long queueSize = 0;
Map<ActiveMQDestination, Destination> destinationMap = regionBroker.getDestinationMap();
for (Map.Entry<ActiveMQDestination, Destination> entry : destinationMap.entrySet()) {
if (entry.getKey().isQueue()) {
if (entry.getValue().getName().matches(queueName)) {
queueSize = entry.getValue().getDestinationStatistics().getMessages().getCount();
count += queueSize;
if (queueSize > 0) {
LOG.info("Queue has pending message: {} queueSize is: {}", entry.getValue().getName(), queueSize);
}
}
}
}
return count == 0;
}
/**
* This method (both connectorName and queueName are using regex to match)
* 1. stop the connector (supposed the user input the connector which the
* clients connect to) 2. to check whether there is any pending message on
* the queues defined by queueName 3. supposedly, after stop the connector,
* client should failover to other broker and pending messages should be
* forwarded. if no pending messages, the method finally call stop to stop
* the broker.
*
* @param connectorName
* @param queueName
* @param timeout
* @param pollInterval
* @throws Exception
*/
public void stopGracefully(String connectorName, String queueName, long timeout, long pollInterval) throws Exception {
if (isUseJmx()) {
if (connectorName == null || queueName == null || timeout <= 0) {
throw new Exception(
"connectorName and queueName cannot be null and timeout should be >0 for stopGracefully.");
}
if (pollInterval <= 0) {
pollInterval = 30;
}
LOG.info("Stop gracefully with connectorName: {} queueName: {} timeout: {} pollInterval: {}", new Object[]{
connectorName, queueName, timeout, pollInterval
});
TransportConnector connector;
for (int i = 0; i < transportConnectors.size(); i++) {
connector = transportConnectors.get(i);
if (connector != null && connector.getName() != null && connector.getName().matches(connectorName)) {
connector.stop();
}
}
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < timeout * 1000) {
// check quesize until it gets zero
if (checkQueueSize(queueName)) {
stop();
break;
} else {
Thread.sleep(pollInterval * 1000);
}
}
if (stopped.get()) {
LOG.info("Successfully stop the broker.");
} else {
LOG.info("There is still pending message on the queue. Please check and stop the broker manually.");
}
}
}
/**
* A helper method to block the caller thread until the broker has been
* stopped
*/
public void waitUntilStopped() {
while (isStarted() && !stopped.get()) {
try {
stoppedLatch.await();
} catch (InterruptedException e) {
// ignore
}
}
}
/**
* A helper method to block the caller thread until the broker has fully started
* @return boolean true if wait succeeded false if broker was not started or was stopped
*/
public boolean waitUntilStarted() {
boolean waitSucceeded = isStarted();
while (!isStarted() && !stopped.get() && !waitSucceeded) {
try {
if (startException != null) {
return waitSucceeded;
}
waitSucceeded = startedLatch.await(100L, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
}
}
return waitSucceeded;
}
// Properties
// -------------------------------------------------------------------------
/**
* Returns the message broker
*/
public Broker getBroker() throws Exception {
if (broker == null) {
broker = createBroker();
}
return broker;
}
/**
* Returns the administration view of the broker; used to create and destroy
* resources such as queues and topics. Note this method returns null if JMX
* is disabled.
*/
public BrokerView getAdminView() throws Exception {
if (adminView == null) {
// force lazy creation
getBroker();
}
return adminView;
}
public void setAdminView(BrokerView adminView) {
this.adminView = adminView;
}
public String getBrokerName() {
return brokerName;
}
/**
* Sets the name of this broker; which must be unique in the network
*
* @param brokerName
*/
public void setBrokerName(String brokerName) {
if (brokerName == null) {
throw new NullPointerException("The broker name cannot be null");
}
String str = brokerName.replaceAll("[^a-zA-Z0-9\\.\\_\\-\\:]", "_");
if (!str.equals(brokerName)) {
LOG.error("Broker Name: {} contained illegal characters - replaced with {}", brokerName, str);
}
this.brokerName = str.trim();
}
public PersistenceAdapterFactory getPersistenceFactory() {
return persistenceFactory;
}
public File getDataDirectoryFile() {
if (dataDirectoryFile == null) {
dataDirectoryFile = new File(IOHelper.getDefaultDataDirectory());
}
return dataDirectoryFile;
}
public File getBrokerDataDirectory() {
String brokerDir = getBrokerName();
return new File(getDataDirectoryFile(), brokerDir);
}
/**
* Sets the directory in which the data files will be stored by default for
* the JDBC and Journal persistence adaptors.
*
* @param dataDirectory
* the directory to store data files
*/
public void setDataDirectory(String dataDirectory) {
setDataDirectoryFile(new File(dataDirectory));
}
/**
* Sets the directory in which the data files will be stored by default for
* the JDBC and Journal persistence adaptors.
*
* @param dataDirectoryFile
* the directory to store data files
*/
public void setDataDirectoryFile(File dataDirectoryFile) {
this.dataDirectoryFile = dataDirectoryFile;
}
/**
* @return the tmpDataDirectory
*/
public File getTmpDataDirectory() {
if (tmpDataDirectory == null) {
tmpDataDirectory = new File(getBrokerDataDirectory(), "tmp_storage");
}
return tmpDataDirectory;
}
/**
* @param tmpDataDirectory
* the tmpDataDirectory to set
*/
public void setTmpDataDirectory(File tmpDataDirectory) {
this.tmpDataDirectory = tmpDataDirectory;
}
public void setPersistenceFactory(PersistenceAdapterFactory persistenceFactory) {
this.persistenceFactory = persistenceFactory;
}
public void setDestinationFactory(DestinationFactory destinationFactory) {
this.destinationFactory = destinationFactory;
}
public boolean isPersistent() {
return persistent;
}
/**
* Sets whether or not persistence is enabled or disabled.
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setPersistent(boolean persistent) {
this.persistent = persistent;
}
public boolean isPopulateJMSXUserID() {
return populateJMSXUserID;
}
/**
* Sets whether or not the broker should populate the JMSXUserID header.
*/
public void setPopulateJMSXUserID(boolean populateJMSXUserID) {
this.populateJMSXUserID = populateJMSXUserID;
}
public SystemUsage getSystemUsage() {
try {
if (systemUsage == null) {
systemUsage = new SystemUsage("Main", getPersistenceAdapter(), getTempDataStore(), getJobSchedulerStore());
systemUsage.setExecutor(getExecutor());
systemUsage.getMemoryUsage().setLimit(1024L * 1024 * 1024 * 1); // 1 GB
systemUsage.getTempUsage().setLimit(1024L * 1024 * 1024 * 50); // 50 GB
systemUsage.getStoreUsage().setLimit(1024L * 1024 * 1024 * 100); // 100 GB
systemUsage.getJobSchedulerUsage().setLimit(1024L * 1024 * 1024 * 50); // 50 GB
addService(this.systemUsage);
}
return systemUsage;
} catch (IOException e) {
LOG.error("Cannot create SystemUsage", e);
throw new RuntimeException("Fatally failed to create SystemUsage" + e.getMessage(), e);
}
}
public void setSystemUsage(SystemUsage memoryManager) {
if (this.systemUsage != null) {
removeService(this.systemUsage);
}
this.systemUsage = memoryManager;
if (this.systemUsage.getExecutor()==null) {
this.systemUsage.setExecutor(getExecutor());
}
addService(this.systemUsage);
}
/**
* @return the consumerUsageManager
* @throws IOException
*/
public SystemUsage getConsumerSystemUsage() throws IOException {
if (this.consumerSystemUsaage == null) {
if (splitSystemUsageForProducersConsumers) {
this.consumerSystemUsaage = new SystemUsage(getSystemUsage(), "Consumer");
float portion = consumerSystemUsagePortion / 100f;
this.consumerSystemUsaage.getMemoryUsage().setUsagePortion(portion);
addService(this.consumerSystemUsaage);
} else {
consumerSystemUsaage = getSystemUsage();
}
}
return this.consumerSystemUsaage;
}
/**
* @param consumerSystemUsaage
* the storeSystemUsage to set
*/
public void setConsumerSystemUsage(SystemUsage consumerSystemUsaage) {
if (this.consumerSystemUsaage != null) {
removeService(this.consumerSystemUsaage);
}
this.consumerSystemUsaage = consumerSystemUsaage;
addService(this.consumerSystemUsaage);
}
/**
* @return the producerUsageManager
* @throws IOException
*/
public SystemUsage getProducerSystemUsage() throws IOException {
if (producerSystemUsage == null) {
if (splitSystemUsageForProducersConsumers) {
producerSystemUsage = new SystemUsage(getSystemUsage(), "Producer");
float portion = producerSystemUsagePortion / 100f;
producerSystemUsage.getMemoryUsage().setUsagePortion(portion);
addService(producerSystemUsage);
} else {
producerSystemUsage = getSystemUsage();
}
}
return producerSystemUsage;
}
/**
* @param producerUsageManager
* the producerUsageManager to set
*/
public void setProducerSystemUsage(SystemUsage producerUsageManager) {
if (this.producerSystemUsage != null) {
removeService(this.producerSystemUsage);
}
this.producerSystemUsage = producerUsageManager;
addService(this.producerSystemUsage);
}
public PersistenceAdapter getPersistenceAdapter() throws IOException {
if (persistenceAdapter == null) {
persistenceAdapter = createPersistenceAdapter();
configureService(persistenceAdapter);
this.persistenceAdapter = registerPersistenceAdapterMBean(persistenceAdapter);
}
return persistenceAdapter;
}
/**
* Sets the persistence adaptor implementation to use for this broker
*
* @throws IOException
*/
public void setPersistenceAdapter(PersistenceAdapter persistenceAdapter) throws IOException {
if (!isPersistent() && ! (persistenceAdapter instanceof MemoryPersistenceAdapter)) {
LOG.warn("persistent=\"false\", ignoring configured persistenceAdapter: {}", persistenceAdapter);
return;
}
this.persistenceAdapter = persistenceAdapter;
configureService(this.persistenceAdapter);
this.persistenceAdapter = registerPersistenceAdapterMBean(persistenceAdapter);
}
public TaskRunnerFactory getTaskRunnerFactory() {
if (this.taskRunnerFactory == null) {
this.taskRunnerFactory = new TaskRunnerFactory("ActiveMQ BrokerService["+getBrokerName()+"] Task", getTaskRunnerPriority(), true, 1000,
isDedicatedTaskRunner());
}
return this.taskRunnerFactory;
}
public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory) {
this.taskRunnerFactory = taskRunnerFactory;
}
public TaskRunnerFactory getPersistenceTaskRunnerFactory() {
if (taskRunnerFactory == null) {
persistenceTaskRunnerFactory = new TaskRunnerFactory("Persistence Adaptor Task", persistenceThreadPriority,
true, 1000, isDedicatedTaskRunner());
}
return persistenceTaskRunnerFactory;
}
public void setPersistenceTaskRunnerFactory(TaskRunnerFactory persistenceTaskRunnerFactory) {
this.persistenceTaskRunnerFactory = persistenceTaskRunnerFactory;
}
public boolean isUseJmx() {
return useJmx;
}
public boolean isEnableStatistics() {
return enableStatistics;
}
/**
* Sets whether or not the Broker's services enable statistics or not.
*/
public void setEnableStatistics(boolean enableStatistics) {
this.enableStatistics = enableStatistics;
}
/**
* Sets whether or not the Broker's services should be exposed into JMX or
* not.
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setUseJmx(boolean useJmx) {
this.useJmx = useJmx;
}
public ObjectName getBrokerObjectName() throws MalformedObjectNameException {
if (brokerObjectName == null) {
brokerObjectName = createBrokerObjectName();
}
return brokerObjectName;
}
/**
* Sets the JMX ObjectName for this broker
*/
public void setBrokerObjectName(ObjectName brokerObjectName) {
this.brokerObjectName = brokerObjectName;
}
public ManagementContext getManagementContext() {
if (managementContext == null) {
managementContext = new ManagementContext();
}
return managementContext;
}
public void setManagementContext(ManagementContext managementContext) {
this.managementContext = managementContext;
}
public NetworkConnector getNetworkConnectorByName(String connectorName) {
for (NetworkConnector connector : networkConnectors) {
if (connector.getName().equals(connectorName)) {
return connector;
}
}
return null;
}
public String[] getNetworkConnectorURIs() {
return networkConnectorURIs;
}
public void setNetworkConnectorURIs(String[] networkConnectorURIs) {
this.networkConnectorURIs = networkConnectorURIs;
}
public TransportConnector getConnectorByName(String connectorName) {
for (TransportConnector connector : transportConnectors) {
if (connector.getName().equals(connectorName)) {
return connector;
}
}
return null;
}
public Map<String, String> getTransportConnectorURIsAsMap() {
Map<String, String> answer = new HashMap<String, String>();
for (TransportConnector connector : transportConnectors) {
try {
URI uri = connector.getConnectUri();
if (uri != null) {
String scheme = uri.getScheme();
if (scheme != null) {
answer.put(scheme.toLowerCase(Locale.ENGLISH), uri.toString());
}
}
} catch (Exception e) {
LOG.debug("Failed to read URI to build transportURIsAsMap", e);
}
}
return answer;
}
public ProducerBrokerExchange getProducerBrokerExchange(ProducerInfo producerInfo){
ProducerBrokerExchange result = null;
for (TransportConnector connector : transportConnectors) {
for (TransportConnection tc: connector.getConnections()){
result = tc.getProducerBrokerExchangeIfExists(producerInfo);
if (result !=null){
return result;
}
}
}
return result;
}
public String[] getTransportConnectorURIs() {
return transportConnectorURIs;
}
public void setTransportConnectorURIs(String[] transportConnectorURIs) {
this.transportConnectorURIs = transportConnectorURIs;
}
/**
* @return Returns the jmsBridgeConnectors.
*/
public JmsConnector[] getJmsBridgeConnectors() {
return jmsBridgeConnectors;
}
/**
* @param jmsConnectors
* The jmsBridgeConnectors to set.
*/
public void setJmsBridgeConnectors(JmsConnector[] jmsConnectors) {
this.jmsBridgeConnectors = jmsConnectors;
}
public Service[] getServices() {
return services.toArray(new Service[0]);
}
/**
* Sets the services associated with this broker.
*/
public void setServices(Service[] services) {
this.services.clear();
if (services != null) {
for (int i = 0; i < services.length; i++) {
this.services.add(services[i]);
}
}
}
/**
* Adds a new service so that it will be started as part of the broker
* lifecycle
*/
public void addService(Service service) {
services.add(service);
}
public void removeService(Service service) {
services.remove(service);
}
public boolean isUseLoggingForShutdownErrors() {
return useLoggingForShutdownErrors;
}
/**
* Sets whether or not we should use commons-logging when reporting errors
* when shutting down the broker
*/
public void setUseLoggingForShutdownErrors(boolean useLoggingForShutdownErrors) {
this.useLoggingForShutdownErrors = useLoggingForShutdownErrors;
}
public boolean isUseShutdownHook() {
return useShutdownHook;
}
/**
* Sets whether or not we should use a shutdown handler to close down the
* broker cleanly if the JVM is terminated. It is recommended you leave this
* enabled.
*/
public void setUseShutdownHook(boolean useShutdownHook) {
this.useShutdownHook = useShutdownHook;
}
public boolean isAdvisorySupport() {
return advisorySupport;
}
/**
* Allows the support of advisory messages to be disabled for performance
* reasons.
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setAdvisorySupport(boolean advisorySupport) {
this.advisorySupport = advisorySupport;
}
public List<TransportConnector> getTransportConnectors() {
return new ArrayList<TransportConnector>(transportConnectors);
}
/**
* Sets the transport connectors which this broker will listen on for new
* clients
*
* @org.apache.xbean.Property
* nestedType="org.apache.activemq.broker.TransportConnector"
*/
public void setTransportConnectors(List<TransportConnector> transportConnectors) throws Exception {
for (TransportConnector connector : transportConnectors) {
addConnector(connector);
}
}
public TransportConnector getTransportConnectorByName(String name){
for (TransportConnector transportConnector : transportConnectors){
if (name.equals(transportConnector.getName())){
return transportConnector;
}
}
return null;
}
public TransportConnector getTransportConnectorByScheme(String scheme){
for (TransportConnector transportConnector : transportConnectors){
if (scheme.equals(transportConnector.getUri().getScheme())){
return transportConnector;
}
}
return null;
}
public List<NetworkConnector> getNetworkConnectors() {
return new ArrayList<NetworkConnector>(networkConnectors);
}
public List<ProxyConnector> getProxyConnectors() {
return new ArrayList<ProxyConnector>(proxyConnectors);
}
/**
* Sets the network connectors which this broker will use to connect to
* other brokers in a federated network
*
* @org.apache.xbean.Property
* nestedType="org.apache.activemq.network.NetworkConnector"
*/
public void setNetworkConnectors(List<?> networkConnectors) throws Exception {
for (Object connector : networkConnectors) {
addNetworkConnector((NetworkConnector) connector);
}
}
/**
* Sets the network connectors which this broker will use to connect to
* other brokers in a federated network
*/
public void setProxyConnectors(List<?> proxyConnectors) throws Exception {
for (Object connector : proxyConnectors) {
addProxyConnector((ProxyConnector) connector);
}
}
public PolicyMap getDestinationPolicy() {
return destinationPolicy;
}
/**
* Sets the destination specific policies available either for exact
* destinations or for wildcard areas of destinations.
*/
public void setDestinationPolicy(PolicyMap policyMap) {
this.destinationPolicy = policyMap;
}
public BrokerPlugin[] getPlugins() {
return plugins;
}
/**
* Sets a number of broker plugins to install such as for security
* authentication or authorization
*/
public void setPlugins(BrokerPlugin[] plugins) {
this.plugins = plugins;
}
public MessageAuthorizationPolicy getMessageAuthorizationPolicy() {
return messageAuthorizationPolicy;
}
/**
* Sets the policy used to decide if the current connection is authorized to
* consume a given message
*/
public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) {
this.messageAuthorizationPolicy = messageAuthorizationPolicy;
}
/**
* Delete all messages from the persistent store
*
* @throws IOException
*/
public void deleteAllMessages() throws IOException {
getPersistenceAdapter().deleteAllMessages();
}
public boolean isDeleteAllMessagesOnStartup() {
return deleteAllMessagesOnStartup;
}
/**
* Sets whether or not all messages are deleted on startup - mostly only
* useful for testing.
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setDeleteAllMessagesOnStartup(boolean deletePersistentMessagesOnStartup) {
this.deleteAllMessagesOnStartup = deletePersistentMessagesOnStartup;
}
public URI getVmConnectorURI() {
if (vmConnectorURI == null) {
try {
vmConnectorURI = new URI("vm://" + getBrokerName().replaceAll("[^a-zA-Z0-9\\.\\_\\-]", "_"));
} catch (URISyntaxException e) {
LOG.error("Badly formed URI from {}", getBrokerName(), e);
}
}
return vmConnectorURI;
}
public void setVmConnectorURI(URI vmConnectorURI) {
this.vmConnectorURI = vmConnectorURI;
}
public String getDefaultSocketURIString() {
if (started.get()) {
if (this.defaultSocketURIString == null) {
for (TransportConnector tc:this.transportConnectors) {
String result = null;
try {
result = tc.getPublishableConnectString();
} catch (Exception e) {
LOG.warn("Failed to get the ConnectURI for {}", tc, e);
}
if (result != null) {
// find first publishable uri
if (tc.isUpdateClusterClients() || tc.isRebalanceClusterClients()) {
this.defaultSocketURIString = result;
break;
} else {
// or use the first defined
if (this.defaultSocketURIString == null) {
this.defaultSocketURIString = result;
}
}
}
}
}
return this.defaultSocketURIString;
}
return null;
}
/**
* @return Returns the shutdownOnMasterFailure.
*/
public boolean isShutdownOnMasterFailure() {
return shutdownOnMasterFailure;
}
/**
* @param shutdownOnMasterFailure
* The shutdownOnMasterFailure to set.
*/
public void setShutdownOnMasterFailure(boolean shutdownOnMasterFailure) {
this.shutdownOnMasterFailure = shutdownOnMasterFailure;
}
public boolean isKeepDurableSubsActive() {
return keepDurableSubsActive;
}
public void setKeepDurableSubsActive(boolean keepDurableSubsActive) {
this.keepDurableSubsActive = keepDurableSubsActive;
}
public boolean isUseVirtualTopics() {
return useVirtualTopics;
}
/**
* Sets whether or not <a
* href="http://activemq.apache.org/virtual-destinations.html">Virtual
* Topics</a> should be supported by default if they have not been
* explicitly configured.
*/
public void setUseVirtualTopics(boolean useVirtualTopics) {
this.useVirtualTopics = useVirtualTopics;
}
public DestinationInterceptor[] getDestinationInterceptors() {
return destinationInterceptors;
}
public boolean isUseMirroredQueues() {
return useMirroredQueues;
}
/**
* Sets whether or not <a
* href="http://activemq.apache.org/mirrored-queues.html">Mirrored
* Queues</a> should be supported by default if they have not been
* explicitly configured.
*/
public void setUseMirroredQueues(boolean useMirroredQueues) {
this.useMirroredQueues = useMirroredQueues;
}
/**
* Sets the destination interceptors to use
*/
public void setDestinationInterceptors(DestinationInterceptor[] destinationInterceptors) {
this.destinationInterceptors = destinationInterceptors;
}
public ActiveMQDestination[] getDestinations() {
return destinations;
}
/**
* Sets the destinations which should be loaded/created on startup
*/
public void setDestinations(ActiveMQDestination[] destinations) {
this.destinations = destinations;
}
/**
* @return the tempDataStore
*/
public synchronized PListStore getTempDataStore() {
if (tempDataStore == null) {
if (!isPersistent()) {
return null;
}
try {
PersistenceAdapter pa = getPersistenceAdapter();
if( pa!=null && pa instanceof PListStore) {
return (PListStore) pa;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
boolean result = true;
boolean empty = true;
try {
File directory = getTmpDataDirectory();
if (directory.exists() && directory.isDirectory()) {
File[] files = directory.listFiles();
if (files != null && files.length > 0) {
empty = false;
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (!file.isDirectory()) {
result &= file.delete();
}
}
}
}
if (!empty) {
String str = result ? "Successfully deleted" : "Failed to delete";
LOG.info("{} temporary storage", str);
}
String clazz = "org.apache.activemq.store.kahadb.plist.PListStoreImpl";
this.tempDataStore = (PListStore) getClass().getClassLoader().loadClass(clazz).newInstance();
this.tempDataStore.setDirectory(getTmpDataDirectory());
configureService(tempDataStore);
this.tempDataStore.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tempDataStore;
}
/**
* @param tempDataStore
* the tempDataStore to set
*/
public void setTempDataStore(PListStore tempDataStore) {
this.tempDataStore = tempDataStore;
configureService(tempDataStore);
try {
tempDataStore.start();
} catch (Exception e) {
RuntimeException exception = new RuntimeException("Failed to start provided temp data store: " + tempDataStore, e);
LOG.error(exception.getLocalizedMessage(), e);
throw exception;
}
}
public int getPersistenceThreadPriority() {
return persistenceThreadPriority;
}
public void setPersistenceThreadPriority(int persistenceThreadPriority) {
this.persistenceThreadPriority = persistenceThreadPriority;
}
/**
* @return the useLocalHostBrokerName
*/
public boolean isUseLocalHostBrokerName() {
return this.useLocalHostBrokerName;
}
/**
* @param useLocalHostBrokerName
* the useLocalHostBrokerName to set
*/
public void setUseLocalHostBrokerName(boolean useLocalHostBrokerName) {
this.useLocalHostBrokerName = useLocalHostBrokerName;
if (useLocalHostBrokerName && !started.get() && brokerName == null || brokerName == DEFAULT_BROKER_NAME) {
brokerName = LOCAL_HOST_NAME;
}
}
/**
* @return the supportFailOver
*/
public boolean isSupportFailOver() {
return this.supportFailOver;
}
/**
* @param supportFailOver
* the supportFailOver to set
*/
public void setSupportFailOver(boolean supportFailOver) {
this.supportFailOver = supportFailOver;
}
/**
* Looks up and lazily creates if necessary the destination for the given
* JMS name
*/
public Destination getDestination(ActiveMQDestination destination) throws Exception {
return getBroker().addDestination(getAdminConnectionContext(), destination,false);
}
public void removeDestination(ActiveMQDestination destination) throws Exception {
getBroker().removeDestination(getAdminConnectionContext(), destination, 0);
}
public int getProducerSystemUsagePortion() {
return producerSystemUsagePortion;
}
public void setProducerSystemUsagePortion(int producerSystemUsagePortion) {
this.producerSystemUsagePortion = producerSystemUsagePortion;
}
public int getConsumerSystemUsagePortion() {
return consumerSystemUsagePortion;
}
public void setConsumerSystemUsagePortion(int consumerSystemUsagePortion) {
this.consumerSystemUsagePortion = consumerSystemUsagePortion;
}
public boolean isSplitSystemUsageForProducersConsumers() {
return splitSystemUsageForProducersConsumers;
}
public void setSplitSystemUsageForProducersConsumers(boolean splitSystemUsageForProducersConsumers) {
this.splitSystemUsageForProducersConsumers = splitSystemUsageForProducersConsumers;
}
public boolean isMonitorConnectionSplits() {
return monitorConnectionSplits;
}
public void setMonitorConnectionSplits(boolean monitorConnectionSplits) {
this.monitorConnectionSplits = monitorConnectionSplits;
}
public int getTaskRunnerPriority() {
return taskRunnerPriority;
}
public void setTaskRunnerPriority(int taskRunnerPriority) {
this.taskRunnerPriority = taskRunnerPriority;
}
public boolean isDedicatedTaskRunner() {
return dedicatedTaskRunner;
}
public void setDedicatedTaskRunner(boolean dedicatedTaskRunner) {
this.dedicatedTaskRunner = dedicatedTaskRunner;
}
public boolean isCacheTempDestinations() {
return cacheTempDestinations;
}
public void setCacheTempDestinations(boolean cacheTempDestinations) {
this.cacheTempDestinations = cacheTempDestinations;
}
public int getTimeBeforePurgeTempDestinations() {
return timeBeforePurgeTempDestinations;
}
public void setTimeBeforePurgeTempDestinations(int timeBeforePurgeTempDestinations) {
this.timeBeforePurgeTempDestinations = timeBeforePurgeTempDestinations;
}
public boolean isUseTempMirroredQueues() {
return useTempMirroredQueues;
}
public void setUseTempMirroredQueues(boolean useTempMirroredQueues) {
this.useTempMirroredQueues = useTempMirroredQueues;
}
public synchronized JobSchedulerStore getJobSchedulerStore() {
// If support is off don't allow any scheduler even is user configured their own.
if (!isSchedulerSupport()) {
return null;
}
// If the user configured their own we use it even if persistence is disabled since
// we don't know anything about their implementation.
if (jobSchedulerStore == null) {
if (!isPersistent()) {
return null;
}
try {
PersistenceAdapter pa = getPersistenceAdapter();
if (pa != null && pa instanceof JobSchedulerStore) {
this.jobSchedulerStore = (JobSchedulerStore) pa;
configureService(jobSchedulerStore);
return this.jobSchedulerStore;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
String clazz = "org.apache.activemq.store.kahadb.scheduler.JobSchedulerStoreImpl";
jobSchedulerStore = (JobSchedulerStore) getClass().getClassLoader().loadClass(clazz).newInstance();
jobSchedulerStore.setDirectory(getSchedulerDirectoryFile());
configureService(jobSchedulerStore);
jobSchedulerStore.start();
LOG.info("JobScheduler using directory: {}", getSchedulerDirectoryFile());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return jobSchedulerStore;
}
public void setJobSchedulerStore(JobSchedulerStore jobSchedulerStore) {
this.jobSchedulerStore = jobSchedulerStore;
configureService(jobSchedulerStore);
try {
jobSchedulerStore.start();
} catch (Exception e) {
RuntimeException exception = new RuntimeException(
"Failed to start provided job scheduler store: " + jobSchedulerStore, e);
LOG.error(exception.getLocalizedMessage(), e);
throw exception;
}
}
//
// Implementation methods
// -------------------------------------------------------------------------
/**
* Handles any lazy-creation helper properties which are added to make
* things easier to configure inside environments such as Spring
*
* @throws Exception
*/
protected void processHelperProperties() throws Exception {
if (transportConnectorURIs != null) {
for (int i = 0; i < transportConnectorURIs.length; i++) {
String uri = transportConnectorURIs[i];
addConnector(uri);
}
}
if (networkConnectorURIs != null) {
for (int i = 0; i < networkConnectorURIs.length; i++) {
String uri = networkConnectorURIs[i];
addNetworkConnector(uri);
}
}
if (jmsBridgeConnectors != null) {
for (int i = 0; i < jmsBridgeConnectors.length; i++) {
addJmsConnector(jmsBridgeConnectors[i]);
}
}
}
protected void checkSystemUsageLimits() throws IOException {
SystemUsage usage = getSystemUsage();
long memLimit = usage.getMemoryUsage().getLimit();
long jvmLimit = Runtime.getRuntime().maxMemory();
if (memLimit > jvmLimit) {
usage.getMemoryUsage().setPercentOfJvmHeap(70);
LOG.error("Memory Usage for the Broker (" + memLimit / (1024 * 1024) +
" mb) is more than the maximum available for the JVM: " +
jvmLimit / (1024 * 1024) + " mb - resetting to 70% of maximum available: " + (usage.getMemoryUsage().getLimit() / (1024 * 1024)) + " mb");
}
if (getPersistenceAdapter() != null) {
PersistenceAdapter adapter = getPersistenceAdapter();
File dir = adapter.getDirectory();
if (dir != null) {
String dirPath = dir.getAbsolutePath();
if (!dir.isAbsolute()) {
dir = new File(dirPath);
}
while (dir != null && !dir.isDirectory()) {
dir = dir.getParentFile();
}
long storeLimit = usage.getStoreUsage().getLimit();
+ long storeCurrent = usage.getStoreUsage().getUsage();
long dirFreeSpace = dir.getUsableSpace();
- if (storeLimit > dirFreeSpace) {
+ if (storeLimit > (dirFreeSpace + storeCurrent)) {
LOG.warn("Store limit is " + storeLimit / (1024 * 1024) +
- " mb, whilst the data directory: " + dir.getAbsolutePath() +
+ " mb (current store usage is " + storeCurrent / (1024 * 1024) +
+ " mb). The data directory: " + dir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) +
" mb of usable space - resetting to maximum available disk space: " +
- dirFreeSpace / (1024 * 1024) + " mb");
- usage.getStoreUsage().setLimit(dirFreeSpace);
+ (dirFreeSpace + storeCurrent) / (1024 * 1024) + " mb");
+ usage.getStoreUsage().setLimit(dirFreeSpace + storeCurrent);
}
}
long maxJournalFileSize = 0;
long storeLimit = usage.getStoreUsage().getLimit();
if (adapter instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) adapter).getJournalMaxFileLength();
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the store will not accept any data when used.");
}
}
File tmpDir = getTmpDataDirectory();
if (tmpDir != null) {
String tmpDirPath = tmpDir.getAbsolutePath();
if (!tmpDir.isAbsolute()) {
tmpDir = new File(tmpDirPath);
}
long storeLimit = usage.getTempUsage().getLimit();
while (tmpDir != null && !tmpDir.isDirectory()) {
tmpDir = tmpDir.getParentFile();
}
long dirFreeSpace = tmpDir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the temporary data directory: " + tmpDirPath +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to maximum available " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getTempUsage().setLimit(dirFreeSpace);
}
if (isPersistent()) {
long maxJournalFileSize;
PListStore store = usage.getTempUsage().getStore();
if (store != null && store instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) store).getJournalMaxFileLength();
} else {
maxJournalFileSize = DEFAULT_MAX_FILE_LENGTH;
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the temporary store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the temp store will not accept any data when used.");
}
}
}
if (getJobSchedulerStore() != null) {
JobSchedulerStore scheduler = getJobSchedulerStore();
File schedulerDir = scheduler.getDirectory();
if (schedulerDir != null) {
String schedulerDirPath = schedulerDir.getAbsolutePath();
if (!schedulerDir.isAbsolute()) {
schedulerDir = new File(schedulerDirPath);
}
while (schedulerDir != null && !schedulerDir.isDirectory()) {
schedulerDir = schedulerDir.getParentFile();
}
long schedulerLimit = usage.getJobSchedulerUsage().getLimit();
long dirFreeSpace = schedulerDir.getUsableSpace();
if (schedulerLimit > dirFreeSpace) {
LOG.warn("Job Scheduler Store limit is " + schedulerLimit / (1024 * 1024) +
" mb, whilst the data directory: " + schedulerDir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getJobSchedulerUsage().setLimit(dirFreeSpace);
}
}
}
}
public void stopAllConnectors(ServiceStopper stopper) {
for (Iterator<NetworkConnector> iter = getNetworkConnectors().iterator(); iter.hasNext();) {
NetworkConnector connector = iter.next();
unregisterNetworkConnectorMBean(connector);
stopper.stop(connector);
}
for (Iterator<ProxyConnector> iter = getProxyConnectors().iterator(); iter.hasNext();) {
ProxyConnector connector = iter.next();
stopper.stop(connector);
}
for (Iterator<JmsConnector> iter = jmsConnectors.iterator(); iter.hasNext();) {
JmsConnector connector = iter.next();
stopper.stop(connector);
}
for (Iterator<TransportConnector> iter = getTransportConnectors().iterator(); iter.hasNext();) {
TransportConnector connector = iter.next();
try {
unregisterConnectorMBean(connector);
} catch (IOException e) {
}
stopper.stop(connector);
}
}
protected TransportConnector registerConnectorMBean(TransportConnector connector) throws IOException {
try {
ObjectName objectName = createConnectorObjectName(connector);
connector = connector.asManagedConnector(getManagementContext(), objectName);
ConnectorViewMBean view = new ConnectorView(connector);
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
return connector;
} catch (Throwable e) {
throw IOExceptionSupport.create("Transport Connector could not be registered in JMX: " + e.getMessage(), e);
}
}
protected void unregisterConnectorMBean(TransportConnector connector) throws IOException {
if (isUseJmx()) {
try {
ObjectName objectName = createConnectorObjectName(connector);
getManagementContext().unregisterMBean(objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create(
"Transport Connector could not be unregistered in JMX: " + e.getMessage(), e);
}
}
}
protected PersistenceAdapter registerPersistenceAdapterMBean(PersistenceAdapter adaptor) throws IOException {
return adaptor;
}
protected void unregisterPersistenceAdapterMBean(PersistenceAdapter adaptor) throws IOException {
if (isUseJmx()) {}
}
private ObjectName createConnectorObjectName(TransportConnector connector) throws MalformedObjectNameException {
return BrokerMBeanSupport.createConnectorName(getBrokerObjectName(), "clientConnectors", connector.getName());
}
public void registerNetworkConnectorMBean(NetworkConnector connector) throws IOException {
NetworkConnectorViewMBean view = new NetworkConnectorView(connector);
try {
ObjectName objectName = createNetworkConnectorObjectName(connector);
connector.setObjectName(objectName);
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("Network Connector could not be registered in JMX: " + e.getMessage(), e);
}
}
protected ObjectName createNetworkConnectorObjectName(NetworkConnector connector) throws MalformedObjectNameException {
return BrokerMBeanSupport.createNetworkConnectorName(getBrokerObjectName(), "networkConnectors", connector.getName());
}
public ObjectName createDuplexNetworkConnectorObjectName(String transport) throws MalformedObjectNameException {
return BrokerMBeanSupport.createNetworkConnectorName(getBrokerObjectName(), "duplexNetworkConnectors", transport);
}
protected void unregisterNetworkConnectorMBean(NetworkConnector connector) {
if (isUseJmx()) {
try {
ObjectName objectName = createNetworkConnectorObjectName(connector);
getManagementContext().unregisterMBean(objectName);
} catch (Exception e) {
LOG.warn("Network Connector could not be unregistered from JMX due " + e.getMessage() + ". This exception is ignored.", e);
}
}
}
protected void registerProxyConnectorMBean(ProxyConnector connector) throws IOException {
ProxyConnectorView view = new ProxyConnectorView(connector);
try {
ObjectName objectName = BrokerMBeanSupport.createNetworkConnectorName(getBrokerObjectName(), "proxyConnectors", connector.getName());
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e);
}
}
protected void registerJmsConnectorMBean(JmsConnector connector) throws IOException {
JmsConnectorView view = new JmsConnectorView(connector);
try {
ObjectName objectName = BrokerMBeanSupport.createNetworkConnectorName(getBrokerObjectName(), "jmsConnectors", connector.getName());
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e);
}
}
/**
* Factory method to create a new broker
*
* @throws Exception
* @throws
* @throws
*/
protected Broker createBroker() throws Exception {
regionBroker = createRegionBroker();
Broker broker = addInterceptors(regionBroker);
// Add a filter that will stop access to the broker once stopped
broker = new MutableBrokerFilter(broker) {
Broker old;
@Override
public void stop() throws Exception {
old = this.next.getAndSet(new ErrorBroker("Broker has been stopped: " + this) {
// Just ignore additional stop actions.
@Override
public void stop() throws Exception {
}
});
old.stop();
}
@Override
public void start() throws Exception {
if (forceStart && old != null) {
this.next.set(old);
}
getNext().start();
}
};
return broker;
}
/**
* Factory method to create the core region broker onto which interceptors
* are added
*
* @throws Exception
*/
protected Broker createRegionBroker() throws Exception {
if (destinationInterceptors == null) {
destinationInterceptors = createDefaultDestinationInterceptor();
}
configureServices(destinationInterceptors);
DestinationInterceptor destinationInterceptor = new CompositeDestinationInterceptor(destinationInterceptors);
if (destinationFactory == null) {
destinationFactory = new DestinationFactoryImpl(this, getTaskRunnerFactory(), getPersistenceAdapter());
}
return createRegionBroker(destinationInterceptor);
}
protected Broker createRegionBroker(DestinationInterceptor destinationInterceptor) throws IOException {
RegionBroker regionBroker;
if (isUseJmx()) {
try {
regionBroker = new ManagedRegionBroker(this, getManagementContext(), getBrokerObjectName(),
getTaskRunnerFactory(), getConsumerSystemUsage(), destinationFactory, destinationInterceptor,getScheduler(),getExecutor());
} catch(MalformedObjectNameException me){
LOG.warn("Cannot create ManagedRegionBroker due " + me.getMessage(), me);
throw new IOException(me);
}
} else {
regionBroker = new RegionBroker(this, getTaskRunnerFactory(), getConsumerSystemUsage(), destinationFactory,
destinationInterceptor,getScheduler(),getExecutor());
}
destinationFactory.setRegionBroker(regionBroker);
regionBroker.setKeepDurableSubsActive(keepDurableSubsActive);
regionBroker.setBrokerName(getBrokerName());
regionBroker.getDestinationStatistics().setEnabled(enableStatistics);
regionBroker.setAllowTempAutoCreationOnSend(isAllowTempAutoCreationOnSend());
if (brokerId != null) {
regionBroker.setBrokerId(brokerId);
}
return regionBroker;
}
/**
* Create the default destination interceptor
*/
protected DestinationInterceptor[] createDefaultDestinationInterceptor() {
List<DestinationInterceptor> answer = new ArrayList<DestinationInterceptor>();
if (isUseVirtualTopics()) {
VirtualDestinationInterceptor interceptor = new VirtualDestinationInterceptor();
VirtualTopic virtualTopic = new VirtualTopic();
virtualTopic.setName("VirtualTopic.>");
VirtualDestination[] virtualDestinations = { virtualTopic };
interceptor.setVirtualDestinations(virtualDestinations);
answer.add(interceptor);
}
if (isUseMirroredQueues()) {
MirroredQueue interceptor = new MirroredQueue();
answer.add(interceptor);
}
DestinationInterceptor[] array = new DestinationInterceptor[answer.size()];
answer.toArray(array);
return array;
}
/**
* Strategy method to add interceptors to the broker
*
* @throws IOException
*/
protected Broker addInterceptors(Broker broker) throws Exception {
if (isSchedulerSupport()) {
SchedulerBroker sb = new SchedulerBroker(this, broker, getJobSchedulerStore());
if (isUseJmx()) {
JobSchedulerViewMBean view = new JobSchedulerView(sb.getJobScheduler());
try {
ObjectName objectName = BrokerMBeanSupport.createJobSchedulerServiceName(getBrokerObjectName());
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
this.adminView.setJMSJobScheduler(objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("JobScheduler could not be registered in JMX: "
+ e.getMessage(), e);
}
}
broker = sb;
}
if (isUseJmx()) {
HealthViewMBean statusView = new HealthView((ManagedRegionBroker)getRegionBroker());
try {
ObjectName objectName = BrokerMBeanSupport.createHealthServiceName(getBrokerObjectName());
AnnotatedMBean.registerMBean(getManagementContext(), statusView, objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("Status MBean could not be registered in JMX: "
+ e.getMessage(), e);
}
}
if (isAdvisorySupport()) {
broker = new AdvisoryBroker(broker);
}
broker = new CompositeDestinationBroker(broker);
broker = new TransactionBroker(broker, getPersistenceAdapter().createTransactionStore());
if (isPopulateJMSXUserID()) {
UserIDBroker userIDBroker = new UserIDBroker(broker);
userIDBroker.setUseAuthenticatePrincipal(isUseAuthenticatedPrincipalForJMSXUserID());
broker = userIDBroker;
}
if (isMonitorConnectionSplits()) {
broker = new ConnectionSplitBroker(broker);
}
if (plugins != null) {
for (int i = 0; i < plugins.length; i++) {
BrokerPlugin plugin = plugins[i];
broker = plugin.installPlugin(broker);
}
}
return broker;
}
protected PersistenceAdapter createPersistenceAdapter() throws IOException {
if (isPersistent()) {
PersistenceAdapterFactory fac = getPersistenceFactory();
if (fac != null) {
return fac.createPersistenceAdapter();
} else {
try {
String clazz = "org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter";
PersistenceAdapter adaptor = (PersistenceAdapter)getClass().getClassLoader().loadClass(clazz).newInstance();
File dir = new File(getBrokerDataDirectory(),"KahaDB");
adaptor.setDirectory(dir);
return adaptor;
} catch (Throwable e) {
throw IOExceptionSupport.create(e);
}
}
} else {
return new MemoryPersistenceAdapter();
}
}
protected ObjectName createBrokerObjectName() throws MalformedObjectNameException {
return BrokerMBeanSupport.createBrokerObjectName(getManagementContext().getJmxDomainName(), getBrokerName());
}
protected TransportConnector createTransportConnector(URI brokerURI) throws Exception {
TransportServer transport = TransportFactorySupport.bind(this, brokerURI);
return new TransportConnector(transport);
}
/**
* Extracts the port from the options
*/
protected Object getPort(Map<?,?> options) {
Object port = options.get("port");
if (port == null) {
port = DEFAULT_PORT;
LOG.warn("No port specified so defaulting to: {}", port);
}
return port;
}
protected void addShutdownHook() {
if (useShutdownHook) {
shutdownHook = new Thread("ActiveMQ ShutdownHook") {
@Override
public void run() {
containerShutdown();
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}
protected void removeShutdownHook() {
if (shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} catch (Exception e) {
LOG.debug("Caught exception, must be shutting down. This exception is ignored.", e);
}
}
}
/**
* Sets hooks to be executed when broker shut down
*
* @org.apache.xbean.Property
*/
public void setShutdownHooks(List<Runnable> hooks) throws Exception {
for (Runnable hook : hooks) {
addShutdownHook(hook);
}
}
/**
* Causes a clean shutdown of the container when the VM is being shut down
*/
protected void containerShutdown() {
try {
stop();
} catch (IOException e) {
Throwable linkedException = e.getCause();
if (linkedException != null) {
logError("Failed to shut down: " + e + ". Reason: " + linkedException, linkedException);
} else {
logError("Failed to shut down: " + e, e);
}
if (!useLoggingForShutdownErrors) {
e.printStackTrace(System.err);
}
} catch (Exception e) {
logError("Failed to shut down: " + e, e);
}
}
protected void logError(String message, Throwable e) {
if (useLoggingForShutdownErrors) {
LOG.error("Failed to shut down: " + e);
} else {
System.err.println("Failed to shut down: " + e);
}
}
/**
* Starts any configured destinations on startup
*/
protected void startDestinations() throws Exception {
if (destinations != null) {
ConnectionContext adminConnectionContext = getAdminConnectionContext();
for (int i = 0; i < destinations.length; i++) {
ActiveMQDestination destination = destinations[i];
getBroker().addDestination(adminConnectionContext, destination,true);
}
}
if (isUseVirtualTopics()) {
startVirtualConsumerDestinations();
}
}
/**
* Returns the broker's administration connection context used for
* configuring the broker at startup
*/
public ConnectionContext getAdminConnectionContext() throws Exception {
return BrokerSupport.getConnectionContext(getBroker());
}
protected void startManagementContext() throws Exception {
getManagementContext().setBrokerName(brokerName);
getManagementContext().start();
adminView = new BrokerView(this, null);
ObjectName objectName = getBrokerObjectName();
AnnotatedMBean.registerMBean(getManagementContext(), adminView, objectName);
}
/**
* Start all transport and network connections, proxies and bridges
*
* @throws Exception
*/
public void startAllConnectors() throws Exception {
Set<ActiveMQDestination> durableDestinations = getBroker().getDurableDestinations();
List<TransportConnector> al = new ArrayList<TransportConnector>();
for (Iterator<TransportConnector> iter = getTransportConnectors().iterator(); iter.hasNext();) {
TransportConnector connector = iter.next();
connector.setBrokerService(this);
al.add(startTransportConnector(connector));
}
if (al.size() > 0) {
// let's clear the transportConnectors list and replace it with
// the started transportConnector instances
this.transportConnectors.clear();
setTransportConnectors(al);
}
this.slave = false;
URI uri = getVmConnectorURI();
Map<String, String> map = new HashMap<String, String>(URISupport.parseParameters(uri));
map.put("network", "true");
map.put("async", "false");
uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map));
if (!stopped.get()) {
ThreadPoolExecutor networkConnectorStartExecutor = null;
if (isNetworkConnectorStartAsync()) {
// spin up as many threads as needed
networkConnectorStartExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
10, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
new ThreadFactory() {
int count=0;
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "NetworkConnector Start Thread-" +(count++));
thread.setDaemon(true);
return thread;
}
});
}
for (Iterator<NetworkConnector> iter = getNetworkConnectors().iterator(); iter.hasNext();) {
final NetworkConnector connector = iter.next();
connector.setLocalUri(uri);
connector.setBrokerName(getBrokerName());
connector.setDurableDestinations(durableDestinations);
if (getDefaultSocketURIString() != null) {
connector.setBrokerURL(getDefaultSocketURIString());
}
if (networkConnectorStartExecutor != null) {
networkConnectorStartExecutor.execute(new Runnable() {
@Override
public void run() {
try {
LOG.info("Async start of {}", connector);
connector.start();
} catch(Exception e) {
LOG.error("Async start of network connector: {} failed", connector, e);
}
}
});
} else {
connector.start();
}
}
if (networkConnectorStartExecutor != null) {
// executor done when enqueued tasks are complete
ThreadPoolUtils.shutdown(networkConnectorStartExecutor);
}
for (Iterator<ProxyConnector> iter = getProxyConnectors().iterator(); iter.hasNext();) {
ProxyConnector connector = iter.next();
connector.start();
}
for (Iterator<JmsConnector> iter = jmsConnectors.iterator(); iter.hasNext();) {
JmsConnector connector = iter.next();
connector.start();
}
for (Service service : services) {
configureService(service);
service.start();
}
}
}
protected TransportConnector startTransportConnector(TransportConnector connector) throws Exception {
connector.setTaskRunnerFactory(getTaskRunnerFactory());
MessageAuthorizationPolicy policy = getMessageAuthorizationPolicy();
if (policy != null) {
connector.setMessageAuthorizationPolicy(policy);
}
if (isUseJmx()) {
connector = registerConnectorMBean(connector);
}
connector.getStatistics().setEnabled(enableStatistics);
connector.start();
return connector;
}
/**
* Perform any custom dependency injection
*/
protected void configureServices(Object[] services) {
for (Object service : services) {
configureService(service);
}
}
/**
* Perform any custom dependency injection
*/
protected void configureService(Object service) {
if (service instanceof BrokerServiceAware) {
BrokerServiceAware serviceAware = (BrokerServiceAware) service;
serviceAware.setBrokerService(this);
}
}
public void handleIOException(IOException exception) {
if (ioExceptionHandler != null) {
ioExceptionHandler.handle(exception);
} else {
LOG.info("No IOExceptionHandler registered, ignoring IO exception", exception);
}
}
protected void startVirtualConsumerDestinations() throws Exception {
ConnectionContext adminConnectionContext = getAdminConnectionContext();
Set<ActiveMQDestination> destinations = destinationFactory.getDestinations();
DestinationFilter filter = getVirtualTopicConsumerDestinationFilter();
if (!destinations.isEmpty()) {
for (ActiveMQDestination destination : destinations) {
if (filter.matches(destination) == true) {
broker.addDestination(adminConnectionContext, destination, false);
}
}
}
}
private DestinationFilter getVirtualTopicConsumerDestinationFilter() {
// created at startup, so no sync needed
if (virtualConsumerDestinationFilter == null) {
Set <ActiveMQQueue> consumerDestinations = new HashSet<ActiveMQQueue>();
if (destinationInterceptors != null) {
for (DestinationInterceptor interceptor : destinationInterceptors) {
if (interceptor instanceof VirtualDestinationInterceptor) {
VirtualDestinationInterceptor virtualDestinationInterceptor = (VirtualDestinationInterceptor) interceptor;
for (VirtualDestination virtualDestination: virtualDestinationInterceptor.getVirtualDestinations()) {
if (virtualDestination instanceof VirtualTopic) {
consumerDestinations.add(new ActiveMQQueue(((VirtualTopic) virtualDestination).getPrefix() + DestinationFilter.ANY_DESCENDENT));
}
}
}
}
}
ActiveMQQueue filter = new ActiveMQQueue();
filter.setCompositeDestinations(consumerDestinations.toArray(new ActiveMQDestination[]{}));
virtualConsumerDestinationFilter = DestinationFilter.parseFilter(filter);
}
return virtualConsumerDestinationFilter;
}
protected synchronized ThreadPoolExecutor getExecutor() {
if (this.executor == null) {
this.executor = new ThreadPoolExecutor(1, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
private long i = 0;
@Override
public Thread newThread(Runnable runnable) {
this.i++;
Thread thread = new Thread(runnable, "ActiveMQ BrokerService.worker." + this.i);
thread.setDaemon(true);
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
LOG.error("Error in thread '{}'", t.getName(), e);
}
});
return thread;
}
}, new RejectedExecutionHandler() {
@Override
public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
try {
executor.getQueue().offer(r, 60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RejectedExecutionException("Interrupted waiting for BrokerService.worker");
}
throw new RejectedExecutionException("Timed Out while attempting to enqueue Task.");
}
});
}
return this.executor;
}
public synchronized Scheduler getScheduler() {
if (this.scheduler==null) {
this.scheduler = new Scheduler("ActiveMQ Broker["+getBrokerName()+"] Scheduler");
try {
this.scheduler.start();
} catch (Exception e) {
LOG.error("Failed to start Scheduler", e);
}
}
return this.scheduler;
}
public Broker getRegionBroker() {
return regionBroker;
}
public void setRegionBroker(Broker regionBroker) {
this.regionBroker = regionBroker;
}
public void addShutdownHook(Runnable hook) {
synchronized (shutdownHooks) {
shutdownHooks.add(hook);
}
}
public void removeShutdownHook(Runnable hook) {
synchronized (shutdownHooks) {
shutdownHooks.remove(hook);
}
}
public boolean isSystemExitOnShutdown() {
return systemExitOnShutdown;
}
/**
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setSystemExitOnShutdown(boolean systemExitOnShutdown) {
this.systemExitOnShutdown = systemExitOnShutdown;
}
public int getSystemExitOnShutdownExitCode() {
return systemExitOnShutdownExitCode;
}
public void setSystemExitOnShutdownExitCode(int systemExitOnShutdownExitCode) {
this.systemExitOnShutdownExitCode = systemExitOnShutdownExitCode;
}
public SslContext getSslContext() {
return sslContext;
}
public void setSslContext(SslContext sslContext) {
this.sslContext = sslContext;
}
public boolean isShutdownOnSlaveFailure() {
return shutdownOnSlaveFailure;
}
/**
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setShutdownOnSlaveFailure(boolean shutdownOnSlaveFailure) {
this.shutdownOnSlaveFailure = shutdownOnSlaveFailure;
}
public boolean isWaitForSlave() {
return waitForSlave;
}
/**
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setWaitForSlave(boolean waitForSlave) {
this.waitForSlave = waitForSlave;
}
public long getWaitForSlaveTimeout() {
return this.waitForSlaveTimeout;
}
public void setWaitForSlaveTimeout(long waitForSlaveTimeout) {
this.waitForSlaveTimeout = waitForSlaveTimeout;
}
/**
* Get the passiveSlave
* @return the passiveSlave
*/
public boolean isPassiveSlave() {
return this.passiveSlave;
}
/**
* Set the passiveSlave
* @param passiveSlave the passiveSlave to set
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setPassiveSlave(boolean passiveSlave) {
this.passiveSlave = passiveSlave;
}
/**
* override the Default IOException handler, called when persistence adapter
* has experiences File or JDBC I/O Exceptions
*
* @param ioExceptionHandler
*/
public void setIoExceptionHandler(IOExceptionHandler ioExceptionHandler) {
configureService(ioExceptionHandler);
this.ioExceptionHandler = ioExceptionHandler;
}
public IOExceptionHandler getIoExceptionHandler() {
return ioExceptionHandler;
}
/**
* @return the schedulerSupport
*/
public boolean isSchedulerSupport() {
return this.schedulerSupport && (isPersistent() || jobSchedulerStore != null);
}
/**
* @param schedulerSupport the schedulerSupport to set
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setSchedulerSupport(boolean schedulerSupport) {
this.schedulerSupport = schedulerSupport;
}
/**
* @return the schedulerDirectory
*/
public File getSchedulerDirectoryFile() {
if (this.schedulerDirectoryFile == null) {
this.schedulerDirectoryFile = new File(getBrokerDataDirectory(), "scheduler");
}
return schedulerDirectoryFile;
}
/**
* @param schedulerDirectory the schedulerDirectory to set
*/
public void setSchedulerDirectoryFile(File schedulerDirectory) {
this.schedulerDirectoryFile = schedulerDirectory;
}
public void setSchedulerDirectory(String schedulerDirectory) {
setSchedulerDirectoryFile(new File(schedulerDirectory));
}
public int getSchedulePeriodForDestinationPurge() {
return this.schedulePeriodForDestinationPurge;
}
public void setSchedulePeriodForDestinationPurge(int schedulePeriodForDestinationPurge) {
this.schedulePeriodForDestinationPurge = schedulePeriodForDestinationPurge;
}
public int getMaxPurgedDestinationsPerSweep() {
return this.maxPurgedDestinationsPerSweep;
}
public void setMaxPurgedDestinationsPerSweep(int maxPurgedDestinationsPerSweep) {
this.maxPurgedDestinationsPerSweep = maxPurgedDestinationsPerSweep;
}
public BrokerContext getBrokerContext() {
return brokerContext;
}
public void setBrokerContext(BrokerContext brokerContext) {
this.brokerContext = brokerContext;
}
public void setBrokerId(String brokerId) {
this.brokerId = new BrokerId(brokerId);
}
public boolean isUseAuthenticatedPrincipalForJMSXUserID() {
return useAuthenticatedPrincipalForJMSXUserID;
}
public void setUseAuthenticatedPrincipalForJMSXUserID(boolean useAuthenticatedPrincipalForJMSXUserID) {
this.useAuthenticatedPrincipalForJMSXUserID = useAuthenticatedPrincipalForJMSXUserID;
}
/**
* Should MBeans that support showing the Authenticated User Name information have this
* value filled in or not.
*
* @return true if user names should be exposed in MBeans
*/
public boolean isPopulateUserNameInMBeans() {
return this.populateUserNameInMBeans;
}
/**
* Sets whether Authenticated User Name information is shown in MBeans that support this field.
* @param value if MBeans should expose user name information.
*/
public void setPopulateUserNameInMBeans(boolean value) {
this.populateUserNameInMBeans = value;
}
/**
* Gets the time in Milliseconds that an invocation of an MBean method will wait before
* failing. The default value is to wait forever (zero).
*
* @return timeout in milliseconds before MBean calls fail, (default is 0 or no timeout).
*/
public long getMbeanInvocationTimeout() {
return mbeanInvocationTimeout;
}
/**
* Gets the time in Milliseconds that an invocation of an MBean method will wait before
* failing. The default value is to wait forever (zero).
*
* @param mbeanInvocationTimeout
* timeout in milliseconds before MBean calls fail, (default is 0 or no timeout).
*/
public void setMbeanInvocationTimeout(long mbeanInvocationTimeout) {
this.mbeanInvocationTimeout = mbeanInvocationTimeout;
}
public boolean isNetworkConnectorStartAsync() {
return networkConnectorStartAsync;
}
public void setNetworkConnectorStartAsync(boolean networkConnectorStartAsync) {
this.networkConnectorStartAsync = networkConnectorStartAsync;
}
public boolean isAllowTempAutoCreationOnSend() {
return allowTempAutoCreationOnSend;
}
/**
* enable if temp destinations need to be propagated through a network when
* advisorySupport==false. This is used in conjunction with the policy
* gcInactiveDestinations for matching temps so they can get removed
* when inactive
*
* @param allowTempAutoCreationOnSend
*/
public void setAllowTempAutoCreationOnSend(boolean allowTempAutoCreationOnSend) {
this.allowTempAutoCreationOnSend = allowTempAutoCreationOnSend;
}
public long getOfflineDurableSubscriberTimeout() {
return offlineDurableSubscriberTimeout;
}
public void setOfflineDurableSubscriberTimeout(long offlineDurableSubscriberTimeout) {
this.offlineDurableSubscriberTimeout = offlineDurableSubscriberTimeout;
}
public long getOfflineDurableSubscriberTaskSchedule() {
return offlineDurableSubscriberTaskSchedule;
}
public void setOfflineDurableSubscriberTaskSchedule(long offlineDurableSubscriberTaskSchedule) {
this.offlineDurableSubscriberTaskSchedule = offlineDurableSubscriberTaskSchedule;
}
public boolean shouldRecordVirtualDestination(ActiveMQDestination destination) {
return isUseVirtualTopics() && destination.isQueue() &&
getVirtualTopicConsumerDestinationFilter().matches(destination);
}
public Throwable getStartException() {
return startException;
}
public boolean isStartAsync() {
return startAsync;
}
public void setStartAsync(boolean startAsync) {
this.startAsync = startAsync;
}
public boolean isSlave() {
return this.slave;
}
public boolean isStopping() {
return this.stopping.get();
}
/**
* @return true if the broker allowed to restart on shutdown.
*/
public boolean isRestartAllowed() {
return restartAllowed;
}
/**
* Sets if the broker allowed to restart on shutdown.
* @return
*/
public void setRestartAllowed(boolean restartAllowed) {
this.restartAllowed = restartAllowed;
}
/**
* A lifecycle manager of the BrokerService should
* inspect this property after a broker shutdown has occurred
* to find out if the broker needs to be re-created and started
* again.
*
* @return true if the broker wants to be restarted after it shuts down.
*/
public boolean isRestartRequested() {
return restartRequested;
}
public void requestRestart() {
this.restartRequested = true;
}
public int getStoreOpenWireVersion() {
return storeOpenWireVersion;
}
public void setStoreOpenWireVersion(int storeOpenWireVersion) {
this.storeOpenWireVersion = storeOpenWireVersion;
}
}
| false | true | protected void checkSystemUsageLimits() throws IOException {
SystemUsage usage = getSystemUsage();
long memLimit = usage.getMemoryUsage().getLimit();
long jvmLimit = Runtime.getRuntime().maxMemory();
if (memLimit > jvmLimit) {
usage.getMemoryUsage().setPercentOfJvmHeap(70);
LOG.error("Memory Usage for the Broker (" + memLimit / (1024 * 1024) +
" mb) is more than the maximum available for the JVM: " +
jvmLimit / (1024 * 1024) + " mb - resetting to 70% of maximum available: " + (usage.getMemoryUsage().getLimit() / (1024 * 1024)) + " mb");
}
if (getPersistenceAdapter() != null) {
PersistenceAdapter adapter = getPersistenceAdapter();
File dir = adapter.getDirectory();
if (dir != null) {
String dirPath = dir.getAbsolutePath();
if (!dir.isAbsolute()) {
dir = new File(dirPath);
}
while (dir != null && !dir.isDirectory()) {
dir = dir.getParentFile();
}
long storeLimit = usage.getStoreUsage().getLimit();
long dirFreeSpace = dir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.warn("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the data directory: " + dir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) +
" mb of usable space - resetting to maximum available disk space: " +
dirFreeSpace / (1024 * 1024) + " mb");
usage.getStoreUsage().setLimit(dirFreeSpace);
}
}
long maxJournalFileSize = 0;
long storeLimit = usage.getStoreUsage().getLimit();
if (adapter instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) adapter).getJournalMaxFileLength();
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the store will not accept any data when used.");
}
}
File tmpDir = getTmpDataDirectory();
if (tmpDir != null) {
String tmpDirPath = tmpDir.getAbsolutePath();
if (!tmpDir.isAbsolute()) {
tmpDir = new File(tmpDirPath);
}
long storeLimit = usage.getTempUsage().getLimit();
while (tmpDir != null && !tmpDir.isDirectory()) {
tmpDir = tmpDir.getParentFile();
}
long dirFreeSpace = tmpDir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the temporary data directory: " + tmpDirPath +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to maximum available " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getTempUsage().setLimit(dirFreeSpace);
}
if (isPersistent()) {
long maxJournalFileSize;
PListStore store = usage.getTempUsage().getStore();
if (store != null && store instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) store).getJournalMaxFileLength();
} else {
maxJournalFileSize = DEFAULT_MAX_FILE_LENGTH;
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the temporary store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the temp store will not accept any data when used.");
}
}
}
if (getJobSchedulerStore() != null) {
JobSchedulerStore scheduler = getJobSchedulerStore();
File schedulerDir = scheduler.getDirectory();
if (schedulerDir != null) {
String schedulerDirPath = schedulerDir.getAbsolutePath();
if (!schedulerDir.isAbsolute()) {
schedulerDir = new File(schedulerDirPath);
}
while (schedulerDir != null && !schedulerDir.isDirectory()) {
schedulerDir = schedulerDir.getParentFile();
}
long schedulerLimit = usage.getJobSchedulerUsage().getLimit();
long dirFreeSpace = schedulerDir.getUsableSpace();
if (schedulerLimit > dirFreeSpace) {
LOG.warn("Job Scheduler Store limit is " + schedulerLimit / (1024 * 1024) +
" mb, whilst the data directory: " + schedulerDir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getJobSchedulerUsage().setLimit(dirFreeSpace);
}
}
}
}
| protected void checkSystemUsageLimits() throws IOException {
SystemUsage usage = getSystemUsage();
long memLimit = usage.getMemoryUsage().getLimit();
long jvmLimit = Runtime.getRuntime().maxMemory();
if (memLimit > jvmLimit) {
usage.getMemoryUsage().setPercentOfJvmHeap(70);
LOG.error("Memory Usage for the Broker (" + memLimit / (1024 * 1024) +
" mb) is more than the maximum available for the JVM: " +
jvmLimit / (1024 * 1024) + " mb - resetting to 70% of maximum available: " + (usage.getMemoryUsage().getLimit() / (1024 * 1024)) + " mb");
}
if (getPersistenceAdapter() != null) {
PersistenceAdapter adapter = getPersistenceAdapter();
File dir = adapter.getDirectory();
if (dir != null) {
String dirPath = dir.getAbsolutePath();
if (!dir.isAbsolute()) {
dir = new File(dirPath);
}
while (dir != null && !dir.isDirectory()) {
dir = dir.getParentFile();
}
long storeLimit = usage.getStoreUsage().getLimit();
long storeCurrent = usage.getStoreUsage().getUsage();
long dirFreeSpace = dir.getUsableSpace();
if (storeLimit > (dirFreeSpace + storeCurrent)) {
LOG.warn("Store limit is " + storeLimit / (1024 * 1024) +
" mb (current store usage is " + storeCurrent / (1024 * 1024) +
" mb). The data directory: " + dir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) +
" mb of usable space - resetting to maximum available disk space: " +
(dirFreeSpace + storeCurrent) / (1024 * 1024) + " mb");
usage.getStoreUsage().setLimit(dirFreeSpace + storeCurrent);
}
}
long maxJournalFileSize = 0;
long storeLimit = usage.getStoreUsage().getLimit();
if (adapter instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) adapter).getJournalMaxFileLength();
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the store will not accept any data when used.");
}
}
File tmpDir = getTmpDataDirectory();
if (tmpDir != null) {
String tmpDirPath = tmpDir.getAbsolutePath();
if (!tmpDir.isAbsolute()) {
tmpDir = new File(tmpDirPath);
}
long storeLimit = usage.getTempUsage().getLimit();
while (tmpDir != null && !tmpDir.isDirectory()) {
tmpDir = tmpDir.getParentFile();
}
long dirFreeSpace = tmpDir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the temporary data directory: " + tmpDirPath +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to maximum available " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getTempUsage().setLimit(dirFreeSpace);
}
if (isPersistent()) {
long maxJournalFileSize;
PListStore store = usage.getTempUsage().getStore();
if (store != null && store instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) store).getJournalMaxFileLength();
} else {
maxJournalFileSize = DEFAULT_MAX_FILE_LENGTH;
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the temporary store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the temp store will not accept any data when used.");
}
}
}
if (getJobSchedulerStore() != null) {
JobSchedulerStore scheduler = getJobSchedulerStore();
File schedulerDir = scheduler.getDirectory();
if (schedulerDir != null) {
String schedulerDirPath = schedulerDir.getAbsolutePath();
if (!schedulerDir.isAbsolute()) {
schedulerDir = new File(schedulerDirPath);
}
while (schedulerDir != null && !schedulerDir.isDirectory()) {
schedulerDir = schedulerDir.getParentFile();
}
long schedulerLimit = usage.getJobSchedulerUsage().getLimit();
long dirFreeSpace = schedulerDir.getUsableSpace();
if (schedulerLimit > dirFreeSpace) {
LOG.warn("Job Scheduler Store limit is " + schedulerLimit / (1024 * 1024) +
" mb, whilst the data directory: " + schedulerDir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getJobSchedulerUsage().setLimit(dirFreeSpace);
}
}
}
}
|
diff --git a/tests/org.jboss.tools.switchyard.ui.bot.test/src/org/jboss/tools/switchyard/ui/bot/test/BPMTest.java b/tests/org.jboss.tools.switchyard.ui.bot.test/src/org/jboss/tools/switchyard/ui/bot/test/BPMTest.java
index 45c6fd12..787e3b04 100644
--- a/tests/org.jboss.tools.switchyard.ui.bot.test/src/org/jboss/tools/switchyard/ui/bot/test/BPMTest.java
+++ b/tests/org.jboss.tools.switchyard.ui.bot.test/src/org/jboss/tools/switchyard/ui/bot/test/BPMTest.java
@@ -1,163 +1,164 @@
package org.jboss.tools.switchyard.ui.bot.test;
import static org.junit.Assert.assertEquals;
import org.jboss.reddeer.eclipse.jdt.ui.ProjectExplorer;
import org.jboss.reddeer.eclipse.jdt.ui.packageexplorer.ProjectItem;
import org.jboss.reddeer.swt.impl.button.PushButton;
import org.jboss.reddeer.swt.impl.menu.ShellMenu;
import org.jboss.reddeer.swt.impl.shell.WorkbenchShell;
import org.jboss.reddeer.swt.impl.text.LabeledText;
import org.jboss.reddeer.swt.impl.tree.DefaultTreeItem;
import org.jboss.reddeer.swt.test.RedDeerTest;
import org.jboss.reddeer.swt.wait.AbstractWait;
import org.jboss.reddeer.workbench.view.impl.WorkbenchView;
import org.jboss.tools.bpmn2.reddeer.view.BPMN2Editor;
import org.jboss.tools.bpmn2.reddeer.view.BPMN2PropertiesView;
import org.jboss.tools.bpmn2.reddeer.editor.ConstructType;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.FromDataOutput;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.FromVariable;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.InputParameterMapping;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.OutputParameterMapping;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.ToDataInput;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.ToVariable;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.endevents.TerminateEndEvent;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.startevents.StartEvent;
import org.jboss.tools.bpmn2.reddeer.editor.switchyard.activities.SwitchYardServiceTask;
import org.jboss.tools.switchyard.reddeer.component.BPM;
import org.jboss.tools.switchyard.reddeer.component.Bean;
import org.jboss.tools.switchyard.reddeer.component.Component;
import org.jboss.tools.switchyard.reddeer.component.Service;
import org.jboss.tools.switchyard.reddeer.editor.SwitchYardEditor;
import org.jboss.tools.switchyard.reddeer.editor.TextEditor;
import org.jboss.tools.switchyard.reddeer.view.JUnitView;
import org.jboss.tools.switchyard.reddeer.widget.ProjectItemExt;
import org.jboss.tools.switchyard.reddeer.wizard.ReferenceWizard;
import org.jboss.tools.switchyard.reddeer.wizard.SwitchYardProjectWizard;
import org.jboss.tools.switchyard.ui.bot.test.suite.CleanWorkspaceRequirement.CleanWorkspace;
import org.jboss.tools.switchyard.ui.bot.test.suite.PerspectiveRequirement.Perspective;
import org.jboss.tools.switchyard.ui.bot.test.suite.SwitchyardSuite;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Create simple BPMN process with a switchyard service task, run JUnit test.
* @author lfabriko
*
*/
@CleanWorkspace
@Perspective(name = "Java EE")
@RunWith(SwitchyardSuite.class)
public class BPMTest extends RedDeerTest {
private static final String PROJECT = "switchyard-bpm-processgreet";
private static final String PACKAGE = "org.switchyard.quickstarts.bpm.service";
private static final String GROUP_ID = "org.switchyard.quickstarts.bpm.service";
private static final String PROCESS_GREET = "ProcessGreet";
private static final String BPMN_FILE_NAME = "ProcessGreet.bpmn";
private static final String PACKAGE_MAIN_JAVA = "src/main/java";
private static final String PACKAGE_MAIN_RESOURCES = "src/main/resources";
private static final Integer[] BPM_COORDS = { 50, 200 };
private static final Integer[] BEAN_COORDS = { 250, 200 };
private static final String EVAL_GREET = "EvalGreet";
private static final String PROCESS_GREET_DECL = "public boolean checkGreetIsPolite(String greet);";
private static final String EVAL_GREET_DECL = "public boolean checkGreet(String greet);";
private static final String EVAL_GREET_BEAN = EVAL_GREET + "Bean";
@Before @After
public void closeSwitchyardFile() {
try {
new SwitchYardEditor().saveAndClose();
} catch (Exception ex) {
// it is ok, we just try to close switchyard.xml if it is open
}
}
@Test
public void bpmCreationTest() {
new WorkbenchShell().maximize();
// Create new Switchyard project, Add support for Bean, BPM
new SwitchYardProjectWizard(PROJECT).impl("Bean", "BPM (jBPM)")
.groupId(GROUP_ID).packageName(PACKAGE).create();
openFile(PROJECT, PACKAGE_MAIN_RESOURCES, "META-INF", "switchyard.xml");
new BPM().setService(PROCESS_GREET).setBpmnFileName(BPMN_FILE_NAME)
.create(BPM_COORDS);
AbstractWait.sleep(1000);
new Bean().setService(EVAL_GREET).create(BEAN_COORDS);
AbstractWait.sleep(1000);
// reference to bean
new Component(PROCESS_GREET).contextButton("Reference").click();
new ReferenceWizard().selectJavaInterface(EVAL_GREET).finish();
AbstractWait.sleep(2 * 1000);
// declare ProcessGreet interface
new Service(PROCESS_GREET, 1).openTextEditor();
new TextEditor(PROCESS_GREET + ".java").typeAfter("interface",
PROCESS_GREET_DECL);
// declare EvalGreet interface
openFile(PROJECT, PACKAGE_MAIN_JAVA, PACKAGE, EVAL_GREET + ".java");
new TextEditor(EVAL_GREET + ".java").typeAfter("interface",
EVAL_GREET_DECL);
// implement EvalGreetBean
openFile(PROJECT, PACKAGE_MAIN_JAVA, PACKAGE, EVAL_GREET_BEAN + ".java");
new TextEditor(EVAL_GREET_BEAN + ".java")
.typeAfter("implements", "@Override")
.newLine()
.type("public boolean checkGreet(String greet){")
.newLine()
.type("return (greet.equals(\"Good evening\")) ? true : false;")
.newLine().type("}");
// BPM Process and its properties
openFile(PROJECT, PACKAGE_MAIN_RESOURCES, BPMN_FILE_NAME);
BPMN2Editor editor = new BPMN2Editor();
editor.click(1, 1);
new BPMN2PropertiesView().selectTab("Process");
new LabeledText("Id").setText(PROCESS_GREET);
editor.setFocus();
new TerminateEndEvent("EndProcess").delete();
new StartEvent("StartProcess").append("EvalGreet",
ConstructType.SWITCHYARD_SERVICE_TASK);
SwitchYardServiceTask task = new SwitchYardServiceTask("EvalGreet");
task.setTaskAttribute("Operation Name", "checkGreet");
task.setTaskAttribute("Service Name", EVAL_GREET);
task.addParameterMapping(new InputParameterMapping(new FromVariable(
- PROCESS_GREET + "/Parameter"), new ToDataInput("Parameter")));
+ PROCESS_GREET + "/Parameter"), new ToDataInput("Parameter", "String")));
task.addParameterMapping(new OutputParameterMapping(new FromDataOutput(
- "Result"), new ToVariable(PROCESS_GREET + "/Result")));
+ "Result", "String"), new ToVariable(PROCESS_GREET + "/Result")));
task.append("EndProcess", ConstructType.TERMINATE_END_EVENT);
openFile(PROJECT, PACKAGE_MAIN_RESOURCES, "META-INF", "switchyard.xml");
// Junit
new Service(PROCESS_GREET, 1).newServiceTestClass();
new TextEditor(PROCESS_GREET + "Test.java")
.deleteLineWith("null")
.deleteLineWith("assertTrue")
.typeBefore("boolean", "String message = \"Good evening\";")
.newLine()
.typeAfter("getContent", "Assert.assertTrue(result);")
.newLine()
.type("Assert.assertFalse(service.operation(\"checkGreetIsPolite\").sendInOut(\"hi\").getContent(Boolean.class));");
new ShellMenu("File", "Save All").select();
AbstractWait.sleep(1000);
new PushButton("No").click();// BPMN nature
ProjectItem item = new ProjectExplorer().getProject(PROJECT)
.getProjectItem("src/test/java", PACKAGE,
PROCESS_GREET + "Test.java");
new ProjectItemExt(item).runAsJUnitTest();
+ AbstractWait.sleep(30 * 1000);
assertEquals("1/1", new JUnitView().getRunStatus());
assertEquals(0, new JUnitView().getNumberOfErrors());
assertEquals(0, new JUnitView().getNumberOfFailures());
}
private void openFile(String... file) {
// focus on project explorer
new WorkbenchView("General", "Project Explorer").open();
new DefaultTreeItem(0, file).doubleClick();
}
}
| false | true | public void bpmCreationTest() {
new WorkbenchShell().maximize();
// Create new Switchyard project, Add support for Bean, BPM
new SwitchYardProjectWizard(PROJECT).impl("Bean", "BPM (jBPM)")
.groupId(GROUP_ID).packageName(PACKAGE).create();
openFile(PROJECT, PACKAGE_MAIN_RESOURCES, "META-INF", "switchyard.xml");
new BPM().setService(PROCESS_GREET).setBpmnFileName(BPMN_FILE_NAME)
.create(BPM_COORDS);
AbstractWait.sleep(1000);
new Bean().setService(EVAL_GREET).create(BEAN_COORDS);
AbstractWait.sleep(1000);
// reference to bean
new Component(PROCESS_GREET).contextButton("Reference").click();
new ReferenceWizard().selectJavaInterface(EVAL_GREET).finish();
AbstractWait.sleep(2 * 1000);
// declare ProcessGreet interface
new Service(PROCESS_GREET, 1).openTextEditor();
new TextEditor(PROCESS_GREET + ".java").typeAfter("interface",
PROCESS_GREET_DECL);
// declare EvalGreet interface
openFile(PROJECT, PACKAGE_MAIN_JAVA, PACKAGE, EVAL_GREET + ".java");
new TextEditor(EVAL_GREET + ".java").typeAfter("interface",
EVAL_GREET_DECL);
// implement EvalGreetBean
openFile(PROJECT, PACKAGE_MAIN_JAVA, PACKAGE, EVAL_GREET_BEAN + ".java");
new TextEditor(EVAL_GREET_BEAN + ".java")
.typeAfter("implements", "@Override")
.newLine()
.type("public boolean checkGreet(String greet){")
.newLine()
.type("return (greet.equals(\"Good evening\")) ? true : false;")
.newLine().type("}");
// BPM Process and its properties
openFile(PROJECT, PACKAGE_MAIN_RESOURCES, BPMN_FILE_NAME);
BPMN2Editor editor = new BPMN2Editor();
editor.click(1, 1);
new BPMN2PropertiesView().selectTab("Process");
new LabeledText("Id").setText(PROCESS_GREET);
editor.setFocus();
new TerminateEndEvent("EndProcess").delete();
new StartEvent("StartProcess").append("EvalGreet",
ConstructType.SWITCHYARD_SERVICE_TASK);
SwitchYardServiceTask task = new SwitchYardServiceTask("EvalGreet");
task.setTaskAttribute("Operation Name", "checkGreet");
task.setTaskAttribute("Service Name", EVAL_GREET);
task.addParameterMapping(new InputParameterMapping(new FromVariable(
PROCESS_GREET + "/Parameter"), new ToDataInput("Parameter")));
task.addParameterMapping(new OutputParameterMapping(new FromDataOutput(
"Result"), new ToVariable(PROCESS_GREET + "/Result")));
task.append("EndProcess", ConstructType.TERMINATE_END_EVENT);
openFile(PROJECT, PACKAGE_MAIN_RESOURCES, "META-INF", "switchyard.xml");
// Junit
new Service(PROCESS_GREET, 1).newServiceTestClass();
new TextEditor(PROCESS_GREET + "Test.java")
.deleteLineWith("null")
.deleteLineWith("assertTrue")
.typeBefore("boolean", "String message = \"Good evening\";")
.newLine()
.typeAfter("getContent", "Assert.assertTrue(result);")
.newLine()
.type("Assert.assertFalse(service.operation(\"checkGreetIsPolite\").sendInOut(\"hi\").getContent(Boolean.class));");
new ShellMenu("File", "Save All").select();
AbstractWait.sleep(1000);
new PushButton("No").click();// BPMN nature
ProjectItem item = new ProjectExplorer().getProject(PROJECT)
.getProjectItem("src/test/java", PACKAGE,
PROCESS_GREET + "Test.java");
new ProjectItemExt(item).runAsJUnitTest();
assertEquals("1/1", new JUnitView().getRunStatus());
assertEquals(0, new JUnitView().getNumberOfErrors());
assertEquals(0, new JUnitView().getNumberOfFailures());
}
| public void bpmCreationTest() {
new WorkbenchShell().maximize();
// Create new Switchyard project, Add support for Bean, BPM
new SwitchYardProjectWizard(PROJECT).impl("Bean", "BPM (jBPM)")
.groupId(GROUP_ID).packageName(PACKAGE).create();
openFile(PROJECT, PACKAGE_MAIN_RESOURCES, "META-INF", "switchyard.xml");
new BPM().setService(PROCESS_GREET).setBpmnFileName(BPMN_FILE_NAME)
.create(BPM_COORDS);
AbstractWait.sleep(1000);
new Bean().setService(EVAL_GREET).create(BEAN_COORDS);
AbstractWait.sleep(1000);
// reference to bean
new Component(PROCESS_GREET).contextButton("Reference").click();
new ReferenceWizard().selectJavaInterface(EVAL_GREET).finish();
AbstractWait.sleep(2 * 1000);
// declare ProcessGreet interface
new Service(PROCESS_GREET, 1).openTextEditor();
new TextEditor(PROCESS_GREET + ".java").typeAfter("interface",
PROCESS_GREET_DECL);
// declare EvalGreet interface
openFile(PROJECT, PACKAGE_MAIN_JAVA, PACKAGE, EVAL_GREET + ".java");
new TextEditor(EVAL_GREET + ".java").typeAfter("interface",
EVAL_GREET_DECL);
// implement EvalGreetBean
openFile(PROJECT, PACKAGE_MAIN_JAVA, PACKAGE, EVAL_GREET_BEAN + ".java");
new TextEditor(EVAL_GREET_BEAN + ".java")
.typeAfter("implements", "@Override")
.newLine()
.type("public boolean checkGreet(String greet){")
.newLine()
.type("return (greet.equals(\"Good evening\")) ? true : false;")
.newLine().type("}");
// BPM Process and its properties
openFile(PROJECT, PACKAGE_MAIN_RESOURCES, BPMN_FILE_NAME);
BPMN2Editor editor = new BPMN2Editor();
editor.click(1, 1);
new BPMN2PropertiesView().selectTab("Process");
new LabeledText("Id").setText(PROCESS_GREET);
editor.setFocus();
new TerminateEndEvent("EndProcess").delete();
new StartEvent("StartProcess").append("EvalGreet",
ConstructType.SWITCHYARD_SERVICE_TASK);
SwitchYardServiceTask task = new SwitchYardServiceTask("EvalGreet");
task.setTaskAttribute("Operation Name", "checkGreet");
task.setTaskAttribute("Service Name", EVAL_GREET);
task.addParameterMapping(new InputParameterMapping(new FromVariable(
PROCESS_GREET + "/Parameter"), new ToDataInput("Parameter", "String")));
task.addParameterMapping(new OutputParameterMapping(new FromDataOutput(
"Result", "String"), new ToVariable(PROCESS_GREET + "/Result")));
task.append("EndProcess", ConstructType.TERMINATE_END_EVENT);
openFile(PROJECT, PACKAGE_MAIN_RESOURCES, "META-INF", "switchyard.xml");
// Junit
new Service(PROCESS_GREET, 1).newServiceTestClass();
new TextEditor(PROCESS_GREET + "Test.java")
.deleteLineWith("null")
.deleteLineWith("assertTrue")
.typeBefore("boolean", "String message = \"Good evening\";")
.newLine()
.typeAfter("getContent", "Assert.assertTrue(result);")
.newLine()
.type("Assert.assertFalse(service.operation(\"checkGreetIsPolite\").sendInOut(\"hi\").getContent(Boolean.class));");
new ShellMenu("File", "Save All").select();
AbstractWait.sleep(1000);
new PushButton("No").click();// BPMN nature
ProjectItem item = new ProjectExplorer().getProject(PROJECT)
.getProjectItem("src/test/java", PACKAGE,
PROCESS_GREET + "Test.java");
new ProjectItemExt(item).runAsJUnitTest();
AbstractWait.sleep(30 * 1000);
assertEquals("1/1", new JUnitView().getRunStatus());
assertEquals(0, new JUnitView().getNumberOfErrors());
assertEquals(0, new JUnitView().getNumberOfFailures());
}
|
diff --git a/src/java/org/apache/cassandra/cli/CliClient.java b/src/java/org/apache/cassandra/cli/CliClient.java
index d25ebb48..0320d658 100644
--- a/src/java/org/apache/cassandra/cli/CliClient.java
+++ b/src/java/org/apache/cassandra/cli/CliClient.java
@@ -1,2168 +1,2168 @@
/**
* 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.cassandra.cli;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.util.*;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import org.antlr.runtime.tree.Tree;
import org.apache.cassandra.auth.SimpleAuthenticator;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.db.ColumnFamilyStoreMBean;
import org.apache.cassandra.db.CompactionManagerMBean;
import org.apache.cassandra.db.marshal.*;
import org.apache.cassandra.service.StorageProxy;
import org.apache.cassandra.thrift.*;
import org.apache.cassandra.tools.NodeProbe;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.UUIDGen;
import org.apache.thrift.TBaseHelper;
import org.apache.thrift.TException;
import org.safehaus.uuid.UUIDGenerator;
// Cli Client Side Library
public class CliClient extends CliUserHelp
{
/**
* Available value conversion functions
* Used by convertValueByFunction(Tree functionCall) method
*/
public enum Function
{
BYTES (BytesType.instance),
INTEGER (IntegerType.instance),
LONG (LongType.instance),
LEXICALUUID (LexicalUUIDType.instance),
TIMEUUID (TimeUUIDType.instance),
UTF8 (UTF8Type.instance),
ASCII (AsciiType.instance);
private AbstractType validator;
Function(AbstractType validator)
{
this.validator = validator;
}
public AbstractType getValidator()
{
return this.validator;
}
public static String getFunctionNames()
{
Function[] functions = Function.values();
StringBuilder functionNames = new StringBuilder();
for (int i = 0; i < functions.length; i++)
{
StringBuilder currentName = new StringBuilder(functions[i].name().toLowerCase());
functionNames.append(currentName.append(((i != functions.length-1) ? ", " : ".")));
}
return functionNames.toString();
}
}
/*
* the <i>add keyspace</i> command requires a list of arguments,
* this enum defines which arguments are valid
*/
private enum AddKeyspaceArgument {
REPLICATION_FACTOR,
PLACEMENT_STRATEGY,
STRATEGY_OPTIONS
}
private static final String DEFAULT_PLACEMENT_STRATEGY = "org.apache.cassandra.locator.SimpleStrategy";
private Cassandra.Client thriftClient = null;
private CliSessionState sessionState = null;
private String keySpace = null;
private String username = null;
private Map<String, KsDef> keyspacesMap = new HashMap<String, KsDef>();
private Map<String, AbstractType> cfKeysComparators;
private ConsistencyLevel consistencyLevel = ConsistencyLevel.ONE;
public CliClient(CliSessionState cliSessionState, Cassandra.Client thriftClient)
{
this.sessionState = cliSessionState;
this.thriftClient = thriftClient;
this.cfKeysComparators = new HashMap<String, AbstractType>();
}
// Execute a CLI Statement
public void executeCLIStatement(String statement)
{
Tree tree = CliCompiler.compileQuery(statement);
try
{
switch (tree.getType())
{
case CliParser.NODE_EXIT:
cleanupAndExit();
break;
case CliParser.NODE_THRIFT_GET:
executeGet(tree);
break;
case CliParser.NODE_THRIFT_GET_WITH_CONDITIONS:
executeGetWithConditions(tree);
break;
case CliParser.NODE_HELP:
printCmdHelp(tree, sessionState);
break;
case CliParser.NODE_THRIFT_SET:
executeSet(tree);
break;
case CliParser.NODE_THRIFT_DEL:
executeDelete(tree);
break;
case CliParser.NODE_THRIFT_COUNT:
executeCount(tree);
break;
case CliParser.NODE_ADD_KEYSPACE:
executeAddKeySpace(tree.getChild(0));
break;
case CliParser.NODE_ADD_COLUMN_FAMILY:
executeAddColumnFamily(tree.getChild(0));
break;
case CliParser.NODE_UPDATE_KEYSPACE:
executeUpdateKeySpace(tree.getChild(0));
break;
case CliParser.NODE_UPDATE_COLUMN_FAMILY:
executeUpdateColumnFamily(tree.getChild(0));
break;
case CliParser.NODE_DEL_COLUMN_FAMILY:
executeDelColumnFamily(tree);
break;
case CliParser.NODE_DEL_KEYSPACE:
executeDelKeySpace(tree);
break;
case CliParser.NODE_SHOW_CLUSTER_NAME:
executeShowClusterName();
break;
case CliParser.NODE_SHOW_VERSION:
executeShowVersion();
break;
case CliParser.NODE_SHOW_KEYSPACES:
executeShowKeySpaces();
break;
case CliParser.NODE_DESCRIBE_TABLE:
executeDescribeKeySpace(tree);
break;
case CliParser.NODE_DESCRIBE_CLUSTER:
executeDescribeCluster();
break;
case CliParser.NODE_USE_TABLE:
executeUseKeySpace(tree);
break;
case CliParser.NODE_CONNECT:
executeConnect(tree);
break;
case CliParser.NODE_LIST:
executeList(tree);
break;
case CliParser.NODE_TRUNCATE:
executeTruncate(tree.getChild(0).getText());
break;
case CliParser.NODE_ASSUME:
executeAssumeStatement(tree);
break;
case CliParser.NODE_CONSISTENCY_LEVEL:
executeConsistencyLevelStatement(tree);
break;
case CliParser.NODE_NO_OP:
// comment lines come here; they are treated as no ops.
break;
default:
sessionState.err.println("Invalid Statement (Type: " + tree.getType() + ")");
if (sessionState.batch)
System.exit(2);
break;
}
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e.getWhy());
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
private void cleanupAndExit()
{
CliMain.disconnect();
System.exit(0);
}
public KsDef getKSMetaData(String keyspace)
throws NotFoundException, InvalidRequestException, TException
{
// Lazily lookup keyspace meta-data.
if (!(keyspacesMap.containsKey(keyspace)))
keyspacesMap.put(keyspace, thriftClient.describe_keyspace(keyspace));
return keyspacesMap.get(keyspace);
}
private void executeCount(Tree statement)
throws TException, InvalidRequestException, UnavailableException, TimedOutException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
Tree columnFamilySpec = statement.getChild(0);
String key = CliCompiler.getKey(columnFamilySpec);
String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, keyspacesMap.get(keySpace).cf_defs);
int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
ColumnParent colParent = new ColumnParent(columnFamily).setSuper_column((ByteBuffer) null);
if (columnSpecCnt != 0)
{
byte[] superColumn = columnNameAsByteArray(CliCompiler.getColumn(columnFamilySpec, 0), columnFamily);
colParent = new ColumnParent(columnFamily).setSuper_column(superColumn);
}
SliceRange range = new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER, ByteBufferUtil.EMPTY_BYTE_BUFFER, false, Integer.MAX_VALUE);
SlicePredicate predicate = new SlicePredicate().setColumn_names(null).setSlice_range(range);
int count = thriftClient.get_count(ByteBufferUtil.bytes(key), colParent, predicate, consistencyLevel);
sessionState.out.printf("%d columns%n", count);
}
private void executeDelete(Tree statement)
throws TException, InvalidRequestException, UnavailableException, TimedOutException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
Tree columnFamilySpec = statement.getChild(0);
String key = CliCompiler.getKey(columnFamilySpec);
String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, keyspacesMap.get(keySpace).cf_defs);
int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
byte[] superColumnName = null;
byte[] columnName = null;
CfDef cfDef = getCfDef(columnFamily);
boolean isSuper = cfDef.column_type.equals("Super");
if ((columnSpecCnt < 0) || (columnSpecCnt > 2))
{
sessionState.out.println("Invalid row, super column, or column specification.");
return;
}
if (columnSpecCnt == 1)
{
// table.cf['key']['column']
if (isSuper)
superColumnName = columnNameAsByteArray(CliCompiler.getColumn(columnFamilySpec, 0), cfDef);
else
columnName = columnNameAsByteArray(CliCompiler.getColumn(columnFamilySpec, 0), cfDef);
}
else if (columnSpecCnt == 2)
{
// table.cf['key']['column']['column']
superColumnName = columnNameAsByteArray(CliCompiler.getColumn(columnFamilySpec, 0), cfDef);
columnName = subColumnNameAsByteArray(CliCompiler.getColumn(columnFamilySpec, 1), cfDef);
}
ColumnPath path = new ColumnPath(columnFamily);
if (superColumnName != null)
path.setSuper_column(superColumnName);
if (columnName != null)
path.setColumn(columnName);
thriftClient.remove(ByteBufferUtil.bytes(key), path,
FBUtilities.timestampMicros(), consistencyLevel);
sessionState.out.println(String.format("%s removed.", (columnSpecCnt == 0) ? "row" : "column"));
}
private void doSlice(String keyspace, ByteBuffer key, String columnFamily, byte[] superColumnName, int limit)
throws InvalidRequestException, UnavailableException, TimedOutException, TException, IllegalAccessException, NotFoundException, InstantiationException, NoSuchFieldException
{
ColumnParent parent = new ColumnParent(columnFamily);
if(superColumnName != null)
parent.setSuper_column(superColumnName);
SliceRange range = new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER, ByteBufferUtil.EMPTY_BYTE_BUFFER, false, limit);
List<ColumnOrSuperColumn> columns = thriftClient.get_slice(key, parent, new SlicePredicate().setColumn_names(null).setSlice_range(range), consistencyLevel);
AbstractType validator;
CfDef cfDef = getCfDef(columnFamily);
boolean isSuperCF = cfDef.column_type.equals("Super");
// Print out super columns or columns.
for (ColumnOrSuperColumn cosc : columns)
{
if (cosc.isSetSuper_column())
{
SuperColumn superColumn = cosc.super_column;
sessionState.out.printf("=> (super_column=%s,", formatSuperColumnName(keyspace, columnFamily, superColumn));
for (Column col : superColumn.getColumns())
{
validator = getValidatorForValue(cfDef, col.getName());
sessionState.out.printf("%n (column=%s, value=%s, timestamp=%d%s)", formatSubcolumnName(keyspace, columnFamily, col),
validator.getString(col.value), col.timestamp,
col.isSetTtl() ? String.format(", ttl=%d", col.getTtl()) : "");
}
sessionState.out.println(")");
}
else
{
Column column = cosc.column;
validator = getValidatorForValue(cfDef, column.getName());
String formattedName = isSuperCF
? formatSubcolumnName(keyspace, columnFamily, column)
: formatColumnName(keyspace, columnFamily, column);
sessionState.out.printf("=> (column=%s, value=%s, timestamp=%d%s)%n",
formattedName,
validator.getString(column.value),
column.timestamp,
column.isSetTtl() ? String.format(", ttl=%d", column.getTtl()) : "");
}
}
sessionState.out.println("Returned " + columns.size() + " results.");
}
private AbstractType getFormatTypeForColumn(String compareWith)
{
Function function;
try
{
function = Function.valueOf(compareWith.toUpperCase());
}
catch (IllegalArgumentException e)
{
try
{
return FBUtilities.getComparator(compareWith);
}
catch (ConfigurationException ce)
{
StringBuilder errorMessage = new StringBuilder("Unknown comparator '" + compareWith + "'. ");
errorMessage.append("Available functions: ");
throw new RuntimeException(errorMessage.append(Function.getFunctionNames()).toString());
}
}
return function.getValidator();
}
// Execute GET statement
private void executeGet(Tree statement)
throws TException, NotFoundException, InvalidRequestException, UnavailableException, TimedOutException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchFieldException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
Tree columnFamilySpec = statement.getChild(0);
String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, keyspacesMap.get(keySpace).cf_defs);
ByteBuffer key = getKeyAsBytes(columnFamily, columnFamilySpec.getChild(1));
int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
CfDef cfDef = getCfDef(columnFamily);
boolean isSuper = cfDef.column_type.equals("Super");
byte[] superColumnName = null;
ByteBuffer columnName;
Tree typeTree = null;
Tree limitTree = null;
int limit = 1000000;
if (statement.getChildCount() >= 2)
{
if (statement.getChild(1).getType() == CliParser.CONVERT_TO_TYPE)
{
typeTree = statement.getChild(1).getChild(0);
if (statement.getChildCount() == 3)
limitTree = statement.getChild(2).getChild(0);
}
else
{
limitTree = statement.getChild(1).getChild(0);
}
}
if (limitTree != null)
{
limit = Integer.parseInt(limitTree.getText());
if (limit == 0)
{
throw new IllegalArgumentException("LIMIT should be greater than zero.");
}
}
// table.cf['key'] -- row slice
if (columnSpecCnt == 0)
{
doSlice(keySpace, key, columnFamily, superColumnName, limit);
return;
}
// table.cf['key']['column'] -- slice of a super, or get of a standard
else if (columnSpecCnt == 1)
{
columnName = getColumnName(columnFamily, columnFamilySpec.getChild(2));
if (isSuper)
{
superColumnName = columnName.array();
doSlice(keySpace, key, columnFamily, superColumnName, limit);
return;
}
}
// table.cf['key']['column']['column'] -- get of a sub-column
else if (columnSpecCnt == 2)
{
superColumnName = getColumnName(columnFamily, columnFamilySpec.getChild(2)).array();
columnName = getSubColumnName(columnFamily, columnFamilySpec.getChild(3));
}
// The parser groks an arbitrary number of these so it is possible to get here.
else
{
sessionState.out.println("Invalid row, super column, or column specification.");
return;
}
AbstractType validator = getValidatorForValue(cfDef, TBaseHelper.byteBufferToByteArray(columnName));
// Perform a get()
ColumnPath path = new ColumnPath(columnFamily);
if(superColumnName != null) path.setSuper_column(superColumnName);
path.setColumn(columnName);
Column column;
try
{
column = thriftClient.get(key, path, consistencyLevel).column;
}
catch (NotFoundException e)
{
sessionState.out.println("Value was not found");
return;
}
byte[] columnValue = column.getValue();
String valueAsString;
// we have ^(CONVERT_TO_TYPE <type>) inside of GET statement
// which means that we should try to represent byte[] value according
// to specified type
if (typeTree != null)
{
// .getText() will give us <type>
String typeName = CliUtils.unescapeSQLString(typeTree.getText());
// building AbstractType from <type>
AbstractType valueValidator = getFormatTypeForColumn(typeName);
// setting value for output
valueAsString = valueValidator.getString(ByteBuffer.wrap(columnValue));
// updating column value validator class
updateColumnMetaData(cfDef, columnName, valueValidator.getClass().getName());
}
else
{
valueAsString = (validator == null) ? new String(columnValue, Charsets.UTF_8) : validator.getString(ByteBuffer.wrap(columnValue));
}
String formattedColumnName = isSuper
? formatSubcolumnName(keySpace, columnFamily, column)
: formatColumnName(keySpace, columnFamily, column);
// print results
sessionState.out.printf("=> (column=%s, value=%s, timestamp=%d%s)%n",
formattedColumnName,
valueAsString,
column.timestamp,
column.isSetTtl() ? String.format(", ttl=%d", column.getTtl()) : "");
}
/**
* Process get operation with conditions (using Thrift get_indexed_slices method)
* @param statement - tree representation of the current statement
* Format: ^(NODE_THRIFT_GET_WITH_CONDITIONS cf ^(CONDITIONS ^(CONDITION >= column1 value1) ...) ^(NODE_LIMIT int)*)
*/
private void executeGetWithConditions(Tree statement)
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
IndexClause clause = new IndexClause();
String columnFamily = CliCompiler.getColumnFamily(statement, keyspacesMap.get(keySpace).cf_defs);
// ^(CONDITIONS ^(CONDITION $column $value) ...)
Tree conditions = statement.getChild(1);
// fetching column family definition
CfDef columnFamilyDef = getCfDef(columnFamily);
// fetching all columns
SlicePredicate predicate = new SlicePredicate();
SliceRange sliceRange = new SliceRange();
sliceRange.setStart(new byte[0]).setFinish(new byte[0]);
predicate.setSlice_range(sliceRange);
for (int i = 0; i < conditions.getChildCount(); i++)
{
// ^(CONDITION operator $column $value)
Tree condition = conditions.getChild(i);
// =, >, >=, <, <=
String operator = condition.getChild(0).getText();
String columnNameString = CliUtils.unescapeSQLString(condition.getChild(1).getText());
// it could be a basic string or function call
Tree valueTree = condition.getChild(2);
try
{
ByteBuffer value;
ByteBuffer columnName = columnNameAsBytes(columnNameString, columnFamily);
if (valueTree.getType() == CliParser.FUNCTION_CALL)
{
value = convertValueByFunction(valueTree, columnFamilyDef, columnName);
}
else
{
String valueString = CliUtils.unescapeSQLString(valueTree.getText());
value = columnValueAsBytes(columnName, columnFamily, valueString);
}
// index operator from string
IndexOperator idxOperator = CliUtils.getIndexOperator(operator);
// adding new index expression into index clause
clause.addToExpressions(new IndexExpression(columnName, idxOperator, value));
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
List<KeySlice> slices;
clause.setStart_key(new byte[] {});
// when we have ^(NODE_LIMIT Integer)
if (statement.getChildCount() == 3)
{
Tree limitNode = statement.getChild(2);
int limitValue = Integer.parseInt(limitNode.getChild(0).getText());
if (limitValue == 0)
{
throw new IllegalArgumentException("LIMIT should be greater than zero.");
}
clause.setCount(limitValue);
}
try
{
ColumnParent parent = new ColumnParent(columnFamily);
slices = thriftClient.get_indexed_slices(parent, clause, predicate, consistencyLevel);
printSliceList(columnFamilyDef, slices);
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e.getWhy());
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
// Execute SET statement
private void executeSet(Tree statement)
throws TException, InvalidRequestException, UnavailableException, TimedOutException, NoSuchFieldException, InstantiationException, IllegalAccessException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
// ^(NODE_COLUMN_ACCESS <cf> <key> <column>)
Tree columnFamilySpec = statement.getChild(0);
Tree keyTree = columnFamilySpec.getChild(1); // could be a function or regular text
String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, keyspacesMap.get(keySpace).cf_defs);
CfDef cfDef = getCfDef(columnFamily);
int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
String value = CliUtils.unescapeSQLString(statement.getChild(1).getText());
Tree valueTree = statement.getChild(1);
byte[] superColumnName = null;
ByteBuffer columnName;
// table.cf['key']
if (columnSpecCnt == 0)
{
sessionState.err.println("No column name specified, (type 'help' or '?' for help on syntax).");
return;
}
// table.cf['key']['column'] = 'value'
else if (columnSpecCnt == 1)
{
// get the column name
if (cfDef.column_type.equals("Super"))
{
sessionState.out.println("Column family " + columnFamily + " may only contain SuperColumns");
return;
}
columnName = getColumnName(columnFamily, columnFamilySpec.getChild(2));
}
// table.cf['key']['super_column']['column'] = 'value'
else
{
assert (columnSpecCnt == 2) : "serious parsing error (this is a bug).";
superColumnName = getColumnName(columnFamily, columnFamilySpec.getChild(2)).array();
columnName = getSubColumnName(columnFamily, columnFamilySpec.getChild(3));
}
ByteBuffer columnValueInBytes;
switch (valueTree.getType())
{
case CliParser.FUNCTION_CALL:
columnValueInBytes = convertValueByFunction(valueTree, cfDef, columnName, true);
break;
default:
columnValueInBytes = columnValueAsBytes(columnName, columnFamily, value);
}
ColumnParent parent = new ColumnParent(columnFamily);
if(superColumnName != null)
parent.setSuper_column(superColumnName);
Column columnToInsert = new Column(columnName, columnValueInBytes, FBUtilities.timestampMicros());
// children count = 3 mean that we have ttl in arguments
if (statement.getChildCount() == 3)
{
String ttl = statement.getChild(2).getText();
try
{
columnToInsert.setTtl(Integer.parseInt(ttl));
}
catch (NumberFormatException e)
{
sessionState.err.println(String.format("TTL '%s' is invalid, should be a positive integer.", ttl));
return;
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
// do the insert
thriftClient.insert(getKeyAsBytes(columnFamily, keyTree), parent, columnToInsert, consistencyLevel);
sessionState.out.println("Value inserted.");
}
private void executeShowClusterName() throws TException
{
if (!CliMain.isConnected())
return;
sessionState.out.println(thriftClient.describe_cluster_name());
}
/**
* Add a keyspace
* @param statement - a token tree representing current statement
*/
private void executeAddKeySpace(Tree statement)
{
if (!CliMain.isConnected())
return;
// first value is the keyspace name, after that it is all key=value
String keyspaceName = statement.getChild(0).getText();
KsDef ksDef = new KsDef(keyspaceName, DEFAULT_PLACEMENT_STRATEGY, 1, new LinkedList<CfDef>());
try
{
String mySchemaVersion = thriftClient.system_add_keyspace(updateKsDefAttributes(statement, ksDef));
sessionState.out.println(mySchemaVersion);
validateSchemaIsSettled(mySchemaVersion);
keyspacesMap.put(keyspaceName, thriftClient.describe_keyspace(keyspaceName));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e.getWhy());
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* Add a column family
* @param statement - a token tree representing current statement
*/
private void executeAddColumnFamily(Tree statement)
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
// first value is the column family name, after that it is all key=value
CfDef cfDef = new CfDef(keySpace, statement.getChild(0).getText());
try
{
String mySchemaVersion = thriftClient.system_add_column_family(updateCfDefAttributes(statement, cfDef));
sessionState.out.println(mySchemaVersion);
validateSchemaIsSettled(mySchemaVersion);
keyspacesMap.put(keySpace, thriftClient.describe_keyspace(keySpace));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e.getWhy());
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* Update existing keyspace identified by name
* @param statement - tree represeting statement
*/
private void executeUpdateKeySpace(Tree statement)
{
if (!CliMain.isConnected())
return;
try
{
String keyspaceName = CliCompiler.getKeySpace(statement, thriftClient.describe_keyspaces());
KsDef currentKsDef = getKSMetaData(keyspaceName);
KsDef updatedKsDef = updateKsDefAttributes(statement, currentKsDef);
String mySchemaVersion = thriftClient.system_update_keyspace(updatedKsDef);
sessionState.out.println(mySchemaVersion);
validateSchemaIsSettled(mySchemaVersion);
keyspacesMap.put(keyspaceName, thriftClient.describe_keyspace(keyspaceName));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e.getWhy());
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* Update existing column family identified by name
* @param statement - tree represeting statement
*/
private void executeUpdateColumnFamily(Tree statement)
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
String cfName = CliCompiler.getColumnFamily(statement, keyspacesMap.get(keySpace).cf_defs);
// first child is a column family name
CfDef cfDef = getCfDef(cfName);
try
{
String mySchemaVersion = thriftClient.system_update_column_family(updateCfDefAttributes(statement, cfDef));
sessionState.out.println(mySchemaVersion);
validateSchemaIsSettled(mySchemaVersion);
keyspacesMap.put(keySpace, thriftClient.describe_keyspace(keySpace));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e.getWhy());
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* Used to update keyspace definition attributes
* @param statement - ANTRL tree representing current statement
* @param ksDefToUpdate - keyspace definition to update
* @return ksDef - updated keyspace definition
*/
private KsDef updateKsDefAttributes(Tree statement, KsDef ksDefToUpdate)
{
KsDef ksDef = new KsDef(ksDefToUpdate);
// removing all column definitions - thrift system_update_keyspace method requires that
ksDef.setCf_defs(new LinkedList<CfDef>());
for(int i = 1; i < statement.getChildCount(); i += 2)
{
String currentStatement = statement.getChild(i).getText().toUpperCase();
AddKeyspaceArgument mArgument = AddKeyspaceArgument.valueOf(currentStatement);
String mValue = statement.getChild(i + 1).getText();
switch(mArgument)
{
case PLACEMENT_STRATEGY:
ksDef.setStrategy_class(CliUtils.unescapeSQLString(mValue));
break;
case REPLICATION_FACTOR:
ksDef.setReplication_factor(Integer.parseInt(mValue));
break;
case STRATEGY_OPTIONS:
ksDef.setStrategy_options(getStrategyOptionsFromTree(statement.getChild(i + 1)));
break;
default:
//must match one of the above or we'd throw an exception at the valueOf statement above.
assert(false);
}
}
return ksDef;
}
/**
* Update column family definition attributes
* @param statement - ANTLR tree representing current statement
* @param cfDefToUpdate - column family definition to apply updates on
* @return cfDef - updated column family definition
*/
private CfDef updateCfDefAttributes(Tree statement, CfDef cfDefToUpdate)
{
CfDef cfDef = new CfDef(cfDefToUpdate);
for (int i = 1; i < statement.getChildCount(); i += 2)
{
String currentArgument = statement.getChild(i).getText().toUpperCase();
ColumnFamilyArgument mArgument = ColumnFamilyArgument.valueOf(currentArgument);
String mValue = statement.getChild(i + 1).getText();
switch(mArgument)
{
case COLUMN_TYPE:
cfDef.setColumn_type(CliUtils.unescapeSQLString(mValue));
break;
case COMPARATOR:
cfDef.setComparator_type(CliUtils.unescapeSQLString(mValue));
break;
case SUBCOMPARATOR:
cfDef.setSubcomparator_type(CliUtils.unescapeSQLString(mValue));
break;
case COMMENT:
cfDef.setComment(CliUtils.unescapeSQLString(mValue));
break;
case ROWS_CACHED:
cfDef.setRow_cache_size(Double.parseDouble(mValue));
break;
case KEYS_CACHED:
cfDef.setKey_cache_size(Double.parseDouble(mValue));
break;
case READ_REPAIR_CHANCE:
double chance = Double.parseDouble(mValue);
if (chance > 1)
throw new RuntimeException("Error: read_repair_chance should not be greater than 1.");
cfDef.setRead_repair_chance(chance);
break;
case GC_GRACE:
cfDef.setGc_grace_seconds(Integer.parseInt(mValue));
break;
case COLUMN_METADATA:
Tree arrayOfMetaAttributes = statement.getChild(i + 1);
if (!arrayOfMetaAttributes.getText().equals("ARRAY"))
throw new RuntimeException("'column_metadata' format - [{ k:v, k:v, ..}, { ... }, ...]");
cfDef.setColumn_metadata(getCFColumnMetaFromTree(cfDef, arrayOfMetaAttributes));
break;
case MEMTABLE_OPERATIONS:
cfDef.setMemtable_operations_in_millions(Double.parseDouble(mValue));
break;
case MEMTABLE_FLUSH_AFTER:
cfDef.setMemtable_flush_after_mins(Integer.parseInt(mValue));
break;
case MEMTABLE_THROUGHPUT:
cfDef.setMemtable_throughput_in_mb(Integer.parseInt(mValue));
break;
case ROW_CACHE_SAVE_PERIOD:
cfDef.setRow_cache_save_period_in_seconds(Integer.parseInt(mValue));
break;
case KEY_CACHE_SAVE_PERIOD:
cfDef.setKey_cache_save_period_in_seconds(Integer.parseInt(mValue));
break;
case DEFAULT_VALIDATION_CLASS:
cfDef.setDefault_validation_class(mValue);
break;
case MIN_COMPACTION_THRESHOLD:
cfDef.setMin_compaction_threshold(Integer.parseInt(mValue));
break;
case MAX_COMPACTION_THRESHOLD:
cfDef.setMax_compaction_threshold(Integer.parseInt(mValue));
break;
default:
//must match one of the above or we'd throw an exception at the valueOf statement above.
assert(false);
}
}
return cfDef;
}
/**
* Delete a keyspace
* @param statement - a token tree representing current statement
* @throws TException - exception
* @throws InvalidRequestException - exception
* @throws NotFoundException - exception
*/
private void executeDelKeySpace(Tree statement)
throws TException, InvalidRequestException, NotFoundException
{
if (!CliMain.isConnected())
return;
String keyspaceName = CliCompiler.getKeySpace(statement, thriftClient.describe_keyspaces());
String version = thriftClient.system_drop_keyspace(keyspaceName);
sessionState.out.println(version);
validateSchemaIsSettled(version);
}
/**
* Delete a column family
* @param statement - a token tree representing current statement
* @throws TException - exception
* @throws InvalidRequestException - exception
* @throws NotFoundException - exception
*/
private void executeDelColumnFamily(Tree statement)
throws TException, InvalidRequestException, NotFoundException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
String cfName = CliCompiler.getColumnFamily(statement, keyspacesMap.get(keySpace).cf_defs);
String mySchemaVersion = thriftClient.system_drop_column_family(cfName);
sessionState.out.println(mySchemaVersion);
validateSchemaIsSettled(mySchemaVersion);
}
private void executeList(Tree statement)
throws TException, InvalidRequestException, NotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException, UnavailableException, TimedOutException, CharacterCodingException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
// extract column family
String columnFamily = CliCompiler.getColumnFamily(statement, keyspacesMap.get(keySpace).cf_defs);
String rawStartKey = "";
String rawEndKey = "";
int limitCount = Integer.MAX_VALUE; // will reset to default later if it's not specified
// optional arguments: key range and limit
for (int i = 1; i < statement.getChildCount(); i++)
{
Tree child = statement.getChild(i);
if (child.getType() == CliParser.NODE_KEY_RANGE)
{
if (child.getChildCount() > 0)
{
rawStartKey = CliUtils.unescapeSQLString(child.getChild(0).getText());
if (child.getChildCount() > 1)
rawEndKey = CliUtils.unescapeSQLString(child.getChild(1).getText());
}
}
else
{
if (child.getChildCount() != 1)
{
sessionState.out.println("Invalid limit clause");
return;
}
limitCount = Integer.parseInt(child.getChild(0).getText());
if (limitCount <= 0)
{
sessionState.out.println("Invalid limit " + limitCount);
return;
}
}
}
if (limitCount == Integer.MAX_VALUE)
{
limitCount = 100;
sessionState.out.println("Using default limit of 100");
}
CfDef columnFamilyDef = getCfDef(columnFamily);
// read all columns and superColumns
SlicePredicate predicate = new SlicePredicate();
SliceRange sliceRange = new SliceRange();
sliceRange.setStart(new byte[0]).setFinish(new byte[0]);
sliceRange.setCount(Integer.MAX_VALUE);
predicate.setSlice_range(sliceRange);
// set the key range
KeyRange range = new KeyRange(limitCount);
AbstractType keyComparator = this.cfKeysComparators.get(columnFamily);
ByteBuffer startKey = rawStartKey.isEmpty() ? ByteBufferUtil.EMPTY_BYTE_BUFFER : getBytesAccordingToType(rawStartKey, keyComparator);
ByteBuffer endKey = rawEndKey.isEmpty() ? ByteBufferUtil.EMPTY_BYTE_BUFFER : getBytesAccordingToType(rawEndKey, keyComparator);
range.setStart_key(startKey).setEnd_key(endKey);
ColumnParent columnParent = new ColumnParent(columnFamily);
List<KeySlice> keySlices = thriftClient.get_range_slices(columnParent, predicate, range, consistencyLevel);
printSliceList(columnFamilyDef, keySlices);
}
// TRUNCATE <columnFamily>
private void executeTruncate(String columnFamily)
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
// getting CfDef, it will fail if there is no such column family in current keySpace.
CfDef cfDef = getCfDef(CliCompiler.getColumnFamily(columnFamily, keyspacesMap.get(keySpace).cf_defs));
try
{
thriftClient.truncate(cfDef.getName());
sessionState.out.println(columnFamily + " truncated.");
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e.getWhy());
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
/**
* Command: CONSISTENCYLEVEL AS (ONE | QUORUM ...)
* Tree: ^(NODE_CONSISTENCY_LEVEL AS (ONE | QUORUM ...))
* @param statement - tree representing current statement
*/
private void executeConsistencyLevelStatement(Tree statement)
{
if (!CliMain.isConnected())
return;
String userSuppliedLevel = statement.getChild(0).getText().toUpperCase();
try
{
consistencyLevel = ConsistencyLevel.valueOf(userSuppliedLevel);
}
catch (IllegalArgumentException e)
{
String elements = "ONE, TWO, THREE, QUORUM, ALL, LOCAL_QUORUM, EACH_QUORUM, ANY";
sessionState.out.println(String.format("'%s' is invalid. Available: %s", userSuppliedLevel, elements));
return;
}
sessionState.out.println(String.format("Consistency level is set to '%s'.", consistencyLevel));
}
/**
* Command: ASSUME <columnFamily> (VALIDATOR | COMPARATOR | KEYS | SUB_COMPARATOR) AS <type>
* Tree: ^(NODE_ASSUME <columnFamily> (VALIDATOR | COMPARATOR | KEYS | SUB_COMPARATOR) <type>))
* @param statement - tree representing current statement
*/
private void executeAssumeStatement(Tree statement)
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
String cfName = CliCompiler.getColumnFamily(statement, keyspacesMap.get(keySpace).cf_defs);
CfDef columnFamily = getCfDef(cfName);
// VALIDATOR | COMPARATOR | KEYS | SUB_COMPARATOR
String assumptionElement = statement.getChild(1).getText().toUpperCase();
// used to store in this.cfKeysComparator
AbstractType comparator;
// Could be UTF8Type, IntegerType, LexicalUUIDType etc.
String defaultType = statement.getChild(2).getText();
try
{
comparator = Function.valueOf(defaultType.toUpperCase()).getValidator();
}
catch (Exception e)
{
String functions = Function.getFunctionNames();
sessionState.out.println("Type '" + defaultType + "' was not found. Available: " + functions);
return;
}
if (assumptionElement.equals("COMPARATOR"))
{
columnFamily.setComparator_type(defaultType);
}
else if (assumptionElement.equals("SUB_COMPARATOR"))
{
columnFamily.setSubcomparator_type(defaultType);
}
else if (assumptionElement.equals("VALIDATOR"))
{
columnFamily.setDefault_validation_class(defaultType);
}
else if (assumptionElement.equals("KEYS"))
{
this.cfKeysComparators.put(columnFamily.getName(), comparator);
}
else
{
String elements = "VALIDATOR, COMPARATOR, KEYS, SUB_COMPARATOR.";
sessionState.out.println(String.format("'%s' is invalid. Available: %s", assumptionElement, elements));
return;
}
sessionState.out.println(String.format("Assumption for column family '%s' added successfully.", columnFamily.getName()));
}
// SHOW API VERSION
private void executeShowVersion() throws TException
{
if (!CliMain.isConnected())
return;
sessionState.out.println(thriftClient.describe_version());
}
// SHOW KEYSPACES
private void executeShowKeySpaces() throws TException, InvalidRequestException
{
if (!CliMain.isConnected())
return;
List<KsDef> keySpaces = thriftClient.describe_keyspaces();
Collections.sort(keySpaces, new KsDefNamesComparator());
for (KsDef keySpace : keySpaces)
{
describeKeySpace(keySpace.name, keySpace);
}
}
/**
* Returns true if this.keySpace is set, false otherwise
* @return boolean
*/
private boolean hasKeySpace()
{
if (keySpace == null)
{
sessionState.out.println("Not authenticated to a working keyspace.");
return false;
}
return true;
}
public String getKeySpace()
{
return keySpace == null ? "unknown" : keySpace;
}
public void setKeySpace(String keySpace) throws NotFoundException, InvalidRequestException, TException
{
this.keySpace = keySpace;
// We do nothing with the return value, but it hits a cache and the tab-completer.
getKSMetaData(keySpace);
}
public String getUsername()
{
return username == null ? "default" : username;
}
public void setUsername(String username)
{
this.username = username;
}
// USE <keyspace_name>
private void executeUseKeySpace(Tree statement) throws TException
{
if (!CliMain.isConnected())
return;
int childCount = statement.getChildCount();
String keySpaceName, username = null, password = null;
// Get keyspace name
keySpaceName = statement.getChild(0).getText();
if (childCount == 3) {
username = statement.getChild(1).getText();
password = statement.getChild(2).getText();
}
if (keySpaceName == null)
{
sessionState.out.println("Keyspace argument required");
return;
}
try
{
AuthenticationRequest authRequest;
Map<String, String> credentials = new HashMap<String, String>();
keySpaceName = CliCompiler.getKeySpace(keySpaceName, thriftClient.describe_keyspaces());
thriftClient.set_keyspace(keySpaceName);
if (username != null && password != null)
{
/* remove quotes */
password = password.replace("\'", "");
credentials.put(SimpleAuthenticator.USERNAME_KEY, username);
credentials.put(SimpleAuthenticator.PASSWORD_KEY, password);
authRequest = new AuthenticationRequest(credentials);
thriftClient.login(authRequest);
}
keySpace = keySpaceName;
this.username = username != null ? username : "default";
CliMain.updateCompletor(CliUtils.getCfNamesByKeySpace(getKSMetaData(keySpace)));
sessionState.out.println("Authenticated to keyspace: " + keySpace);
}
catch (AuthenticationException e)
{
sessionState.err.println("Exception during authentication to the cassandra node: " +
"verify keyspace exists, and you are using correct credentials.");
}
catch (AuthorizationException e)
{
sessionState.err.println("You are not authorized to use keyspace: " + keySpaceName);
}
catch (InvalidRequestException e)
{
sessionState.err.println(keySpaceName + " does not exist.");
}
catch (NotFoundException e)
{
sessionState.err.println(keySpaceName + " does not exist.");
}
catch (TException e)
{
if (sessionState.debug)
e.printStackTrace();
sessionState.err.println("Login failure. Did you specify 'keyspace', 'username' and 'password'?");
}
}
private void describeKeySpace(String keySpaceName, KsDef metadata) throws TException
{
NodeProbe probe = sessionState.getNodeProbe();
// getting compaction manager MBean to displaying index building information
CompactionManagerMBean compactionManagerMBean = (probe == null) ? null : probe.getCompactionManagerProxy();
// Describe and display
sessionState.out.println("Keyspace: " + keySpaceName + ":");
try
{
KsDef ks_def;
ks_def = metadata == null ? thriftClient.describe_keyspace(keySpaceName) : metadata;
sessionState.out.println(" Replication Strategy: " + ks_def.strategy_class);
if (ks_def.strategy_class.endsWith(".NetworkTopologyStrategy"))
{
Map<String, String> options = ks_def.strategy_options;
sessionState.out.println(" Options: [" + ((options == null) ? "" : FBUtilities.toString(options)) + "]");
}
else
{
sessionState.out.println(" Replication Factor: " + ks_def.replication_factor);
}
sessionState.out.println(" Column Families:");
boolean isSuper;
Collections.sort(ks_def.cf_defs, new CfDefNamesComparator());
for (CfDef cf_def : ks_def.cf_defs)
{
// fetching bean for current column family store
ColumnFamilyStoreMBean cfMBean = (probe == null) ? null : probe.getCfsProxy(ks_def.getName(), cf_def.getName());
isSuper = cf_def.column_type.equals("Super");
sessionState.out.printf(" ColumnFamily: %s%s%n", cf_def.name, isSuper ? " (Super)" : "");
if (cf_def.comment != null && !cf_def.comment.isEmpty())
{
sessionState.out.printf(" \"%s\"%n", cf_def.comment);
}
if (cf_def.default_validation_class != null)
sessionState.out.printf(" default_validation_class: %s%n", cf_def.default_validation_class);
sessionState.out.printf(" Columns sorted by: %s%s%n", cf_def.comparator_type, cf_def.column_type.equals("Super") ? "/" + cf_def.subcomparator_type : "");
sessionState.out.printf(" Row cache size / save period in seconds: %s/%s%n", cf_def.row_cache_size, cf_def.row_cache_save_period_in_seconds);
sessionState.out.printf(" Key cache size / save period in seconds: %s/%s%n", cf_def.key_cache_size, cf_def.key_cache_save_period_in_seconds);
sessionState.out.printf(" Memtable thresholds: %s/%s/%s (millions of ops/minutes/MB)%n",
- cf_def.memtable_operations_in_millions, cf_def.memtable_throughput_in_mb, cf_def.memtable_flush_after_mins);
+ cf_def.memtable_operations_in_millions, cf_def.memtable_flush_after_mins, cf_def.memtable_throughput_in_mb);
sessionState.out.printf(" GC grace seconds: %s%n", cf_def.gc_grace_seconds);
sessionState.out.printf(" Compaction min/max thresholds: %s/%s%n", cf_def.min_compaction_threshold, cf_def.max_compaction_threshold);
sessionState.out.printf(" Read repair chance: %s%n", cf_def.read_repair_chance);
// if we have connection to the cfMBean established
if (cfMBean != null)
{
sessionState.out.printf(" Built indexes: %s%n", cfMBean.getBuiltIndexes());
}
if (cf_def.getColumn_metadataSize() != 0)
{
String leftSpace = " ";
String columnLeftSpace = leftSpace + " ";
AbstractType columnNameValidator = getFormatTypeForColumn(isSuper ? cf_def.subcomparator_type
: cf_def.comparator_type);
sessionState.out.println(leftSpace + "Column Metadata:");
for (ColumnDef columnDef : cf_def.getColumn_metadata())
{
String columnName = columnNameValidator.getString(columnDef.name);
if (columnNameValidator instanceof BytesType)
{
try
{
String columnString = UTF8Type.instance.getString(columnDef.name);
columnName = columnString + " (" + columnName + ")";
}
catch (MarshalException e)
{
// guess it wasn't a utf8 column name after all
}
}
sessionState.out.println(leftSpace + " Column Name: " + columnName);
sessionState.out.println(columnLeftSpace + "Validation Class: " + columnDef.getValidation_class());
if (columnDef.isSetIndex_name())
{
sessionState.out.println(columnLeftSpace + "Index Name: " + columnDef.getIndex_name());
}
if (columnDef.isSetIndex_type())
{
sessionState.out.println(columnLeftSpace + "Index Type: " + columnDef.getIndex_type().name());
}
}
}
}
// compaction manager information
if (compactionManagerMBean != null)
{
String compactionType = compactionManagerMBean.getCompactionType();
// if ongoing compaction type is index build
if (compactionType != null && compactionType.contains("index build"))
{
String indexName = compactionManagerMBean.getColumnFamilyInProgress();
long bytesCompacted = compactionManagerMBean.getBytesCompacted();
long totalBytesToProcess = compactionManagerMBean.getBytesTotalInProgress();
sessionState.out.printf("%nCurrently building index %s, completed %d of %d bytes.%n", indexName, bytesCompacted, totalBytesToProcess);
}
}
// closing JMX connection
if (probe != null)
probe.close();
}
catch (InvalidRequestException e)
{
sessionState.out.println("Invalid request: " + e);
}
catch (NotFoundException e)
{
sessionState.out.println("Keyspace " + keySpaceName + " could not be found.");
}
catch (IOException e)
{
sessionState.out.println("Error while closing JMX connection: " + e.getMessage());
}
}
// DESCRIBE KEYSPACE (<keyspace_name>)?
private void executeDescribeKeySpace(Tree statement) throws TException, InvalidRequestException
{
if (!CliMain.isConnected())
return;
String keySpaceName;
// Get keyspace name
if (statement.getChildCount() == 0)
{
// trying to use current keyspace if keyspace name was not given
keySpaceName = keySpace;
}
else
{
// we have keyspace name as an argument
keySpaceName = CliCompiler.getKeySpace(statement, thriftClient.describe_keyspaces());
}
if (keySpaceName == null)
{
sessionState.out.println("Keyspace argument required if you are not authorized in any keyspace.");
return;
}
describeKeySpace(keySpaceName, null);
}
// ^(NODE_DESCRIBE_CLUSTER) or describe: schema_versions, partitioner, snitch
private void executeDescribeCluster()
{
if (!CliMain.isConnected())
return;
sessionState.out.println("Cluster Information:");
try
{
sessionState.out.println(" Snitch: " + thriftClient.describe_snitch());
sessionState.out.println(" Partitioner: " + thriftClient.describe_partitioner());
sessionState.out.println(" Schema versions: ");
Map<String,List<String>> versions = thriftClient.describe_schema_versions();
for (String version : versions.keySet())
{
sessionState.out.println("\t" + version + ": " + versions.get(version));
}
}
catch (Exception e)
{
String message = (e instanceof InvalidRequestException) ? ((InvalidRequestException) e).getWhy() : e.getMessage();
sessionState.err.println("Error retrieving data: " + message);
}
}
// process a statement of the form: connect hostname/port
private void executeConnect(Tree statement)
{
Tree idList = statement.getChild(0);
int portNumber = Integer.parseInt(statement.getChild(1).getText());
StringBuilder hostName = new StringBuilder();
int idCount = idList.getChildCount();
for (int idx = 0; idx < idCount; idx++)
{
hostName.append(idList.getChild(idx).getText());
}
// disconnect current connection, if any.
// This is a no-op, if you aren't currently connected.
CliMain.disconnect();
// now, connect to the newly specified host name and port
sessionState.hostName = hostName.toString();
sessionState.thriftPort = portNumber;
// if we have user name and password
if (statement.getChildCount() == 4)
{
sessionState.username = statement.getChild(2).getText();
sessionState.password = CliUtils.unescapeSQLString(statement.getChild(3).getText());
}
CliMain.connect(sessionState.hostName, sessionState.thriftPort);
}
/**
* To get Column Family Definition object from specified keyspace
* @param keySpaceName key space name to search for specific column family
* @param columnFamilyName column family name
* @return CfDef - Column family definition object
*/
private CfDef getCfDef(String keySpaceName, String columnFamilyName)
{
KsDef keySpaceDefinition = keyspacesMap.get(keySpaceName);
for (CfDef columnFamilyDef : keySpaceDefinition.cf_defs)
{
if (columnFamilyDef.name.equals(columnFamilyName))
{
return columnFamilyDef;
}
}
throw new RuntimeException("No such column family: " + columnFamilyName);
}
/**
* Uses getCfDef(keySpaceName, columnFamilyName) with current keyspace
* @param columnFamilyName column family name to find in specified keyspace
* @return CfDef - Column family definition object
*/
private CfDef getCfDef(String columnFamilyName)
{
return getCfDef(this.keySpace, columnFamilyName);
}
/**
* Used to parse meta tree and compile meta attributes into List<ColumnDef>
* @param cfDef - column family definition
* @param meta (Tree representing Array of the hashes with metadata attributes)
* @return List<ColumnDef> List of the ColumnDef's
*
* meta is in following format - ^(ARRAY ^(HASH ^(PAIR .. ..) ^(PAIR .. ..)) ^(HASH ...))
*/
private List<ColumnDef> getCFColumnMetaFromTree(CfDef cfDef, Tree meta)
{
// this list will be returned
List<ColumnDef> columnDefinitions = new ArrayList<ColumnDef>();
// each child node is a ^(HASH ...)
for (int i = 0; i < meta.getChildCount(); i++)
{
Tree metaHash = meta.getChild(i);
ColumnDef columnDefinition = new ColumnDef();
// each child node is ^(PAIR $key $value)
for (int j = 0; j < metaHash.getChildCount(); j++)
{
Tree metaPair = metaHash.getChild(j);
// current $key
String metaKey = CliUtils.unescapeSQLString(metaPair.getChild(0).getText());
// current $value
String metaVal = CliUtils.unescapeSQLString(metaPair.getChild(1).getText());
if (metaKey.equals("column_name"))
{
if (cfDef.column_type.equals("Super"))
columnDefinition.setName(subColumnNameAsByteArray(metaVal, cfDef));
else
columnDefinition.setName(columnNameAsByteArray(metaVal, cfDef));
}
else if (metaKey.equals("validation_class"))
{
columnDefinition.setValidation_class(metaVal);
}
else if (metaKey.equals("index_type"))
{
columnDefinition.setIndex_type(getIndexTypeFromString(metaVal));
}
else if (metaKey.equals("index_name"))
{
columnDefinition.setIndex_name(metaVal);
}
}
// validating columnDef structure, 'name' and 'validation_class' must be set
try
{
columnDefinition.validate();
}
catch (TException e)
{
throw new RuntimeException(e.getMessage(), e);
}
columnDefinitions.add(columnDefinition);
}
return columnDefinitions;
}
/**
* Getting IndexType object from indexType string
* @param indexTypeAsString - string return by parser corresponding to IndexType
* @return IndexType - an IndexType object
*/
private IndexType getIndexTypeFromString(String indexTypeAsString)
{
IndexType indexType;
try
{
indexType = IndexType.findByValue(new Integer(indexTypeAsString));
}
catch (NumberFormatException e)
{
try
{
// if this is not an integer lets try to get IndexType by name
indexType = IndexType.valueOf(indexTypeAsString);
}
catch (IllegalArgumentException ie)
{
throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported.");
}
}
if (indexType == null)
{
throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported.");
}
return indexType;
}
/**
* Converts object represented as string into byte[] according to comparator
* @param object - object to covert into byte array
* @param comparator - comparator used to convert object
* @return byte[] - object in the byte array representation
*/
private ByteBuffer getBytesAccordingToType(String object, AbstractType comparator)
{
if (comparator == null) // default comparator is BytesType
comparator = BytesType.instance;
return comparator.fromString(object);
}
/**
* Converts column name into byte[] according to comparator type
* @param column - column name from parser
* @param columnFamily - column family name from parser
* @return ByteBuffer - bytes into which column name was converted according to comparator type
*/
private ByteBuffer columnNameAsBytes(String column, String columnFamily)
{
CfDef columnFamilyDef = getCfDef(columnFamily);
return columnNameAsBytes(column, columnFamilyDef);
}
/**
* Converts column name into byte[] according to comparator type
* @param column - column name from parser
* @param columnFamilyDef - column family from parser
* @return ByteBuffer bytes - into which column name was converted according to comparator type
*/
private ByteBuffer columnNameAsBytes(String column, CfDef columnFamilyDef)
{
String comparatorClass = columnFamilyDef.comparator_type;
return getBytesAccordingToType(column, getFormatTypeForColumn(comparatorClass));
}
/**
* Converts column name into byte[] according to comparator type
* @param column - column name from parser
* @param columnFamily - column family name from parser
* @return bytes[] - into which column name was converted according to comparator type
*/
private byte[] columnNameAsByteArray(String column, String columnFamily)
{
return TBaseHelper.byteBufferToByteArray(columnNameAsBytes(column, columnFamily));
}
/**
* Converts column name into byte[] according to comparator type
* @param column - column name from parser
* @param cfDef - column family from parser
* @return bytes[] - into which column name was converted according to comparator type
*/
private byte[] columnNameAsByteArray(String column, CfDef cfDef)
{
return TBaseHelper.byteBufferToByteArray(columnNameAsBytes(column, cfDef));
}
/**
* Converts sub-column name into ByteBuffer according to comparator type
* @param superColumn - sub-column name from parser
* @param columnFamily - column family name from parser
* @return ByteBuffer bytes - into which column name was converted according to comparator type
*/
private ByteBuffer subColumnNameAsBytes(String superColumn, String columnFamily)
{
CfDef columnFamilyDef = getCfDef(columnFamily);
return subColumnNameAsBytes(superColumn, columnFamilyDef);
}
/**
* Converts column name into ByteBuffer according to comparator type
* @param superColumn - sub-column name from parser
* @param columnFamilyDef - column family from parser
* @return ByteBuffer bytes - into which column name was converted according to comparator type
*/
private ByteBuffer subColumnNameAsBytes(String superColumn, CfDef columnFamilyDef)
{
String comparatorClass = columnFamilyDef.subcomparator_type;
if (comparatorClass == null)
{
sessionState.out.println(String.format("Notice: defaulting to BytesType subcomparator for '%s'", columnFamilyDef.getName()));
comparatorClass = "BytesType";
}
return getBytesAccordingToType(superColumn, getFormatTypeForColumn(comparatorClass));
}
/**
* Converts column name into byte[] according to comparator type
* @param superColumn - sub-column name from parser
* @param columnFamily - column family name from parser
* @return bytes[] - into which column name was converted according to comparator type
*/
private byte[] subColumnNameAsByteArray(String superColumn, String columnFamily)
{
return TBaseHelper.byteBufferToByteArray(subColumnNameAsBytes(superColumn, columnFamily));
}
/**
* Converts sub-column name into byte[] according to comparator type
* @param superColumn - sub-column name from parser
* @param cfDef - column family from parser
* @return bytes[] - into which column name was converted according to comparator type
*/
private byte[] subColumnNameAsByteArray(String superColumn, CfDef cfDef)
{
return TBaseHelper.byteBufferToByteArray(subColumnNameAsBytes(superColumn, cfDef));
}
/**
* Converts column value into byte[] according to validation class
* @param columnName - column name to which value belongs
* @param columnFamilyName - column family name
* @param columnValue - actual column value
* @return value in byte array representation
*/
private ByteBuffer columnValueAsBytes(ByteBuffer columnName, String columnFamilyName, String columnValue)
{
CfDef columnFamilyDef = getCfDef(columnFamilyName);
for (ColumnDef columnDefinition : columnFamilyDef.getColumn_metadata())
{
byte[] currentColumnName = columnDefinition.getName();
if (ByteBufferUtil.compare(currentColumnName, columnName) == 0)
{
try
{
String validationClass = columnDefinition.getValidation_class();
return getBytesAccordingToType(columnValue, getFormatTypeForColumn(validationClass));
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage(), e);
}
}
}
// if no validation were set returning simple .getBytes()
return ByteBufferUtil.bytes(columnValue);
}
/**
* Get validator for specific column value
* @param ColumnFamilyDef - CfDef object representing column family with metadata
* @param columnNameInBytes - column name as byte array
* @return AbstractType - validator for column value
*/
private AbstractType getValidatorForValue(CfDef ColumnFamilyDef, byte[] columnNameInBytes)
{
String defaultValidator = ColumnFamilyDef.default_validation_class;
for (ColumnDef columnDefinition : ColumnFamilyDef.getColumn_metadata())
{
byte[] nameInBytes = columnDefinition.getName();
if (Arrays.equals(nameInBytes, columnNameInBytes))
{
return getFormatTypeForColumn(columnDefinition.getValidation_class());
}
}
if (defaultValidator != null && !defaultValidator.isEmpty())
{
return getFormatTypeForColumn(defaultValidator);
}
return null;
}
/**
* Used to get Map of the provided options by create/update keyspace commands
* @param options - tree representing options
* @return Map - strategy_options map
*/
private Map<String, String> getStrategyOptionsFromTree(Tree options)
{
// this map will be returned
Map<String, String> strategyOptions = new HashMap<String, String>();
// each child node is a ^(HASH ...)
for (int i = 0; i < options.getChildCount(); i++)
{
Tree optionsHash = options.getChild(i);
// each child node is ^(PAIR $key $value)
for (int j = 0; j < optionsHash.getChildCount(); j++)
{
Tree optionPair = optionsHash.getChild(j);
// current $key
String key = CliUtils.unescapeSQLString(optionPair.getChild(0).getText());
// current $value
String val = CliUtils.unescapeSQLString(optionPair.getChild(1).getText());
strategyOptions.put(key, val);
}
}
return strategyOptions;
}
/**
* Used to convert value (function argument, string) into byte[]
* calls convertValueByFunction method with "withUpdate" set to false
* @param functionCall - tree representing function call ^(FUNCTION_CALL function_name value)
* @param columnFamily - column family definition (CfDef)
* @param columnName - also updates column family metadata for given column
* @return byte[] - string value as byte[]
*/
private ByteBuffer convertValueByFunction(Tree functionCall, CfDef columnFamily, ByteBuffer columnName)
{
return convertValueByFunction(functionCall, columnFamily, columnName, false);
}
/**
* Used to convert value (function argument, string) into byte[]
* @param functionCall - tree representing function call ^(FUNCTION_CALL function_name value)
* @param columnFamily - column family definition (CfDef)
* @param columnName - column name as byte[] (used to update CfDef)
* @param withUpdate - also updates column family metadata for given column
* @return byte[] - string value as byte[]
*/
private ByteBuffer convertValueByFunction(Tree functionCall, CfDef columnFamily, ByteBuffer columnName, boolean withUpdate)
{
String functionName = functionCall.getChild(0).getText();
Tree argumentTree = functionCall.getChild(1);
String functionArg = (argumentTree == null) ? "" : CliUtils.unescapeSQLString(argumentTree.getText());
AbstractType validator = getTypeByFunction(functionName);
try
{
ByteBuffer value;
if (functionArg.isEmpty())
{
if (validator instanceof TimeUUIDType)
{
value = ByteBuffer.wrap(UUIDGenerator.getInstance().generateTimeBasedUUID().asByteArray());
}
else if (validator instanceof LexicalUUIDType)
{
value = ByteBuffer.wrap(UUIDGen.decompose(UUID.randomUUID()));
}
else if (validator instanceof BytesType)
{
value = ByteBuffer.wrap(new byte[0]);
}
else
{
throw new RuntimeException(String.format("Argument for '%s' could not be empty.", functionName));
}
}
else
{
value = getBytesAccordingToType(functionArg, validator);
}
// performing ColumnDef local validator update
if (withUpdate)
{
updateColumnMetaData(columnFamily, columnName, validator.getClass().getName());
}
return value;
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage());
}
}
/**
* Get AbstractType by function name
* @param functionName - name of the function e.g. utf8, integer, long etc.
* @return AbstractType type corresponding to the function name
*/
public static AbstractType getTypeByFunction(String functionName)
{
Function function;
try
{
function = Function.valueOf(functionName.toUpperCase());
}
catch (IllegalArgumentException e)
{
StringBuilder errorMessage = new StringBuilder("Function '" + functionName + "' not found. ");
errorMessage.append("Available functions: ");
throw new RuntimeException(errorMessage.append(Function.getFunctionNames()).toString());
}
return function.getValidator();
}
/**
* Used to locally update column family definition with new column metadata
* @param columnFamily - CfDef record
* @param columnName - column name represented as byte[]
* @param validationClass - value validation class
*/
private void updateColumnMetaData(CfDef columnFamily, ByteBuffer columnName, String validationClass)
{
List<ColumnDef> columnMetaData = columnFamily.getColumn_metadata();
ColumnDef column = getColumnDefByName(columnFamily, columnName);
if (column != null)
{
// if validation class is the same - no need to modify it
if (column.getValidation_class().equals(validationClass))
return;
// updating column definition with new validation_class
column.setValidation_class(validationClass);
}
else
{
columnMetaData.add(new ColumnDef(columnName, validationClass));
}
}
/**
* Get specific ColumnDef in column family meta data by column name
* @param columnFamily - CfDef record
* @param columnName - column name represented as byte[]
* @return ColumnDef - found column definition
*/
private ColumnDef getColumnDefByName(CfDef columnFamily, ByteBuffer columnName)
{
for (ColumnDef columnDef : columnFamily.getColumn_metadata())
{
byte[] currName = columnDef.getName();
if (ByteBufferUtil.compare(currName, columnName) == 0)
{
return columnDef;
}
}
return null;
}
/**
* Prints out KeySlice list
* @param columnFamilyDef - column family definition
* @param slices - list of the KeySlice's to print out
* @throws NotFoundException - column not found
* @throws TException - transfer is broken
* @throws IllegalAccessException - can't do operation
* @throws InstantiationException - can't instantiate a class
* @throws NoSuchFieldException - column not found
*/
private void printSliceList(CfDef columnFamilyDef, List<KeySlice> slices)
throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException, CharacterCodingException
{
AbstractType validator;
String columnFamilyName = columnFamilyDef.getName();
AbstractType keyComparator = this.cfKeysComparators.get(columnFamilyName);
for (KeySlice ks : slices)
{
String keyName = (keyComparator == null) ? ByteBufferUtil.string(ks.key) : keyComparator.getString(ks.key);
sessionState.out.printf("-------------------%n");
sessionState.out.printf("RowKey: %s%n", keyName);
Iterator<ColumnOrSuperColumn> iterator = ks.getColumnsIterator();
while (iterator.hasNext())
{
ColumnOrSuperColumn columnOrSuperColumn = iterator.next();
if (columnOrSuperColumn.column != null)
{
Column col = columnOrSuperColumn.column;
validator = getValidatorForValue(columnFamilyDef, col.getName());
sessionState.out.printf("=> (column=%s, value=%s, timestamp=%d%s)%n",
formatColumnName(keySpace, columnFamilyName, col), validator.getString(col.value), col.timestamp,
col.isSetTtl() ? String.format(", ttl=%d", col.getTtl()) : "");
}
else if (columnOrSuperColumn.super_column != null)
{
SuperColumn superCol = columnOrSuperColumn.super_column;
sessionState.out.printf("=> (super_column=%s,", formatSuperColumnName(keySpace, columnFamilyName, superCol));
for (Column col : superCol.columns)
{
validator = getValidatorForValue(columnFamilyDef, col.getName());
sessionState.out.printf("%n (column=%s, value=%s, timestamp=%d%s)",
formatSubcolumnName(keySpace, columnFamilyName, col), validator.getString(col.value), col.timestamp,
col.isSetTtl() ? String.format(", ttl=%d", col.getTtl()) : "");
}
sessionState.out.println(")");
}
}
}
sessionState.out.printf("%n%d Row%s Returned.%n", slices.size(), (slices.size() > 1 ? "s" : ""));
}
// returnsub-columnmn name in human-readable format
private String formatSuperColumnName(String keyspace, String columnFamily, SuperColumn column)
throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException
{
return getFormatTypeForColumn(getCfDef(keyspace,columnFamily).comparator_type).getString(column.name);
}
// retuns sub-column name in human-readable format
private String formatSubcolumnName(String keyspace, String columnFamily, Column subcolumn)
throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException
{
return getFormatTypeForColumn(getCfDef(keyspace,columnFamily).subcomparator_type).getString(subcolumn.name);
}
// retuns column name in human-readable format
private String formatColumnName(String keyspace, String columnFamily, Column column)
throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException
{
return getFormatTypeForColumn(getCfDef(keyspace, columnFamily).comparator_type).getString(ByteBuffer.wrap(column.getName()));
}
private ByteBuffer getColumnName(String columnFamily, Tree columnTree)
{
return (columnTree.getType() == CliParser.FUNCTION_CALL)
? convertValueByFunction(columnTree, null, null)
: columnNameAsBytes(CliUtils.unescapeSQLString(columnTree.getText()), columnFamily);
}
private ByteBuffer getSubColumnName(String columnFamily, Tree columnTree)
{
return (columnTree.getType() == CliParser.FUNCTION_CALL)
? convertValueByFunction(columnTree, null, null)
: subColumnNameAsBytes(CliUtils.unescapeSQLString(columnTree.getText()), columnFamily);
}
public ByteBuffer getKeyAsBytes(String columnFamily, Tree keyTree)
{
if (keyTree.getType() == CliParser.FUNCTION_CALL)
return convertValueByFunction(keyTree, null, null);
String key = CliUtils.unescapeSQLString(keyTree.getText());
AbstractType keyComparator = this.cfKeysComparators.get(columnFamily);
return getBytesAccordingToType(key, keyComparator);
}
private static class KsDefNamesComparator implements Comparator<KsDef>
{
public int compare(KsDef a, KsDef b)
{
return a.name.compareTo(b.name);
}
}
/** validates schema is propagated to all nodes */
private void validateSchemaIsSettled(String currentVersionId)
{
sessionState.out.println("Waiting for schema agreement...");
Map<String, List<String>> versions = null;
long limit = System.currentTimeMillis() + sessionState.schema_mwt;
boolean inAgreement = false;
outer:
while (limit - System.currentTimeMillis() >= 0 && !inAgreement)
{
try
{
versions = thriftClient.describe_schema_versions(); // getting schema version for nodes of the ring
}
catch (Exception e)
{
sessionState.err.println((e instanceof InvalidRequestException) ? ((InvalidRequestException) e).getWhy() : e.getMessage());
continue;
}
for (String version : versions.keySet())
{
if (!version.equals(currentVersionId) && !version.equals(StorageProxy.UNREACHABLE))
continue outer;
}
inAgreement = true;
}
if (versions.containsKey(StorageProxy.UNREACHABLE))
sessionState.err.printf("Warning: unreachable nodes %s", Joiner.on(", ").join(versions.get(StorageProxy.UNREACHABLE)));
if (!inAgreement)
{
sessionState.err.printf("The schema has not settled in %d seconds; further migrations are ill-advised until it does.%nVersions are %s%n",
sessionState.schema_mwt / 1000, FBUtilities.toString(versions));
System.exit(-1);
}
sessionState.out.println("... schemas agree across the cluster");
}
private static class CfDefNamesComparator implements Comparator<CfDef>
{
public int compare(CfDef a, CfDef b)
{
return a.name.compareTo(b.name);
}
}
}
| true | true | private void describeKeySpace(String keySpaceName, KsDef metadata) throws TException
{
NodeProbe probe = sessionState.getNodeProbe();
// getting compaction manager MBean to displaying index building information
CompactionManagerMBean compactionManagerMBean = (probe == null) ? null : probe.getCompactionManagerProxy();
// Describe and display
sessionState.out.println("Keyspace: " + keySpaceName + ":");
try
{
KsDef ks_def;
ks_def = metadata == null ? thriftClient.describe_keyspace(keySpaceName) : metadata;
sessionState.out.println(" Replication Strategy: " + ks_def.strategy_class);
if (ks_def.strategy_class.endsWith(".NetworkTopologyStrategy"))
{
Map<String, String> options = ks_def.strategy_options;
sessionState.out.println(" Options: [" + ((options == null) ? "" : FBUtilities.toString(options)) + "]");
}
else
{
sessionState.out.println(" Replication Factor: " + ks_def.replication_factor);
}
sessionState.out.println(" Column Families:");
boolean isSuper;
Collections.sort(ks_def.cf_defs, new CfDefNamesComparator());
for (CfDef cf_def : ks_def.cf_defs)
{
// fetching bean for current column family store
ColumnFamilyStoreMBean cfMBean = (probe == null) ? null : probe.getCfsProxy(ks_def.getName(), cf_def.getName());
isSuper = cf_def.column_type.equals("Super");
sessionState.out.printf(" ColumnFamily: %s%s%n", cf_def.name, isSuper ? " (Super)" : "");
if (cf_def.comment != null && !cf_def.comment.isEmpty())
{
sessionState.out.printf(" \"%s\"%n", cf_def.comment);
}
if (cf_def.default_validation_class != null)
sessionState.out.printf(" default_validation_class: %s%n", cf_def.default_validation_class);
sessionState.out.printf(" Columns sorted by: %s%s%n", cf_def.comparator_type, cf_def.column_type.equals("Super") ? "/" + cf_def.subcomparator_type : "");
sessionState.out.printf(" Row cache size / save period in seconds: %s/%s%n", cf_def.row_cache_size, cf_def.row_cache_save_period_in_seconds);
sessionState.out.printf(" Key cache size / save period in seconds: %s/%s%n", cf_def.key_cache_size, cf_def.key_cache_save_period_in_seconds);
sessionState.out.printf(" Memtable thresholds: %s/%s/%s (millions of ops/minutes/MB)%n",
cf_def.memtable_operations_in_millions, cf_def.memtable_throughput_in_mb, cf_def.memtable_flush_after_mins);
sessionState.out.printf(" GC grace seconds: %s%n", cf_def.gc_grace_seconds);
sessionState.out.printf(" Compaction min/max thresholds: %s/%s%n", cf_def.min_compaction_threshold, cf_def.max_compaction_threshold);
sessionState.out.printf(" Read repair chance: %s%n", cf_def.read_repair_chance);
// if we have connection to the cfMBean established
if (cfMBean != null)
{
sessionState.out.printf(" Built indexes: %s%n", cfMBean.getBuiltIndexes());
}
if (cf_def.getColumn_metadataSize() != 0)
{
String leftSpace = " ";
String columnLeftSpace = leftSpace + " ";
AbstractType columnNameValidator = getFormatTypeForColumn(isSuper ? cf_def.subcomparator_type
: cf_def.comparator_type);
sessionState.out.println(leftSpace + "Column Metadata:");
for (ColumnDef columnDef : cf_def.getColumn_metadata())
{
String columnName = columnNameValidator.getString(columnDef.name);
if (columnNameValidator instanceof BytesType)
{
try
{
String columnString = UTF8Type.instance.getString(columnDef.name);
columnName = columnString + " (" + columnName + ")";
}
catch (MarshalException e)
{
// guess it wasn't a utf8 column name after all
}
}
sessionState.out.println(leftSpace + " Column Name: " + columnName);
sessionState.out.println(columnLeftSpace + "Validation Class: " + columnDef.getValidation_class());
if (columnDef.isSetIndex_name())
{
sessionState.out.println(columnLeftSpace + "Index Name: " + columnDef.getIndex_name());
}
if (columnDef.isSetIndex_type())
{
sessionState.out.println(columnLeftSpace + "Index Type: " + columnDef.getIndex_type().name());
}
}
}
}
// compaction manager information
if (compactionManagerMBean != null)
{
String compactionType = compactionManagerMBean.getCompactionType();
// if ongoing compaction type is index build
if (compactionType != null && compactionType.contains("index build"))
{
String indexName = compactionManagerMBean.getColumnFamilyInProgress();
long bytesCompacted = compactionManagerMBean.getBytesCompacted();
long totalBytesToProcess = compactionManagerMBean.getBytesTotalInProgress();
sessionState.out.printf("%nCurrently building index %s, completed %d of %d bytes.%n", indexName, bytesCompacted, totalBytesToProcess);
}
}
// closing JMX connection
if (probe != null)
probe.close();
}
catch (InvalidRequestException e)
{
sessionState.out.println("Invalid request: " + e);
}
catch (NotFoundException e)
{
sessionState.out.println("Keyspace " + keySpaceName + " could not be found.");
}
catch (IOException e)
{
sessionState.out.println("Error while closing JMX connection: " + e.getMessage());
}
}
| private void describeKeySpace(String keySpaceName, KsDef metadata) throws TException
{
NodeProbe probe = sessionState.getNodeProbe();
// getting compaction manager MBean to displaying index building information
CompactionManagerMBean compactionManagerMBean = (probe == null) ? null : probe.getCompactionManagerProxy();
// Describe and display
sessionState.out.println("Keyspace: " + keySpaceName + ":");
try
{
KsDef ks_def;
ks_def = metadata == null ? thriftClient.describe_keyspace(keySpaceName) : metadata;
sessionState.out.println(" Replication Strategy: " + ks_def.strategy_class);
if (ks_def.strategy_class.endsWith(".NetworkTopologyStrategy"))
{
Map<String, String> options = ks_def.strategy_options;
sessionState.out.println(" Options: [" + ((options == null) ? "" : FBUtilities.toString(options)) + "]");
}
else
{
sessionState.out.println(" Replication Factor: " + ks_def.replication_factor);
}
sessionState.out.println(" Column Families:");
boolean isSuper;
Collections.sort(ks_def.cf_defs, new CfDefNamesComparator());
for (CfDef cf_def : ks_def.cf_defs)
{
// fetching bean for current column family store
ColumnFamilyStoreMBean cfMBean = (probe == null) ? null : probe.getCfsProxy(ks_def.getName(), cf_def.getName());
isSuper = cf_def.column_type.equals("Super");
sessionState.out.printf(" ColumnFamily: %s%s%n", cf_def.name, isSuper ? " (Super)" : "");
if (cf_def.comment != null && !cf_def.comment.isEmpty())
{
sessionState.out.printf(" \"%s\"%n", cf_def.comment);
}
if (cf_def.default_validation_class != null)
sessionState.out.printf(" default_validation_class: %s%n", cf_def.default_validation_class);
sessionState.out.printf(" Columns sorted by: %s%s%n", cf_def.comparator_type, cf_def.column_type.equals("Super") ? "/" + cf_def.subcomparator_type : "");
sessionState.out.printf(" Row cache size / save period in seconds: %s/%s%n", cf_def.row_cache_size, cf_def.row_cache_save_period_in_seconds);
sessionState.out.printf(" Key cache size / save period in seconds: %s/%s%n", cf_def.key_cache_size, cf_def.key_cache_save_period_in_seconds);
sessionState.out.printf(" Memtable thresholds: %s/%s/%s (millions of ops/minutes/MB)%n",
cf_def.memtable_operations_in_millions, cf_def.memtable_flush_after_mins, cf_def.memtable_throughput_in_mb);
sessionState.out.printf(" GC grace seconds: %s%n", cf_def.gc_grace_seconds);
sessionState.out.printf(" Compaction min/max thresholds: %s/%s%n", cf_def.min_compaction_threshold, cf_def.max_compaction_threshold);
sessionState.out.printf(" Read repair chance: %s%n", cf_def.read_repair_chance);
// if we have connection to the cfMBean established
if (cfMBean != null)
{
sessionState.out.printf(" Built indexes: %s%n", cfMBean.getBuiltIndexes());
}
if (cf_def.getColumn_metadataSize() != 0)
{
String leftSpace = " ";
String columnLeftSpace = leftSpace + " ";
AbstractType columnNameValidator = getFormatTypeForColumn(isSuper ? cf_def.subcomparator_type
: cf_def.comparator_type);
sessionState.out.println(leftSpace + "Column Metadata:");
for (ColumnDef columnDef : cf_def.getColumn_metadata())
{
String columnName = columnNameValidator.getString(columnDef.name);
if (columnNameValidator instanceof BytesType)
{
try
{
String columnString = UTF8Type.instance.getString(columnDef.name);
columnName = columnString + " (" + columnName + ")";
}
catch (MarshalException e)
{
// guess it wasn't a utf8 column name after all
}
}
sessionState.out.println(leftSpace + " Column Name: " + columnName);
sessionState.out.println(columnLeftSpace + "Validation Class: " + columnDef.getValidation_class());
if (columnDef.isSetIndex_name())
{
sessionState.out.println(columnLeftSpace + "Index Name: " + columnDef.getIndex_name());
}
if (columnDef.isSetIndex_type())
{
sessionState.out.println(columnLeftSpace + "Index Type: " + columnDef.getIndex_type().name());
}
}
}
}
// compaction manager information
if (compactionManagerMBean != null)
{
String compactionType = compactionManagerMBean.getCompactionType();
// if ongoing compaction type is index build
if (compactionType != null && compactionType.contains("index build"))
{
String indexName = compactionManagerMBean.getColumnFamilyInProgress();
long bytesCompacted = compactionManagerMBean.getBytesCompacted();
long totalBytesToProcess = compactionManagerMBean.getBytesTotalInProgress();
sessionState.out.printf("%nCurrently building index %s, completed %d of %d bytes.%n", indexName, bytesCompacted, totalBytesToProcess);
}
}
// closing JMX connection
if (probe != null)
probe.close();
}
catch (InvalidRequestException e)
{
sessionState.out.println("Invalid request: " + e);
}
catch (NotFoundException e)
{
sessionState.out.println("Keyspace " + keySpaceName + " could not be found.");
}
catch (IOException e)
{
sessionState.out.println("Error while closing JMX connection: " + e.getMessage());
}
}
|
diff --git a/src/main/java/org/codehaus/gmavenplus/mojo/AbstractGroovydocMojo.java b/src/main/java/org/codehaus/gmavenplus/mojo/AbstractGroovydocMojo.java
index b24b1694..7cbe6da6 100644
--- a/src/main/java/org/codehaus/gmavenplus/mojo/AbstractGroovydocMojo.java
+++ b/src/main/java/org/codehaus/gmavenplus/mojo/AbstractGroovydocMojo.java
@@ -1,241 +1,241 @@
/*
* Copyright (C) 2011 the original author or authors.
*
* 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 org.codehaus.gmavenplus.mojo;
import com.google.common.io.Closer;
import org.apache.maven.shared.model.fileset.util.FileSetManager;
import org.codehaus.gmavenplus.model.Scopes;
import org.codehaus.gmavenplus.model.Version;
import org.codehaus.gmavenplus.groovyworkarounds.GroovyDocTemplateInfo;
import org.codehaus.gmavenplus.util.ReflectionUtils;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import org.apache.maven.shared.model.fileset.FileSet;
/**
* The base groovydoc mojo, which all groovydoc mojos extend.
*
* @author Keegan Witt
*/
public abstract class AbstractGroovydocMojo extends AbstractGroovySourcesMojo {
// TODO: support Groovy 1.5.0 - 1.6.1?
/*
* For some reason some NPE about a rootDoc occurs with older versions
* (note that I used a different constructor and an addSource(File) instead
* of addSources(List<File>) because that didn't exist back then.
*/
/**
* The minimum version of Groovy that this mojo supports.
*/
protected static final Version MIN_GROOVY_VERSION = new Version(1, 6, 2);
/**
* The location for the generated API docs.
*
* @parameter default-value="${project.build.directory}/gapidocs"
*/
protected File groovydocOutputDirectory;
/**
* The location for the generated test API docs.
*
* @parameter default-value="${project.build.directory}/testgapidocs"
*/
protected File testGroovydocOutputDirectory;
/**
* The window title.
*
* @parameter default-value="Groovy Documentation"
*/
protected String windowTitle;
/**
* The page title.
*
* @parameter default-value="Groovy Documentation"
*/
protected String docTitle;
/**
* The page footer.
*
* @parameter default-value="Groovy Documentation"
*/
protected String footer;
/**
* The page header.
*
* @parameter default-value="Groovy Documentation"
*/
protected String header;
/**
* Whether to display the author in the generated Groovydoc.
*
* @parameter default-value="true"
*/
protected boolean displayAuthor;
/**
* The HTML file to be used for overview documentation.
*
* @parameter
*/
protected File overviewFile;
/**
* The stylesheet file (absolute path) to copy to output directory (will overwrite default stylesheet.css).
*
* @parameter
*/
protected File stylesheetFile;
/**
* The encoding of stylesheetFile.
*
* @parameter default-value="UTF-8"
*/
protected String stylesheetEncoding;
/**
* The scope to generate Groovydoc for, should be one of:
* <ul>
* <li>"public"</li>
* <li>"protected"</li>
* <li>"package"</li>
* <li>"private"</li>
* </ul>
*
* @parameter default-value="private"
*/
protected String scope;
// TODO: add links parameter
/**
* Generates the groovydoc for the specified sources.
*
* @param sourceDirectories The source directories to generate groovydoc for
* @param outputDirectory The directory to save the generated groovydoc in
* @throws ClassNotFoundException When a class needed for groovydoc generation cannot be found
* @throws InstantiationException When a class needed for groovydoc generation cannot be instantiated
* @throws IllegalAccessException When a method needed for groovydoc generation cannot be accessed
* @throws InvocationTargetException When a reflection invocation needed for groovydoc generation cannot be completed
*/
protected void generateGroovydoc(final FileSet[] sourceDirectories, final File outputDirectory) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
// get classes we need with reflection
Class<?> groovyDocToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.GroovyDocTool");
Class<?> outputToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.OutputTool");
Class<?> fileOutputToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.FileOutputTool");
Class<?> resourceManagerClass = Class.forName("org.codehaus.groovy.tools.groovydoc.ResourceManager");
Class<?> classpathResourceManagerClass = Class.forName("org.codehaus.groovy.tools.groovydoc.ClasspathResourceManager");
// set up Groovydoc options
List links = new ArrayList();
Properties properties = new Properties();
properties.setProperty("windowTitle", windowTitle);
properties.setProperty("docTitle", docTitle);
properties.setProperty("footer", footer);
properties.setProperty("header", header);
properties.setProperty("author", Boolean.toString(displayAuthor));
properties.setProperty("overviewFile", overviewFile != null ? overviewFile.getAbsolutePath() : "");
try {
Scopes scopeVal = Scopes.valueOf(scope.toUpperCase());
if (scopeVal.equals(Scopes.PUBLIC)) {
properties.setProperty("publicScope", "true");
} else if (scopeVal.equals(Scopes.PROTECTED)) {
properties.setProperty("protectedScope", "true");
} else if (scopeVal.equals(Scopes.PACKAGE)) {
properties.setProperty("packageScope", "true");
} else if (scopeVal.equals(Scopes.PRIVATE)) {
properties.setProperty("privateScope", "true");
}
} catch (IllegalArgumentException e) {
getLog().warn("Scope (" + scope + ") was not recognized. Skipping argument.");
}
Object fileOutputTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(fileOutputToolClass));
Object classpathResourceManager = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(classpathResourceManagerClass));
// generate Groovydoc
+ FileSetManager fileSetManager = new FileSetManager(getLog());
for (FileSet sourceDirectory : sourceDirectories) {
Object groovyDocTool;
groovyDocTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyDocToolClass, resourceManagerClass, String[].class, String[].class, String[].class, String[].class, List.class, Properties.class),
classpathResourceManager,
new String[] {sourceDirectory.getDirectory()},
GroovyDocTemplateInfo.DEFAULT_DOC_TEMPLATES,
GroovyDocTemplateInfo.DEFAULT_PACKAGE_TEMPLATES,
GroovyDocTemplateInfo.DEFAULT_CLASS_TEMPLATES,
links,
properties
);
- FileSetManager fileSetManager = new FileSetManager(getLog());
- ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "add", List.class), groovyDocTool, fileSetManager.getIncludedFiles(sourceDirectory));
+ ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "add", List.class), groovyDocTool, Arrays.asList(fileSetManager.getIncludedFiles(sourceDirectory)));
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "renderToOutput", outputToolClass, String.class), groovyDocTool, fileOutputTool, outputDirectory.getAbsolutePath());
}
// overwrite stylesheet.css with provided stylesheet (if configured)
if (stylesheetFile != null) {
copyStylesheet(outputDirectory);
}
}
/**
* Copies the stylesheet to the specified output directory.
*
* @param outputDirectory The output directory to copy the stylesheet to
*/
private void copyStylesheet(final File outputDirectory) {
getLog().info("Using stylesheet from " + stylesheetFile.getAbsolutePath() + ".");
Closer closer = Closer.create();
try {
try {
BufferedReader bufferedReader = closer.register(new BufferedReader(new InputStreamReader(new FileInputStream(stylesheetFile), stylesheetEncoding)));
StringBuilder css = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
css.append(line).append("\n");
}
File outfile = new File(outputDirectory, "stylesheet.css");
BufferedWriter bufferedWriter = closer.register(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), stylesheetEncoding)));
bufferedWriter.write(css.toString());
} catch (Throwable throwable) {
throw closer.rethrow(throwable);
} finally {
closer.close();
}
} catch (IOException e) {
getLog().warn("Unable to copy specified stylesheet (" + stylesheetFile.getAbsolutePath() + ").");
}
}
/**
* Determines whether this mojo can be run with the version of Groovy supplied.
* Must be >= 1.6.2 because not all the classes/methods needed were available
* and functioning correctly in previous versions.
*
* @return <code>true</code> only if the version of Groovy supports this mojo
*/
protected boolean groovyVersionSupportsAction() {
return Version.parseFromString(getGroovyVersion()).compareTo(MIN_GROOVY_VERSION) >= 0;
}
}
| false | true | protected void generateGroovydoc(final FileSet[] sourceDirectories, final File outputDirectory) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
// get classes we need with reflection
Class<?> groovyDocToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.GroovyDocTool");
Class<?> outputToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.OutputTool");
Class<?> fileOutputToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.FileOutputTool");
Class<?> resourceManagerClass = Class.forName("org.codehaus.groovy.tools.groovydoc.ResourceManager");
Class<?> classpathResourceManagerClass = Class.forName("org.codehaus.groovy.tools.groovydoc.ClasspathResourceManager");
// set up Groovydoc options
List links = new ArrayList();
Properties properties = new Properties();
properties.setProperty("windowTitle", windowTitle);
properties.setProperty("docTitle", docTitle);
properties.setProperty("footer", footer);
properties.setProperty("header", header);
properties.setProperty("author", Boolean.toString(displayAuthor));
properties.setProperty("overviewFile", overviewFile != null ? overviewFile.getAbsolutePath() : "");
try {
Scopes scopeVal = Scopes.valueOf(scope.toUpperCase());
if (scopeVal.equals(Scopes.PUBLIC)) {
properties.setProperty("publicScope", "true");
} else if (scopeVal.equals(Scopes.PROTECTED)) {
properties.setProperty("protectedScope", "true");
} else if (scopeVal.equals(Scopes.PACKAGE)) {
properties.setProperty("packageScope", "true");
} else if (scopeVal.equals(Scopes.PRIVATE)) {
properties.setProperty("privateScope", "true");
}
} catch (IllegalArgumentException e) {
getLog().warn("Scope (" + scope + ") was not recognized. Skipping argument.");
}
Object fileOutputTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(fileOutputToolClass));
Object classpathResourceManager = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(classpathResourceManagerClass));
// generate Groovydoc
for (FileSet sourceDirectory : sourceDirectories) {
Object groovyDocTool;
groovyDocTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyDocToolClass, resourceManagerClass, String[].class, String[].class, String[].class, String[].class, List.class, Properties.class),
classpathResourceManager,
new String[] {sourceDirectory.getDirectory()},
GroovyDocTemplateInfo.DEFAULT_DOC_TEMPLATES,
GroovyDocTemplateInfo.DEFAULT_PACKAGE_TEMPLATES,
GroovyDocTemplateInfo.DEFAULT_CLASS_TEMPLATES,
links,
properties
);
FileSetManager fileSetManager = new FileSetManager(getLog());
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "add", List.class), groovyDocTool, fileSetManager.getIncludedFiles(sourceDirectory));
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "renderToOutput", outputToolClass, String.class), groovyDocTool, fileOutputTool, outputDirectory.getAbsolutePath());
}
// overwrite stylesheet.css with provided stylesheet (if configured)
if (stylesheetFile != null) {
copyStylesheet(outputDirectory);
}
}
| protected void generateGroovydoc(final FileSet[] sourceDirectories, final File outputDirectory) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
// get classes we need with reflection
Class<?> groovyDocToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.GroovyDocTool");
Class<?> outputToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.OutputTool");
Class<?> fileOutputToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.FileOutputTool");
Class<?> resourceManagerClass = Class.forName("org.codehaus.groovy.tools.groovydoc.ResourceManager");
Class<?> classpathResourceManagerClass = Class.forName("org.codehaus.groovy.tools.groovydoc.ClasspathResourceManager");
// set up Groovydoc options
List links = new ArrayList();
Properties properties = new Properties();
properties.setProperty("windowTitle", windowTitle);
properties.setProperty("docTitle", docTitle);
properties.setProperty("footer", footer);
properties.setProperty("header", header);
properties.setProperty("author", Boolean.toString(displayAuthor));
properties.setProperty("overviewFile", overviewFile != null ? overviewFile.getAbsolutePath() : "");
try {
Scopes scopeVal = Scopes.valueOf(scope.toUpperCase());
if (scopeVal.equals(Scopes.PUBLIC)) {
properties.setProperty("publicScope", "true");
} else if (scopeVal.equals(Scopes.PROTECTED)) {
properties.setProperty("protectedScope", "true");
} else if (scopeVal.equals(Scopes.PACKAGE)) {
properties.setProperty("packageScope", "true");
} else if (scopeVal.equals(Scopes.PRIVATE)) {
properties.setProperty("privateScope", "true");
}
} catch (IllegalArgumentException e) {
getLog().warn("Scope (" + scope + ") was not recognized. Skipping argument.");
}
Object fileOutputTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(fileOutputToolClass));
Object classpathResourceManager = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(classpathResourceManagerClass));
// generate Groovydoc
FileSetManager fileSetManager = new FileSetManager(getLog());
for (FileSet sourceDirectory : sourceDirectories) {
Object groovyDocTool;
groovyDocTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyDocToolClass, resourceManagerClass, String[].class, String[].class, String[].class, String[].class, List.class, Properties.class),
classpathResourceManager,
new String[] {sourceDirectory.getDirectory()},
GroovyDocTemplateInfo.DEFAULT_DOC_TEMPLATES,
GroovyDocTemplateInfo.DEFAULT_PACKAGE_TEMPLATES,
GroovyDocTemplateInfo.DEFAULT_CLASS_TEMPLATES,
links,
properties
);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "add", List.class), groovyDocTool, Arrays.asList(fileSetManager.getIncludedFiles(sourceDirectory)));
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "renderToOutput", outputToolClass, String.class), groovyDocTool, fileOutputTool, outputDirectory.getAbsolutePath());
}
// overwrite stylesheet.css with provided stylesheet (if configured)
if (stylesheetFile != null) {
copyStylesheet(outputDirectory);
}
}
|
diff --git a/grails/src/commons/grails/util/GrailsUtil.java b/grails/src/commons/grails/util/GrailsUtil.java
index db1b5d3e7..b62aa987f 100644
--- a/grails/src/commons/grails/util/GrailsUtil.java
+++ b/grails/src/commons/grails/util/GrailsUtil.java
@@ -1,196 +1,198 @@
/* Copyright 2004-2005 the original author or authors.
*
* 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 c;pWARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package grails.util;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.ApplicationAttributes;
import org.codehaus.groovy.grails.commons.DefaultGrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.ApplicationHolder;
import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator;
import org.codehaus.groovy.grails.exceptions.GrailsConfigurationException;
import org.codehaus.groovy.grails.support.MockResourceLoader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.util.Assert;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Manifest;
import java.util.jar.Attributes;
import java.io.IOException;
/**
*
* Grails utility methods for command line and GUI applications
*
* @author Graeme Rocher
* @since 0.2
*
* @version $Revision$
* First Created: 02-Jun-2006
* Last Updated: $Date$
*
*/
public class GrailsUtil {
private static final Log LOG = LogFactory.getLog(GrailsUtil.class);
private static final String GRAILS_IMPLEMENTATION_TITLE = "Grails";
private static final String GRAILS_VERSION;
static {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
Resource[] manifests = resolver.getResources("classpath*:META-INF/GRAILS-MANIFEST.MF");
Manifest grailsManifest = null;
for (int i = 0; i < manifests.length; i++) {
Resource r = manifests[i];
Manifest mf = new Manifest(r.getInputStream());
String implTitle = mf.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_TITLE);
if(!StringUtils.isBlank(implTitle) && implTitle.equals(GRAILS_IMPLEMENTATION_TITLE)) {
grailsManifest = mf;
break;
}
}
String version = null;
if(grailsManifest != null) {
version = grailsManifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
}
if(!StringUtils.isBlank(version)) {
GRAILS_VERSION = version;
}
else {
GRAILS_VERSION = null;
throw new GrailsConfigurationException("Unable to read Grails version from MANIFEST.MF. Are you sure it the grails-core jar is on the classpath? " );
}
} catch (IOException e) {
throw new GrailsConfigurationException("Unable to read Grails version from MANIFEST.MF. Are you sure it the grails-core jar is on the classpath? " + e.getMessage(), e);
}
}
private static final String PRODUCTION_ENV_SHORT_NAME = "prod";
private static final String DEVELOPMENT_ENVIRONMENT_SHORT_NAME = "dev";
private static final String TEST_ENVIRONMENT_SHORT_NAME = "test";
private static Map envNameMappings = new HashMap() {{
put(DEVELOPMENT_ENVIRONMENT_SHORT_NAME, GrailsApplication.ENV_DEVELOPMENT);
put(PRODUCTION_ENV_SHORT_NAME, GrailsApplication.ENV_PRODUCTION);
put(TEST_ENVIRONMENT_SHORT_NAME, GrailsApplication.ENV_TEST);
}};
public static ApplicationContext bootstrapGrailsFromClassPath() {
LOG.info("Loading Grails environment");
ApplicationContext parent = new ClassPathXmlApplicationContext("applicationContext.xml");
DefaultGrailsApplication application = (DefaultGrailsApplication)parent.getBean("grailsApplication", DefaultGrailsApplication.class);
GrailsRuntimeConfigurator config = new GrailsRuntimeConfigurator(application,parent);
MockServletContext servletContext = new MockServletContext(new MockResourceLoader());
ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)config.configure(servletContext);
servletContext.setAttribute( ApplicationAttributes.APPLICATION_CONTEXT, appCtx);
Assert.notNull(appCtx);
return appCtx;
}
/**
* Retrieves the current execution environment
*
* @return The environment Grails is executing under
*/
public static String getEnvironment() {
GrailsApplication app = ApplicationHolder.getApplication();
String envName = null;
if(app!=null) {
- envName = (String)app.getMetadata().get(GrailsApplication.ENVIRONMENT);
+ Map metadata = app.getMetadata();
+ if(metadata!=null)
+ envName = (String)metadata.get(GrailsApplication.ENVIRONMENT);
}
if(StringUtils.isBlank(envName))
envName = System.getProperty(GrailsApplication.ENVIRONMENT);
if(StringUtils.isBlank(envName)) {
// for now if no environment specified default to production
return GrailsApplication.ENV_PRODUCTION;
}
else {
if(envNameMappings.containsKey(envName)) {
return (String)envNameMappings.get(envName);
}
else {
return envName;
}
}
}
/**
* Retrieves whether the current execution environment is the development one
*
* @return True if it is the development environment
*/
public static boolean isDevelopmentEnv() {
return GrailsApplication.ENV_DEVELOPMENT.equals(GrailsUtil.getEnvironment());
}
public static String getGrailsVersion() {
return GRAILS_VERSION;
}
/**
* Logs warning message about deprecation of specified property or method of some class.
*
* @param clazz A class
* @param methodOrPropName Name of deprecated property or method
*/
public static void deprecated(Class clazz, String methodOrPropName ) {
deprecated(clazz, methodOrPropName, getGrailsVersion());
}
/**
* Logs warning message about deprecation of specified property or method of some class.
*
* @param clazz A class
* @param methodOrPropName Name of deprecated property or method
* @param version Version of Grails release in which property or method were deprecated
*/
public static void deprecated(Class clazz, String methodOrPropName, String version ) {
deprecated("Property or method [" + methodOrPropName + "] of class [" + clazz.getName() +
"] is deprecated in [" + getGrailsVersion() +
"] and will be removed in future releases");
}
/**
* Logs warning message about some deprecation and code style related hints.
*
* @param message Message to display
*/
public static void deprecated(String message) {
LOG.warn("[DEPRECATED] " + message);
}
}
| true | true | public static String getEnvironment() {
GrailsApplication app = ApplicationHolder.getApplication();
String envName = null;
if(app!=null) {
envName = (String)app.getMetadata().get(GrailsApplication.ENVIRONMENT);
}
if(StringUtils.isBlank(envName))
envName = System.getProperty(GrailsApplication.ENVIRONMENT);
if(StringUtils.isBlank(envName)) {
// for now if no environment specified default to production
return GrailsApplication.ENV_PRODUCTION;
}
else {
if(envNameMappings.containsKey(envName)) {
return (String)envNameMappings.get(envName);
}
else {
return envName;
}
}
}
| public static String getEnvironment() {
GrailsApplication app = ApplicationHolder.getApplication();
String envName = null;
if(app!=null) {
Map metadata = app.getMetadata();
if(metadata!=null)
envName = (String)metadata.get(GrailsApplication.ENVIRONMENT);
}
if(StringUtils.isBlank(envName))
envName = System.getProperty(GrailsApplication.ENVIRONMENT);
if(StringUtils.isBlank(envName)) {
// for now if no environment specified default to production
return GrailsApplication.ENV_PRODUCTION;
}
else {
if(envNameMappings.containsKey(envName)) {
return (String)envNameMappings.get(envName);
}
else {
return envName;
}
}
}
|
diff --git a/src/org/openstatic/irc/IrcUser.java b/src/org/openstatic/irc/IrcUser.java
index 7be951b..37cbb38 100755
--- a/src/org/openstatic/irc/IrcUser.java
+++ b/src/org/openstatic/irc/IrcUser.java
@@ -1,427 +1,431 @@
package org.openstatic.irc;
import java.util.Enumeration;
import java.util.Vector;
public class IrcUser extends Thread
{
private String username;
private String nickname;
private String realname;
private String away_message;
private String password;
private String client_host;
private String domain;
private boolean welcomed;
private int idle_time;
private boolean stay_connected;
private IrcServer server;
private GatewayConnection connection;
public IrcUser(IrcServer server)
{
this.nickname = null;
this.realname = null;
this.username = null;
this.away_message = null;
this.welcomed = false;
this.server = server;
}
public void initGatewayConnection(GatewayConnection connection)
{
this.connection = connection;
this.stay_connected = true;
Thread idleClock = new Thread()
{
public void run()
{
while (IrcUser.this.stay_connected)
{
IrcUser.this.idle_time++;
try
{
Thread.sleep(1000);
} catch (Exception vxc) {}
}
}
};
idleClock.start();
this.server.log(this.connection.getClientHostname(), 1, "IrcUser Class initGatewayConnection()");
}
public void disconnect()
{
this.server.log(this.username, 1, "IrcUser Class " + this.nickname + " disconnect()");
this.connection.close();
this.stay_connected = false;
this.server.removeUser(this);
}
private String stringVector(Vector<String> vec, String sep)
{
StringBuffer new_string = new StringBuffer("");
for (Enumeration<String> e = vec.elements(); e.hasMoreElements(); )
{
String ca = e.nextElement();
new_string.append(ca);
if (e.hasMoreElements())
{
new_string.append(sep);
}
}
return new_string.toString();
}
public void onGatewayCommand(IRCMessage cmd)
{
// we only want to set the command source if the user is fully authenticated.
if (this.isWelcomed())
{
cmd.setSource(this.toString());
}
// Reset idle time on activity, as long as its not a ping, pong or ison
if (!cmd.is("PING") && !cmd.is("PONG") && !cmd.is("ISON"))
{
this.idle_time = 0;
}
// Here is where we process the main commands
if (cmd.is("NICK")) {
if (this.server.findUser(cmd.getArg(0)) == null)
{
if (this.isWelcomed())
{
sendCommand(new IRCMessage(cmd, this));
for(Enumeration<IrcChannel> e = this.server.getChannels().elements(); e.hasMoreElements(); )
{
IrcChannel chan = e.nextElement();
chan.updateNick(this, cmd.getArg(0));
}
}
this.setNick(cmd.getArg(0));
} else {
sendResponse("433", ":" + cmd.getArg(0) + " is already in use");
}
} else if (cmd.is("KICK")) {
if (cmd.argCount() >= 2)
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(0));
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("INVITE")) {
if (cmd.argCount() >= 2)
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(1));
if (desired_channel != null)
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("JOIN") || cmd.is("PART") || cmd.is("WHO") ) {
if (cmd.argCount() >= 1)
{
String[] rooms = cmd.getArg(0).split(",");
for (int rms = 0; rms < rooms.length; rms++)
{
IrcChannel desired_channel = this.server.findChannel(rooms[rms]);
if (desired_channel != null)
{
if (cmd.is("JOIN"))
desired_channel.pendingJoin(this);
desired_channel.getHandler().onCommand(cmd);
} else if (cmd.is("JOIN")) {
- sendResponse("403", rooms[rms] + " :No IrcChannel Class to handle this request");
+ IrcChannel chan = new IrcChannel(rooms[rms]);
+ this.server.addChannel(chan);
+ chan.pendingJoin(this);
+ chan.getHandler().onCommand(cmd);
+ //sendResponse("403", rooms[rms] + " :No IrcChannel Class to handle this request");
}
}
}
} else if (cmd.is("TOPIC")) {
if (cmd.argCount() >= 2)
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(0));
if (desired_channel != null)
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("MODE")) {
// channels require three arguments
if (cmd.argCount() >= 3 && (cmd.getArg(0).startsWith("#") || cmd.getArg(0).startsWith("&") || cmd.getArg(0).startsWith("!") || cmd.getArg(0).startsWith("+")))
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(0));
if (desired_channel != null)
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("AWAY")) {
if (cmd.argCount() >= 1)
{
this.setAway(cmd.getArg(0));
sendResponse("306", ":You are now marked as away");
} else {
this.setAway(null);
sendResponse("305", ":You are no longer marked as away");
}
} else if (cmd.is("PING")) {
IRCMessage pong = IRCMessage.prepare("PONG");
pong.addArg(cmd.getArg(0));
sendCommand(pong);
} else if (cmd.is("ISON")) {
Vector<String> on_nicks = new Vector<String>();
for (int ison_n = 0; ison_n < cmd.argCount(); ison_n++)
{
IrcUser ison = this.server.findUser(cmd.getArg(ison_n));
if (ison != null)
{
on_nicks.add(cmd.getArg(ison_n));
}
}
sendResponse("303", stringVector(on_nicks, " "));
} else if (cmd.is("WHOIS")) {
IrcUser wi = this.server.findUser(cmd.getArg(0));
if (wi != null)
{
sendResponse("311", wi.getNick() + " " + wi.getUserName() + " " + wi.getClientHostname() + " * :" + wi.getRealName());
sendResponse("312", wi.getNick() + " " + wi.getServerHostname() + " :IRC Server");
//sendResponse("338", wi.getNick() + " 255.255.255.255 :actually using host");
if (wi.getAway() != null)
{
sendResponse("301", wi.getNick() + " :" + wi.getAway());
}
sendResponse("317", wi.getNick() + " " + String.valueOf(wi.getIdleTime()) + " :Seconds Idle");
}
sendResponse("318", ":End of WHOIS list");
} else if (cmd.is("LIST")) {
// TODO: Add support For channel filtering
for (Enumeration<IrcChannel> e = this.server.getChannels().elements(); e.hasMoreElements(); )
{
IrcChannel room = e.nextElement();
sendResponse("322", room.getName() + " " + String.valueOf(room.getMemberCount()) + " :" + room.getTopic());
}
sendResponse("323", ":End of List");
} else if (cmd.is("PRIVMSG") || cmd.is("NOTICE")) {
if (cmd.getArg(0).startsWith("$"))
{
// todo
} else if (cmd.getArg(0).startsWith("#") || cmd.getArg(0).startsWith("&") || cmd.getArg(0).startsWith("!") || cmd.getArg(0).startsWith("+")) {
IrcChannel possible_target = this.server.findChannel(cmd.getArg(0));
if (possible_target != null)
{
possible_target.getHandler().onCommand(cmd);
} else {
sendResponse("401", cmd.getArg(0) + " :No such nick/channel");
}
} else {
IrcUser possible_target2 = this.server.findUser(cmd.getArg(0));
if (possible_target2 != null)
{
if (possible_target2.getAway() != null)
{
sendResponse("301", possible_target2.getNick() + " :" + possible_target2.getAway());
}
possible_target2.sendCommand(new IRCMessage(cmd, this));
} else {
sendResponse("401", cmd.getArg(0) + " :No such nick/channel");
}
}
} else if (cmd.is("QUIT")) {
this.disconnect();
} else if (cmd.is("USER")) {
this.processUser(cmd.getArgs());
} else if (cmd.is("PONG")) {
// just to stop the else
} else {
sendResponse("421", cmd.getCommand() + " :Unknown Command");
}
if (this.isReady() && !this.isWelcomed())
{
String chanCount = String.valueOf(this.server.getChannelCount());
String connCount = String.valueOf(this.server.getUserCount());
Vector<String> motd = this.server.getMotd();
sendResponse("001", ":Welcome to the Internet Relay Chat Network");
sendResponse("002", ":Your host is " + this.getServerHostname() + ", running version org.openstatic.irc");
sendResponse("003", ":This server was created on " + this.server.getBootTime());
sendResponse("004", this.getServerHostname() + " org.openstatic.irc * *");
sendResponse("251", ":There are " + connCount + " users on 1 server");
sendResponse("252", "0 :IRC Operators online");
sendResponse("254", chanCount + " :channels formed");
sendResponse("255", ":I have " + connCount + " clients and 0 servers");
sendResponse("265", ":Current local users: " + connCount + " Max: 0");
sendResponse("266", ":Current global users: 0 Max: 0");
sendResponse("250", ":Highest connection count: " + connCount + " (" + connCount + " clients)");
sendResponse("375", ":- " + this.getServerHostname() + " Message of the day -");
if (motd != null)
{
for (Enumeration<String> motd_e = motd.elements(); motd_e.hasMoreElements(); )
{
sendResponse("372", ":- " + motd_e.nextElement());
}
}
sendResponse("376", ":End of MOTD command");
this.setWelcomed(true);
}
}
// Is Block, booleans and stuff
public boolean hasNick()
{
if (this.nickname != null)
{
return true;
} else {
return false;
}
}
public boolean isReady()
{
if (this.username != null && this.nickname != null)
{
return true;
} else {
return false;
}
}
public boolean isWelcomed()
{
return this.welcomed;
}
public boolean is(String value)
{
if (this.nickname != null)
{
if (this.nickname.equals(value) || this.toString().equals(value))
return true;
else
return false;
} else {
return false;
}
}
// Get Methods
public int getIdleTime()
{
return this.idle_time;
}
public String getServerHostname()
{
return this.connection.getServerHostname();
}
public String getClientHostname()
{
return this.client_host;
}
public GatewayConnection getGatewayConnection()
{
return this.connection;
}
public IrcServer getIrcServer()
{
return this.server;
}
public String getRealName()
{
return this.realname;
}
public String getNick()
{
return this.nickname;
}
public String getAway()
{
return this.away_message;
}
public String getUserName()
{
return this.username;
}
// Set Methods
public void setWelcomed(boolean bool)
{
this.welcomed = bool;
}
public void setAway(String value)
{
this.away_message = value;
}
public void setNick(String nick)
{
this.nickname = nick;
}
public void setRealName(String realname)
{
this.realname = realname;
}
public void setUserName(String username)
{
this.username = username;
}
public void setClientHost(String value)
{
this.client_host = value;
}
// Action functions
public void sendCommand(IRCMessage pc)
{
this.connection.sendCommand(pc);
}
public void sendResponse(String response, String args)
{
this.connection.sendResponse(response, args);
}
private void processUser(Vector<String> args)
{
if (args.size() == 4)
{
this.username = args.elementAt(0);
this.domain = args.elementAt(1).replaceAll("\"","");
this.client_host = args.elementAt(2).replaceAll("\"","");
this.realname = args.elementAt(3);
}
}
public void loginUser(String username, String password)
{
this.server.log(this.connection.getClientHostname(), 1, "IrcUser Manual Authentication (" + username + ")");
this.username = username;
this.nickname = username;
this.password = password;
this.welcomed = true;
}
public String toString()
{
return this.nickname + "!" + this.username + "@" + this.getClientHostname();
}
}
| true | true | public void onGatewayCommand(IRCMessage cmd)
{
// we only want to set the command source if the user is fully authenticated.
if (this.isWelcomed())
{
cmd.setSource(this.toString());
}
// Reset idle time on activity, as long as its not a ping, pong or ison
if (!cmd.is("PING") && !cmd.is("PONG") && !cmd.is("ISON"))
{
this.idle_time = 0;
}
// Here is where we process the main commands
if (cmd.is("NICK")) {
if (this.server.findUser(cmd.getArg(0)) == null)
{
if (this.isWelcomed())
{
sendCommand(new IRCMessage(cmd, this));
for(Enumeration<IrcChannel> e = this.server.getChannels().elements(); e.hasMoreElements(); )
{
IrcChannel chan = e.nextElement();
chan.updateNick(this, cmd.getArg(0));
}
}
this.setNick(cmd.getArg(0));
} else {
sendResponse("433", ":" + cmd.getArg(0) + " is already in use");
}
} else if (cmd.is("KICK")) {
if (cmd.argCount() >= 2)
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(0));
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("INVITE")) {
if (cmd.argCount() >= 2)
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(1));
if (desired_channel != null)
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("JOIN") || cmd.is("PART") || cmd.is("WHO") ) {
if (cmd.argCount() >= 1)
{
String[] rooms = cmd.getArg(0).split(",");
for (int rms = 0; rms < rooms.length; rms++)
{
IrcChannel desired_channel = this.server.findChannel(rooms[rms]);
if (desired_channel != null)
{
if (cmd.is("JOIN"))
desired_channel.pendingJoin(this);
desired_channel.getHandler().onCommand(cmd);
} else if (cmd.is("JOIN")) {
sendResponse("403", rooms[rms] + " :No IrcChannel Class to handle this request");
}
}
}
} else if (cmd.is("TOPIC")) {
if (cmd.argCount() >= 2)
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(0));
if (desired_channel != null)
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("MODE")) {
// channels require three arguments
if (cmd.argCount() >= 3 && (cmd.getArg(0).startsWith("#") || cmd.getArg(0).startsWith("&") || cmd.getArg(0).startsWith("!") || cmd.getArg(0).startsWith("+")))
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(0));
if (desired_channel != null)
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("AWAY")) {
if (cmd.argCount() >= 1)
{
this.setAway(cmd.getArg(0));
sendResponse("306", ":You are now marked as away");
} else {
this.setAway(null);
sendResponse("305", ":You are no longer marked as away");
}
} else if (cmd.is("PING")) {
IRCMessage pong = IRCMessage.prepare("PONG");
pong.addArg(cmd.getArg(0));
sendCommand(pong);
} else if (cmd.is("ISON")) {
Vector<String> on_nicks = new Vector<String>();
for (int ison_n = 0; ison_n < cmd.argCount(); ison_n++)
{
IrcUser ison = this.server.findUser(cmd.getArg(ison_n));
if (ison != null)
{
on_nicks.add(cmd.getArg(ison_n));
}
}
sendResponse("303", stringVector(on_nicks, " "));
} else if (cmd.is("WHOIS")) {
IrcUser wi = this.server.findUser(cmd.getArg(0));
if (wi != null)
{
sendResponse("311", wi.getNick() + " " + wi.getUserName() + " " + wi.getClientHostname() + " * :" + wi.getRealName());
sendResponse("312", wi.getNick() + " " + wi.getServerHostname() + " :IRC Server");
//sendResponse("338", wi.getNick() + " 255.255.255.255 :actually using host");
if (wi.getAway() != null)
{
sendResponse("301", wi.getNick() + " :" + wi.getAway());
}
sendResponse("317", wi.getNick() + " " + String.valueOf(wi.getIdleTime()) + " :Seconds Idle");
}
sendResponse("318", ":End of WHOIS list");
} else if (cmd.is("LIST")) {
// TODO: Add support For channel filtering
for (Enumeration<IrcChannel> e = this.server.getChannels().elements(); e.hasMoreElements(); )
{
IrcChannel room = e.nextElement();
sendResponse("322", room.getName() + " " + String.valueOf(room.getMemberCount()) + " :" + room.getTopic());
}
sendResponse("323", ":End of List");
} else if (cmd.is("PRIVMSG") || cmd.is("NOTICE")) {
if (cmd.getArg(0).startsWith("$"))
{
// todo
} else if (cmd.getArg(0).startsWith("#") || cmd.getArg(0).startsWith("&") || cmd.getArg(0).startsWith("!") || cmd.getArg(0).startsWith("+")) {
IrcChannel possible_target = this.server.findChannel(cmd.getArg(0));
if (possible_target != null)
{
possible_target.getHandler().onCommand(cmd);
} else {
sendResponse("401", cmd.getArg(0) + " :No such nick/channel");
}
} else {
IrcUser possible_target2 = this.server.findUser(cmd.getArg(0));
if (possible_target2 != null)
{
if (possible_target2.getAway() != null)
{
sendResponse("301", possible_target2.getNick() + " :" + possible_target2.getAway());
}
possible_target2.sendCommand(new IRCMessage(cmd, this));
} else {
sendResponse("401", cmd.getArg(0) + " :No such nick/channel");
}
}
} else if (cmd.is("QUIT")) {
this.disconnect();
} else if (cmd.is("USER")) {
this.processUser(cmd.getArgs());
} else if (cmd.is("PONG")) {
// just to stop the else
} else {
sendResponse("421", cmd.getCommand() + " :Unknown Command");
}
if (this.isReady() && !this.isWelcomed())
{
String chanCount = String.valueOf(this.server.getChannelCount());
String connCount = String.valueOf(this.server.getUserCount());
Vector<String> motd = this.server.getMotd();
sendResponse("001", ":Welcome to the Internet Relay Chat Network");
sendResponse("002", ":Your host is " + this.getServerHostname() + ", running version org.openstatic.irc");
sendResponse("003", ":This server was created on " + this.server.getBootTime());
sendResponse("004", this.getServerHostname() + " org.openstatic.irc * *");
sendResponse("251", ":There are " + connCount + " users on 1 server");
sendResponse("252", "0 :IRC Operators online");
sendResponse("254", chanCount + " :channels formed");
sendResponse("255", ":I have " + connCount + " clients and 0 servers");
sendResponse("265", ":Current local users: " + connCount + " Max: 0");
sendResponse("266", ":Current global users: 0 Max: 0");
sendResponse("250", ":Highest connection count: " + connCount + " (" + connCount + " clients)");
sendResponse("375", ":- " + this.getServerHostname() + " Message of the day -");
if (motd != null)
{
for (Enumeration<String> motd_e = motd.elements(); motd_e.hasMoreElements(); )
{
sendResponse("372", ":- " + motd_e.nextElement());
}
}
sendResponse("376", ":End of MOTD command");
this.setWelcomed(true);
}
}
| public void onGatewayCommand(IRCMessage cmd)
{
// we only want to set the command source if the user is fully authenticated.
if (this.isWelcomed())
{
cmd.setSource(this.toString());
}
// Reset idle time on activity, as long as its not a ping, pong or ison
if (!cmd.is("PING") && !cmd.is("PONG") && !cmd.is("ISON"))
{
this.idle_time = 0;
}
// Here is where we process the main commands
if (cmd.is("NICK")) {
if (this.server.findUser(cmd.getArg(0)) == null)
{
if (this.isWelcomed())
{
sendCommand(new IRCMessage(cmd, this));
for(Enumeration<IrcChannel> e = this.server.getChannels().elements(); e.hasMoreElements(); )
{
IrcChannel chan = e.nextElement();
chan.updateNick(this, cmd.getArg(0));
}
}
this.setNick(cmd.getArg(0));
} else {
sendResponse("433", ":" + cmd.getArg(0) + " is already in use");
}
} else if (cmd.is("KICK")) {
if (cmd.argCount() >= 2)
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(0));
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("INVITE")) {
if (cmd.argCount() >= 2)
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(1));
if (desired_channel != null)
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("JOIN") || cmd.is("PART") || cmd.is("WHO") ) {
if (cmd.argCount() >= 1)
{
String[] rooms = cmd.getArg(0).split(",");
for (int rms = 0; rms < rooms.length; rms++)
{
IrcChannel desired_channel = this.server.findChannel(rooms[rms]);
if (desired_channel != null)
{
if (cmd.is("JOIN"))
desired_channel.pendingJoin(this);
desired_channel.getHandler().onCommand(cmd);
} else if (cmd.is("JOIN")) {
IrcChannel chan = new IrcChannel(rooms[rms]);
this.server.addChannel(chan);
chan.pendingJoin(this);
chan.getHandler().onCommand(cmd);
//sendResponse("403", rooms[rms] + " :No IrcChannel Class to handle this request");
}
}
}
} else if (cmd.is("TOPIC")) {
if (cmd.argCount() >= 2)
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(0));
if (desired_channel != null)
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("MODE")) {
// channels require three arguments
if (cmd.argCount() >= 3 && (cmd.getArg(0).startsWith("#") || cmd.getArg(0).startsWith("&") || cmd.getArg(0).startsWith("!") || cmd.getArg(0).startsWith("+")))
{
IrcChannel desired_channel = this.server.findChannel(cmd.getArg(0));
if (desired_channel != null)
{
desired_channel.getHandler().onCommand(cmd);
}
}
} else if (cmd.is("AWAY")) {
if (cmd.argCount() >= 1)
{
this.setAway(cmd.getArg(0));
sendResponse("306", ":You are now marked as away");
} else {
this.setAway(null);
sendResponse("305", ":You are no longer marked as away");
}
} else if (cmd.is("PING")) {
IRCMessage pong = IRCMessage.prepare("PONG");
pong.addArg(cmd.getArg(0));
sendCommand(pong);
} else if (cmd.is("ISON")) {
Vector<String> on_nicks = new Vector<String>();
for (int ison_n = 0; ison_n < cmd.argCount(); ison_n++)
{
IrcUser ison = this.server.findUser(cmd.getArg(ison_n));
if (ison != null)
{
on_nicks.add(cmd.getArg(ison_n));
}
}
sendResponse("303", stringVector(on_nicks, " "));
} else if (cmd.is("WHOIS")) {
IrcUser wi = this.server.findUser(cmd.getArg(0));
if (wi != null)
{
sendResponse("311", wi.getNick() + " " + wi.getUserName() + " " + wi.getClientHostname() + " * :" + wi.getRealName());
sendResponse("312", wi.getNick() + " " + wi.getServerHostname() + " :IRC Server");
//sendResponse("338", wi.getNick() + " 255.255.255.255 :actually using host");
if (wi.getAway() != null)
{
sendResponse("301", wi.getNick() + " :" + wi.getAway());
}
sendResponse("317", wi.getNick() + " " + String.valueOf(wi.getIdleTime()) + " :Seconds Idle");
}
sendResponse("318", ":End of WHOIS list");
} else if (cmd.is("LIST")) {
// TODO: Add support For channel filtering
for (Enumeration<IrcChannel> e = this.server.getChannels().elements(); e.hasMoreElements(); )
{
IrcChannel room = e.nextElement();
sendResponse("322", room.getName() + " " + String.valueOf(room.getMemberCount()) + " :" + room.getTopic());
}
sendResponse("323", ":End of List");
} else if (cmd.is("PRIVMSG") || cmd.is("NOTICE")) {
if (cmd.getArg(0).startsWith("$"))
{
// todo
} else if (cmd.getArg(0).startsWith("#") || cmd.getArg(0).startsWith("&") || cmd.getArg(0).startsWith("!") || cmd.getArg(0).startsWith("+")) {
IrcChannel possible_target = this.server.findChannel(cmd.getArg(0));
if (possible_target != null)
{
possible_target.getHandler().onCommand(cmd);
} else {
sendResponse("401", cmd.getArg(0) + " :No such nick/channel");
}
} else {
IrcUser possible_target2 = this.server.findUser(cmd.getArg(0));
if (possible_target2 != null)
{
if (possible_target2.getAway() != null)
{
sendResponse("301", possible_target2.getNick() + " :" + possible_target2.getAway());
}
possible_target2.sendCommand(new IRCMessage(cmd, this));
} else {
sendResponse("401", cmd.getArg(0) + " :No such nick/channel");
}
}
} else if (cmd.is("QUIT")) {
this.disconnect();
} else if (cmd.is("USER")) {
this.processUser(cmd.getArgs());
} else if (cmd.is("PONG")) {
// just to stop the else
} else {
sendResponse("421", cmd.getCommand() + " :Unknown Command");
}
if (this.isReady() && !this.isWelcomed())
{
String chanCount = String.valueOf(this.server.getChannelCount());
String connCount = String.valueOf(this.server.getUserCount());
Vector<String> motd = this.server.getMotd();
sendResponse("001", ":Welcome to the Internet Relay Chat Network");
sendResponse("002", ":Your host is " + this.getServerHostname() + ", running version org.openstatic.irc");
sendResponse("003", ":This server was created on " + this.server.getBootTime());
sendResponse("004", this.getServerHostname() + " org.openstatic.irc * *");
sendResponse("251", ":There are " + connCount + " users on 1 server");
sendResponse("252", "0 :IRC Operators online");
sendResponse("254", chanCount + " :channels formed");
sendResponse("255", ":I have " + connCount + " clients and 0 servers");
sendResponse("265", ":Current local users: " + connCount + " Max: 0");
sendResponse("266", ":Current global users: 0 Max: 0");
sendResponse("250", ":Highest connection count: " + connCount + " (" + connCount + " clients)");
sendResponse("375", ":- " + this.getServerHostname() + " Message of the day -");
if (motd != null)
{
for (Enumeration<String> motd_e = motd.elements(); motd_e.hasMoreElements(); )
{
sendResponse("372", ":- " + motd_e.nextElement());
}
}
sendResponse("376", ":End of MOTD command");
this.setWelcomed(true);
}
}
|
diff --git a/gov.va.med.iss.meditor/src/gov/va/med/iss/meditor/utils/RoutineChangedDialog.java b/gov.va.med.iss.meditor/src/gov/va/med/iss/meditor/utils/RoutineChangedDialog.java
index e919ff9..1febe66 100644
--- a/gov.va.med.iss.meditor/src/gov/va/med/iss/meditor/utils/RoutineChangedDialog.java
+++ b/gov.va.med.iss.meditor/src/gov/va/med/iss/meditor/utils/RoutineChangedDialog.java
@@ -1,195 +1,195 @@
package gov.va.med.iss.meditor.utils;
import javax.swing.JLabel;
import javax.swing.JTextField;
import gov.va.med.iss.connection.utilities.ConnectionUtilities;
import gov.va.med.iss.meditor.MEditorPlugin;
import gov.va.med.iss.meditor.preferences.MEditorPrefs;
import gov.va.med.iss.meditor.utils.RoutineCompare;
import gov.va.med.iss.connection.actions.VistaConnection;
import gov.va.med.iss.connection.utilities.MPiece;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Control;
public class RoutineChangedDialog extends Dialog {
private Label lblQuestion;
private Button btnOK;
private Button btnCancel;
private Button btnView;
private Button chkSaveCopy;
private RoutineChangedDialogData result;
private String textString;
private String routineName;
private boolean isSaveValue;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public RoutineChangedDialog(Shell parent, int style) {
super(parent, style);
}
public RoutineChangedDialog(Shell parent) {
this(parent, 0);
}
String file1;
String file2;
public RoutineChangedDialogData open(String rouName, String infile1, String infile2, boolean isSave, boolean isMult) {
result = new RoutineChangedDialogData();
routineName = rouName;
isSaveValue = isSave;
final Shell shell = new Shell(getParent(), SWT.DIALOG_TRIM |
- SWT.APPLICATION_MODAL);
+ SWT.APPLICATION_MODAL | SWT.CENTER);
String strVal = MPiece.getPiece(VistaConnection.getCurrentServer(),";");
strVal = "Routine "+routineName+" Changed on Server '"+strVal+"'";
String strProject = MPiece.getPiece(VistaConnection.getCurrentServer(),";",4);
if (! (strProject.compareTo("") == 0)) {
strVal = strVal + " (Project "+strProject+")";
}
//shell.setText("Routine "+routineName+" Changed on Server "+MPiece.getPiece(VistaConnection.getCurrentServer(),";"));
shell.setText(strVal);
shell.setSize(400,200);
file1 = infile1;
file2 = infile2;
lblQuestion = new Label(shell, SWT.NONE);
lblQuestion.setLocation(20,10);
lblQuestion.setSize(350,20);
lblQuestion.setText("The version on the server has changed. Do you still want to save");
if (! isSave) {
lblQuestion.setText("The version on the server has changed. Do you still want to load");
}
Label lblQ2 = new Label(shell, SWT.NONE);
lblQ2.setLocation(20,30);
lblQ2.setSize(350,20);
- lblQ2.setText("this version on the server? (note that the changes HAVE");
+ lblQ2.setText("this version onto the server? (note that the changes HAVE");
String projectName = VistaConnection.getCurrentProject();
if (projectName.compareTo("") == 0) {
projectName = MEditorPrefs.getPrefs(MEditorPlugin.P_PROJECT_NAME);
}
Label lblQ4 = new Label(shell, SWT.NONE);
lblQ4.setLocation(20,50);
lblQ4.setSize(350,20);
lblQ4.setText("been saved in the "+projectName+" directory and you may open that");
if (! isSave) {
lblQ2.setText("this version from the server?");
lblQ4.setText("");
}
if (isMult) {
lblQ2.setText("this version on the Server?");
lblQ4.setText("");
}
Label lblQ5 = new Label(shell, SWT.NONE);
lblQ5.setLocation(20,70);
lblQ5.setSize(350,20);
lblQ5.setText("file later (not loading from the server), edit it and then save to ");
Label lblQ7 = new Label(shell, SWT.NONE);
lblQ7.setLocation(20,90);
lblQ7.setSize(350,20);
lblQ7.setText("the server.)");
if ((!isSave)|| isMult) {
lblQ5.setText("");
lblQ7.setText("");
}
chkSaveCopy = new Button(shell, SWT.CHECK);
chkSaveCopy.setText("Check to Save a Copy");
chkSaveCopy.setLocation(20,110);
chkSaveCopy.setSize(300,20);
if (!isSave) { // don't show check box if loading from server
chkSaveCopy.setVisible(false);
chkSaveCopy.setSelection(false);
}
btnOK = new Button(shell, SWT.PUSH);
btnOK.setText("&OK");
btnOK.setLocation(20,130);
btnOK.setSize(55,25);
shell.setDefaultButton(btnOK);
btnCancel = new Button(shell, SWT.PUSH);
btnCancel.setText("&Cancel");
btnCancel.setLocation(320,130);
btnCancel.setSize(55,25);
btnView = new Button(shell, SWT.PUSH);
btnView.setText("&View");
btnView.setLocation(168,130);
btnView.setSize(55,25);
if (isMult && isSave) {
textString = "the version being saved to the server";
}
else {
textString = "the PREVIOUS version loaded from the server";
}
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == btnView) {
try {
RoutineCompare.compareRoutines(file1,file2,textString,routineName,isSaveValue);
} catch (Exception e) {
MessageDialog.openInformation(
MEditorUtilities.getIWorkbenchWindow().getShell(),
"M-Editor Plug-in",
"Error encountered while comparing versions on server "+e.getMessage());
}
}
if (event.widget == btnOK) {
result.setReturnValue(true);
result.setSaveServerRoutine(chkSaveCopy.getSelection());
shell.setVisible(false);
shell.close();
}
if (event.widget == btnCancel) {
result.setReturnValue(false);
result.setSaveServerRoutine(false);
shell.setVisible(false);
shell.close();
}
}
};
btnOK.addListener(SWT.Selection, listener);
btnCancel.addListener(SWT.Selection, listener);
btnView.addListener(SWT.Selection, listener);
shell.open();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
return result;
}
}
| false | true | public RoutineChangedDialogData open(String rouName, String infile1, String infile2, boolean isSave, boolean isMult) {
result = new RoutineChangedDialogData();
routineName = rouName;
isSaveValue = isSave;
final Shell shell = new Shell(getParent(), SWT.DIALOG_TRIM |
SWT.APPLICATION_MODAL);
String strVal = MPiece.getPiece(VistaConnection.getCurrentServer(),";");
strVal = "Routine "+routineName+" Changed on Server '"+strVal+"'";
String strProject = MPiece.getPiece(VistaConnection.getCurrentServer(),";",4);
if (! (strProject.compareTo("") == 0)) {
strVal = strVal + " (Project "+strProject+")";
}
//shell.setText("Routine "+routineName+" Changed on Server "+MPiece.getPiece(VistaConnection.getCurrentServer(),";"));
shell.setText(strVal);
shell.setSize(400,200);
file1 = infile1;
file2 = infile2;
lblQuestion = new Label(shell, SWT.NONE);
lblQuestion.setLocation(20,10);
lblQuestion.setSize(350,20);
lblQuestion.setText("The version on the server has changed. Do you still want to save");
if (! isSave) {
lblQuestion.setText("The version on the server has changed. Do you still want to load");
}
Label lblQ2 = new Label(shell, SWT.NONE);
lblQ2.setLocation(20,30);
lblQ2.setSize(350,20);
lblQ2.setText("this version on the server? (note that the changes HAVE");
String projectName = VistaConnection.getCurrentProject();
if (projectName.compareTo("") == 0) {
projectName = MEditorPrefs.getPrefs(MEditorPlugin.P_PROJECT_NAME);
}
Label lblQ4 = new Label(shell, SWT.NONE);
lblQ4.setLocation(20,50);
lblQ4.setSize(350,20);
lblQ4.setText("been saved in the "+projectName+" directory and you may open that");
if (! isSave) {
lblQ2.setText("this version from the server?");
lblQ4.setText("");
}
if (isMult) {
lblQ2.setText("this version on the Server?");
lblQ4.setText("");
}
Label lblQ5 = new Label(shell, SWT.NONE);
lblQ5.setLocation(20,70);
lblQ5.setSize(350,20);
lblQ5.setText("file later (not loading from the server), edit it and then save to ");
Label lblQ7 = new Label(shell, SWT.NONE);
lblQ7.setLocation(20,90);
lblQ7.setSize(350,20);
lblQ7.setText("the server.)");
if ((!isSave)|| isMult) {
lblQ5.setText("");
lblQ7.setText("");
}
chkSaveCopy = new Button(shell, SWT.CHECK);
chkSaveCopy.setText("Check to Save a Copy");
chkSaveCopy.setLocation(20,110);
chkSaveCopy.setSize(300,20);
if (!isSave) { // don't show check box if loading from server
chkSaveCopy.setVisible(false);
chkSaveCopy.setSelection(false);
}
btnOK = new Button(shell, SWT.PUSH);
btnOK.setText("&OK");
btnOK.setLocation(20,130);
btnOK.setSize(55,25);
shell.setDefaultButton(btnOK);
btnCancel = new Button(shell, SWT.PUSH);
btnCancel.setText("&Cancel");
btnCancel.setLocation(320,130);
btnCancel.setSize(55,25);
btnView = new Button(shell, SWT.PUSH);
btnView.setText("&View");
btnView.setLocation(168,130);
btnView.setSize(55,25);
if (isMult && isSave) {
textString = "the version being saved to the server";
}
else {
textString = "the PREVIOUS version loaded from the server";
}
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == btnView) {
try {
RoutineCompare.compareRoutines(file1,file2,textString,routineName,isSaveValue);
} catch (Exception e) {
MessageDialog.openInformation(
MEditorUtilities.getIWorkbenchWindow().getShell(),
"M-Editor Plug-in",
"Error encountered while comparing versions on server "+e.getMessage());
}
}
if (event.widget == btnOK) {
result.setReturnValue(true);
result.setSaveServerRoutine(chkSaveCopy.getSelection());
shell.setVisible(false);
shell.close();
}
if (event.widget == btnCancel) {
result.setReturnValue(false);
result.setSaveServerRoutine(false);
shell.setVisible(false);
shell.close();
}
}
};
btnOK.addListener(SWT.Selection, listener);
btnCancel.addListener(SWT.Selection, listener);
btnView.addListener(SWT.Selection, listener);
shell.open();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
return result;
}
| public RoutineChangedDialogData open(String rouName, String infile1, String infile2, boolean isSave, boolean isMult) {
result = new RoutineChangedDialogData();
routineName = rouName;
isSaveValue = isSave;
final Shell shell = new Shell(getParent(), SWT.DIALOG_TRIM |
SWT.APPLICATION_MODAL | SWT.CENTER);
String strVal = MPiece.getPiece(VistaConnection.getCurrentServer(),";");
strVal = "Routine "+routineName+" Changed on Server '"+strVal+"'";
String strProject = MPiece.getPiece(VistaConnection.getCurrentServer(),";",4);
if (! (strProject.compareTo("") == 0)) {
strVal = strVal + " (Project "+strProject+")";
}
//shell.setText("Routine "+routineName+" Changed on Server "+MPiece.getPiece(VistaConnection.getCurrentServer(),";"));
shell.setText(strVal);
shell.setSize(400,200);
file1 = infile1;
file2 = infile2;
lblQuestion = new Label(shell, SWT.NONE);
lblQuestion.setLocation(20,10);
lblQuestion.setSize(350,20);
lblQuestion.setText("The version on the server has changed. Do you still want to save");
if (! isSave) {
lblQuestion.setText("The version on the server has changed. Do you still want to load");
}
Label lblQ2 = new Label(shell, SWT.NONE);
lblQ2.setLocation(20,30);
lblQ2.setSize(350,20);
lblQ2.setText("this version onto the server? (note that the changes HAVE");
String projectName = VistaConnection.getCurrentProject();
if (projectName.compareTo("") == 0) {
projectName = MEditorPrefs.getPrefs(MEditorPlugin.P_PROJECT_NAME);
}
Label lblQ4 = new Label(shell, SWT.NONE);
lblQ4.setLocation(20,50);
lblQ4.setSize(350,20);
lblQ4.setText("been saved in the "+projectName+" directory and you may open that");
if (! isSave) {
lblQ2.setText("this version from the server?");
lblQ4.setText("");
}
if (isMult) {
lblQ2.setText("this version on the Server?");
lblQ4.setText("");
}
Label lblQ5 = new Label(shell, SWT.NONE);
lblQ5.setLocation(20,70);
lblQ5.setSize(350,20);
lblQ5.setText("file later (not loading from the server), edit it and then save to ");
Label lblQ7 = new Label(shell, SWT.NONE);
lblQ7.setLocation(20,90);
lblQ7.setSize(350,20);
lblQ7.setText("the server.)");
if ((!isSave)|| isMult) {
lblQ5.setText("");
lblQ7.setText("");
}
chkSaveCopy = new Button(shell, SWT.CHECK);
chkSaveCopy.setText("Check to Save a Copy");
chkSaveCopy.setLocation(20,110);
chkSaveCopy.setSize(300,20);
if (!isSave) { // don't show check box if loading from server
chkSaveCopy.setVisible(false);
chkSaveCopy.setSelection(false);
}
btnOK = new Button(shell, SWT.PUSH);
btnOK.setText("&OK");
btnOK.setLocation(20,130);
btnOK.setSize(55,25);
shell.setDefaultButton(btnOK);
btnCancel = new Button(shell, SWT.PUSH);
btnCancel.setText("&Cancel");
btnCancel.setLocation(320,130);
btnCancel.setSize(55,25);
btnView = new Button(shell, SWT.PUSH);
btnView.setText("&View");
btnView.setLocation(168,130);
btnView.setSize(55,25);
if (isMult && isSave) {
textString = "the version being saved to the server";
}
else {
textString = "the PREVIOUS version loaded from the server";
}
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == btnView) {
try {
RoutineCompare.compareRoutines(file1,file2,textString,routineName,isSaveValue);
} catch (Exception e) {
MessageDialog.openInformation(
MEditorUtilities.getIWorkbenchWindow().getShell(),
"M-Editor Plug-in",
"Error encountered while comparing versions on server "+e.getMessage());
}
}
if (event.widget == btnOK) {
result.setReturnValue(true);
result.setSaveServerRoutine(chkSaveCopy.getSelection());
shell.setVisible(false);
shell.close();
}
if (event.widget == btnCancel) {
result.setReturnValue(false);
result.setSaveServerRoutine(false);
shell.setVisible(false);
shell.close();
}
}
};
btnOK.addListener(SWT.Selection, listener);
btnCancel.addListener(SWT.Selection, listener);
btnView.addListener(SWT.Selection, listener);
shell.open();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
return result;
}
|
diff --git a/src/main/java/com/od/swing/eventbus/UIEventBus.java b/src/main/java/com/od/swing/eventbus/UIEventBus.java
index d77d8bf..7567b3a 100644
--- a/src/main/java/com/od/swing/eventbus/UIEventBus.java
+++ b/src/main/java/com/od/swing/eventbus/UIEventBus.java
@@ -1,74 +1,74 @@
package com.od.swing.eventbus;
import com.od.swing.util.UIUtilities;
import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: Nick
* Date: 12-Dec-2010
* Time: 10:59:02
*/
public class UIEventBus {
private static UIEventBus singleton;
private Map<Class, List> listenerClassToListeners = new HashMap<Class, List>();
private UIEventBus() {}
public <E> boolean addEventListener(Class<E> listenerInterface, E listener) {
List listeners = getListenerList(listenerInterface);
boolean result = false;
if (! listeners.contains(listener)) {
listeners.add(listener);
result = true;
}
return result;
}
public <E> boolean removeEventListener(Class<E> listenerInterface, E listener) {
List listeners = getListenerList(listenerInterface);
boolean result = false;
//use a set to search, faster than list even with creation overhead
return listeners.remove(listener);
}
public <E> void fireEvent(final Class<E> listenerClass, final EventSender<E> eventSender) {
//run in event thread, if this is not already the event thread
UIUtilities.runInDispatchThread(
new Runnable() {
public void run() {
- List listeners = listenerClassToListeners.get(listenerClass);
+ List listeners = getListenerList(listenerClass);
LinkedList snapshot = new LinkedList(listeners);
for (Object o : snapshot) {
try {
eventSender.sendEvent((E) o);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
);
}
private <E> List getListenerList(Class<E> listenerInterface) {
List listeners = listenerClassToListeners.get(listenerInterface);
if ( listeners == null ) {
listeners = new LinkedList<E>();
listenerClassToListeners.put(listenerInterface, listeners);
}
return listeners;
}
public synchronized static UIEventBus getInstance() {
if ( singleton == null) {
singleton = new UIEventBus();
}
return singleton;
}
}
| true | true | public <E> void fireEvent(final Class<E> listenerClass, final EventSender<E> eventSender) {
//run in event thread, if this is not already the event thread
UIUtilities.runInDispatchThread(
new Runnable() {
public void run() {
List listeners = listenerClassToListeners.get(listenerClass);
LinkedList snapshot = new LinkedList(listeners);
for (Object o : snapshot) {
try {
eventSender.sendEvent((E) o);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
);
}
| public <E> void fireEvent(final Class<E> listenerClass, final EventSender<E> eventSender) {
//run in event thread, if this is not already the event thread
UIUtilities.runInDispatchThread(
new Runnable() {
public void run() {
List listeners = getListenerList(listenerClass);
LinkedList snapshot = new LinkedList(listeners);
for (Object o : snapshot) {
try {
eventSender.sendEvent((E) o);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
);
}
|
diff --git a/components/bio-formats/src/loci/formats/in/TillVisionReader.java b/components/bio-formats/src/loci/formats/in/TillVisionReader.java
index 50bbe03b0..663cddf6d 100644
--- a/components/bio-formats/src/loci/formats/in/TillVisionReader.java
+++ b/components/bio-formats/src/loci/formats/in/TillVisionReader.java
@@ -1,477 +1,479 @@
//
// TillVisionReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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 loci.formats.in;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.DateTools;
import loci.common.IniList;
import loci.common.IniParser;
import loci.common.IniTable;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.services.POIService;
/**
* TillVisionReader is the file format reader for TillVision files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/TillVisionReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/TillVisionReader.java">SVN</a></dd></dl>
*/
public class TillVisionReader extends FormatReader {
// -- Constants --
private static final byte[] MARKER_0 = new byte[] {(byte) 0x80, 3, 0};
private static final byte[] MARKER_1 = new byte[] {(byte) 0x81, 3, 0};
private static final String[] DATE_FORMATS = new String[] {
"mm/dd/yy HH:mm:ss aa", "mm/dd/yy HH:mm:ss.SSS aa", "mm/dd/yy",
"HH:mm:ss aa", "HH:mm:ss.SSS aa"};
// -- Fields --
private String[] pixelsFiles;
private RandomAccessInputStream[] pixelsStream;
private Hashtable<Integer, Double> exposureTimes;
private boolean embeddedImages;
private long embeddedOffset;
private Vector<String> imageNames = new Vector<String>();
private Vector<String> types = new Vector<String>();
private Vector<String> dates = new Vector<String>();
// -- Constructor --
/** Constructs a new TillVision reader. */
public TillVisionReader() {
super("TillVision", "vws");
domains = new String[] {FormatTools.LM_DOMAIN};
}
// -- IFormatReader API methods --
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int plane = FormatTools.getPlaneSize(this);
if (embeddedImages) {
in.seek(embeddedOffset + no * plane);
readPlane(in, x, y, w, h, buf);
}
else if ((no + 1) * plane <= pixelsStream[series].length()) {
pixelsStream[series].seek(no * plane);
readPlane(pixelsStream[series], x, y, w, h, buf);
}
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
if (pixelsStream != null) {
for (RandomAccessInputStream stream : pixelsStream) {
if (stream != null) stream.close();
}
}
pixelsStream = null;
pixelsFiles = null;
embeddedOffset = 0;
embeddedImages = false;
exposureTimes = null;
imageNames.clear();
types.clear();
dates.clear();
}
}
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return !new Location(id.replaceAll(".vws", ".pst")).exists();
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> files = new Vector<String>();
files.add(currentId);
if (!noPixels) {
for (String file : pixelsFiles) {
if (file != null) files.add(file);
}
}
return files.toArray(new String[files.size()]);
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
exposureTimes = new Hashtable<Integer, Double>();
POIService poi = null;
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
}
catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(id);
Vector<String> documents = poi.getDocumentList();
int nImages = 0;
Hashtable tmpSeriesMetadata = new Hashtable();
for (String name : documents) {
LOGGER.debug("Reading {}", name);
if (name.equals("Root Entry" + File.separator + "Contents")) {
RandomAccessInputStream s = poi.getDocumentStream(name);
s.order(true);
int nFound = 0;
embeddedImages = s.read() == 1;
LOGGER.debug("Images are {}embedded", embeddedImages ? "" : "not ");
if (embeddedImages) {
s.skipBytes(12);
int len = s.readShort();
String type = s.readString(len);
if (!type.equals("CImage")) {
embeddedImages = false;
continue;
}
s.seek(27);
len = s.read();
while (len != 0) {
s.skipBytes(len);
len = s.read();
}
s.skipBytes(1243);
core[0].sizeX = s.readInt();
core[0].sizeY = s.readInt();
core[0].sizeZ = s.readInt();
core[0].sizeC = s.readInt();
core[0].sizeT = s.readInt();
core[0].pixelType = convertPixelType(s.readInt());
embeddedOffset = s.getFilePointer() + 28;
in = poi.getDocumentStream(name);
nImages++;
break;
}
byte[] marker = getMarker(s);
if (marker == null) {
throw new FormatException("Could not find known marker.");
}
LOGGER.debug("Marker: {}, {}, {}",
new Object[] {marker[0], marker[1], marker[2]});
s.seek(0);
while (s.getFilePointer() < s.length() - 2) {
LOGGER.debug(" Looking for image at {}", s.getFilePointer());
s.order(false);
int nextOffset = findNextOffset(s, marker);
if (nextOffset < 0 || nextOffset >= s.length()) break;
s.seek(nextOffset);
s.skipBytes(3);
int len = s.readShort();
if (len <= 0) continue;
imageNames.add(s.readString(len));
s.skipBytes(6);
s.order(true);
len = s.readShort();
if (len < 0 || len > 0x1000) continue;
String description = s.readString(len);
LOGGER.debug("Description: {}", description);
// parse key/value pairs from description
String dateTime = "";
String[] lines = description.split("[\r\n]");
for (String line : lines) {
line = line.trim();
int colon = line.indexOf(":");
if (colon != -1 && !line.startsWith(";")) {
String key = line.substring(0, colon).trim();
String value = line.substring(colon + 1).trim();
String metaKey = "Series " + nImages + " " + key;
addMeta(metaKey, value, tmpSeriesMetadata);
if (key.equals("Start time of experiment")) {
// HH:mm:ss aa OR HH:mm:ss.sss aa
dateTime += " " + value;
}
else if (key.equals("Date")) {
// mm/dd/yy ?
dateTime = value + " " + dateTime;
}
else if (key.equals("Exposure time [ms]")) {
double exp = Double.parseDouble(value) / 1000;
exposureTimes.put(new Integer(nImages), new Double(exp));
}
else if (key.equals("Image type")) {
types.add(value);
}
}
}
dateTime = dateTime.trim();
if (!dateTime.equals("")) {
boolean success = false;
for (String format : DATE_FORMATS) {
try {
dateTime = DateTools.formatDate(dateTime, format);
success = true;
}
catch (NullPointerException e) { }
}
dates.add(success ? dateTime : "");
}
nImages++;
}
}
}
Location directory =
new Location(currentId).getAbsoluteFile().getParentFile();
String[] pixelsFile = new String[nImages];
if (!embeddedImages) {
if (nImages == 0) {
throw new FormatException("No images found.");
}
core = new CoreMetadata[nImages];
// look for appropriate pixels files
String[] files = directory.list(true);
+ String name = currentId.substring(
+ currentId.lastIndexOf(File.separator) + 1, currentId.lastIndexOf("."));
int nextFile = 0;
for (String f : files) {
- if (f.endsWith(".pst")) {
+ if (checkSuffix(f, "pst") && f.startsWith(name)) {
Location pst = new Location(directory, f);
if (pst.isDirectory()) {
String[] subfiles = pst.list(true);
for (String q : subfiles) {
- if (q.endsWith(".pst") && nextFile < nImages) {
+ if (checkSuffix(q, "pst") && nextFile < nImages) {
pixelsFile[nextFile++] = f + File.separator + q;
}
}
}
else if (nextFile < nImages) {
pixelsFile[nextFile++] = f;
}
}
}
if (nextFile == 0) {
throw new FormatException("No image files found.");
}
}
Arrays.sort(pixelsFile);
pixelsStream = new RandomAccessInputStream[getSeriesCount()];
pixelsFiles = new String[getSeriesCount()];
Object[] metadataKeys = tmpSeriesMetadata.keySet().toArray();
IniParser parser = new IniParser();
for (int i=0; i<getSeriesCount(); i++) {
if (!embeddedImages) {
core[i] = new CoreMetadata();
setSeries(i);
// make sure that pixels file exists
String file = pixelsFile[i];
file = file.replace('/', File.separatorChar);
file = file.replace('\\', File.separatorChar);
String oldFile = file;
Location f = new Location(directory, oldFile);
if (!f.exists()) {
oldFile = oldFile.substring(oldFile.lastIndexOf(File.separator) + 1);
f = new Location(directory, oldFile);
if (!f.exists()) {
throw new FormatException("Could not find pixels file '" + file);
}
}
file = f.getAbsolutePath();
pixelsStream[i] = new RandomAccessInputStream(file);
pixelsFiles[i] = file;
// read key/value pairs from .inf files
int dot = file.lastIndexOf(".");
String inf = file.substring(0, dot) + ".inf";
IniList data = parser.parseINI(new BufferedReader(new FileReader(inf)));
IniTable infoTable = data.getTable("Info");
core[i].sizeX = Integer.parseInt(infoTable.get("Width"));
core[i].sizeY = Integer.parseInt(infoTable.get("Height"));
core[i].sizeC = Integer.parseInt(infoTable.get("Bands"));
core[i].sizeZ = Integer.parseInt(infoTable.get("Slices"));
core[i].sizeT = Integer.parseInt(infoTable.get("Frames"));
int dataType = Integer.parseInt(infoTable.get("Datatype"));
core[i].pixelType = convertPixelType(dataType);
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
for (IniTable table : data) {
for (String key : table.keySet()) {
addSeriesMeta(key, table.get(key));
}
}
}
}
core[i].imageCount = core[i].sizeZ * core[i].sizeC * core[i].sizeT;
core[i].rgb = false;
core[i].littleEndian = true;
core[i].dimensionOrder = "XYCZT";
core[i].seriesMetadata = new Hashtable();
for (Object key : metadataKeys) {
String keyName = key.toString();
if (keyName.startsWith("Series " + i + " ")) {
keyName = keyName.replaceAll("Series " + i + " ", "");
core[i].seriesMetadata.put(keyName, tmpSeriesMetadata.get(key));
}
}
}
tmpSeriesMetadata = null;
populateMetadataStore();
}
// -- Helper methods --
private void populateMetadataStore() throws FormatException {
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
for (int i=0; i<getSeriesCount(); i++) {
// populate Image data
if (i < imageNames.size()) {
store.setImageName(imageNames.get(i), i);
}
String date = i < dates.size() ? dates.get(i) : "";
if (date != null && !date.equals("")) {
store.setImageAcquiredDate(date, i);
}
else MetadataTools.setDefaultCreationDate(store, currentId, i);
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
for (int i=0; i<getSeriesCount(); i++) {
// populate PlaneTiming data
for (int q=0; q<core[i].imageCount; q++) {
store.setPlaneExposureTime(exposureTimes.get(i), i, q);
}
// populate Experiment data
if (i < types.size()) {
store.setExperimentType(getExperimentType(types.get(i)), i);
}
}
}
}
private int convertPixelType(int type) throws FormatException {
boolean signed = type % 2 == 1;
int bytes = (type / 2) + (signed ? 1 : 0);
return FormatTools.pixelTypeFromBytes(bytes, signed, false);
}
private byte[] getMarker(RandomAccessInputStream s) throws IOException {
s.seek(0);
int offset = findNextOffset(s, MARKER_0);
if (offset != -1) return MARKER_0;
s.seek(0);
offset = findNextOffset(s, MARKER_1);
return offset == -1 ? null : MARKER_1;
}
private int findNextOffset(RandomAccessInputStream s, byte[] marker)
throws IOException
{
for (long i=s.getFilePointer(); i<s.length()-marker.length; i++) {
s.seek(i);
boolean found = true;
for (int q=0; q<marker.length; q++) {
if (marker[q] != s.readByte()) {
found = false;
break;
}
}
if (found) return (int) (i + marker.length);
}
return -1;
}
}
| false | true | protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
exposureTimes = new Hashtable<Integer, Double>();
POIService poi = null;
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
}
catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(id);
Vector<String> documents = poi.getDocumentList();
int nImages = 0;
Hashtable tmpSeriesMetadata = new Hashtable();
for (String name : documents) {
LOGGER.debug("Reading {}", name);
if (name.equals("Root Entry" + File.separator + "Contents")) {
RandomAccessInputStream s = poi.getDocumentStream(name);
s.order(true);
int nFound = 0;
embeddedImages = s.read() == 1;
LOGGER.debug("Images are {}embedded", embeddedImages ? "" : "not ");
if (embeddedImages) {
s.skipBytes(12);
int len = s.readShort();
String type = s.readString(len);
if (!type.equals("CImage")) {
embeddedImages = false;
continue;
}
s.seek(27);
len = s.read();
while (len != 0) {
s.skipBytes(len);
len = s.read();
}
s.skipBytes(1243);
core[0].sizeX = s.readInt();
core[0].sizeY = s.readInt();
core[0].sizeZ = s.readInt();
core[0].sizeC = s.readInt();
core[0].sizeT = s.readInt();
core[0].pixelType = convertPixelType(s.readInt());
embeddedOffset = s.getFilePointer() + 28;
in = poi.getDocumentStream(name);
nImages++;
break;
}
byte[] marker = getMarker(s);
if (marker == null) {
throw new FormatException("Could not find known marker.");
}
LOGGER.debug("Marker: {}, {}, {}",
new Object[] {marker[0], marker[1], marker[2]});
s.seek(0);
while (s.getFilePointer() < s.length() - 2) {
LOGGER.debug(" Looking for image at {}", s.getFilePointer());
s.order(false);
int nextOffset = findNextOffset(s, marker);
if (nextOffset < 0 || nextOffset >= s.length()) break;
s.seek(nextOffset);
s.skipBytes(3);
int len = s.readShort();
if (len <= 0) continue;
imageNames.add(s.readString(len));
s.skipBytes(6);
s.order(true);
len = s.readShort();
if (len < 0 || len > 0x1000) continue;
String description = s.readString(len);
LOGGER.debug("Description: {}", description);
// parse key/value pairs from description
String dateTime = "";
String[] lines = description.split("[\r\n]");
for (String line : lines) {
line = line.trim();
int colon = line.indexOf(":");
if (colon != -1 && !line.startsWith(";")) {
String key = line.substring(0, colon).trim();
String value = line.substring(colon + 1).trim();
String metaKey = "Series " + nImages + " " + key;
addMeta(metaKey, value, tmpSeriesMetadata);
if (key.equals("Start time of experiment")) {
// HH:mm:ss aa OR HH:mm:ss.sss aa
dateTime += " " + value;
}
else if (key.equals("Date")) {
// mm/dd/yy ?
dateTime = value + " " + dateTime;
}
else if (key.equals("Exposure time [ms]")) {
double exp = Double.parseDouble(value) / 1000;
exposureTimes.put(new Integer(nImages), new Double(exp));
}
else if (key.equals("Image type")) {
types.add(value);
}
}
}
dateTime = dateTime.trim();
if (!dateTime.equals("")) {
boolean success = false;
for (String format : DATE_FORMATS) {
try {
dateTime = DateTools.formatDate(dateTime, format);
success = true;
}
catch (NullPointerException e) { }
}
dates.add(success ? dateTime : "");
}
nImages++;
}
}
}
Location directory =
new Location(currentId).getAbsoluteFile().getParentFile();
String[] pixelsFile = new String[nImages];
if (!embeddedImages) {
if (nImages == 0) {
throw new FormatException("No images found.");
}
core = new CoreMetadata[nImages];
// look for appropriate pixels files
String[] files = directory.list(true);
int nextFile = 0;
for (String f : files) {
if (f.endsWith(".pst")) {
Location pst = new Location(directory, f);
if (pst.isDirectory()) {
String[] subfiles = pst.list(true);
for (String q : subfiles) {
if (q.endsWith(".pst") && nextFile < nImages) {
pixelsFile[nextFile++] = f + File.separator + q;
}
}
}
else if (nextFile < nImages) {
pixelsFile[nextFile++] = f;
}
}
}
if (nextFile == 0) {
throw new FormatException("No image files found.");
}
}
Arrays.sort(pixelsFile);
pixelsStream = new RandomAccessInputStream[getSeriesCount()];
pixelsFiles = new String[getSeriesCount()];
Object[] metadataKeys = tmpSeriesMetadata.keySet().toArray();
IniParser parser = new IniParser();
for (int i=0; i<getSeriesCount(); i++) {
if (!embeddedImages) {
core[i] = new CoreMetadata();
setSeries(i);
// make sure that pixels file exists
String file = pixelsFile[i];
file = file.replace('/', File.separatorChar);
file = file.replace('\\', File.separatorChar);
String oldFile = file;
Location f = new Location(directory, oldFile);
if (!f.exists()) {
oldFile = oldFile.substring(oldFile.lastIndexOf(File.separator) + 1);
f = new Location(directory, oldFile);
if (!f.exists()) {
throw new FormatException("Could not find pixels file '" + file);
}
}
file = f.getAbsolutePath();
pixelsStream[i] = new RandomAccessInputStream(file);
pixelsFiles[i] = file;
// read key/value pairs from .inf files
int dot = file.lastIndexOf(".");
String inf = file.substring(0, dot) + ".inf";
IniList data = parser.parseINI(new BufferedReader(new FileReader(inf)));
IniTable infoTable = data.getTable("Info");
core[i].sizeX = Integer.parseInt(infoTable.get("Width"));
core[i].sizeY = Integer.parseInt(infoTable.get("Height"));
core[i].sizeC = Integer.parseInt(infoTable.get("Bands"));
core[i].sizeZ = Integer.parseInt(infoTable.get("Slices"));
core[i].sizeT = Integer.parseInt(infoTable.get("Frames"));
int dataType = Integer.parseInt(infoTable.get("Datatype"));
core[i].pixelType = convertPixelType(dataType);
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
for (IniTable table : data) {
for (String key : table.keySet()) {
addSeriesMeta(key, table.get(key));
}
}
}
}
core[i].imageCount = core[i].sizeZ * core[i].sizeC * core[i].sizeT;
core[i].rgb = false;
core[i].littleEndian = true;
core[i].dimensionOrder = "XYCZT";
core[i].seriesMetadata = new Hashtable();
for (Object key : metadataKeys) {
String keyName = key.toString();
if (keyName.startsWith("Series " + i + " ")) {
keyName = keyName.replaceAll("Series " + i + " ", "");
core[i].seriesMetadata.put(keyName, tmpSeriesMetadata.get(key));
}
}
}
tmpSeriesMetadata = null;
populateMetadataStore();
}
| protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
exposureTimes = new Hashtable<Integer, Double>();
POIService poi = null;
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
}
catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(id);
Vector<String> documents = poi.getDocumentList();
int nImages = 0;
Hashtable tmpSeriesMetadata = new Hashtable();
for (String name : documents) {
LOGGER.debug("Reading {}", name);
if (name.equals("Root Entry" + File.separator + "Contents")) {
RandomAccessInputStream s = poi.getDocumentStream(name);
s.order(true);
int nFound = 0;
embeddedImages = s.read() == 1;
LOGGER.debug("Images are {}embedded", embeddedImages ? "" : "not ");
if (embeddedImages) {
s.skipBytes(12);
int len = s.readShort();
String type = s.readString(len);
if (!type.equals("CImage")) {
embeddedImages = false;
continue;
}
s.seek(27);
len = s.read();
while (len != 0) {
s.skipBytes(len);
len = s.read();
}
s.skipBytes(1243);
core[0].sizeX = s.readInt();
core[0].sizeY = s.readInt();
core[0].sizeZ = s.readInt();
core[0].sizeC = s.readInt();
core[0].sizeT = s.readInt();
core[0].pixelType = convertPixelType(s.readInt());
embeddedOffset = s.getFilePointer() + 28;
in = poi.getDocumentStream(name);
nImages++;
break;
}
byte[] marker = getMarker(s);
if (marker == null) {
throw new FormatException("Could not find known marker.");
}
LOGGER.debug("Marker: {}, {}, {}",
new Object[] {marker[0], marker[1], marker[2]});
s.seek(0);
while (s.getFilePointer() < s.length() - 2) {
LOGGER.debug(" Looking for image at {}", s.getFilePointer());
s.order(false);
int nextOffset = findNextOffset(s, marker);
if (nextOffset < 0 || nextOffset >= s.length()) break;
s.seek(nextOffset);
s.skipBytes(3);
int len = s.readShort();
if (len <= 0) continue;
imageNames.add(s.readString(len));
s.skipBytes(6);
s.order(true);
len = s.readShort();
if (len < 0 || len > 0x1000) continue;
String description = s.readString(len);
LOGGER.debug("Description: {}", description);
// parse key/value pairs from description
String dateTime = "";
String[] lines = description.split("[\r\n]");
for (String line : lines) {
line = line.trim();
int colon = line.indexOf(":");
if (colon != -1 && !line.startsWith(";")) {
String key = line.substring(0, colon).trim();
String value = line.substring(colon + 1).trim();
String metaKey = "Series " + nImages + " " + key;
addMeta(metaKey, value, tmpSeriesMetadata);
if (key.equals("Start time of experiment")) {
// HH:mm:ss aa OR HH:mm:ss.sss aa
dateTime += " " + value;
}
else if (key.equals("Date")) {
// mm/dd/yy ?
dateTime = value + " " + dateTime;
}
else if (key.equals("Exposure time [ms]")) {
double exp = Double.parseDouble(value) / 1000;
exposureTimes.put(new Integer(nImages), new Double(exp));
}
else if (key.equals("Image type")) {
types.add(value);
}
}
}
dateTime = dateTime.trim();
if (!dateTime.equals("")) {
boolean success = false;
for (String format : DATE_FORMATS) {
try {
dateTime = DateTools.formatDate(dateTime, format);
success = true;
}
catch (NullPointerException e) { }
}
dates.add(success ? dateTime : "");
}
nImages++;
}
}
}
Location directory =
new Location(currentId).getAbsoluteFile().getParentFile();
String[] pixelsFile = new String[nImages];
if (!embeddedImages) {
if (nImages == 0) {
throw new FormatException("No images found.");
}
core = new CoreMetadata[nImages];
// look for appropriate pixels files
String[] files = directory.list(true);
String name = currentId.substring(
currentId.lastIndexOf(File.separator) + 1, currentId.lastIndexOf("."));
int nextFile = 0;
for (String f : files) {
if (checkSuffix(f, "pst") && f.startsWith(name)) {
Location pst = new Location(directory, f);
if (pst.isDirectory()) {
String[] subfiles = pst.list(true);
for (String q : subfiles) {
if (checkSuffix(q, "pst") && nextFile < nImages) {
pixelsFile[nextFile++] = f + File.separator + q;
}
}
}
else if (nextFile < nImages) {
pixelsFile[nextFile++] = f;
}
}
}
if (nextFile == 0) {
throw new FormatException("No image files found.");
}
}
Arrays.sort(pixelsFile);
pixelsStream = new RandomAccessInputStream[getSeriesCount()];
pixelsFiles = new String[getSeriesCount()];
Object[] metadataKeys = tmpSeriesMetadata.keySet().toArray();
IniParser parser = new IniParser();
for (int i=0; i<getSeriesCount(); i++) {
if (!embeddedImages) {
core[i] = new CoreMetadata();
setSeries(i);
// make sure that pixels file exists
String file = pixelsFile[i];
file = file.replace('/', File.separatorChar);
file = file.replace('\\', File.separatorChar);
String oldFile = file;
Location f = new Location(directory, oldFile);
if (!f.exists()) {
oldFile = oldFile.substring(oldFile.lastIndexOf(File.separator) + 1);
f = new Location(directory, oldFile);
if (!f.exists()) {
throw new FormatException("Could not find pixels file '" + file);
}
}
file = f.getAbsolutePath();
pixelsStream[i] = new RandomAccessInputStream(file);
pixelsFiles[i] = file;
// read key/value pairs from .inf files
int dot = file.lastIndexOf(".");
String inf = file.substring(0, dot) + ".inf";
IniList data = parser.parseINI(new BufferedReader(new FileReader(inf)));
IniTable infoTable = data.getTable("Info");
core[i].sizeX = Integer.parseInt(infoTable.get("Width"));
core[i].sizeY = Integer.parseInt(infoTable.get("Height"));
core[i].sizeC = Integer.parseInt(infoTable.get("Bands"));
core[i].sizeZ = Integer.parseInt(infoTable.get("Slices"));
core[i].sizeT = Integer.parseInt(infoTable.get("Frames"));
int dataType = Integer.parseInt(infoTable.get("Datatype"));
core[i].pixelType = convertPixelType(dataType);
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
for (IniTable table : data) {
for (String key : table.keySet()) {
addSeriesMeta(key, table.get(key));
}
}
}
}
core[i].imageCount = core[i].sizeZ * core[i].sizeC * core[i].sizeT;
core[i].rgb = false;
core[i].littleEndian = true;
core[i].dimensionOrder = "XYCZT";
core[i].seriesMetadata = new Hashtable();
for (Object key : metadataKeys) {
String keyName = key.toString();
if (keyName.startsWith("Series " + i + " ")) {
keyName = keyName.replaceAll("Series " + i + " ", "");
core[i].seriesMetadata.put(keyName, tmpSeriesMetadata.get(key));
}
}
}
tmpSeriesMetadata = null;
populateMetadataStore();
}
|
diff --git a/webapp/WEB-INF/classes/org/makumba/parade/tools/TriggerFilter.java b/webapp/WEB-INF/classes/org/makumba/parade/tools/TriggerFilter.java
index 01e8c98..6d7d71e 100644
--- a/webapp/WEB-INF/classes/org/makumba/parade/tools/TriggerFilter.java
+++ b/webapp/WEB-INF/classes/org/makumba/parade/tools/TriggerFilter.java
@@ -1,190 +1,193 @@
package org.makumba.parade.tools;
import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.makumba.parade.access.ActionLogDTO;
/**
* This filter invokes a servlet before and another servlet after each access to a servlet context or an entire servlet
* engine. The servlets can be in any of the servlet contexts. If servlets from other contexts are used, in Tomcat,
* server.xml must include <DefaultContext crossContext="true"/>.<br>
* When this class is used for all Tomcat contexts, it should be configured in tomcat/conf/web.xml, and should be
* available statically (e.g. in tomcat/common/classes. The great advantage is that all servlets that it invokes can be
* loaded dynamically. beforeServlet and afterServlet are not invoked with the original request, but with a dummy
* request, that contains the original request, response and context as the attributes
* "org.eu.best.tools.TriggerFilter.request", "org.eu.best.tools.TriggerFilter.response",
* "org.eu.best.tools.TriggerFilter.context".<br>
* The beforeServlet can indicate that it whishes the chain not to be invoked by resetting the attribute
* "org.eu.best.tools.TriggerFilter.request" to null.<br>
*
* TODO read POST parameters from the requests
*
* @author Cristian Bogdan
* @author Manuel Gay
*/
public class TriggerFilter implements Filter {
ServletContext context;
String beforeContext, afterContext, beforeServlet, afterServlet;
public void init(FilterConfig conf) {
context = conf.getServletContext();
if (context.getContext("/") == context) {
LogHandler.setStaticContext(context);
}
beforeContext = conf.getInitParameter("beforeContext");
beforeServlet = conf.getInitParameter("beforeServlet");
afterContext = conf.getInitParameter("afterContext");
afterServlet = conf.getInitParameter("afterServlet");
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws java.io.IOException,
ServletException {
ServletRequest origReq = req;
PerThreadPrintStream.setEnabled(true);
ServletContext ctx = context.getContext(beforeContext);
// we create an initial ActionLogDTO and set it to the ThreadLocal
ActionLogDTO log = new ActionLogDTO();
getActionContext(req, log);
LogHandler.actionLog.set(log);
// we set the original attributes to be passed on
HttpServletRequest dummyReq = new HttpServletRequestDummy();
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.request", req);
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.response", resp);
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.context", context);
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.actionlog", log);
req.setAttribute("org.eu.best.tools.TriggerFilter.dummyRequest", dummyReq);
req.setAttribute("org.eu.best.tools.TriggerFilter.request", req);
req.setAttribute("org.eu.best.tools.TriggerFilter.response", resp);
req.setAttribute("org.eu.best.tools.TriggerFilter.context", context);
req.setAttribute("org.eu.best.tools.TriggerFilter.actionlog", log);
if (ctx == null) {
checkCrossContext(req, beforeContext);
} else {
if (beforeServlet != null)
LogHandler.invokeServlet(beforeServlet, ctx, dummyReq, resp);
// first, we ask the db servlet to log our actionlog
dummyReq.setAttribute("org.makumba.parade.servletParam", log);
LogHandler.invokeServlet("/servlet/org.makumba.parade.access.DatabaseLogServlet", ctx, dummyReq, resp);
// now we have the user gracefully provided by the beforeServlet so we can set the prefix
LogHandler.setPrefix();
}
req = (ServletRequest) dummyReq.getAttribute("org.eu.best.tools.TriggerFilter.request");
if (req == null) {
boolean unauthorizedAccess = (dummyReq.getAttribute("org.makumba.parade.unauthorizedAccess") != null);
boolean directoryServerError = (dummyReq.getAttribute("org.makumba.parade.directoryAccessError") != null);
if (unauthorizedAccess || directoryServerError) {
req = origReq;
String errorPageURI = "/unauthorized/index.jsp";
if (directoryServerError)
errorPageURI = "/unauthorized/directoryServerError.jsp";
try {
- LogHandler.getRequestDispatcher(errorPageURI).forward(req, resp);
+ ctx.getRequestDispatcher(errorPageURI).forward(req, resp);
+ //LogHandler.getRequestDispatcher(errorPageURI).forward(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
+ } catch(NullPointerException npe) {
+ npe.printStackTrace();
}
// chain.doFilter(req, resp);
return;
} else {
// beforeServlet signaled closure
return;
}
}
resp = (ServletResponse) dummyReq.getAttribute("org.eu.best.tools.TriggerFilter.response");
chain.doFilter(req, resp);
ctx = context.getContext(afterContext);
if (ctx == null) {
checkCrossContext(req, afterContext);
} else {
if (afterServlet != null)
LogHandler.invokeServlet(afterServlet, ctx, req, resp);
}
// we make sure the actionLog is null after each access
LogHandler.actionLog.set(null);
}
/**
* Tries to determine the context information of an action, meaning not only the servlet context but also other
* relevant information.
*
* @param req
* the ServletRequest corresponding to the access
* @param log
* the ActionLogDTO which will hold the information
*
* TODO get the POST parameters as well by reading the inputstream of the request
*/
private void getActionContext(ServletRequest req, ActionLogDTO log) {
HttpServletRequest httpReq = ((HttpServletRequest) req);
String contextPath = httpReq.getContextPath();
if (contextPath.equals("")) { // FIXME heuristic
contextPath = "parade2";
} else {
contextPath = contextPath.substring(1);
}
log.setContext(contextPath);
log.setDate(new Date());
String pathInfo = httpReq.getPathInfo();
log.setUrl(httpReq.getServletPath() + (pathInfo == null ? "" : pathInfo));
log.setQueryString(httpReq.getQueryString());
}
/**
* Checks if the crossContext is enabled.
*
* @param req
* the ServletRequest corresponding to the current access
* @param ctxName
* the context name of the current context
*/
private void checkCrossContext(ServletRequest req, String ctxName) {
if (!((HttpServletRequest) req).getContextPath().equals("/manager"))
System.out
.println("got null trying to search context "
+ ctxName
+ " from context "
+ ((HttpServletRequest) req).getContextPath()
+ " it may be that <DefaultContext crossContext=\"true\"/> is not configured in Tomcat's conf/server.xml, under Engine or Host");
}
public void destroy() {
}
}
| false | true | public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws java.io.IOException,
ServletException {
ServletRequest origReq = req;
PerThreadPrintStream.setEnabled(true);
ServletContext ctx = context.getContext(beforeContext);
// we create an initial ActionLogDTO and set it to the ThreadLocal
ActionLogDTO log = new ActionLogDTO();
getActionContext(req, log);
LogHandler.actionLog.set(log);
// we set the original attributes to be passed on
HttpServletRequest dummyReq = new HttpServletRequestDummy();
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.request", req);
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.response", resp);
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.context", context);
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.actionlog", log);
req.setAttribute("org.eu.best.tools.TriggerFilter.dummyRequest", dummyReq);
req.setAttribute("org.eu.best.tools.TriggerFilter.request", req);
req.setAttribute("org.eu.best.tools.TriggerFilter.response", resp);
req.setAttribute("org.eu.best.tools.TriggerFilter.context", context);
req.setAttribute("org.eu.best.tools.TriggerFilter.actionlog", log);
if (ctx == null) {
checkCrossContext(req, beforeContext);
} else {
if (beforeServlet != null)
LogHandler.invokeServlet(beforeServlet, ctx, dummyReq, resp);
// first, we ask the db servlet to log our actionlog
dummyReq.setAttribute("org.makumba.parade.servletParam", log);
LogHandler.invokeServlet("/servlet/org.makumba.parade.access.DatabaseLogServlet", ctx, dummyReq, resp);
// now we have the user gracefully provided by the beforeServlet so we can set the prefix
LogHandler.setPrefix();
}
req = (ServletRequest) dummyReq.getAttribute("org.eu.best.tools.TriggerFilter.request");
if (req == null) {
boolean unauthorizedAccess = (dummyReq.getAttribute("org.makumba.parade.unauthorizedAccess") != null);
boolean directoryServerError = (dummyReq.getAttribute("org.makumba.parade.directoryAccessError") != null);
if (unauthorizedAccess || directoryServerError) {
req = origReq;
String errorPageURI = "/unauthorized/index.jsp";
if (directoryServerError)
errorPageURI = "/unauthorized/directoryServerError.jsp";
try {
LogHandler.getRequestDispatcher(errorPageURI).forward(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// chain.doFilter(req, resp);
return;
} else {
// beforeServlet signaled closure
return;
}
}
resp = (ServletResponse) dummyReq.getAttribute("org.eu.best.tools.TriggerFilter.response");
chain.doFilter(req, resp);
ctx = context.getContext(afterContext);
if (ctx == null) {
checkCrossContext(req, afterContext);
} else {
if (afterServlet != null)
LogHandler.invokeServlet(afterServlet, ctx, req, resp);
}
// we make sure the actionLog is null after each access
LogHandler.actionLog.set(null);
}
| public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws java.io.IOException,
ServletException {
ServletRequest origReq = req;
PerThreadPrintStream.setEnabled(true);
ServletContext ctx = context.getContext(beforeContext);
// we create an initial ActionLogDTO and set it to the ThreadLocal
ActionLogDTO log = new ActionLogDTO();
getActionContext(req, log);
LogHandler.actionLog.set(log);
// we set the original attributes to be passed on
HttpServletRequest dummyReq = new HttpServletRequestDummy();
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.request", req);
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.response", resp);
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.context", context);
dummyReq.setAttribute("org.eu.best.tools.TriggerFilter.actionlog", log);
req.setAttribute("org.eu.best.tools.TriggerFilter.dummyRequest", dummyReq);
req.setAttribute("org.eu.best.tools.TriggerFilter.request", req);
req.setAttribute("org.eu.best.tools.TriggerFilter.response", resp);
req.setAttribute("org.eu.best.tools.TriggerFilter.context", context);
req.setAttribute("org.eu.best.tools.TriggerFilter.actionlog", log);
if (ctx == null) {
checkCrossContext(req, beforeContext);
} else {
if (beforeServlet != null)
LogHandler.invokeServlet(beforeServlet, ctx, dummyReq, resp);
// first, we ask the db servlet to log our actionlog
dummyReq.setAttribute("org.makumba.parade.servletParam", log);
LogHandler.invokeServlet("/servlet/org.makumba.parade.access.DatabaseLogServlet", ctx, dummyReq, resp);
// now we have the user gracefully provided by the beforeServlet so we can set the prefix
LogHandler.setPrefix();
}
req = (ServletRequest) dummyReq.getAttribute("org.eu.best.tools.TriggerFilter.request");
if (req == null) {
boolean unauthorizedAccess = (dummyReq.getAttribute("org.makumba.parade.unauthorizedAccess") != null);
boolean directoryServerError = (dummyReq.getAttribute("org.makumba.parade.directoryAccessError") != null);
if (unauthorizedAccess || directoryServerError) {
req = origReq;
String errorPageURI = "/unauthorized/index.jsp";
if (directoryServerError)
errorPageURI = "/unauthorized/directoryServerError.jsp";
try {
ctx.getRequestDispatcher(errorPageURI).forward(req, resp);
//LogHandler.getRequestDispatcher(errorPageURI).forward(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(NullPointerException npe) {
npe.printStackTrace();
}
// chain.doFilter(req, resp);
return;
} else {
// beforeServlet signaled closure
return;
}
}
resp = (ServletResponse) dummyReq.getAttribute("org.eu.best.tools.TriggerFilter.response");
chain.doFilter(req, resp);
ctx = context.getContext(afterContext);
if (ctx == null) {
checkCrossContext(req, afterContext);
} else {
if (afterServlet != null)
LogHandler.invokeServlet(afterServlet, ctx, req, resp);
}
// we make sure the actionLog is null after each access
LogHandler.actionLog.set(null);
}
|
diff --git a/src/ufly/frs/Select.java b/src/ufly/frs/Select.java
index 6ad9b5a..0495237 100644
--- a/src/ufly/frs/Select.java
+++ b/src/ufly/frs/Select.java
@@ -1,141 +1,142 @@
package ufly.frs;
import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import ufly.entities.*;
@SuppressWarnings("serial")
public class Select extends UflyServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException,ServletException
{
/**
* we probably got here because of a redirect from login,
* because we were required to login to book a flight
*/
String departopt;
String returnopt;
HttpSession session= req.getSession();
if(session.getAttribute("departopt")!=null)
{
departopt=(String) session.getAttribute("departopt");
returnopt=(String) session.getAttribute("returnopt");
Integer numPass = (Integer) session.getAttribute("numPass");
session.setAttribute("departopt",null);
session.setAttribute("returnopt", null);
session.setAttribute("numPass", null);
buildPage(departopt,returnopt,numPass,req,resp);
}else{
resp.sendRedirect("/");
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException,ServletException
{
/**
* We need to be logged in at this point, If we are not logged in, redirect
* them to login page. before we do that we want to save the flights that they are
* trying to book. We'll do that in the session.
*/
User loggedInUser=null;
try {
loggedInUser = getLoggedInUser(req.getSession());
} catch (UserInactivityTimeout e) {
}
if(loggedInUser == null)
{
// //DEBUGGING --remove when done
// //if no user logged in, log user in
// login("email",req.getSession());
// }else if (false){
// //ENDDEBUGGING
HttpSession session= req.getSession();
session.setAttribute("departopt",req.getParameter("departopt") );
session.setAttribute("returnopt", req.getParameter("returnopt"));
session.setAttribute("numPass", Integer.parseInt((String)req.getParameter("numPassengers")));
resp.sendRedirect("/login?errorMsg=Please%20log%20in,%20you%20will%20be%20returned%20to%20the%20booking%20process%20afterwards");
return;
}
/**
* make sure the session attributes are cleared
*/
String departopt= req.getParameter("departopt");
String returnopt=req.getParameter("returnopt");
Integer numPass=Integer.parseInt((String)req.getParameter("numPassengers"));
buildPage(departopt,returnopt,numPass,req,resp);
}
private void buildPage(String departopt,String returnopt,Integer numPass,HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
List<Flight> FlightList=new Vector<Flight>();
addFlightsToFlightList(FlightList,departopt);
if(returnopt!=null)
{
addFlightsToFlightList(FlightList,returnopt);
}
Vector<HashMap<String,Object>> allFlightsInfo = new Vector<HashMap<String,Object>>();
Integer priceInCents=0;
for(Flight f:FlightList)
{
HashMap<String,Object> hm = f.getHashMap();
allFlightsInfo.add(hm);
priceInCents+=f.getPriceInCents();
}
priceInCents *= numPass;
String price="$"+new Integer(priceInCents/100).toString()+".";
priceInCents%=100;
Customer loggedInUser=null;
if(priceInCents<10){
price+="0";
}
try{
loggedInUser = (Customer)getLoggedInUser(req.getSession());
}catch(ClassCastException e){
+ resp.sendRedirect("/index.jsp?errorMsg=You must be logged in as customer to make a booking");
return;
}catch(UserInactivityTimeout e){
return;
}
price+=priceInCents.toString();
req.setAttribute("TotalCostString",price);
req.setAttribute("loyaltyPoints",loggedInUser.getLoyaltyPoints());
req.setAttribute("flightInfo", allFlightsInfo);
req.setAttribute("numPassengers", numPass);
req.getRequestDispatcher("bookFlightNew.jsp").forward(req, resp);
}
private void addFlightsToFlightList(List<Flight> flightList,
String flightsStr) {
SimpleDateFormat convertToDate = new SimpleDateFormat("yyyy/MM/dd HH:mm");
String[] flights=flightsStr.split("\\|");
for(int i=0;i<flights.length;i++){
if(flights[i].equals("")){
break;
}
String flightNo = flights[i].split("_")[0];
Date departureTime = convertToDate.parse(flights[i].split("_")[1], new ParsePosition(0));
flightList.add(Flight.getFlight(flightNo,departureTime));
}
}
}
| true | true | private void buildPage(String departopt,String returnopt,Integer numPass,HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
List<Flight> FlightList=new Vector<Flight>();
addFlightsToFlightList(FlightList,departopt);
if(returnopt!=null)
{
addFlightsToFlightList(FlightList,returnopt);
}
Vector<HashMap<String,Object>> allFlightsInfo = new Vector<HashMap<String,Object>>();
Integer priceInCents=0;
for(Flight f:FlightList)
{
HashMap<String,Object> hm = f.getHashMap();
allFlightsInfo.add(hm);
priceInCents+=f.getPriceInCents();
}
priceInCents *= numPass;
String price="$"+new Integer(priceInCents/100).toString()+".";
priceInCents%=100;
Customer loggedInUser=null;
if(priceInCents<10){
price+="0";
}
try{
loggedInUser = (Customer)getLoggedInUser(req.getSession());
}catch(ClassCastException e){
return;
}catch(UserInactivityTimeout e){
return;
}
price+=priceInCents.toString();
req.setAttribute("TotalCostString",price);
req.setAttribute("loyaltyPoints",loggedInUser.getLoyaltyPoints());
req.setAttribute("flightInfo", allFlightsInfo);
req.setAttribute("numPassengers", numPass);
req.getRequestDispatcher("bookFlightNew.jsp").forward(req, resp);
}
| private void buildPage(String departopt,String returnopt,Integer numPass,HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
List<Flight> FlightList=new Vector<Flight>();
addFlightsToFlightList(FlightList,departopt);
if(returnopt!=null)
{
addFlightsToFlightList(FlightList,returnopt);
}
Vector<HashMap<String,Object>> allFlightsInfo = new Vector<HashMap<String,Object>>();
Integer priceInCents=0;
for(Flight f:FlightList)
{
HashMap<String,Object> hm = f.getHashMap();
allFlightsInfo.add(hm);
priceInCents+=f.getPriceInCents();
}
priceInCents *= numPass;
String price="$"+new Integer(priceInCents/100).toString()+".";
priceInCents%=100;
Customer loggedInUser=null;
if(priceInCents<10){
price+="0";
}
try{
loggedInUser = (Customer)getLoggedInUser(req.getSession());
}catch(ClassCastException e){
resp.sendRedirect("/index.jsp?errorMsg=You must be logged in as customer to make a booking");
return;
}catch(UserInactivityTimeout e){
return;
}
price+=priceInCents.toString();
req.setAttribute("TotalCostString",price);
req.setAttribute("loyaltyPoints",loggedInUser.getLoyaltyPoints());
req.setAttribute("flightInfo", allFlightsInfo);
req.setAttribute("numPassengers", numPass);
req.getRequestDispatcher("bookFlightNew.jsp").forward(req, resp);
}
|
diff --git a/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java b/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java
index 9cd8331..a0fdebc 100644
--- a/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java
+++ b/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java
@@ -1,169 +1,169 @@
package hudson.plugins.msbuild;
import hudson.*;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.tasks.Builder;
import hudson.util.ArgumentListBuilder;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
/**
* @author [email protected]
* @author Gregory Boissinot - Zenika
* 2009/03/01 - Added the possibility to manage multiple Msbuild version
* 2009/05/20 - Fixed #3610
* 2010/04/02 - Fixed #4121
* 2010/05/05 - Added environment and build variables resolving in fields
*/
public class MsBuildBuilder extends Builder {
/**
* GUI fields
*/
private final String msBuildName;
private final String msBuildFile;
private final String cmdLineArgs;
/**
* When this builder is created in the project configuration step,
* the builder object will be created from the strings below.
*
* @param msBuildName The Visual studio logical name
* @param msBuildFile The name/location of the msbuild file
* @param cmdLineArgs Whitespace separated list of command line arguments
*/
@DataBoundConstructor
@SuppressWarnings("unused")
public MsBuildBuilder(String msBuildName, String msBuildFile, String cmdLineArgs) {
this.msBuildName = msBuildName;
this.msBuildFile = msBuildFile;
this.cmdLineArgs = cmdLineArgs;
}
@SuppressWarnings("unused")
public String getCmdLineArgs() {
return cmdLineArgs;
}
@SuppressWarnings("unused")
public String getMsBuildFile() {
return msBuildFile;
}
@SuppressWarnings("unused")
public String getMsBuildName() {
return msBuildName;
}
public MsBuildInstallation getMsBuild() {
for (MsBuildInstallation i : DESCRIPTOR.getInstallations()) {
if (msBuildName != null && i.getName().equals(msBuildName))
return i;
}
return null;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
String execName = "msbuild.exe";
MsBuildInstallation ai = getMsBuild();
if (ai == null) {
listener.getLogger().println("Path To MSBuild.exe: " + execName);
args.add(execName);
} else {
String pathToMsBuild = ai.getPathToMsBuild();
FilePath exec = new FilePath(launcher.getChannel(), pathToMsBuild);
try {
if (!exec.exists()) {
listener.fatalError(pathToMsBuild + " doesn't exist");
return false;
}
} catch (IOException e) {
listener.fatalError("Failed checking for existence of " + pathToMsBuild);
return false;
}
listener.getLogger().println("Path To MSBuild.exe: " + pathToMsBuild);
args.add(pathToMsBuild);
}
EnvVars env = build.getEnvironment(listener);
String normalizedArgs = cmdLineArgs.replaceAll("[\t\r\n]+", " ");
normalizedArgs = Util.replaceMacro(normalizedArgs, env);
normalizedArgs = Util.replaceMacro(normalizedArgs, build.getBuildVariables());
if (normalizedArgs.trim().length() > 0)
args.addTokenized(normalizedArgs);
args.addKeyValuePairs("-P:", build.getBuildVariables());
//If a msbuild file is specified, then add it as an argument, otherwise
//msbuild will search for any file that ends in .proj or .sln
if (msBuildFile != null && msBuildFile.trim().length() > 0) {
String normalizedFile = msBuildFile.replaceAll("[\t\r\n]+", " ");
normalizedFile = Util.replaceMacro(normalizedFile, env);
normalizedFile = Util.replaceMacro(normalizedFile, build.getBuildVariables());
- if (normalizedArgs.length() > 0)
+ if (normalizedFile.length() > 0)
args.add(normalizedFile);
}
if (!launcher.isUnix()) {
args.prepend("cmd.exe", "/C");
args.add("&&", "exit", "%%ERRORLEVEL%%");
}
listener.getLogger().println("Executing command: " + args.toStringWithQuote());
try {
int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(build.getModuleRoot()).join();
return r == 0;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
return false;
}
}
@Override
public Descriptor<Builder> getDescriptor() {
return DESCRIPTOR;
}
/**
* Descriptor should be singleton.
*/
@Extension
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends Descriptor<Builder> {
@CopyOnWrite
private volatile MsBuildInstallation[] installations = new MsBuildInstallation[0];
DescriptorImpl() {
super(MsBuildBuilder.class);
load();
}
public String getDisplayName() {
return "Build a Visual Studio project or solution using MSBuild.";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
installations = req.bindParametersToList(MsBuildInstallation.class, "msbuild.").toArray(new MsBuildInstallation[0]);
save();
return true;
}
public MsBuildInstallation[] getInstallations() {
return installations;
}
}
}
| true | true | public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
String execName = "msbuild.exe";
MsBuildInstallation ai = getMsBuild();
if (ai == null) {
listener.getLogger().println("Path To MSBuild.exe: " + execName);
args.add(execName);
} else {
String pathToMsBuild = ai.getPathToMsBuild();
FilePath exec = new FilePath(launcher.getChannel(), pathToMsBuild);
try {
if (!exec.exists()) {
listener.fatalError(pathToMsBuild + " doesn't exist");
return false;
}
} catch (IOException e) {
listener.fatalError("Failed checking for existence of " + pathToMsBuild);
return false;
}
listener.getLogger().println("Path To MSBuild.exe: " + pathToMsBuild);
args.add(pathToMsBuild);
}
EnvVars env = build.getEnvironment(listener);
String normalizedArgs = cmdLineArgs.replaceAll("[\t\r\n]+", " ");
normalizedArgs = Util.replaceMacro(normalizedArgs, env);
normalizedArgs = Util.replaceMacro(normalizedArgs, build.getBuildVariables());
if (normalizedArgs.trim().length() > 0)
args.addTokenized(normalizedArgs);
args.addKeyValuePairs("-P:", build.getBuildVariables());
//If a msbuild file is specified, then add it as an argument, otherwise
//msbuild will search for any file that ends in .proj or .sln
if (msBuildFile != null && msBuildFile.trim().length() > 0) {
String normalizedFile = msBuildFile.replaceAll("[\t\r\n]+", " ");
normalizedFile = Util.replaceMacro(normalizedFile, env);
normalizedFile = Util.replaceMacro(normalizedFile, build.getBuildVariables());
if (normalizedArgs.length() > 0)
args.add(normalizedFile);
}
if (!launcher.isUnix()) {
args.prepend("cmd.exe", "/C");
args.add("&&", "exit", "%%ERRORLEVEL%%");
}
listener.getLogger().println("Executing command: " + args.toStringWithQuote());
try {
int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(build.getModuleRoot()).join();
return r == 0;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
return false;
}
}
| public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
String execName = "msbuild.exe";
MsBuildInstallation ai = getMsBuild();
if (ai == null) {
listener.getLogger().println("Path To MSBuild.exe: " + execName);
args.add(execName);
} else {
String pathToMsBuild = ai.getPathToMsBuild();
FilePath exec = new FilePath(launcher.getChannel(), pathToMsBuild);
try {
if (!exec.exists()) {
listener.fatalError(pathToMsBuild + " doesn't exist");
return false;
}
} catch (IOException e) {
listener.fatalError("Failed checking for existence of " + pathToMsBuild);
return false;
}
listener.getLogger().println("Path To MSBuild.exe: " + pathToMsBuild);
args.add(pathToMsBuild);
}
EnvVars env = build.getEnvironment(listener);
String normalizedArgs = cmdLineArgs.replaceAll("[\t\r\n]+", " ");
normalizedArgs = Util.replaceMacro(normalizedArgs, env);
normalizedArgs = Util.replaceMacro(normalizedArgs, build.getBuildVariables());
if (normalizedArgs.trim().length() > 0)
args.addTokenized(normalizedArgs);
args.addKeyValuePairs("-P:", build.getBuildVariables());
//If a msbuild file is specified, then add it as an argument, otherwise
//msbuild will search for any file that ends in .proj or .sln
if (msBuildFile != null && msBuildFile.trim().length() > 0) {
String normalizedFile = msBuildFile.replaceAll("[\t\r\n]+", " ");
normalizedFile = Util.replaceMacro(normalizedFile, env);
normalizedFile = Util.replaceMacro(normalizedFile, build.getBuildVariables());
if (normalizedFile.length() > 0)
args.add(normalizedFile);
}
if (!launcher.isUnix()) {
args.prepend("cmd.exe", "/C");
args.add("&&", "exit", "%%ERRORLEVEL%%");
}
listener.getLogger().println("Executing command: " + args.toStringWithQuote());
try {
int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(build.getModuleRoot()).join();
return r == 0;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
return false;
}
}
|
diff --git a/src/de/ub0r/android/websms/WebSMS.java b/src/de/ub0r/android/websms/WebSMS.java
index ec094938..7b08f6e1 100644
--- a/src/de/ub0r/android/websms/WebSMS.java
+++ b/src/de/ub0r/android/websms/WebSMS.java
@@ -1,1764 +1,1769 @@
/*
* Copyright (C) 2010 Felix Bechstein, Lado Kumsiashvili
*
* This file is part of WebSMS.
*
* 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 de.ub0r.android.websms;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.telephony.gsm.SmsMessage;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import de.ub0r.android.websms.connector.common.Connector;
import de.ub0r.android.websms.connector.common.ConnectorCommand;
import de.ub0r.android.websms.connector.common.ConnectorSpec;
import de.ub0r.android.websms.connector.common.Utils;
import de.ub0r.android.websms.connector.common.ConnectorSpec.SubConnectorSpec;
/**
* Main Activity.
*
* @author flx
*/
@SuppressWarnings("deprecation")
public class WebSMS extends Activity implements OnClickListener,
OnDateSetListener, OnTimeSetListener {
/** Tag for output. */
private static final String TAG = "WebSMS";
/** Static reference to running Activity. */
private static WebSMS me;
/** Preference's name: last version run. */
private static final String PREFS_LAST_RUN = "lastrun";
/** Preference's name: user's phonenumber. */
static final String PREFS_SENDER = "sender";
/** Preference's name: default prefix. */
static final String PREFS_DEFPREFIX = "defprefix";
/** Preference's name: update balace on start. */
private static final String PREFS_AUTOUPDATE = "autoupdate";
/** Preference's name: exit after sending. */
private static final String PREFS_AUTOEXIT = "autoexit";
/** Preference's name: show mobile numbers only. */
private static final String PREFS_MOBILES_ONLY = "mobiles_only";
/** Preference's name: vibrate on failed sending. */
static final String PREFS_FAIL_VIBRATE = "fail_vibrate";
/** Preference's name: sound on failed sending. */
static final String PREFS_FAIL_SOUND = "fail_sound";
/** Preferemce's name: enable change connector button. */
private static final String PREFS_HIDE_CHANGE_CONNECTOR_BUTTON = // .
"hide_change_connector_button";
/** Preferemce's name: hide select recipients button. */
private static final String PREFS_HIDE_SELECT_RECIPIENTS_BUTTON = // .
"hide_select_recipients_button";
/** Preferemce's name: hide clear recipients button. */
private static final String PREFS_HIDE_CLEAR_RECIPIENTS_BUTTON = // .
"hide_clear_recipients_button";
/** Preference's name: hide send menu item. */
private static final String PREFS_HIDE_SEND_IN_MENU = "hide_send_in_menu";
/** Preferemce's name: hide emoticons button. */
private static final String PREFS_HIDE_EMO_BUTTON = "hide_emo_button";
/** Preferemce's name: hide cancel button. */
private static final String PREFS_HIDE_CANCEL_BUTTON = "hide_cancel_button";
/** Cache {@link ConnectorSpec}s. */
private static final String PREFS_CONNECTORS = "connectors";
/** Preference's name: hide ads. */
private static final String PREFS_HIDEADS = "hideads";
/** Preference's name: default recipient. */
private static final String PREFS_DEFAULT_RECIPIENT = "default_recipient";
/** Path to file containing signatures of UID Hash. */
private static final String NOADS_SIGNATURES = "/sdcard/websms.noads";
/** Preference's name: to. */
private static final String PREFS_TO = "to";
/** Preference's name: text. */
private static final String PREFS_TEXT = "text";
/** Preference's name: selected {@link ConnectorSpec} ID. */
private static final String PREFS_CONNECTOR_ID = "connector_id";
/** Preference's name: selected {@link SubConnectorSpec} ID. */
private static final String PREFS_SUBCONNECTOR_ID = "subconnector_id";
/** Sleep before autoexit. */
private static final int SLEEP_BEFORE_EXIT = 75;
/** Buffersize for saving and loading Connectors. */
private static final int BUFSIZE = 4096;
/** Preferences: hide ads. */
private static boolean prefsNoAds = false;
/** Show AdView on top. */
private boolean onTop = false;
/** Hashed IMEI. */
private static String imeiHash = null;
/** Preferences: selected {@link ConnectorSpec}. */
private static ConnectorSpec prefsConnectorSpec = null;
/** Preferences: selected {@link SubConnectorSpec}. */
private static SubConnectorSpec prefsSubConnectorSpec = null;
/** Save prefsConnectorSpec.getPackage() here. */
private static String prefsConnectorID = null;
/** List of available {@link ConnectorSpec}s. */
private static final ArrayList<ConnectorSpec> CONNECTORS = // .
new ArrayList<ConnectorSpec>();
/** Crypto algorithm for signing UID hashs. */
private static final String ALGO = "RSA";
/** Crypto hash algorithm for signing UID hashs. */
private static final String SIGALGO = "SHA1with" + ALGO;
/** My public key for verifying UID hashs. */
private static final String KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNAD"
+ "CBiQKBgQCgnfT4bRMLOv3rV8tpjcEqsNmC1OJaaEYRaTHOCC"
+ "F4sCIZ3pEfDcNmrZZQc9Y0im351ekKOzUzlLLoG09bsaOeMd"
+ "Y89+o2O0mW9NnBch3l8K/uJ3FRn+8Li75SqoTqFj3yCrd9IT"
+ "sOJC7PxcR5TvNpeXsogcyxxo3fMdJdjkafYwIDAQAB";
/** true if preferences got opened. */
static boolean doPreferences = false;
/** Dialog: updates. */
private static final int DIALOG_UPDATE = 2;
/** Dialog: custom sender. */
private static final int DIALOG_CUSTOMSENDER = 3;
/** Dialog: send later: date. */
private static final int DIALOG_SENDLATER_DATE = 4;
/** Dialog: send later: time. */
private static final int DIALOG_SENDLATER_TIME = 5;
/** Dialog: pre donate. */
private static final int DIALOG_PREDONATE = 6;
/** Dialog: post donate. */
private static final int DIALOG_POSTDONATE = 7;
/** Dialog: emo. */
private static final int DIALOG_EMO = 8;
/** {@link Activity} result request. */
private static final int ARESULT_PICK_PHONE = 1;
/** Size of the emoticons png. */
private static final int EMOTICONS_SIZE = 30;
/** Intent's extra for error messages. */
static final String EXTRA_ERRORMESSAGE = // .
"de.ub0r.android.intent.extra.ERRORMESSAGE";
/** Persistent Message store. */
private static String lastMsg = null;
/** Persistent Recipient store. */
private static String lastTo = null;
/** Backup for params: custom sender. */
private static String lastCustomSender = null;
/** Backup for params: send later. */
private static long lastSendLater = -1;
/** {@link MultiAutoCompleteTextView} holding recipients. */
private MultiAutoCompleteTextView etTo;
/** {@link EditText} holding text. */
private EditText etText;
/** {@link TextView} holding balances. */
private TextView tvBalances;
/** {@link View} holding extras. */
private View vExtras;
/** {@link View} holding custom sender. */
private View vCustomSender;
/** {@link View} holding flashsms. */
private View vFlashSMS;
/** {@link View} holding send later. */
private View vSendLater;
/** Text's label. */
private TextView etTextLabel;
/** Show extras. */
private boolean showExtras = false;
/** TextWatcher updating char count on writing. */
private TextWatcher textWatcher = new TextWatcher() {
/**
* {@inheritDoc}
*/
public void afterTextChanged(final Editable s) {
int[] l = SmsMessage.calculateLength(s, false);
WebSMS.this.etTextLabel.setText(l[0] + "/" + l[2]);
}
/** Needed dummy. */
public void beforeTextChanged(final CharSequence s, final int start,
final int count, final int after) {
}
/** Needed dummy. */
public void onTextChanged(final CharSequence s, final int start,
final int before, final int count) {
}
};
/**
* Parse data pushed by {@link Intent}.
*
* @param intent
* {@link Intent}
*/
private void parseIntent(final Intent intent) {
final String action = intent.getAction();
if (action == null) {
return;
}
final Uri uri = intent.getData();
if (uri != null) {
// launched by clicking a sms: link, target number is in URI.
final String scheme = uri.getScheme();
if (scheme != null
&& (scheme.equals("sms") || scheme.equals("smsto"))) {
final String s = uri.getSchemeSpecificPart();
this.parseSchemeSpecificPart(s);
this.displayAds(true);
}
}
final Bundle extras = intent.getExtras();
if (extras != null) {
CharSequence s = extras.getCharSequence(Intent.EXTRA_TEXT);
if (s != null) {
((EditText) this.findViewById(R.id.text)).setText(s);
lastMsg = s.toString();
}
s = extras.getString(EXTRA_ERRORMESSAGE);
if (s != null) {
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
}
}
/**
* parseSchemeSpecificPart from {@link Uri} and initialize WebSMS
* properties.
*
* @param part
* scheme specific part
*/
private void parseSchemeSpecificPart(final String part) {
String s = part;
if (s == null) {
return;
}
s = s.trim();
if (s.endsWith(",")) {
s = s.substring(0, s.length() - 1).trim();
}
if (s.indexOf('<') < 0) {
// try to fetch recipient's name from phonebook
String n = ContactsWrapper.getInstance().getNameForNumber(this, s);
if (n != null) {
s = n + " <" + s + ">, ";
}
}
((EditText) this.findViewById(R.id.to)).setText(s);
lastTo = s;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
// save ref to me.
me = this;
// Restore preferences
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(this);
// inflate XML
this.setContentView(R.layout.main);
this.etTo = (MultiAutoCompleteTextView) this.findViewById(R.id.to);
this.etText = (EditText) this.findViewById(R.id.text);
this.etTextLabel = (TextView) this.findViewById(R.id.text_);
this.tvBalances = (TextView) this.findViewById(R.id.freecount);
this.vExtras = this.findViewById(R.id.extras);
this.vCustomSender = this.findViewById(R.id.custom_sender);
this.vFlashSMS = this.findViewById(R.id.flashsms);
this.vSendLater = this.findViewById(R.id.send_later);
// display changelog?
String v0 = p.getString(PREFS_LAST_RUN, "");
String v1 = this.getString(R.string.app_version);
if (!v0.equals(v1)) {
SharedPreferences.Editor editor = p.edit();
editor.putString(PREFS_LAST_RUN, v1);
editor.remove(PREFS_CONNECTORS); // remove cache
editor.commit();
this.showDialog(DIALOG_UPDATE);
}
v0 = null;
v1 = null;
// get cached Connectors
String s = p.getString(PREFS_CONNECTORS, "");
if (s.length() == 0) {
this.updateConnectors();
} else if (CONNECTORS.size() == 0) {
// skip static remaining connectors
try {
ArrayList<ConnectorSpec> cache;
cache = (ArrayList<ConnectorSpec>) (new ObjectInputStream(
new BufferedInputStream(new ByteArrayInputStream(
Base64Coder.decode(s)), BUFSIZE))).readObject();
CONNECTORS.addAll(cache);
if (p.getBoolean(PREFS_AUTOUPDATE, false)) {
final String defPrefix = p
.getString(PREFS_DEFPREFIX, "+49");
final String defSender = p.getString(PREFS_SENDER, "");
for (ConnectorSpec c : CONNECTORS) {
runCommand(me, c, ConnectorCommand.update(defPrefix,
defSender));
}
}
} catch (Exception e) {
Log.d(TAG, "error loading connectors", e);
}
}
s = null;
Log.d(TAG, "loaded connectors: " + CONNECTORS.size());
this.reloadPrefs();
lastTo = p.getString(PREFS_TO, "");
lastMsg = p.getString(PREFS_TEXT, "");
// register Listener
this.findViewById(R.id.send_).setOnClickListener(this);
this.findViewById(R.id.cancel).setOnClickListener(this);
this.findViewById(R.id.change_connector).setOnClickListener(this);
this.vExtras.setOnClickListener(this);
this.vCustomSender.setOnClickListener(this);
this.vSendLater.setOnClickListener(this);
this.findViewById(R.id.select).setOnClickListener(this);
this.findViewById(R.id.clear).setOnClickListener(this);
this.findViewById(R.id.emo).setOnClickListener(this);
this.tvBalances.setOnClickListener(this);
this.etText.addTextChangedListener(this.textWatcher);
this.etTo.setAdapter(new MobilePhoneAdapter(this));
this.etTo.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
this.etTo.requestFocus();
this.parseIntent(this.getIntent());
// check default prefix
if (!p.getString(PREFS_DEFPREFIX, "").startsWith("+")) {
WebSMS.this.log(R.string.log_wrong_defprefix);
}
}
/**
* {@inheritDoc}
*/
@Override
protected final void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
if (requestCode == ARESULT_PICK_PHONE) {
if (resultCode == RESULT_OK) {
final Uri u = data.getData();
if (u == null) {
return;
}
final String phone = ContactsWrapper.getInstance()
.getNameAndNumber(this, u)
+ ", ";
String t = this.etTo.getText().toString().trim();
if (t.length() == 0) {
t = phone;
} else if (t.endsWith(",")) {
t += " " + phone;
} else {
t += ", " + phone;
}
lastTo = t;
this.etTo.setText(t);
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected final void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
this.parseIntent(intent);
}
/**
* Update {@link ConnectorSpec}s.
*/
private void updateConnectors() {
// query for connectors
final Intent i = new Intent(Connector.ACTION_CONNECTOR_UPDATE);
Log.d(TAG, "send broadcast: " + i.getAction());
this.sendBroadcast(i);
}
/**
* {@inheritDoc}
*/
@Override
protected final void onResume() {
super.onResume();
// set accounts' balance to gui
this.updateBalance();
// if coming from prefs..
if (doPreferences) {
this.reloadPrefs();
this.updateConnectors();
doPreferences = false;
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(this);
final String defPrefix = p.getString(PREFS_DEFPREFIX, "+49");
final String defSender = p.getString(PREFS_SENDER, "");
final ConnectorSpec[] css = getConnectors(
ConnectorSpec.CAPABILITIES_BOOTSTRAP, // .
(short) (ConnectorSpec.STATUS_ENABLED | // .
ConnectorSpec.STATUS_READY));
for (ConnectorSpec cs : css) {
runCommand(this, cs, ConnectorCommand.bootstrap(defPrefix,
defSender));
}
} else {
// check is count of connectors changed
final List<ResolveInfo> ri = this.getPackageManager()
.queryBroadcastReceivers(
new Intent(Connector.ACTION_CONNECTOR_UPDATE), 0);
final int s1 = ri.size();
final int s2 = CONNECTORS.size();
if (s1 != s2) {
Log.d(TAG, "clear connector cache (" + s1 + "/" + s2 + ")");
CONNECTORS.clear();
this.updateConnectors();
}
}
this.setButtons();
if (lastTo == null || lastTo.length() == 0) {
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(this);
lastTo = p.getString(PREFS_DEFAULT_RECIPIENT, null);
}
// reload text/recipient from local store
if (lastMsg != null) {
this.etText.setText(lastMsg);
} else {
this.etText.setText("");
}
if (lastTo != null) {
this.etTo.setText(lastTo);
} else {
this.etTo.setText("");
}
if (lastTo != null && lastTo.length() > 0) {
this.etText.requestFocus();
} else {
this.etTo.requestFocus();
}
}
/**
* Update balance.
*/
private void updateBalance() {
final StringBuilder buf = new StringBuilder();
final ConnectorSpec[] css = getConnectors(
ConnectorSpec.CAPABILITIES_UPDATE, // .
ConnectorSpec.STATUS_ENABLED);
for (ConnectorSpec cs : css) {
final String b = cs.getBalance();
if (b == null || b.length() == 0) {
continue;
}
if (buf.length() > 0) {
buf.append(", ");
}
buf.append(cs.getName());
buf.append(": ");
buf.append(b);
}
this.tvBalances.setText(this.getString(R.string.free_) + " "
+ buf.toString() + " "
+ this.getString(R.string.click_for_update));
}
/**
* {@inheritDoc}
*/
@Override
protected final void onPause() {
super.onPause();
// store input data to persitent stores
lastMsg = this.etText.getText().toString();
lastTo = this.etTo.getText().toString();
// store input data to preferences
final Editor editor = PreferenceManager.getDefaultSharedPreferences(
this).edit();
// common
editor.putString(PREFS_TO, lastTo);
editor.putString(PREFS_TEXT, lastMsg);
// commit changes
editor.commit();
this.savePreferences();
}
@Override
protected final void onDestroy() {
super.onDestroy();
final Editor editor = PreferenceManager.getDefaultSharedPreferences(
this).edit();
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(
new BufferedOutputStream(out, BUFSIZE));
objOut.writeObject(CONNECTORS);
objOut.close();
final String s = String.valueOf(Base64Coder.encode(out
.toByteArray()));
Log.d(TAG, s);
editor.putString(PREFS_CONNECTORS, s);
} catch (IOException e) {
editor.remove(PREFS_CONNECTORS);
Log.e(TAG, "IO", e);
}
editor.commit();
}
/**
* Read static variables holding preferences.
*/
private void reloadPrefs() {
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(this);
final boolean bShowChangeConnector = !p.getBoolean(
PREFS_HIDE_CHANGE_CONNECTOR_BUTTON, false);
final boolean bShowEmoticons = !p.getBoolean(PREFS_HIDE_EMO_BUTTON,
false);
final boolean bShowCancel = !p.getBoolean(PREFS_HIDE_CANCEL_BUTTON,
false);
final boolean bShowClearRecipients = !p.getBoolean(
PREFS_HIDE_CLEAR_RECIPIENTS_BUTTON, false);
final boolean bShowSelectRecipients = !p.getBoolean(
PREFS_HIDE_SELECT_RECIPIENTS_BUTTON, false);
View v = this.findViewById(R.id.select);
if (bShowSelectRecipients) {
v.setVisibility(View.VISIBLE);
} else {
v.setVisibility(View.GONE);
}
v = this.findViewById(R.id.clear);
if (bShowClearRecipients) {
v.setVisibility(View.VISIBLE);
} else {
v.setVisibility(View.GONE);
}
v = this.findViewById(R.id.emo);
if (bShowEmoticons) {
v.setVisibility(View.VISIBLE);
} else {
v.setVisibility(View.GONE);
}
v = this.findViewById(R.id.change_connector);
if (bShowChangeConnector) {
v.setVisibility(View.VISIBLE);
} else {
v.setVisibility(View.GONE);
}
v = this.findViewById(R.id.cancel);
if (bShowCancel) {
v.setVisibility(View.VISIBLE);
} else {
v.setVisibility(View.GONE);
}
prefsConnectorID = p.getString(PREFS_CONNECTOR_ID, "");
prefsConnectorSpec = getConnectorByID(prefsConnectorID);
if (prefsConnectorSpec != null
&& prefsConnectorSpec.hasStatus(ConnectorSpec.STATUS_ENABLED)) {
prefsSubConnectorSpec = prefsConnectorSpec.getSubConnector(p
.getString(PREFS_SUBCONNECTOR_ID, ""));
if (prefsSubConnectorSpec == null) {
prefsSubConnectorSpec = prefsConnectorSpec.// .
getSubConnectors()[0];
}
} else {
ConnectorSpec[] connectors = getConnectors(
ConnectorSpec.CAPABILITIES_SEND,
ConnectorSpec.STATUS_ENABLED);
if (connectors.length == 1) {
prefsConnectorSpec = connectors[0];
prefsSubConnectorSpec = prefsConnectorSpec // .
.getSubConnectors()[0];
Toast.makeText(
this,
this.getString(R.string.connectors_switch) + " "
+ prefsConnectorSpec.getName(),
Toast.LENGTH_LONG).show();
} else {
prefsConnectorSpec = null;
prefsSubConnectorSpec = null;
}
}
MobilePhoneAdapter.setMoileNubersObly(p.getBoolean(PREFS_MOBILES_ONLY,
false));
prefsNoAds = this.hideAds();
this.displayAds(false);
this.setButtons();
}
/**
* Check for signature updates.
*
* @return true if ads should be hidden
*/
private boolean hideAds() {
Log.d(TAG, "hideAds()");
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(this);
final File f = new File(NOADS_SIGNATURES);
try {
if (f.exists()) {
Log.d(TAG, "found file " + NOADS_SIGNATURES);
final BufferedReader br = new BufferedReader(new FileReader(f));
final byte[] publicKey = Base64Coder.decode(KEY);
final KeyFactory keyFactory = KeyFactory.getInstance(ALGO);
PublicKey pk = keyFactory
.generatePublic(new X509EncodedKeySpec(publicKey));
final String h = this.getImeiHash();
Log.d(TAG, "hash: " + h);
boolean ret = false;
while (true) {
String l = br.readLine();
if (l == null) {
Log.d(TAG, "break;");
break;
}
Log.d(TAG, "read line: " + l);
try {
byte[] signature = Base64Coder.decode(l);
Signature sig = Signature.getInstance(SIGALGO);
sig.initVerify(pk);
sig.update(h.getBytes());
ret = sig.verify(signature);
Log.d(TAG, "ret: " + ret);
if (ret) {
break;
}
} catch (IllegalArgumentException e) {
Log.w(TAG, "error reading line", e);
}
}
br.close();
f.delete();
Log.d(TAG, "put: " + ret);
p.edit().putBoolean(PREFS_HIDEADS, ret).commit();
}
} catch (Exception e) {
Log.e(TAG, "error reading signatures", e);
}
Log.d(TAG, "return: " + p.getBoolean(PREFS_HIDEADS, false));
return p.getBoolean(PREFS_HIDEADS, false);
}
/**
* Show/hide, enable/disable send buttons.
*/
private void setButtons() {
if (prefsConnectorSpec != null && prefsSubConnectorSpec != null
&& prefsConnectorSpec.hasStatus(ConnectorSpec.STATUS_ENABLED)) {
final boolean sFlashsms = prefsSubConnectorSpec
.hasFeatures(SubConnectorSpec.FEATURE_FLASHSMS);
final boolean sCustomsender = prefsSubConnectorSpec
.hasFeatures(SubConnectorSpec.FEATURE_CUSTOMSENDER);
final boolean sSendLater = prefsSubConnectorSpec
.hasFeatures(SubConnectorSpec.FEATURE_SENDLATER);
if (sFlashsms || sCustomsender || sSendLater) {
this.vExtras.setVisibility(View.VISIBLE);
} else {
this.vExtras.setVisibility(View.GONE);
}
if (this.showExtras && sFlashsms) {
this.vFlashSMS.setVisibility(View.VISIBLE);
} else {
this.vFlashSMS.setVisibility(View.GONE);
}
if (this.showExtras && sCustomsender) {
this.vCustomSender.setVisibility(View.VISIBLE);
} else {
this.vCustomSender.setVisibility(View.GONE);
}
if (this.showExtras && sSendLater) {
this.vSendLater.setVisibility(View.VISIBLE);
} else {
this.vSendLater.setVisibility(View.GONE);
}
String t = this.getString(R.string.app_name) + " - "
+ prefsConnectorSpec.getName();
if (prefsConnectorSpec.getSubConnectorCount() > 1) {
t += " - " + prefsSubConnectorSpec.getName();
}
this.setTitle(t);
((TextView) this.findViewById(R.id.text_connector))
.setText(prefsConnectorSpec.getName());
((Button) this.findViewById(R.id.send_)).setEnabled(true);
} else {
this.setTitle(R.string.app_name);
((TextView) this.findViewById(R.id.text_connector)).setText("");
((Button) this.findViewById(R.id.send_)).setEnabled(false);
if (getConnectors(0, 0).length != 0) {
Toast.makeText(this, R.string.log_noselectedconnector,
Toast.LENGTH_SHORT).show();
}
}
}
/**
* Resets persistent store.
*/
private void reset() {
this.etText.setText("");
this.etTo.setText("");
lastMsg = null;
lastTo = null;
lastCustomSender = null;
lastSendLater = -1;
// save user preferences
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(this).edit();
editor.putString(PREFS_TO, "");
editor.putString(PREFS_TEXT, "");
// commit changes
editor.commit();
}
/** Save prefs. */
final void savePreferences() {
if (prefsConnectorSpec != null) {
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putString(PREFS_CONNECTOR_ID,
prefsConnectorSpec.getPackage()).commit();
}
}
/**
* Run Connector.doUpdate().
*/
private void updateFreecount() {
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(this);
final String defPrefix = p.getString(PREFS_DEFPREFIX, "+49");
final String defSender = p.getString(PREFS_SENDER, "");
final ConnectorSpec[] css = getConnectors(
ConnectorSpec.CAPABILITIES_UPDATE, // .
(short) (ConnectorSpec.STATUS_ENABLED | // .
ConnectorSpec.STATUS_READY));
for (ConnectorSpec cs : css) {
if (cs.isRunning()) {
// skip running connectors
Log.d(TAG, "skip running connector: " + cs.getName());
continue;
}
runCommand(this, cs, ConnectorCommand.update(defPrefix, defSender));
}
}
/**
* Send a command as broadcast.
*
* @param context
* WebSMS required for performance issues
* @param connector
* {@link ConnectorSpec}
* @param command
* {@link ConnectorCommand}
*/
static final void runCommand(final WebSMS context,
final ConnectorSpec connector, final ConnectorCommand command) {
connector.setErrorMessage((String) null);
final Intent intent = command.setToIntent(null);
short t = command.getType();
switch (t) {
case ConnectorCommand.TYPE_BOOTSTRAP:
intent.setAction(connector.getPackage()
+ Connector.ACTION_RUN_BOOTSTRAP);
connector.addStatus(ConnectorSpec.STATUS_BOOTSTRAPPING);
break;
case ConnectorCommand.TYPE_SEND:
intent.setAction(connector.getPackage() // .
+ Connector.ACTION_RUN_SEND);
connector.setToIntent(intent);
connector.addStatus(ConnectorSpec.STATUS_SENDING);
break;
case ConnectorCommand.TYPE_UPDATE:
intent.setAction(connector.getPackage()
+ Connector.ACTION_RUN_UPDATE);
connector.addStatus(ConnectorSpec.STATUS_UPDATING);
break;
default:
break;
}
if (me != null && (t == ConnectorCommand.TYPE_BOOTSTRAP || // .
t == ConnectorCommand.TYPE_UPDATE)) {
me.setProgressBarIndeterminateVisibility(true);
}
Log.d(TAG, "send broadcast: " + intent.getAction());
context.sendBroadcast(intent);
}
/**
* {@inheritDoc}
*/
public final void onClick(final View v) {
switch (v.getId()) {
case R.id.freecount:
this.updateFreecount();
return;
case R.id.send_:
this.send(prefsConnectorSpec, WebSMS.getSelectedSubConnectorID());
return;
case R.id.cancel:
this.reset();
return;
case R.id.select:
this.startActivityForResult(ContactsWrapper.getInstance()
.getPickPhoneIntent(), ARESULT_PICK_PHONE);
return;
case R.id.clear:
this.etTo.setText("");
lastTo = null;
return;
case R.id.change_connector:
this.changeConnectorMenu();
return;
case R.id.extras:
this.showExtras = !this.showExtras;
this.setButtons();
return;
case R.id.custom_sender:
final CheckBox cs = (CheckBox) this.vCustomSender;
if (cs.isChecked()) {
this.showDialog(DIALOG_CUSTOMSENDER);
} else {
lastCustomSender = null;
}
return;
case R.id.send_later:
final CheckBox sl = (CheckBox) this.vSendLater;
if (sl.isChecked()) {
this.showDialog(DIALOG_SENDLATER_DATE);
} else {
lastSendLater = -1;
}
return;
case R.id.emo:
this.showDialog(DIALOG_EMO);
return;
default:
return;
}
}
/**
* {@inheritDoc}
*/
@Override
public final boolean onCreateOptionsMenu(final Menu menu) {
MenuInflater inflater = this.getMenuInflater();
inflater.inflate(R.menu.menu, menu);
if (prefsNoAds) {
menu.removeItem(R.id.item_donate);
}
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(this);
final boolean bShowSendButton = !p.getBoolean(PREFS_HIDE_SEND_IN_MENU,
false);
if (!bShowSendButton) {
menu.removeItem(R.id.item_send);
}
return true;
}
/**
* Display "change connector" menu.
*/
private void changeConnectorMenu() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_menu_share);
builder.setTitle(R.string.change_connector_);
final ArrayList<String> items = new ArrayList<String>();
final ConnectorSpec[] css = getConnectors(
ConnectorSpec.CAPABILITIES_SEND, ConnectorSpec.STATUS_ENABLED);
SubConnectorSpec[] scs;
String n;
for (ConnectorSpec cs : css) {
scs = cs.getSubConnectors();
if (scs.length <= 1) {
items.add(cs.getName());
} else {
n = cs.getName() + " - ";
for (SubConnectorSpec sc : scs) {
items.add(n + sc.getName());
}
}
}
scs = null;
n = null;
if (items.size() == 0) {
Toast.makeText(this, R.string.log_noreadyconnector,
Toast.LENGTH_LONG).show();
}
builder.setItems(items.toArray(new String[0]),
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface d, // .
final int item) {
final SubConnectorSpec[] ret = ConnectorSpec
.getSubConnectorReturnArray();
prefsConnectorSpec = getConnectorByName(
items.get(item), ret);
prefsSubConnectorSpec = ret[0];
WebSMS.this.setButtons();
// save user preferences
final Editor e = PreferenceManager
.getDefaultSharedPreferences(WebSMS.this)
.edit();
e.putString(PREFS_CONNECTOR_ID, prefsConnectorSpec
.getPackage());
e.putString(PREFS_SUBCONNECTOR_ID,
prefsSubConnectorSpec.getID());
e.commit();
}
});
builder.create().show();
}
/**
* Save some characters by stripping blanks.
*/
private void saveChars() {
String s = this.etText.getText().toString().trim();
if (s.length() == 0 || s.indexOf(" ") < 0) {
return;
}
StringBuilder buf = new StringBuilder();
final String[] ss = s.split(" ");
s = null;
for (String ts : ss) {
final int l = ts.length();
if (l == 0) {
continue;
}
buf.append(Character.toUpperCase(ts.charAt(0)));
if (l == 1) {
continue;
}
buf.append(ts.substring(1));
}
this.etText.setText(buf.toString());
}
/**
*{@inheritDoc}
*/
@Override
public final boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.item_send:
// send by menu item
this.send(prefsConnectorSpec, WebSMS.getSelectedSubConnectorID());
return true;
case R.id.item_savechars:
this.saveChars();
return true;
case R.id.item_settings: // start settings activity
this.startActivity(new Intent(this, Preferences.class));
return true;
case R.id.item_donate:
this.showDialog(DIALOG_PREDONATE);
return true;
case R.id.item_connector:
this.changeConnectorMenu();
return true;
default:
return false;
}
}
/**
* Create a Emoticons {@link Dialog}.
*
* @return Emoticons {@link Dialog}
*/
private Dialog createEmoticonsDialog() {
final Dialog d = new Dialog(this);
d.setTitle(R.string.emo_);
d.setContentView(R.layout.emo);
d.setCancelable(true);
final GridView gridview = (GridView) d.findViewById(R.id.gridview);
gridview.setAdapter(new BaseAdapter() {
// references to our images
private Integer[] mThumbIds = { R.drawable.emo_im_angel,
R.drawable.emo_im_cool, R.drawable.emo_im_crying,
R.drawable.emo_im_foot_in_mouth, R.drawable.emo_im_happy,
R.drawable.emo_im_kissing, R.drawable.emo_im_laughing,
R.drawable.emo_im_lips_are_sealed,
R.drawable.emo_im_money_mouth, R.drawable.emo_im_sad,
R.drawable.emo_im_surprised,
R.drawable.emo_im_tongue_sticking_out,
R.drawable.emo_im_undecided, R.drawable.emo_im_winking,
R.drawable.emo_im_wtf, R.drawable.emo_im_yelling };
@Override
public long getItemId(final int position) {
return 0;
}
@Override
public Object getItem(final int position) {
return null;
}
@Override
public int getCount() {
return this.mThumbIds.length;
}
@Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled,
// initialize some attributes
imageView = new ImageView(WebSMS.this);
imageView.setLayoutParams(new GridView.LayoutParams(
EMOTICONS_SIZE, EMOTICONS_SIZE));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(this.mThumbIds[position]);
return imageView;
}
});
gridview.setOnItemClickListener(new OnItemClickListener() {
/** Emoticon id: angel. */
private static final int EMO_ANGEL = 0;
/** Emoticon id: cool. */
private static final int EMO_COOL = 1;
/** Emoticon id: crying. */
private static final int EMO_CRYING = 2;
/** Emoticon id: foot in mouth. */
private static final int EMO_FOOT_IN_MOUTH = 3;
/** Emoticon id: happy. */
private static final int EMO_HAPPY = 4;
/** Emoticon id: kissing. */
private static final int EMO_KISSING = 5;
/** Emoticon id: laughing. */
private static final int EMO_LAUGHING = 6;
/** Emoticon id: lips are sealed. */
private static final int EMO_LIPS_SEALED = 7;
/** Emoticon id: money. */
private static final int EMO_MONEY = 8;
/** Emoticon id: sad. */
private static final int EMO_SAD = 9;
/** Emoticon id: suprised. */
private static final int EMO_SUPRISED = 10;
/** Emoticon id: tongue sticking out. */
private static final int EMO_TONGUE = 11;
/** Emoticon id: undecided. */
private static final int EMO_UNDICIDED = 12;
/** Emoticon id: winking. */
private static final int EMO_WINKING = 13;
/** Emoticon id: wtf. */
private static final int EMO_WTF = 14;
/** Emoticon id: yell. */
private static final int EMO_YELL = 15;
@Override
public void onItemClick(final AdapterView<?> adapter, final View v,
final int id, final long arg3) {
EditText et = WebSMS.this.etText;
String e = null;
switch (id) {
case EMO_ANGEL:
e = "O:-)";
break;
case EMO_COOL:
e = "8-)";
break;
case EMO_CRYING:
e = ";-)";
break;
case EMO_FOOT_IN_MOUTH:
e = ":-?";
break;
case EMO_HAPPY:
e = ":-)";
break;
case EMO_KISSING:
e = ":-*";
break;
case EMO_LAUGHING:
e = ":-D";
break;
case EMO_LIPS_SEALED:
e = ":-X";
break;
case EMO_MONEY:
e = ":-$";
break;
case EMO_SAD:
e = ":-(";
break;
case EMO_SUPRISED:
e = ":o";
break;
case EMO_TONGUE:
e = ":-P";
break;
case EMO_UNDICIDED:
e = ":-\\";
break;
case EMO_WINKING:
e = ";-)";
break;
case EMO_WTF:
e = "o.O";
break;
case EMO_YELL:
e = ":O";
break;
default:
break;
}
int i = et.getSelectionStart();
int j = et.getSelectionEnd();
+ if (i > j) {
+ int x = i;
+ i = j;
+ j = x;
+ }
String t = et.getText().toString();
StringBuilder buf = new StringBuilder();
buf.append(t.substring(0, i));
buf.append(e);
buf.append(t.substring(j));
et.setText(buf.toString());
et.setSelection(i + e.length());
d.dismiss();
et.requestFocus();
}
});
return d;
}
/**
* {@inheritDoc}
*/
@Override
protected final Dialog onCreateDialog(final int id) {
AlertDialog.Builder builder;
switch (id) {
case DIALOG_PREDONATE:
builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_menu_star);
builder.setTitle(R.string.donate_);
builder.setMessage(R.string.predonate);
builder.setPositiveButton(R.string.donate_,
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int which) {
try {
WebSMS.this.startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse(// .
WebSMS.this.getString(// .
R.string.donate_url))));
} catch (ActivityNotFoundException e) {
Log.e(TAG, "no browser", e);
} finally {
WebSMS.this.showDialog(DIALOG_POSTDONATE);
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
case DIALOG_POSTDONATE:
builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_menu_star);
builder.setTitle(R.string.remove_ads_);
builder.setMessage(R.string.postdonate);
builder.setPositiveButton(R.string.send_,
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int which) {
final Intent in = new Intent(Intent.ACTION_SEND);
in.putExtra(Intent.EXTRA_EMAIL, new String[] {
WebSMS.this.getString(// .
R.string.donate_mail), "" });
// FIXME: "" is a k9 hack. This is fixed in market
// on 26.01.10. wait some more time..
in.putExtra(Intent.EXTRA_TEXT, WebSMS.this
.getImeiHash());
in.putExtra(Intent.EXTRA_SUBJECT, WebSMS.this
.getString(// .
R.string.app_name)
+ " " + WebSMS.this.getString(// .
R.string.donate_subject));
in.setType("text/plain");
WebSMS.this.startActivity(in);
}
});
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
case DIALOG_UPDATE:
builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle(R.string.changelog_);
final String[] changes = this.getResources().getStringArray(
R.array.updates);
final StringBuilder buf = new StringBuilder();
Object o = this.getPackageManager().getLaunchIntentForPackage(
"de.ub0r.android.smsdroid");
if (o == null) {
buf.append(changes[0]);
}
for (int i = 1; i < changes.length; i++) {
buf.append("\n\n");
buf.append(changes[i]);
}
builder.setIcon(android.R.drawable.ic_menu_info_details);
builder.setMessage(buf.toString().trim());
builder.setCancelable(true);
builder.setPositiveButton(android.R.string.ok, null);
if (o == null) {
builder.setNeutralButton("get SMSdroid",
new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface d,
final int which) {
try {
WebSMS.this.startActivity(// .
new Intent(
Intent.ACTION_VIEW,
Uri.parse(// .
"market://search?q=pname:de.ub0r.android.smsdroid")));
} catch (ActivityNotFoundException e) {
Log.e(TAG, "no market", e);
}
}
});
}
return builder.create();
case DIALOG_CUSTOMSENDER:
builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.custom_sender);
builder.setCancelable(true);
final EditText et = new EditText(this);
builder.setView(et);
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int id) {
WebSMS.lastCustomSender = et.getText().toString();
}
});
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
case DIALOG_SENDLATER_DATE:
Calendar c = Calendar.getInstance();
return new DatePickerDialog(this, this, c.get(Calendar.YEAR), c
.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
case DIALOG_SENDLATER_TIME:
c = Calendar.getInstance();
return new MyTimePickerDialog(this, this, c
.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true);
case DIALOG_EMO:
return this.createEmoticonsDialog();
default:
return null;
}
}
/**
* Log text.
*
* @param text
* text as resID
*/
public final void log(final int text) {
this.log(this.getString(text));
}
/**
* Log text.
*
* @param text
* text
*/
public final void log(final String text) {
try {
Toast.makeText(this.getApplicationContext(), text,
Toast.LENGTH_LONG).show();
} catch (RuntimeException e) {
Log.e(TAG, null, e);
}
}
/**
* Show AdView on top or on bottom.
*
* @param top
* display ads on top.
*/
private void displayAds(final boolean top) {
if (prefsNoAds) {
// do not display any ads for donators
return;
}
if (top) {
// switch to AdView on top
this.onTop = true;
}
if (this.onTop) {
Log.d(TAG, "display ads on top");
this.findViewById(R.id.ad).setVisibility(View.VISIBLE);
this.findViewById(R.id.ad_bottom).setVisibility(View.GONE);
} else {
Log.d(TAG, "display ads on bottom");
this.findViewById(R.id.ad).setVisibility(View.GONE);
this.findViewById(R.id.ad_bottom).setVisibility(View.VISIBLE);
}
}
/**
* Send text.
*
* @param connector
* which connector should be used.
* @param subconnector
* selected {@link SubConnectorSpec} ID
*/
private void send(final ConnectorSpec connector, // .
final String subconnector) {
// fetch text/recipient
final String to = this.etTo.getText().toString();
final String text = this.etText.getText().toString();
if (to.length() == 0 || text.length() == 0) {
return;
}
this.displayAds(true);
CheckBox v = (CheckBox) this.findViewById(R.id.flashsms);
final boolean flashSMS = (v.getVisibility() == View.VISIBLE)
&& v.isEnabled() && v.isChecked();
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(this);
final String defPrefix = p.getString(PREFS_DEFPREFIX, "+49");
final String defSender = p.getString(PREFS_SENDER, "");
final String[] tos = Utils.parseRecipients(to);
final ConnectorCommand command = ConnectorCommand.send(subconnector,
defPrefix, defSender, tos, text, flashSMS);
command.setCustomSender(lastCustomSender);
command.setSendLater(lastSendLater);
try {
if (connector.getSubConnector(subconnector).hasFeatures(
SubConnectorSpec.FEATURE_MULTIRECIPIENTS)
|| tos.length == 1) {
runCommand(this, connector, command);
} else {
ConnectorCommand cc;
for (String t : tos) {
if (t.trim().length() < 1) {
continue;
}
cc = (ConnectorCommand) command.clone();
cc.setRecipients(t);
runCommand(this, connector, cc);
}
}
} catch (Exception e) {
Log.e(TAG, null, e);
} finally {
this.reset();
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
PREFS_AUTOEXIT, false)) {
try {
Thread.sleep(SLEEP_BEFORE_EXIT);
} catch (InterruptedException e) {
Log.e(TAG, null, e);
}
this.finish();
}
}
}
/**
* @return ID of selected {@link SubConnectorSpec}
*/
private static String getSelectedSubConnectorID() {
if (prefsSubConnectorSpec == null) {
return null;
}
return prefsSubConnectorSpec.getID();
}
/**
* A Date was set.
*
* @param view
* DatePicker View
* @param year
* year set
* @param monthOfYear
* month set
* @param dayOfMonth
* day set
*/
public final void onDateSet(final DatePicker view, final int year,
final int monthOfYear, final int dayOfMonth) {
final Calendar c = Calendar.getInstance();
if (lastSendLater > 0) {
c.setTimeInMillis(lastSendLater);
}
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, monthOfYear);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
lastSendLater = c.getTimeInMillis();
MyTimePickerDialog.setOnlyQuaters(prefsSubConnectorSpec
.hasFeatures(SubConnectorSpec.FEATURE_SENDLATER_QUARTERS));
this.showDialog(DIALOG_SENDLATER_TIME);
}
/**
* A Time was set.
*
* @param view
* TimePicker View
* @param hour
* hour set
* @param minutes
* minutes set
*/
public final void onTimeSet(final TimePicker view, final int hour,
final int minutes) {
if (prefsSubConnectorSpec
.hasFeatures(SubConnectorSpec.FEATURE_SENDLATER_QUARTERS)
&& minutes % 15 != 0) {
Toast.makeText(this, R.string.error_sendlater_quater,
Toast.LENGTH_LONG).show();
return;
}
final Calendar c = Calendar.getInstance();
if (lastSendLater > 0) {
c.setTimeInMillis(lastSendLater);
}
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minutes);
lastSendLater = c.getTimeInMillis();
}
/**
* Get MD5 hash of the IMEI (device id).
*
* @return MD5 hash of IMEI
*/
private String getImeiHash() {
if (imeiHash == null) {
// get imei
TelephonyManager mTelephonyMgr = (TelephonyManager) this
.getSystemService(TELEPHONY_SERVICE);
final String did = mTelephonyMgr.getDeviceId();
if (did != null) {
imeiHash = Utils.md5(did);
}
}
return imeiHash;
}
/**
* Add or update a {@link ConnectorSpec}.
*
* @param connector
* connector
*/
static final void addConnector(final ConnectorSpec connector) {
synchronized (CONNECTORS) {
if (connector == null || connector.getPackage() == null
|| connector.getName() == null) {
return;
}
ConnectorSpec c = getConnectorByID(connector.getPackage());
if (c != null) {
c.setErrorMessage((String) null); // fix sticky error status
c.update(connector);
} else {
final String name = connector.getName();
if (connector.getSubConnectorCount() == 0 || name == null
|| connector.getPackage() == null) {
Log.w(TAG, "skipped adding defect connector: " + name);
return;
}
Log.d(TAG, "add connector with id: " + connector.getPackage());
Log.d(TAG, "add connector with name: " + name);
boolean added = false;
final int l = CONNECTORS.size();
ConnectorSpec cs;
try {
for (int i = 0; i < l; i++) {
cs = CONNECTORS.get(i);
if (name.compareToIgnoreCase(cs.getName()) < 0) {
CONNECTORS.add(i, connector);
added = true;
break;
}
}
} catch (NullPointerException e) {
Log.e(TAG, "error while sorting", e);
}
if (!added) {
CONNECTORS.add(connector);
}
c = connector;
if (me != null) {
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(me);
// update connectors balance if needed
if (c.getBalance() == null && c.isReady() && !c.isRunning()
&& c.hasCapabilities(// .
ConnectorSpec.CAPABILITIES_UPDATE)
&& p.getBoolean(PREFS_AUTOUPDATE, false)) {
final String defPrefix = p.getString(PREFS_DEFPREFIX,
"+49");
final String defSender = p.getString(PREFS_SENDER, "");
runCommand(me, c, ConnectorCommand.update(defPrefix,
defSender));
}
}
}
if (me != null) {
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(me);
if (prefsConnectorSpec == null
&& prefsConnectorID.equals(connector.getPackage())) {
prefsConnectorSpec = connector;
prefsSubConnectorSpec = connector.getSubConnector(p
.getString(PREFS_SUBCONNECTOR_ID, ""));
me.setButtons();
}
final String b = c.getBalance();
final String ob = c.getOldBalance();
if (b != null && (ob == null || !b.equals(ob))) {
me.updateBalance();
}
boolean runningConnectors = getConnectors(
ConnectorSpec.CAPABILITIES_UPDATE,
ConnectorSpec.STATUS_ENABLED
| ConnectorSpec.STATUS_UPDATING).length != 0;
if (!runningConnectors) {
runningConnectors = getConnectors(
ConnectorSpec.CAPABILITIES_BOOTSTRAP,
ConnectorSpec.STATUS_ENABLED
| ConnectorSpec.STATUS_BOOTSTRAPPING).// .
length != 0;
}
me.setProgressBarIndeterminateVisibility(runningConnectors);
if (prefsConnectorSpec != null && // .
prefsConnectorSpec.equals(c)) {
me.setButtons();
}
}
}
}
/**
* Get {@link ConnectorSpec} by ID.
*
* @param id
* ID
* @return {@link ConnectorSpec}
*/
private static ConnectorSpec getConnectorByID(final String id) {
synchronized (CONNECTORS) {
if (id == null) {
return null;
}
final int l = CONNECTORS.size();
ConnectorSpec c;
for (int i = 0; i < l; i++) {
c = CONNECTORS.get(i);
if (id.equals(c.getPackage())) {
return c;
}
}
}
return null;
}
/**
* Get {@link ConnectorSpec} by name.
*
* @param name
* name
* @param returnSelectedSubConnector
* if not null, array[0] will be set to selected
* {@link SubConnectorSpec}
* @return {@link ConnectorSpec}
*/
private static ConnectorSpec getConnectorByName(final String name,
final SubConnectorSpec[] returnSelectedSubConnector) {
synchronized (CONNECTORS) {
if (name == null) {
return null;
}
final int l = CONNECTORS.size();
ConnectorSpec c;
String n;
SubConnectorSpec[] scs;
for (int i = 0; i < l; i++) {
c = CONNECTORS.get(i);
n = c.getName();
if (name.startsWith(n)) {
if (name.length() == n.length()) {
if (returnSelectedSubConnector != null) {
returnSelectedSubConnector[0] = c
.getSubConnectors()[0];
}
return c;
} else if (returnSelectedSubConnector != null) {
scs = c.getSubConnectors();
if (scs == null || scs.length == 0) {
continue;
}
for (SubConnectorSpec sc : scs) {
if (name.endsWith(sc.getName())) {
returnSelectedSubConnector[0] = sc;
return c;
}
}
}
}
}
}
return null;
}
/**
* Get {@link ConnectorSpec}s by capabilities and/or status.
*
* @param capabilities
* capabilities needed
* @param status
* status required {@link SubConnectorSpec}
* @return {@link ConnectorSpec}s
*/
static final ConnectorSpec[] getConnectors(final int capabilities,
final int status) {
synchronized (CONNECTORS) {
final ArrayList<ConnectorSpec> ret = new ArrayList<ConnectorSpec>(
CONNECTORS.size());
final int l = CONNECTORS.size();
ConnectorSpec c;
for (int i = 0; i < l; i++) {
c = CONNECTORS.get(i);
if (c.hasCapabilities((short) capabilities)
&& c.hasStatus((short) status)) {
ret.add(c);
}
}
return ret.toArray(new ConnectorSpec[0]);
}
}
}
| true | true | private Dialog createEmoticonsDialog() {
final Dialog d = new Dialog(this);
d.setTitle(R.string.emo_);
d.setContentView(R.layout.emo);
d.setCancelable(true);
final GridView gridview = (GridView) d.findViewById(R.id.gridview);
gridview.setAdapter(new BaseAdapter() {
// references to our images
private Integer[] mThumbIds = { R.drawable.emo_im_angel,
R.drawable.emo_im_cool, R.drawable.emo_im_crying,
R.drawable.emo_im_foot_in_mouth, R.drawable.emo_im_happy,
R.drawable.emo_im_kissing, R.drawable.emo_im_laughing,
R.drawable.emo_im_lips_are_sealed,
R.drawable.emo_im_money_mouth, R.drawable.emo_im_sad,
R.drawable.emo_im_surprised,
R.drawable.emo_im_tongue_sticking_out,
R.drawable.emo_im_undecided, R.drawable.emo_im_winking,
R.drawable.emo_im_wtf, R.drawable.emo_im_yelling };
@Override
public long getItemId(final int position) {
return 0;
}
@Override
public Object getItem(final int position) {
return null;
}
@Override
public int getCount() {
return this.mThumbIds.length;
}
@Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled,
// initialize some attributes
imageView = new ImageView(WebSMS.this);
imageView.setLayoutParams(new GridView.LayoutParams(
EMOTICONS_SIZE, EMOTICONS_SIZE));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(this.mThumbIds[position]);
return imageView;
}
});
gridview.setOnItemClickListener(new OnItemClickListener() {
/** Emoticon id: angel. */
private static final int EMO_ANGEL = 0;
/** Emoticon id: cool. */
private static final int EMO_COOL = 1;
/** Emoticon id: crying. */
private static final int EMO_CRYING = 2;
/** Emoticon id: foot in mouth. */
private static final int EMO_FOOT_IN_MOUTH = 3;
/** Emoticon id: happy. */
private static final int EMO_HAPPY = 4;
/** Emoticon id: kissing. */
private static final int EMO_KISSING = 5;
/** Emoticon id: laughing. */
private static final int EMO_LAUGHING = 6;
/** Emoticon id: lips are sealed. */
private static final int EMO_LIPS_SEALED = 7;
/** Emoticon id: money. */
private static final int EMO_MONEY = 8;
/** Emoticon id: sad. */
private static final int EMO_SAD = 9;
/** Emoticon id: suprised. */
private static final int EMO_SUPRISED = 10;
/** Emoticon id: tongue sticking out. */
private static final int EMO_TONGUE = 11;
/** Emoticon id: undecided. */
private static final int EMO_UNDICIDED = 12;
/** Emoticon id: winking. */
private static final int EMO_WINKING = 13;
/** Emoticon id: wtf. */
private static final int EMO_WTF = 14;
/** Emoticon id: yell. */
private static final int EMO_YELL = 15;
@Override
public void onItemClick(final AdapterView<?> adapter, final View v,
final int id, final long arg3) {
EditText et = WebSMS.this.etText;
String e = null;
switch (id) {
case EMO_ANGEL:
e = "O:-)";
break;
case EMO_COOL:
e = "8-)";
break;
case EMO_CRYING:
e = ";-)";
break;
case EMO_FOOT_IN_MOUTH:
e = ":-?";
break;
case EMO_HAPPY:
e = ":-)";
break;
case EMO_KISSING:
e = ":-*";
break;
case EMO_LAUGHING:
e = ":-D";
break;
case EMO_LIPS_SEALED:
e = ":-X";
break;
case EMO_MONEY:
e = ":-$";
break;
case EMO_SAD:
e = ":-(";
break;
case EMO_SUPRISED:
e = ":o";
break;
case EMO_TONGUE:
e = ":-P";
break;
case EMO_UNDICIDED:
e = ":-\\";
break;
case EMO_WINKING:
e = ";-)";
break;
case EMO_WTF:
e = "o.O";
break;
case EMO_YELL:
e = ":O";
break;
default:
break;
}
int i = et.getSelectionStart();
int j = et.getSelectionEnd();
String t = et.getText().toString();
StringBuilder buf = new StringBuilder();
buf.append(t.substring(0, i));
buf.append(e);
buf.append(t.substring(j));
et.setText(buf.toString());
et.setSelection(i + e.length());
d.dismiss();
et.requestFocus();
}
});
return d;
}
| private Dialog createEmoticonsDialog() {
final Dialog d = new Dialog(this);
d.setTitle(R.string.emo_);
d.setContentView(R.layout.emo);
d.setCancelable(true);
final GridView gridview = (GridView) d.findViewById(R.id.gridview);
gridview.setAdapter(new BaseAdapter() {
// references to our images
private Integer[] mThumbIds = { R.drawable.emo_im_angel,
R.drawable.emo_im_cool, R.drawable.emo_im_crying,
R.drawable.emo_im_foot_in_mouth, R.drawable.emo_im_happy,
R.drawable.emo_im_kissing, R.drawable.emo_im_laughing,
R.drawable.emo_im_lips_are_sealed,
R.drawable.emo_im_money_mouth, R.drawable.emo_im_sad,
R.drawable.emo_im_surprised,
R.drawable.emo_im_tongue_sticking_out,
R.drawable.emo_im_undecided, R.drawable.emo_im_winking,
R.drawable.emo_im_wtf, R.drawable.emo_im_yelling };
@Override
public long getItemId(final int position) {
return 0;
}
@Override
public Object getItem(final int position) {
return null;
}
@Override
public int getCount() {
return this.mThumbIds.length;
}
@Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled,
// initialize some attributes
imageView = new ImageView(WebSMS.this);
imageView.setLayoutParams(new GridView.LayoutParams(
EMOTICONS_SIZE, EMOTICONS_SIZE));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(this.mThumbIds[position]);
return imageView;
}
});
gridview.setOnItemClickListener(new OnItemClickListener() {
/** Emoticon id: angel. */
private static final int EMO_ANGEL = 0;
/** Emoticon id: cool. */
private static final int EMO_COOL = 1;
/** Emoticon id: crying. */
private static final int EMO_CRYING = 2;
/** Emoticon id: foot in mouth. */
private static final int EMO_FOOT_IN_MOUTH = 3;
/** Emoticon id: happy. */
private static final int EMO_HAPPY = 4;
/** Emoticon id: kissing. */
private static final int EMO_KISSING = 5;
/** Emoticon id: laughing. */
private static final int EMO_LAUGHING = 6;
/** Emoticon id: lips are sealed. */
private static final int EMO_LIPS_SEALED = 7;
/** Emoticon id: money. */
private static final int EMO_MONEY = 8;
/** Emoticon id: sad. */
private static final int EMO_SAD = 9;
/** Emoticon id: suprised. */
private static final int EMO_SUPRISED = 10;
/** Emoticon id: tongue sticking out. */
private static final int EMO_TONGUE = 11;
/** Emoticon id: undecided. */
private static final int EMO_UNDICIDED = 12;
/** Emoticon id: winking. */
private static final int EMO_WINKING = 13;
/** Emoticon id: wtf. */
private static final int EMO_WTF = 14;
/** Emoticon id: yell. */
private static final int EMO_YELL = 15;
@Override
public void onItemClick(final AdapterView<?> adapter, final View v,
final int id, final long arg3) {
EditText et = WebSMS.this.etText;
String e = null;
switch (id) {
case EMO_ANGEL:
e = "O:-)";
break;
case EMO_COOL:
e = "8-)";
break;
case EMO_CRYING:
e = ";-)";
break;
case EMO_FOOT_IN_MOUTH:
e = ":-?";
break;
case EMO_HAPPY:
e = ":-)";
break;
case EMO_KISSING:
e = ":-*";
break;
case EMO_LAUGHING:
e = ":-D";
break;
case EMO_LIPS_SEALED:
e = ":-X";
break;
case EMO_MONEY:
e = ":-$";
break;
case EMO_SAD:
e = ":-(";
break;
case EMO_SUPRISED:
e = ":o";
break;
case EMO_TONGUE:
e = ":-P";
break;
case EMO_UNDICIDED:
e = ":-\\";
break;
case EMO_WINKING:
e = ";-)";
break;
case EMO_WTF:
e = "o.O";
break;
case EMO_YELL:
e = ":O";
break;
default:
break;
}
int i = et.getSelectionStart();
int j = et.getSelectionEnd();
if (i > j) {
int x = i;
i = j;
j = x;
}
String t = et.getText().toString();
StringBuilder buf = new StringBuilder();
buf.append(t.substring(0, i));
buf.append(e);
buf.append(t.substring(j));
et.setText(buf.toString());
et.setSelection(i + e.length());
d.dismiss();
et.requestFocus();
}
});
return d;
}
|
diff --git a/src/java/org/apache/cassandra/io/compress/CompressedSequentialWriter.java b/src/java/org/apache/cassandra/io/compress/CompressedSequentialWriter.java
index f9af7489..af8ec26d 100644
--- a/src/java/org/apache/cassandra/io/compress/CompressedSequentialWriter.java
+++ b/src/java/org/apache/cassandra/io/compress/CompressedSequentialWriter.java
@@ -1,208 +1,208 @@
/**
* 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.cassandra.io.compress;
import java.io.File;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import org.apache.cassandra.io.util.FileMark;
import org.apache.cassandra.io.util.SequentialWriter;
import org.xerial.snappy.Snappy;
public class CompressedSequentialWriter extends SequentialWriter
{
public static final int CHUNK_LENGTH = 65536;
public static SequentialWriter open(String dataFilePath, String indexFilePath, boolean skipIOCache) throws IOException
{
return new CompressedSequentialWriter(new File(dataFilePath), indexFilePath, skipIOCache);
}
// holds offset in the file where current chunk should be written
// changed only by flush() method where data buffer gets compressed and stored to the file
private long chunkOffset = 0;
// index file writer (random I/O)
private final CompressionMetadata.Writer metadataWriter;
// used to store compressed data
private final byte[] compressed;
// holds a number of already written chunks
private int chunkCount = 0;
private final Checksum checksum = new CRC32();
public CompressedSequentialWriter(File file, String indexFilePath, boolean skipIOCache) throws IOException
{
super(file, CHUNK_LENGTH, skipIOCache);
// buffer for compression should be the same size as buffer itself
compressed = new byte[Snappy.maxCompressedLength(buffer.length)];
/* Index File (-CompressionInfo.db component) and it's header */
metadataWriter = new CompressionMetadata.Writer(indexFilePath);
metadataWriter.writeHeader(Snappy.class.getSimpleName(), CHUNK_LENGTH);
}
@Override
public void sync() throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public void flush() throws IOException
{
throw new UnsupportedOperationException();
}
@Override
protected void flushData() throws IOException
{
seekToChunkStart();
// compressing data with buffer re-use
int compressedLength = Snappy.rawCompress(buffer, 0, validBufferBytes, compressed, 0);
// update checksum
checksum.update(buffer, 0, validBufferBytes);
// write an offset of the newly written chunk to the index file
metadataWriter.writeLong(chunkOffset);
chunkCount++;
assert compressedLength <= compressed.length;
// write data itself
out.write(compressed, 0, compressedLength);
// write corresponding checksum
out.writeInt((int) checksum.getValue());
// reset checksum object to the blank state for re-use
checksum.reset();
// next chunk should be written right after current + length of the checksum (int)
chunkOffset += compressedLength + 4;
}
@Override
public FileMark mark()
{
return new CompressedFileWriterMark(chunkOffset, current, validBufferBytes, chunkCount + 1);
}
@Override
public synchronized void resetAndTruncate(FileMark mark) throws IOException
{
assert mark instanceof CompressedFileWriterMark;
CompressedFileWriterMark realMark = ((CompressedFileWriterMark) mark);
// reset position
current = realMark.uncDataOffset;
if (realMark.chunkOffset == chunkOffset) // current buffer
{
// just reset a buffer offset and return
validBufferBytes = realMark.bufferOffset;
return;
}
// synchronize current buffer with disk
// because we don't want any data loss
syncInternal();
// setting marker as a current offset
chunkOffset = realMark.chunkOffset;
// compressed chunk size (- 4 bytes reserved for checksum)
int chunkSize = (int) (metadataWriter.chunkOffsetBy(realMark.nextChunkIndex) - chunkOffset - 4);
out.seek(chunkOffset);
- out.read(compressed, 0, chunkSize);
+ out.readFully(compressed, 0, chunkSize);
// decompress data chunk and store its length
int validBytes = Snappy.rawUncompress(compressed, 0, chunkSize, buffer, 0);
checksum.update(buffer, 0, validBytes);
if (out.readInt() != (int) checksum.getValue())
throw new CorruptedBlockException(getPath(), chunkOffset, chunkSize);
checksum.reset();
// reset buffer
validBufferBytes = realMark.bufferOffset;
bufferOffset = current - validBufferBytes;
chunkCount = realMark.nextChunkIndex - 1;
// truncate data and index file
truncate(chunkOffset);
metadataWriter.resetAndTruncate(realMark.nextChunkIndex);
}
/**
* Seek to the offset where next compressed data chunk should be stored.
*
* @throws IOException on any I/O error.
*/
private void seekToChunkStart() throws IOException
{
if (out.getFilePointer() != chunkOffset)
out.seek(chunkOffset);
}
@Override
public void close() throws IOException
{
if (buffer == null)
return; // already closed
super.close();
metadataWriter.finalizeHeader(current, chunkCount);
metadataWriter.close();
}
/**
* Class to hold a mark to the position of the file
*/
protected static class CompressedFileWriterMark implements FileMark
{
// chunk offset in the compressed file
long chunkOffset;
// uncompressed data offset (real data offset)
long uncDataOffset;
int bufferOffset;
int nextChunkIndex;
public CompressedFileWriterMark(long chunkOffset, long uncDataOffset, int bufferOffset, int nextChunkIndex)
{
this.chunkOffset = chunkOffset;
this.uncDataOffset = uncDataOffset;
this.bufferOffset = bufferOffset;
this.nextChunkIndex = nextChunkIndex;
}
}
}
| true | true | public synchronized void resetAndTruncate(FileMark mark) throws IOException
{
assert mark instanceof CompressedFileWriterMark;
CompressedFileWriterMark realMark = ((CompressedFileWriterMark) mark);
// reset position
current = realMark.uncDataOffset;
if (realMark.chunkOffset == chunkOffset) // current buffer
{
// just reset a buffer offset and return
validBufferBytes = realMark.bufferOffset;
return;
}
// synchronize current buffer with disk
// because we don't want any data loss
syncInternal();
// setting marker as a current offset
chunkOffset = realMark.chunkOffset;
// compressed chunk size (- 4 bytes reserved for checksum)
int chunkSize = (int) (metadataWriter.chunkOffsetBy(realMark.nextChunkIndex) - chunkOffset - 4);
out.seek(chunkOffset);
out.read(compressed, 0, chunkSize);
// decompress data chunk and store its length
int validBytes = Snappy.rawUncompress(compressed, 0, chunkSize, buffer, 0);
checksum.update(buffer, 0, validBytes);
if (out.readInt() != (int) checksum.getValue())
throw new CorruptedBlockException(getPath(), chunkOffset, chunkSize);
checksum.reset();
// reset buffer
validBufferBytes = realMark.bufferOffset;
bufferOffset = current - validBufferBytes;
chunkCount = realMark.nextChunkIndex - 1;
// truncate data and index file
truncate(chunkOffset);
metadataWriter.resetAndTruncate(realMark.nextChunkIndex);
}
| public synchronized void resetAndTruncate(FileMark mark) throws IOException
{
assert mark instanceof CompressedFileWriterMark;
CompressedFileWriterMark realMark = ((CompressedFileWriterMark) mark);
// reset position
current = realMark.uncDataOffset;
if (realMark.chunkOffset == chunkOffset) // current buffer
{
// just reset a buffer offset and return
validBufferBytes = realMark.bufferOffset;
return;
}
// synchronize current buffer with disk
// because we don't want any data loss
syncInternal();
// setting marker as a current offset
chunkOffset = realMark.chunkOffset;
// compressed chunk size (- 4 bytes reserved for checksum)
int chunkSize = (int) (metadataWriter.chunkOffsetBy(realMark.nextChunkIndex) - chunkOffset - 4);
out.seek(chunkOffset);
out.readFully(compressed, 0, chunkSize);
// decompress data chunk and store its length
int validBytes = Snappy.rawUncompress(compressed, 0, chunkSize, buffer, 0);
checksum.update(buffer, 0, validBytes);
if (out.readInt() != (int) checksum.getValue())
throw new CorruptedBlockException(getPath(), chunkOffset, chunkSize);
checksum.reset();
// reset buffer
validBufferBytes = realMark.bufferOffset;
bufferOffset = current - validBufferBytes;
chunkCount = realMark.nextChunkIndex - 1;
// truncate data and index file
truncate(chunkOffset);
metadataWriter.resetAndTruncate(realMark.nextChunkIndex);
}
|
diff --git a/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsPacketRecordReader.java b/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsPacketRecordReader.java
index 98de335..63cffef 100644
--- a/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsPacketRecordReader.java
+++ b/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsPacketRecordReader.java
@@ -1,169 +1,169 @@
package com.packetloop.packetpig.loaders.pcap.packet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.krakenapps.pcap.decoder.ethernet.EthernetType;
import org.krakenapps.pcap.decoder.ip.InternetProtocol;
import org.krakenapps.pcap.decoder.ip.IpDecoder;
import org.krakenapps.pcap.decoder.ip.Ipv4Packet;
import org.krakenapps.pcap.decoder.udp.UdpDecoder;
import org.krakenapps.pcap.decoder.udp.UdpPacket;
import org.krakenapps.pcap.decoder.udp.UdpPortProtocolMapper;
import org.krakenapps.pcap.decoder.udp.UdpProcessor;
import org.krakenapps.pcap.packet.PcapPacket;
import org.krakenapps.pcap.util.Buffer;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.Flags;
import org.xbill.DNS.Message;
import org.xbill.DNS.Record;
import org.xbill.DNS.Section;
import com.packetloop.packetpig.loaders.pcap.PcapRecordReader;
public class DnsPacketRecordReader extends PcapRecordReader {
private ArrayList<Tuple> tupleQueue;
volatile String srcIP;
volatile String dstIP;
volatile int srcPort;
volatile int dstPort;
volatile boolean valid = false;
volatile Message dns;
@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
super.initialize(split, context);
tupleQueue = new ArrayList<Tuple>();
IpDecoder ipDecoder = new IpDecoder();
UdpProcessor udpProcessor = new UdpProcessor() {
@Override
public void process(UdpPacket p) {
try {
Buffer buf = p.getData();
byte[] data = new byte[buf.readableBytes()];
buf.gets(data);
dns = new Message(data);
valid = true;
dstPort = p.getDestinationPort();
srcPort = p.getSourcePort();
} catch (IOException e) {
e.printStackTrace();
clear();
}
}
};
UdpDecoder udpDecoder = new UdpDecoder(new UdpPortProtocolMapper()) {
@Override
public void process(Ipv4Packet packet) {
super.process(packet);
srcIP = packet.getSourceAddress().getHostAddress();
dstIP = packet.getDestinationAddress().getHostAddress();
}
};
udpDecoder.registerUdpProcessor(udpProcessor);
eth.register(EthernetType.IPV4, ipDecoder);
ipDecoder.register(InternetProtocol.UDP, udpDecoder);
}
private void clear()
{
valid = false;
srcIP = null;
dstIP = null;
srcPort = -1;
dstPort = -1;
dns = null;
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
try {
// keep going until the decoder says it found a good one.
PcapPacket packet = null;
do
{
packet = is.getPacket();
eth.decode(packet);
}
while(!valid);
long tv_sec = packet.getPacketHeader().getTsSec();
long tv_usec = packet.getPacketHeader().getTsUsec();
long ts = tv_sec * 1000 + tv_usec / 1000;
key = new Date(ts).getTime() / 1000;
int id = dns.getHeader().getID();
- String mode = dns.getHeader().getFlag(Flags.QR)?"question":"response";
+ String mode = dns.getHeader().getFlag(Flags.QR)?"response":"question";
for(Record rec : dns.getSectionArray(Section.QUESTION))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(5);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
t.set(i++, null); // answer.ip OR null (for ques)
t.set(i++, 0); // qttl
tupleQueue.add(t);
}
for(Record rec : dns.getSectionArray(Section.ANSWER))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(5);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
if (rec instanceof ARecord) {
t.set(i++, ((ARecord)rec).getAddress().getHostAddress()); // answer.ip OR null
}else {
t.set(i++, null);
}
t.set(i++, rec.getTTL()); // qttl
tupleQueue.add(t);
}
clear();
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
else
{
clear();
is.close();
return false;
}
} catch (IOException ignored) {
ignored.printStackTrace();
clear();
is.close();
return false;
}
}
@Override
public void close() throws IOException {
super.close();
is.close();
}
}
| true | true | public boolean nextKeyValue() throws IOException, InterruptedException {
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
try {
// keep going until the decoder says it found a good one.
PcapPacket packet = null;
do
{
packet = is.getPacket();
eth.decode(packet);
}
while(!valid);
long tv_sec = packet.getPacketHeader().getTsSec();
long tv_usec = packet.getPacketHeader().getTsUsec();
long ts = tv_sec * 1000 + tv_usec / 1000;
key = new Date(ts).getTime() / 1000;
int id = dns.getHeader().getID();
String mode = dns.getHeader().getFlag(Flags.QR)?"question":"response";
for(Record rec : dns.getSectionArray(Section.QUESTION))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(5);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
t.set(i++, null); // answer.ip OR null (for ques)
t.set(i++, 0); // qttl
tupleQueue.add(t);
}
for(Record rec : dns.getSectionArray(Section.ANSWER))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(5);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
if (rec instanceof ARecord) {
t.set(i++, ((ARecord)rec).getAddress().getHostAddress()); // answer.ip OR null
}else {
t.set(i++, null);
}
t.set(i++, rec.getTTL()); // qttl
tupleQueue.add(t);
}
clear();
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
else
{
clear();
is.close();
return false;
}
} catch (IOException ignored) {
ignored.printStackTrace();
clear();
is.close();
return false;
}
}
| public boolean nextKeyValue() throws IOException, InterruptedException {
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
try {
// keep going until the decoder says it found a good one.
PcapPacket packet = null;
do
{
packet = is.getPacket();
eth.decode(packet);
}
while(!valid);
long tv_sec = packet.getPacketHeader().getTsSec();
long tv_usec = packet.getPacketHeader().getTsUsec();
long ts = tv_sec * 1000 + tv_usec / 1000;
key = new Date(ts).getTime() / 1000;
int id = dns.getHeader().getID();
String mode = dns.getHeader().getFlag(Flags.QR)?"response":"question";
for(Record rec : dns.getSectionArray(Section.QUESTION))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(5);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
t.set(i++, null); // answer.ip OR null (for ques)
t.set(i++, 0); // qttl
tupleQueue.add(t);
}
for(Record rec : dns.getSectionArray(Section.ANSWER))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(5);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
if (rec instanceof ARecord) {
t.set(i++, ((ARecord)rec).getAddress().getHostAddress()); // answer.ip OR null
}else {
t.set(i++, null);
}
t.set(i++, rec.getTTL()); // qttl
tupleQueue.add(t);
}
clear();
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
else
{
clear();
is.close();
return false;
}
} catch (IOException ignored) {
ignored.printStackTrace();
clear();
is.close();
return false;
}
}
|
diff --git a/app/controllers/AdminCategories.java b/app/controllers/AdminCategories.java
index de9397e..7212e07 100644
--- a/app/controllers/AdminCategories.java
+++ b/app/controllers/AdminCategories.java
@@ -1,114 +1,114 @@
package controllers;
import java.util.List;
import models.Category;
import models.Module;
import play.data.validation.MaxSize;
import play.data.validation.Required;
import play.data.validation.Validation;
import util.Util;
@Check("admin")
public class AdminCategories extends LoggedInController {
public static void index() {
List<Category> categories = Category.allCategories();
render(categories);
}
public static void addForm() {
render();
}
public static void add(@Required @MaxSize(Util.VARCHAR_SIZE) String name,
@MaxSize(Util.TEXT_SIZE) String description) {
if (validationFailed()) {
addForm();
}
Category category = Category.findByName(name);
if(category != null){
Validation.addError("name", "A category with the same name already exists !");
}
if(validationFailed()) {
addForm();
}
category = new Category();
category.name = name;
category.description = description;
category.save();
flash("message", "The category '" + category.name + "' has been created.");
index();
}
public static void editForm(Long id) {
notFoundIfNull(id);
Category category = Category.findById(id);
notFoundIfNull(category);
render(category);
}
public static void edit(@Required Long id,
@Required @MaxSize(Util.VARCHAR_SIZE) String name,
@MaxSize(Util.TEXT_SIZE) String description) {
notFoundIfNull(id);
Category category = Category.findByName(name);
if(category != null) {
if (!category.id.equals(id)) {
Validation.addError("name", "A category with the same name already exists !");
}
}
else {
category = Category.findById(id);
- notFoundIfNull(id);
+ notFoundIfNull(category);
}
if(validationFailed()) {
editForm(id);
}
category.name = name;
category.description = description;
category.save();
flash("message", "The category '" + category.name + "' has been updated.");
index();
}
public static void confirmDelete(Long id) {
notFoundIfNull(id);
Category category = Category.findById(id);
notFoundIfNull(category);
render(category);
}
public static void delete(Long id) {
notFoundIfNull(id);
Category category = Category.findById(id);
notFoundIfNull(category);
// remove the links
int modules = category.modules.size();
for(Module mod : category.modules){
mod.category = null;
mod.save();
}
category.delete();
String message = "The category '" + category.name + "' has been removed.";
if(modules == 1)
message += " 1 module has been updated.";
else if(modules > 1)
message += " " + modules + " modules have been updated.";
flash("message", message);
index();
}
}
| true | true | public static void edit(@Required Long id,
@Required @MaxSize(Util.VARCHAR_SIZE) String name,
@MaxSize(Util.TEXT_SIZE) String description) {
notFoundIfNull(id);
Category category = Category.findByName(name);
if(category != null) {
if (!category.id.equals(id)) {
Validation.addError("name", "A category with the same name already exists !");
}
}
else {
category = Category.findById(id);
notFoundIfNull(id);
}
if(validationFailed()) {
editForm(id);
}
category.name = name;
category.description = description;
category.save();
flash("message", "The category '" + category.name + "' has been updated.");
index();
}
| public static void edit(@Required Long id,
@Required @MaxSize(Util.VARCHAR_SIZE) String name,
@MaxSize(Util.TEXT_SIZE) String description) {
notFoundIfNull(id);
Category category = Category.findByName(name);
if(category != null) {
if (!category.id.equals(id)) {
Validation.addError("name", "A category with the same name already exists !");
}
}
else {
category = Category.findById(id);
notFoundIfNull(category);
}
if(validationFailed()) {
editForm(id);
}
category.name = name;
category.description = description;
category.save();
flash("message", "The category '" + category.name + "' has been updated.");
index();
}
|
diff --git a/src/org/hopto/seed419/Listeners/MushroomListener.java b/src/org/hopto/seed419/Listeners/MushroomListener.java
index e2b4ab6..d662186 100644
--- a/src/org/hopto/seed419/Listeners/MushroomListener.java
+++ b/src/org/hopto/seed419/Listeners/MushroomListener.java
@@ -1,62 +1,62 @@
package org.hopto.seed419.Listeners;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.hopto.seed419.MagicMushrooms;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: seed419
* Date: 4/27/12
* Time: 7:11 PM
* To change this template use File | Settings | File Templates.
*/
public class MushroomListener implements Listener {
private MagicMushrooms mm;
private final Logger log = Logger.getLogger("MagicMushrooms");
public MushroomListener(MagicMushrooms instance) {
this.mm = instance;
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Material mat = event.getBlock().getType();
Player player = event.getPlayer();
if (mat == Material.RED_MUSHROOM || mat == Material.BROWN_MUSHROOM) {
int randomInt = (int) (Math.random()*100);
if (randomInt <= 3) {
for (Player x : mm.getServer().getOnlinePlayers()) {
if (x != player) {
x.sendMessage(player.getDisplayName() + ChatColor.DARK_GREEN + " had a few too many shrooms.");
}
}
log.info(player.getName() + " had a few too many shrooms.");
int randomSpeed = (int) (Math.random()*50);
int randomJump = (int) (Math.random()*10);
int randomConfusion = (int) (Math.random()*50);
int randomBlindness = (int) (Math.random()*50);
player.sendMessage(ChatColor.DARK_GREEN + "That mushroom appears to cause psychoactive effects.");
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 1000, randomConfusion));
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 1000, randomSpeed));
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 1000, randomJump));
- if (randomInt == 5) {
+ if (randomInt == 3) {
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 1000, randomBlindness));
}
}
}
}
}
| true | true | public void onBlockBreak(BlockBreakEvent event) {
Material mat = event.getBlock().getType();
Player player = event.getPlayer();
if (mat == Material.RED_MUSHROOM || mat == Material.BROWN_MUSHROOM) {
int randomInt = (int) (Math.random()*100);
if (randomInt <= 3) {
for (Player x : mm.getServer().getOnlinePlayers()) {
if (x != player) {
x.sendMessage(player.getDisplayName() + ChatColor.DARK_GREEN + " had a few too many shrooms.");
}
}
log.info(player.getName() + " had a few too many shrooms.");
int randomSpeed = (int) (Math.random()*50);
int randomJump = (int) (Math.random()*10);
int randomConfusion = (int) (Math.random()*50);
int randomBlindness = (int) (Math.random()*50);
player.sendMessage(ChatColor.DARK_GREEN + "That mushroom appears to cause psychoactive effects.");
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 1000, randomConfusion));
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 1000, randomSpeed));
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 1000, randomJump));
if (randomInt == 5) {
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 1000, randomBlindness));
}
}
}
}
| public void onBlockBreak(BlockBreakEvent event) {
Material mat = event.getBlock().getType();
Player player = event.getPlayer();
if (mat == Material.RED_MUSHROOM || mat == Material.BROWN_MUSHROOM) {
int randomInt = (int) (Math.random()*100);
if (randomInt <= 3) {
for (Player x : mm.getServer().getOnlinePlayers()) {
if (x != player) {
x.sendMessage(player.getDisplayName() + ChatColor.DARK_GREEN + " had a few too many shrooms.");
}
}
log.info(player.getName() + " had a few too many shrooms.");
int randomSpeed = (int) (Math.random()*50);
int randomJump = (int) (Math.random()*10);
int randomConfusion = (int) (Math.random()*50);
int randomBlindness = (int) (Math.random()*50);
player.sendMessage(ChatColor.DARK_GREEN + "That mushroom appears to cause psychoactive effects.");
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 1000, randomConfusion));
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 1000, randomSpeed));
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 1000, randomJump));
if (randomInt == 3) {
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 1000, randomBlindness));
}
}
}
}
|
diff --git a/src/craig_proj/DashBoardServlet.java b/src/craig_proj/DashBoardServlet.java
index 5799aee..e840515 100644
--- a/src/craig_proj/DashBoardServlet.java
+++ b/src/craig_proj/DashBoardServlet.java
@@ -1,43 +1,43 @@
package craig_proj;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class DashBoardServlet
*/
@WebServlet("/Dashboard")
public class DashBoardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DashBoardServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doBoth(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doBoth(request, response);
}
private void doBoth(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//response.sendRedirect("/WEB-INF/dashboard.jsp"); //HEADER isn't set using this
RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/dashboard.jsp");
rd.forward(request, response);
- session.invalidate();
+ //session.invalidate();
}
}
| true | true | private void doBoth(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//response.sendRedirect("/WEB-INF/dashboard.jsp"); //HEADER isn't set using this
RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/dashboard.jsp");
rd.forward(request, response);
session.invalidate();
}
| private void doBoth(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//response.sendRedirect("/WEB-INF/dashboard.jsp"); //HEADER isn't set using this
RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/dashboard.jsp");
rd.forward(request, response);
//session.invalidate();
}
|
diff --git a/src/main/java/com/hitsoft/mongo/managed/ManagedService.java b/src/main/java/com/hitsoft/mongo/managed/ManagedService.java
index 5545988..de5349c 100644
--- a/src/main/java/com/hitsoft/mongo/managed/ManagedService.java
+++ b/src/main/java/com/hitsoft/mongo/managed/ManagedService.java
@@ -1,143 +1,147 @@
package com.hitsoft.mongo.managed;
import com.hitsoft.types.Currency;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ManagedService {
private static final Logger LOG = LoggerFactory.getLogger(ManagedService.class);
public static DBObject toDBObject(Object object) {
BasicDBObject result = new BasicDBObject();
Class clazz = object.getClass();
while (clazz != null) {
for (Field field : clazz.getDeclaredFields()) {
try {
field.setAccessible(true);
Object fieldValue = field.get(object);
String fieldName = field.getName();
if (fieldValue != null) {
if (field.isAnnotationPresent(EnumField.class)) {
fieldValue = ((Enum) fieldValue).name();
} else if (field.isAnnotationPresent(EnumListField.class)) {
List<String> val = new ArrayList<String>();
for (Enum eVal : (List<Enum>) fieldValue) {
val.add(eVal.name());
}
fieldValue = val;
} else if (field.isAnnotationPresent(EnumSetField.class)) {
Set<String> val = new HashSet<String>();
for (Enum eVal : (Set<Enum>) fieldValue) {
val.add(eVal.name());
}
fieldValue = val;
} else if (field.isAnnotationPresent(ObjectField.class)) {
fieldValue = toDBObject(fieldValue);
} else if (field.isAnnotationPresent(ObjectListField.class)) {
List<DBObject> val = new ArrayList<DBObject>();
for (Object eVal : (List<Object>) fieldValue) {
val.add(toDBObject(eVal));
}
fieldValue = val;
} else if (field.getType().equals(Currency.class)) {
fieldValue = ((Currency) fieldValue).longValue();
}
result.put(fieldName, fieldValue);
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
clazz = clazz.getSuperclass();
}
return result;
}
@SuppressWarnings("unchecked")
public static <T> T fromDBObject(DBObject obj, Class<T> clazz) {
T result = null;
if (obj != null) {
Constructor ctor = getDefaultConstructor(clazz);
try {
result = (T) ctor.newInstance((Object[]) null);
Class currentClass = clazz;
while (currentClass != null) {
for (Field field : currentClass.getDeclaredFields()) {
Object fieldValue = obj.get(field.getName());
if (fieldValue != null) {
if (field.isAnnotationPresent(EnumField.class)) {
fieldValue = Enum.valueOf(field.getAnnotation(EnumField.class).type(), (String) fieldValue);
} else if (field.isAnnotationPresent(ObjectField.class)) {
fieldValue = fromDBObject((DBObject) fieldValue, field.getAnnotation(ObjectField.class).type());
} else if (field.isAnnotationPresent(EnumListField.class)) {
List<Enum> res = (List<Enum>) field.get(result);
for (String dbValue : (List<String>) fieldValue) {
res.add(Enum.valueOf(field.getAnnotation(EnumListField.class).type(), dbValue));
}
fieldValue = res;
} else if (field.isAnnotationPresent(EnumSetField.class)) {
Set<Enum> res = (Set<Enum>) field.get(result);
for (String dbValue : (Iterable<String>) fieldValue) {
res.add(Enum.valueOf(field.getAnnotation(EnumSetField.class).type(), dbValue));
}
fieldValue = res;
} else if (field.isAnnotationPresent(ObjectListField.class)) {
List<Object> res = (List<Object>) field.get(result);
for (DBObject dbValue : (List<DBObject>) fieldValue) {
res.add(fromDBObject(dbValue, field.getAnnotation(ObjectListField.class).type()));
}
fieldValue = res;
}
} else {
if (field.isAnnotationPresent(EnumListField.class)) {
fieldValue = field.get(result);
} else if (field.isAnnotationPresent(EnumSetField.class)) {
fieldValue = field.get(result);
} else if (field.isAnnotationPresent(ObjectListField.class)) {
fieldValue = field.get(result);
}
}
field.setAccessible(true);
if (field.getType().equals(Integer.class) && (fieldValue instanceof Double))
field.set(result, ((Double) (fieldValue)).intValue());
+ else if (field.getType().equals(Long.class) && (fieldValue instanceof Double))
+ field.set(result, ((Double) (fieldValue)).longValue());
+ else if (field.getType().equals(Long.class) && (fieldValue instanceof Integer))
+ field.set(result, ((Integer) (fieldValue)).longValue());
else if (field.getType().equals(Currency.class) && (fieldValue instanceof Double))
field.set(result, Currency.valueOf(((Double) (fieldValue)).intValue()));
else if (field.getType().equals(Currency.class) && (fieldValue instanceof Long))
field.set(result, Currency.valueOf((Long) fieldValue));
else
field.set(result, fieldValue);
}
currentClass = currentClass.getSuperclass();
}
} catch (InstantiationException e) {
LOG.error("Problem on object's loading from DBObject", e);
} catch (IllegalAccessException e) {
LOG.error("Problem on object's loading from DBObject", e);
} catch (InvocationTargetException e) {
LOG.error("Problem on object's loading from DBObject", e);
}
}
return result;
}
private static <T> Constructor getDefaultConstructor(Class<T> clazz) {
try {
Constructor ctor = clazz.getDeclaredConstructor((Class[]) null);
ctor.setAccessible(true);
return ctor;
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Default constructor not found for class: " + clazz.getName());
}
}
}
| true | true | public static <T> T fromDBObject(DBObject obj, Class<T> clazz) {
T result = null;
if (obj != null) {
Constructor ctor = getDefaultConstructor(clazz);
try {
result = (T) ctor.newInstance((Object[]) null);
Class currentClass = clazz;
while (currentClass != null) {
for (Field field : currentClass.getDeclaredFields()) {
Object fieldValue = obj.get(field.getName());
if (fieldValue != null) {
if (field.isAnnotationPresent(EnumField.class)) {
fieldValue = Enum.valueOf(field.getAnnotation(EnumField.class).type(), (String) fieldValue);
} else if (field.isAnnotationPresent(ObjectField.class)) {
fieldValue = fromDBObject((DBObject) fieldValue, field.getAnnotation(ObjectField.class).type());
} else if (field.isAnnotationPresent(EnumListField.class)) {
List<Enum> res = (List<Enum>) field.get(result);
for (String dbValue : (List<String>) fieldValue) {
res.add(Enum.valueOf(field.getAnnotation(EnumListField.class).type(), dbValue));
}
fieldValue = res;
} else if (field.isAnnotationPresent(EnumSetField.class)) {
Set<Enum> res = (Set<Enum>) field.get(result);
for (String dbValue : (Iterable<String>) fieldValue) {
res.add(Enum.valueOf(field.getAnnotation(EnumSetField.class).type(), dbValue));
}
fieldValue = res;
} else if (field.isAnnotationPresent(ObjectListField.class)) {
List<Object> res = (List<Object>) field.get(result);
for (DBObject dbValue : (List<DBObject>) fieldValue) {
res.add(fromDBObject(dbValue, field.getAnnotation(ObjectListField.class).type()));
}
fieldValue = res;
}
} else {
if (field.isAnnotationPresent(EnumListField.class)) {
fieldValue = field.get(result);
} else if (field.isAnnotationPresent(EnumSetField.class)) {
fieldValue = field.get(result);
} else if (field.isAnnotationPresent(ObjectListField.class)) {
fieldValue = field.get(result);
}
}
field.setAccessible(true);
if (field.getType().equals(Integer.class) && (fieldValue instanceof Double))
field.set(result, ((Double) (fieldValue)).intValue());
else if (field.getType().equals(Currency.class) && (fieldValue instanceof Double))
field.set(result, Currency.valueOf(((Double) (fieldValue)).intValue()));
else if (field.getType().equals(Currency.class) && (fieldValue instanceof Long))
field.set(result, Currency.valueOf((Long) fieldValue));
else
field.set(result, fieldValue);
}
currentClass = currentClass.getSuperclass();
}
} catch (InstantiationException e) {
LOG.error("Problem on object's loading from DBObject", e);
} catch (IllegalAccessException e) {
LOG.error("Problem on object's loading from DBObject", e);
} catch (InvocationTargetException e) {
LOG.error("Problem on object's loading from DBObject", e);
}
}
return result;
}
| public static <T> T fromDBObject(DBObject obj, Class<T> clazz) {
T result = null;
if (obj != null) {
Constructor ctor = getDefaultConstructor(clazz);
try {
result = (T) ctor.newInstance((Object[]) null);
Class currentClass = clazz;
while (currentClass != null) {
for (Field field : currentClass.getDeclaredFields()) {
Object fieldValue = obj.get(field.getName());
if (fieldValue != null) {
if (field.isAnnotationPresent(EnumField.class)) {
fieldValue = Enum.valueOf(field.getAnnotation(EnumField.class).type(), (String) fieldValue);
} else if (field.isAnnotationPresent(ObjectField.class)) {
fieldValue = fromDBObject((DBObject) fieldValue, field.getAnnotation(ObjectField.class).type());
} else if (field.isAnnotationPresent(EnumListField.class)) {
List<Enum> res = (List<Enum>) field.get(result);
for (String dbValue : (List<String>) fieldValue) {
res.add(Enum.valueOf(field.getAnnotation(EnumListField.class).type(), dbValue));
}
fieldValue = res;
} else if (field.isAnnotationPresent(EnumSetField.class)) {
Set<Enum> res = (Set<Enum>) field.get(result);
for (String dbValue : (Iterable<String>) fieldValue) {
res.add(Enum.valueOf(field.getAnnotation(EnumSetField.class).type(), dbValue));
}
fieldValue = res;
} else if (field.isAnnotationPresent(ObjectListField.class)) {
List<Object> res = (List<Object>) field.get(result);
for (DBObject dbValue : (List<DBObject>) fieldValue) {
res.add(fromDBObject(dbValue, field.getAnnotation(ObjectListField.class).type()));
}
fieldValue = res;
}
} else {
if (field.isAnnotationPresent(EnumListField.class)) {
fieldValue = field.get(result);
} else if (field.isAnnotationPresent(EnumSetField.class)) {
fieldValue = field.get(result);
} else if (field.isAnnotationPresent(ObjectListField.class)) {
fieldValue = field.get(result);
}
}
field.setAccessible(true);
if (field.getType().equals(Integer.class) && (fieldValue instanceof Double))
field.set(result, ((Double) (fieldValue)).intValue());
else if (field.getType().equals(Long.class) && (fieldValue instanceof Double))
field.set(result, ((Double) (fieldValue)).longValue());
else if (field.getType().equals(Long.class) && (fieldValue instanceof Integer))
field.set(result, ((Integer) (fieldValue)).longValue());
else if (field.getType().equals(Currency.class) && (fieldValue instanceof Double))
field.set(result, Currency.valueOf(((Double) (fieldValue)).intValue()));
else if (field.getType().equals(Currency.class) && (fieldValue instanceof Long))
field.set(result, Currency.valueOf((Long) fieldValue));
else
field.set(result, fieldValue);
}
currentClass = currentClass.getSuperclass();
}
} catch (InstantiationException e) {
LOG.error("Problem on object's loading from DBObject", e);
} catch (IllegalAccessException e) {
LOG.error("Problem on object's loading from DBObject", e);
} catch (InvocationTargetException e) {
LOG.error("Problem on object's loading from DBObject", e);
}
}
return result;
}
|
diff --git a/src/com/google/javascript/jscomp/VarCheck.java b/src/com/google/javascript/jscomp/VarCheck.java
index 3b7eeee06..6a44596c0 100644
--- a/src/com/google/javascript/jscomp/VarCheck.java
+++ b/src/com/google/javascript/jscomp/VarCheck.java
@@ -1,370 +1,371 @@
/*
* Copyright 2004 The Closure Compiler Authors.
*
* 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.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.SyntacticScopeCreator.RedeclarationHandler;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.Set;
/**
* Checks that all variables are declared, that file-private variables are
* accessed only in the file that declares them, and that any var references
* that cross module boundaries respect declared module dependencies.
*
*/
class VarCheck extends AbstractPostOrderCallback implements
HotSwapCompilerPass {
static final DiagnosticType UNDEFINED_VAR_ERROR = DiagnosticType.error(
"JSC_UNDEFINED_VARIABLE",
"variable {0} is undeclared");
static final DiagnosticType VIOLATED_MODULE_DEP_ERROR = DiagnosticType.error(
"JSC_VIOLATED_MODULE_DEPENDENCY",
"module {0} cannot reference {2}, defined in " +
"module {1}, since {1} loads after {0}");
static final DiagnosticType MISSING_MODULE_DEP_ERROR = DiagnosticType.warning(
"JSC_MISSING_MODULE_DEPENDENCY",
"missing module dependency; module {0} should depend " +
"on module {1} because it references {2}");
static final DiagnosticType STRICT_MODULE_DEP_ERROR = DiagnosticType.disabled(
"JSC_STRICT_MODULE_DEPENDENCY",
"module {0} cannot reference {2}, defined in " +
"module {1}");
static final DiagnosticType NAME_REFERENCE_IN_EXTERNS_ERROR =
DiagnosticType.warning(
"JSC_NAME_REFERENCE_IN_EXTERNS",
"accessing name {0} in externs has no effect. " +
"Perhaps you forgot to add a var keyword?");
static final DiagnosticType UNDEFINED_EXTERN_VAR_ERROR =
DiagnosticType.warning(
"JSC_UNDEFINED_EXTERN_VAR_ERROR",
"name {0} is not defined in the externs.");
static final DiagnosticType VAR_MULTIPLY_DECLARED_ERROR =
DiagnosticType.error(
"JSC_VAR_MULTIPLY_DECLARED_ERROR",
"Variable {0} first declared in {1}");
static final DiagnosticType VAR_ARGUMENTS_SHADOWED_ERROR =
DiagnosticType.error(
"JSC_VAR_ARGUMENTS_SHADOWED_ERROR",
"Shadowing \"arguments\" is not allowed");
// The arguments variable is special, in that it's declared in every local
// scope, but not explicitly declared.
private static final String ARGUMENTS = "arguments";
// Vars that still need to be declared in externs. These will be declared
// at the end of the pass, or when we see the equivalent var declared
// in the normal code.
private final Set<String> varsToDeclareInExterns = Sets.newHashSet();
private final AbstractCompiler compiler;
// Whether this is the post-processing sanity check.
private final boolean sanityCheck;
// Whether extern checks emit error.
private final boolean strictExternCheck;
VarCheck(AbstractCompiler compiler) {
this(compiler, false);
}
VarCheck(AbstractCompiler compiler, boolean sanityCheck) {
this.compiler = compiler;
this.strictExternCheck = compiler.getErrorLevel(
JSError.make("", 0, 0, UNDEFINED_EXTERN_VAR_ERROR)) == CheckLevel.ERROR;
this.sanityCheck = sanityCheck;
}
/**
* Create a SyntacticScopeCreator. If not in sanity check mode, use a
* {@link RedeclarationCheckHandler} to check var redeclarations.
* @return the SyntacticScopeCreator
*/
private ScopeCreator createScopeCreator() {
if (sanityCheck) {
return new SyntacticScopeCreator(compiler);
} else {
return new SyntacticScopeCreator(
compiler, new RedeclarationCheckHandler());
}
}
@Override
public void process(Node externs, Node root) {
ScopeCreator scopeCreator = createScopeCreator();
// Don't run externs-checking in sanity check mode. Normalization will
// remove duplicate VAR declarations, which will make
// externs look like they have assigns.
if (!sanityCheck) {
NodeTraversal traversal = new NodeTraversal(
compiler, new NameRefInExternsCheck(), scopeCreator);
traversal.traverse(externs);
}
NodeTraversal t = new NodeTraversal(compiler, this, scopeCreator);
t.traverseRoots(Lists.newArrayList(externs, root));
for (String varName : varsToDeclareInExterns) {
createSynthesizedExternVar(varName);
}
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
Preconditions.checkState(scriptRoot.isScript());
ScopeCreator scopeCreator = createScopeCreator();
NodeTraversal t = new NodeTraversal(compiler, this, scopeCreator);
// Note we use the global scope to prevent wrong "undefined-var errors" on
// variables that are defined in other JS files.
Scope topScope = scopeCreator.createScope(compiler.getRoot(), null);
t.traverseWithScope(scriptRoot, topScope);
// TODO(bashir) Check if we need to createSynthesizedExternVar like process.
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (!n.isName()) {
return;
}
String varName = n.getString();
// Only a function can have an empty name.
if (varName.isEmpty()) {
Preconditions.checkState(parent.isFunction());
Preconditions.checkState(NodeUtil.isFunctionExpression(parent));
return;
}
// Check if this is a declaration for a var that has been declared
// elsewhere. If so, mark it as a duplicate.
if ((parent.isVar() ||
NodeUtil.isFunctionDeclaration(parent)) &&
varsToDeclareInExterns.contains(varName)) {
createSynthesizedExternVar(varName);
n.addSuppression("duplicate");
}
// Check that the var has been declared.
Scope scope = t.getScope();
Scope.Var var = scope.getVar(varName);
if (var == null) {
if (NodeUtil.isFunctionExpression(parent)) {
// e.g. [ function foo() {} ], it's okay if "foo" isn't defined in the
// current scope.
- } else if (!(scope.isLocal() && ARGUMENTS.equals(varName))) {
+ } else {
+ boolean isArguments = scope.isLocal() && ARGUMENTS.equals(varName);
// The extern checks are stricter, don't report a second error.
- if (!strictExternCheck || !t.getInput().isExtern()) {
+ if (!isArguments && !(strictExternCheck && t.getInput().isExtern())) {
t.report(n, UNDEFINED_VAR_ERROR, varName);
}
if (sanityCheck) {
throw new IllegalStateException("Unexpected variable " + varName);
} else {
createSynthesizedExternVar(varName);
scope.getGlobalScope().declare(varName, n,
null, compiler.getSynthesizedExternsInput());
}
}
return;
}
CompilerInput currInput = t.getInput();
CompilerInput varInput = var.input;
if (currInput == varInput || currInput == null || varInput == null) {
// The variable was defined in the same file. This is fine.
return;
}
// Check module dependencies.
JSModule currModule = currInput.getModule();
JSModule varModule = varInput.getModule();
JSModuleGraph moduleGraph = compiler.getModuleGraph();
if (!sanityCheck &&
varModule != currModule && varModule != null && currModule != null) {
if (moduleGraph.dependsOn(currModule, varModule)) {
// The module dependency was properly declared.
} else {
if (scope.isGlobal()) {
if (moduleGraph.dependsOn(varModule, currModule)) {
// The variable reference violates a declared module dependency.
t.report(n, VIOLATED_MODULE_DEP_ERROR,
currModule.getName(), varModule.getName(), varName);
} else {
// The variable reference is between two modules that have no
// dependency relationship. This should probably be considered an
// error, but just issue a warning for now.
t.report(n, MISSING_MODULE_DEP_ERROR,
currModule.getName(), varModule.getName(), varName);
}
} else {
t.report(n, STRICT_MODULE_DEP_ERROR,
currModule.getName(), varModule.getName(), varName);
}
}
}
}
/**
* Create a new variable in a synthetic script. This will prevent
* subsequent compiler passes from crashing.
*/
private void createSynthesizedExternVar(String varName) {
Node nameNode = IR.name(varName);
// Mark the variable as constant if it matches the coding convention
// for constant vars.
// NOTE(nicksantos): honestly, I'm not sure how much this matters.
// AFAIK, all people who use the CONST coding convention also
// compile with undeclaredVars as errors. We have some test
// cases for this configuration though, and it makes them happier.
if (compiler.getCodingConvention().isConstant(varName)) {
nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
}
getSynthesizedExternsRoot().addChildToBack(
IR.var(nameNode));
varsToDeclareInExterns.remove(varName);
compiler.reportCodeChange();
}
/**
* A check for name references in the externs inputs. These used to prevent
* a variable from getting renamed, but no longer have any effect.
*/
private class NameRefInExternsCheck extends AbstractPostOrderCallback {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isName()) {
switch (parent.getType()) {
case Token.VAR:
case Token.FUNCTION:
case Token.PARAM_LIST:
// These are okay.
break;
case Token.GETPROP:
if (n == parent.getFirstChild()) {
Scope scope = t.getScope();
Scope.Var var = scope.getVar(n.getString());
if (var == null) {
t.report(n, UNDEFINED_EXTERN_VAR_ERROR, n.getString());
varsToDeclareInExterns.add(n.getString());
}
}
break;
default:
t.report(n, NAME_REFERENCE_IN_EXTERNS_ERROR, n.getString());
Scope scope = t.getScope();
Scope.Var var = scope.getVar(n.getString());
if (var == null) {
varsToDeclareInExterns.add(n.getString());
}
break;
}
}
}
}
/**
* @param n The name node to check.
* @param origVar The associated Var.
* @return Whether duplicated declarations warnings should be suppressed
* for the given node.
*/
static boolean hasDuplicateDeclarationSuppression(Node n, Scope.Var origVar) {
Preconditions.checkState(n.isName());
Node parent = n.getParent();
Node origParent = origVar.getParentNode();
JSDocInfo info = n.getJSDocInfo();
if (info == null) {
info = parent.getJSDocInfo();
}
if (info != null && info.getSuppressions().contains("duplicate")) {
return true;
}
info = origVar.nameNode.getJSDocInfo();
if (info == null) {
info = origParent.getJSDocInfo();
}
return (info != null && info.getSuppressions().contains("duplicate"));
}
/**
* The handler for duplicate declarations.
*/
private class RedeclarationCheckHandler implements RedeclarationHandler {
@Override
public void onRedeclaration(
Scope s, String name, Node n, CompilerInput input) {
Node parent = n.getParent();
// Don't allow multiple variables to be declared at the top-level scope
if (s.isGlobal()) {
Scope.Var origVar = s.getVar(name);
Node origParent = origVar.getParentNode();
if (origParent.isCatch() &&
parent.isCatch()) {
// Okay, both are 'catch(x)' variables.
return;
}
boolean allowDupe = hasDuplicateDeclarationSuppression(n, origVar);
if (!allowDupe) {
compiler.report(
JSError.make(NodeUtil.getSourceName(n), n,
VAR_MULTIPLY_DECLARED_ERROR,
name,
(origVar.input != null
? origVar.input.getName()
: "??")));
}
} else if (name.equals(ARGUMENTS) && !NodeUtil.isVarDeclaration(n)) {
// Disallow shadowing "arguments" as we can't handle with our current
// scope modeling.
compiler.report(
JSError.make(NodeUtil.getSourceName(n), n,
VAR_ARGUMENTS_SHADOWED_ERROR));
}
}
}
/** Lazily create a "new" externs root for undeclared variables. */
private Node getSynthesizedExternsRoot() {
return compiler.getSynthesizedExternsInput().getAstRoot(compiler);
}
}
| false | true | public void visit(NodeTraversal t, Node n, Node parent) {
if (!n.isName()) {
return;
}
String varName = n.getString();
// Only a function can have an empty name.
if (varName.isEmpty()) {
Preconditions.checkState(parent.isFunction());
Preconditions.checkState(NodeUtil.isFunctionExpression(parent));
return;
}
// Check if this is a declaration for a var that has been declared
// elsewhere. If so, mark it as a duplicate.
if ((parent.isVar() ||
NodeUtil.isFunctionDeclaration(parent)) &&
varsToDeclareInExterns.contains(varName)) {
createSynthesizedExternVar(varName);
n.addSuppression("duplicate");
}
// Check that the var has been declared.
Scope scope = t.getScope();
Scope.Var var = scope.getVar(varName);
if (var == null) {
if (NodeUtil.isFunctionExpression(parent)) {
// e.g. [ function foo() {} ], it's okay if "foo" isn't defined in the
// current scope.
} else if (!(scope.isLocal() && ARGUMENTS.equals(varName))) {
// The extern checks are stricter, don't report a second error.
if (!strictExternCheck || !t.getInput().isExtern()) {
t.report(n, UNDEFINED_VAR_ERROR, varName);
}
if (sanityCheck) {
throw new IllegalStateException("Unexpected variable " + varName);
} else {
createSynthesizedExternVar(varName);
scope.getGlobalScope().declare(varName, n,
null, compiler.getSynthesizedExternsInput());
}
}
return;
}
CompilerInput currInput = t.getInput();
CompilerInput varInput = var.input;
if (currInput == varInput || currInput == null || varInput == null) {
// The variable was defined in the same file. This is fine.
return;
}
// Check module dependencies.
JSModule currModule = currInput.getModule();
JSModule varModule = varInput.getModule();
JSModuleGraph moduleGraph = compiler.getModuleGraph();
if (!sanityCheck &&
varModule != currModule && varModule != null && currModule != null) {
if (moduleGraph.dependsOn(currModule, varModule)) {
// The module dependency was properly declared.
} else {
if (scope.isGlobal()) {
if (moduleGraph.dependsOn(varModule, currModule)) {
// The variable reference violates a declared module dependency.
t.report(n, VIOLATED_MODULE_DEP_ERROR,
currModule.getName(), varModule.getName(), varName);
} else {
// The variable reference is between two modules that have no
// dependency relationship. This should probably be considered an
// error, but just issue a warning for now.
t.report(n, MISSING_MODULE_DEP_ERROR,
currModule.getName(), varModule.getName(), varName);
}
} else {
t.report(n, STRICT_MODULE_DEP_ERROR,
currModule.getName(), varModule.getName(), varName);
}
}
}
}
| public void visit(NodeTraversal t, Node n, Node parent) {
if (!n.isName()) {
return;
}
String varName = n.getString();
// Only a function can have an empty name.
if (varName.isEmpty()) {
Preconditions.checkState(parent.isFunction());
Preconditions.checkState(NodeUtil.isFunctionExpression(parent));
return;
}
// Check if this is a declaration for a var that has been declared
// elsewhere. If so, mark it as a duplicate.
if ((parent.isVar() ||
NodeUtil.isFunctionDeclaration(parent)) &&
varsToDeclareInExterns.contains(varName)) {
createSynthesizedExternVar(varName);
n.addSuppression("duplicate");
}
// Check that the var has been declared.
Scope scope = t.getScope();
Scope.Var var = scope.getVar(varName);
if (var == null) {
if (NodeUtil.isFunctionExpression(parent)) {
// e.g. [ function foo() {} ], it's okay if "foo" isn't defined in the
// current scope.
} else {
boolean isArguments = scope.isLocal() && ARGUMENTS.equals(varName);
// The extern checks are stricter, don't report a second error.
if (!isArguments && !(strictExternCheck && t.getInput().isExtern())) {
t.report(n, UNDEFINED_VAR_ERROR, varName);
}
if (sanityCheck) {
throw new IllegalStateException("Unexpected variable " + varName);
} else {
createSynthesizedExternVar(varName);
scope.getGlobalScope().declare(varName, n,
null, compiler.getSynthesizedExternsInput());
}
}
return;
}
CompilerInput currInput = t.getInput();
CompilerInput varInput = var.input;
if (currInput == varInput || currInput == null || varInput == null) {
// The variable was defined in the same file. This is fine.
return;
}
// Check module dependencies.
JSModule currModule = currInput.getModule();
JSModule varModule = varInput.getModule();
JSModuleGraph moduleGraph = compiler.getModuleGraph();
if (!sanityCheck &&
varModule != currModule && varModule != null && currModule != null) {
if (moduleGraph.dependsOn(currModule, varModule)) {
// The module dependency was properly declared.
} else {
if (scope.isGlobal()) {
if (moduleGraph.dependsOn(varModule, currModule)) {
// The variable reference violates a declared module dependency.
t.report(n, VIOLATED_MODULE_DEP_ERROR,
currModule.getName(), varModule.getName(), varName);
} else {
// The variable reference is between two modules that have no
// dependency relationship. This should probably be considered an
// error, but just issue a warning for now.
t.report(n, MISSING_MODULE_DEP_ERROR,
currModule.getName(), varModule.getName(), varName);
}
} else {
t.report(n, STRICT_MODULE_DEP_ERROR,
currModule.getName(), varModule.getName(), varName);
}
}
}
}
|
diff --git a/src/ch/good2go/Home.java b/src/ch/good2go/Home.java
index 4162f19..a5d2433 100644
--- a/src/ch/good2go/Home.java
+++ b/src/ch/good2go/Home.java
@@ -1,80 +1,80 @@
package ch.good2go;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
public class Home extends TabActivity{
private static final int INSERT_ID = Menu.FIRST;
private static final int ACTIVITY_CREATE=0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
- // Create an Intent to launch an Activity for the tab (to be reused)
- intent = new Intent().setClass(this, RestAccess.class);
//get all locations from resource
String[] locations = res.getStringArray(R.array.location_array);
//create one tab per location
for(int i=0; i<locations.length; i++)
{
+ // Create an Intent to launch an Activity for the tab
+ intent = new Intent().setClass(this, RestAccess.class);
intent.putExtra("location", locations[i]);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec(locations[i]);
spec.setIndicator(locations[i],
res.getDrawable(R.drawable.ic_menu_home))
.setContent(intent);
tabHost.addTab(spec);
}
- tabHost.setCurrentTab(2);
+ tabHost.setCurrentTab(0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId())
{
case INSERT_ID:
createDevice();
return true;
}
return super.onOptionsItemSelected(item);
}
/* public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createDevice();
return true;
}
return super.onMenuItemSelected(featureId, item);
}*/
private void createDevice() {
Intent i = new Intent(this, DeviceEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
//fillData();
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, RestAccess.class);
//get all locations from resource
String[] locations = res.getStringArray(R.array.location_array);
//create one tab per location
for(int i=0; i<locations.length; i++)
{
intent.putExtra("location", locations[i]);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec(locations[i]);
spec.setIndicator(locations[i],
res.getDrawable(R.drawable.ic_menu_home))
.setContent(intent);
tabHost.addTab(spec);
}
tabHost.setCurrentTab(2);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
//get all locations from resource
String[] locations = res.getStringArray(R.array.location_array);
//create one tab per location
for(int i=0; i<locations.length; i++)
{
// Create an Intent to launch an Activity for the tab
intent = new Intent().setClass(this, RestAccess.class);
intent.putExtra("location", locations[i]);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec(locations[i]);
spec.setIndicator(locations[i],
res.getDrawable(R.drawable.ic_menu_home))
.setContent(intent);
tabHost.addTab(spec);
}
tabHost.setCurrentTab(0);
}
|
diff --git a/src/hunternif/mc/dota2items/item/BlinkDagger.java b/src/hunternif/mc/dota2items/item/BlinkDagger.java
index fae66ba..58967a3 100644
--- a/src/hunternif/mc/dota2items/item/BlinkDagger.java
+++ b/src/hunternif/mc/dota2items/item/BlinkDagger.java
@@ -1,234 +1,234 @@
package hunternif.mc.dota2items.item;
import hunternif.mc.dota2items.Dota2Items;
import hunternif.mc.dota2items.Sound;
import hunternif.mc.dota2items.effect.Effect;
import hunternif.mc.dota2items.effect.EffectInstance;
import hunternif.mc.dota2items.event.UseItemEvent;
import hunternif.mc.dota2items.network.EffectPacket;
import hunternif.mc.dota2items.util.BlockUtil;
import hunternif.mc.dota2items.util.SideHit;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlinkDagger extends CooldownItem {
public static final double maxDistance = 50;
public static final float hurtCooldown = 3;
public static final float usualCooldown = 14;
private Random rand;
public BlinkDagger(int id) {
super(id);
rand = new Random();
setCooldown(usualCooldown);
setManaCost(75);
}
@SideOnly(Side.CLIENT)
@Override
public boolean isFull3D() {
return true;
}
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) {
if (!tryUse(itemStack, player)) {
return itemStack;
}
MinecraftForge.EVENT_BUS.post(new UseItemEvent(player, this));
int destX;
int destY;
int destZ;
// Allow landing on all solid and liquid blocks, but the latter only if the player is not in water
Vec3 position = world.getWorldVec3Pool().getVecFromPool(player.posX, player.posY, player.posZ);
if (!world.isRemote) {
// Because in server worlds the Y coordinate of a player is his feet's coordinate, without yOffset.
position = position.addVector(0, 1.62D, 0);
}
Vec3 look = player.getLook(1.0F);
Vec3 lookFar = position.addVector(look.xCoord * maxDistance, look.yCoord * maxDistance, look.zCoord * maxDistance);
boolean isUnderWater = player.isInsideOfMaterial(Material.water);
MovingObjectPosition hit = world.clip(position, lookFar, !isUnderWater); // raytrace
if (hit != null) {
destX = hit.blockX;
destY = hit.blockY;
destZ = hit.blockZ;
// Only blink on top when there's a block of air 1 block above
// target block AND it's reachable straight,
// like this: or this: 0
// 0 00
// 00 0#
// ray -> 0# ray -> 0#
// (0 = air, # = block)
if (hit.sideHit != SideHit.BOTTOM && hit.sideHit != SideHit.TOP) {
if (BlockUtil.isReachableAirAbove(world, hit.sideHit, destX, destY, destZ, 1)) {
// Blink on top of that block
destY += 1;
} else if (BlockUtil.isReachableAirAbove(world, hit.sideHit, destX, destY, destZ, 2)) {
// ...or the one above it
destY += 2;
} else {
// There's no reachable air above, move back 1 block
switch (hit.sideHit) {
case SideHit.NORTH:
destX--;
break;
case SideHit.SOUTH:
destX++;
break;
case SideHit.EAST:
destZ--;
break;
case SideHit.WEST:
destZ++;
break;
}
}
} else {
switch (hit.sideHit) {
case SideHit.BOTTOM:
destY -= 2;
break;
case SideHit.TOP:
destY++;
break;
}
}
// Safeguard in case of an infinite loop.
int timesSubtracted = 0;
while (!blink(itemStack, world, player, destX, destY, destZ) &&
(double) timesSubtracted < maxDistance) {
// Something is obstructing the ray, trace a step back
hit.hitVec = hit.hitVec.addVector(-look.xCoord, -look.yCoord, -look.zCoord);
timesSubtracted ++;
destX = Math.round((float) hit.hitVec.xCoord);
destY = Math.round((float) hit.hitVec.yCoord);
destZ = Math.round((float) hit.hitVec.zCoord);
}
} else {
// Hit empty air
destX = Math.round((float) lookFar.xCoord);
destY = Math.round((float) lookFar.yCoord);
destZ = Math.round((float) lookFar.zCoord);
blink(itemStack, world, player, destX, destY, destZ);
}
return itemStack;
}
/**
* Blinks player to target coordinates, but first looks up then down for
* empty space. Returns true if could blink without moving the player UP
* from the given destination. Otherwise returns false and doesn't blink.
*/
private boolean blink(ItemStack itemStack, World world, EntityPlayer player, int x, int y, int z) {
Entity blinkingEntity;
if (player.ridingEntity != null) {
blinkingEntity = player.ridingEntity;
} else {
blinkingEntity = player;
}
// First of all, check if we are hanging in the air; if so, land.
Material material = world.getBlockMaterial(x, y-1, z);
boolean isUnderWater = blinkingEntity.isInsideOfMaterial(Material.water);
while (!(material.isSolid() || (!isUnderWater && material.isLiquid()))) {
y--;
material = world.getBlockMaterial(x, y-1, z);
if (y <= 0) {
// Reached minimum Y
return false;
}
}
double destX = (double) x + 0.5D;
double destY = (double) y + blinkingEntity.yOffset;
double destZ = (double) z + 0.5D;
// Special care must be taken with fences which are 1.5 blocks high
int landingBlockId = world.getBlockId(x, y-1, z);
if (landingBlockId == Block.fence.blockID || landingBlockId == Block.fenceGate.blockID) {
destY += 0.5;
}
// Also slabs
if (landingBlockId == Block.stoneSingleSlab.blockID || landingBlockId == Block.woodSingleSlab.blockID) {
destY -= 0.5;
}
// Keep previous coordinates
double srcX = blinkingEntity.posX;
double srcY = blinkingEntity.posY;
double srcZ = blinkingEntity.posZ;
blinkingEntity.setPosition(destX, destY, destZ);
blinkingEntity.updateRiderPosition();
// If colliding with something right now, return false immediately:
- if (!world.getCollidingBoundingBoxes(player, player.boundingBox).isEmpty()) {
+ if (!world.getCollidingBlockBounds(player.boundingBox).isEmpty()) {
// Reset player position
blinkingEntity.setPosition(srcX, srcY, srcZ);
blinkingEntity.updateRiderPosition();
return false;
}
//------------------------ Successful blink ------------------------
if (!player.capabilities.isCreativeMode) {
Dota2Items.stats.getOrCreateEntityStats(player).removeMana(getManaCost());
}
blinkingEntity.motionX = 0;
blinkingEntity.motionY = 0;
blinkingEntity.motionZ = 0;
blinkingEntity.fallDistance = 0;
EffectInstance srcEffect = new EffectInstance(Effect.blink, srcX, srcY, srcZ);
EffectInstance destEffect = new EffectInstance(Effect.blink, destX, destY, destZ);
if (!world.isRemote) {
startCooldown(itemStack, player);
// Server side. Play sounds and send packets about the player blinking.
// Play sound both at the initial position and the blink destination,
// if they're far apart enough.
double distance = player.getDistance(srcX, srcY, srcZ);
if (distance < 12) {
world.playSoundToNearExcept(player, Sound.BLINK_OUT.getName(), 1.0F, 1.0F);
} else {
// Sounds for other players to hear:
world.playSoundToNearExcept(player, Sound.BLINK_IN.getName(), 1.0F, 1.0F);
world.playSoundEffect(srcX, srcY, srcZ, Sound.BLINK_OUT.getName(), 1.0F, 1.0F);
}
// Send effect packets to other players
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
if (server != null) {
server.getConfigurationManager().sendToAllNearExcept(player, srcX, srcY, srcZ, 256, player.dimension, new EffectPacket(srcEffect).makePacket());
server.getConfigurationManager().sendToAllNearExcept(player, destX, destY, destZ, 256, player.dimension, new EffectPacket(destEffect).makePacket());
}
} else {
// Client side. Render blink effect.
Minecraft.getMinecraft().sndManager.playSoundFX(Sound.BLINK_OUT.getName(), 1.0F, 1.0F);
srcEffect.perform();
destEffect.perform();
}
return true;
}
}
| true | true | private boolean blink(ItemStack itemStack, World world, EntityPlayer player, int x, int y, int z) {
Entity blinkingEntity;
if (player.ridingEntity != null) {
blinkingEntity = player.ridingEntity;
} else {
blinkingEntity = player;
}
// First of all, check if we are hanging in the air; if so, land.
Material material = world.getBlockMaterial(x, y-1, z);
boolean isUnderWater = blinkingEntity.isInsideOfMaterial(Material.water);
while (!(material.isSolid() || (!isUnderWater && material.isLiquid()))) {
y--;
material = world.getBlockMaterial(x, y-1, z);
if (y <= 0) {
// Reached minimum Y
return false;
}
}
double destX = (double) x + 0.5D;
double destY = (double) y + blinkingEntity.yOffset;
double destZ = (double) z + 0.5D;
// Special care must be taken with fences which are 1.5 blocks high
int landingBlockId = world.getBlockId(x, y-1, z);
if (landingBlockId == Block.fence.blockID || landingBlockId == Block.fenceGate.blockID) {
destY += 0.5;
}
// Also slabs
if (landingBlockId == Block.stoneSingleSlab.blockID || landingBlockId == Block.woodSingleSlab.blockID) {
destY -= 0.5;
}
// Keep previous coordinates
double srcX = blinkingEntity.posX;
double srcY = blinkingEntity.posY;
double srcZ = blinkingEntity.posZ;
blinkingEntity.setPosition(destX, destY, destZ);
blinkingEntity.updateRiderPosition();
// If colliding with something right now, return false immediately:
if (!world.getCollidingBoundingBoxes(player, player.boundingBox).isEmpty()) {
// Reset player position
blinkingEntity.setPosition(srcX, srcY, srcZ);
blinkingEntity.updateRiderPosition();
return false;
}
//------------------------ Successful blink ------------------------
if (!player.capabilities.isCreativeMode) {
Dota2Items.stats.getOrCreateEntityStats(player).removeMana(getManaCost());
}
blinkingEntity.motionX = 0;
blinkingEntity.motionY = 0;
blinkingEntity.motionZ = 0;
blinkingEntity.fallDistance = 0;
EffectInstance srcEffect = new EffectInstance(Effect.blink, srcX, srcY, srcZ);
EffectInstance destEffect = new EffectInstance(Effect.blink, destX, destY, destZ);
if (!world.isRemote) {
startCooldown(itemStack, player);
// Server side. Play sounds and send packets about the player blinking.
// Play sound both at the initial position and the blink destination,
// if they're far apart enough.
double distance = player.getDistance(srcX, srcY, srcZ);
if (distance < 12) {
world.playSoundToNearExcept(player, Sound.BLINK_OUT.getName(), 1.0F, 1.0F);
} else {
// Sounds for other players to hear:
world.playSoundToNearExcept(player, Sound.BLINK_IN.getName(), 1.0F, 1.0F);
world.playSoundEffect(srcX, srcY, srcZ, Sound.BLINK_OUT.getName(), 1.0F, 1.0F);
}
// Send effect packets to other players
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
if (server != null) {
server.getConfigurationManager().sendToAllNearExcept(player, srcX, srcY, srcZ, 256, player.dimension, new EffectPacket(srcEffect).makePacket());
server.getConfigurationManager().sendToAllNearExcept(player, destX, destY, destZ, 256, player.dimension, new EffectPacket(destEffect).makePacket());
}
} else {
// Client side. Render blink effect.
Minecraft.getMinecraft().sndManager.playSoundFX(Sound.BLINK_OUT.getName(), 1.0F, 1.0F);
srcEffect.perform();
destEffect.perform();
}
return true;
}
| private boolean blink(ItemStack itemStack, World world, EntityPlayer player, int x, int y, int z) {
Entity blinkingEntity;
if (player.ridingEntity != null) {
blinkingEntity = player.ridingEntity;
} else {
blinkingEntity = player;
}
// First of all, check if we are hanging in the air; if so, land.
Material material = world.getBlockMaterial(x, y-1, z);
boolean isUnderWater = blinkingEntity.isInsideOfMaterial(Material.water);
while (!(material.isSolid() || (!isUnderWater && material.isLiquid()))) {
y--;
material = world.getBlockMaterial(x, y-1, z);
if (y <= 0) {
// Reached minimum Y
return false;
}
}
double destX = (double) x + 0.5D;
double destY = (double) y + blinkingEntity.yOffset;
double destZ = (double) z + 0.5D;
// Special care must be taken with fences which are 1.5 blocks high
int landingBlockId = world.getBlockId(x, y-1, z);
if (landingBlockId == Block.fence.blockID || landingBlockId == Block.fenceGate.blockID) {
destY += 0.5;
}
// Also slabs
if (landingBlockId == Block.stoneSingleSlab.blockID || landingBlockId == Block.woodSingleSlab.blockID) {
destY -= 0.5;
}
// Keep previous coordinates
double srcX = blinkingEntity.posX;
double srcY = blinkingEntity.posY;
double srcZ = blinkingEntity.posZ;
blinkingEntity.setPosition(destX, destY, destZ);
blinkingEntity.updateRiderPosition();
// If colliding with something right now, return false immediately:
if (!world.getCollidingBlockBounds(player.boundingBox).isEmpty()) {
// Reset player position
blinkingEntity.setPosition(srcX, srcY, srcZ);
blinkingEntity.updateRiderPosition();
return false;
}
//------------------------ Successful blink ------------------------
if (!player.capabilities.isCreativeMode) {
Dota2Items.stats.getOrCreateEntityStats(player).removeMana(getManaCost());
}
blinkingEntity.motionX = 0;
blinkingEntity.motionY = 0;
blinkingEntity.motionZ = 0;
blinkingEntity.fallDistance = 0;
EffectInstance srcEffect = new EffectInstance(Effect.blink, srcX, srcY, srcZ);
EffectInstance destEffect = new EffectInstance(Effect.blink, destX, destY, destZ);
if (!world.isRemote) {
startCooldown(itemStack, player);
// Server side. Play sounds and send packets about the player blinking.
// Play sound both at the initial position and the blink destination,
// if they're far apart enough.
double distance = player.getDistance(srcX, srcY, srcZ);
if (distance < 12) {
world.playSoundToNearExcept(player, Sound.BLINK_OUT.getName(), 1.0F, 1.0F);
} else {
// Sounds for other players to hear:
world.playSoundToNearExcept(player, Sound.BLINK_IN.getName(), 1.0F, 1.0F);
world.playSoundEffect(srcX, srcY, srcZ, Sound.BLINK_OUT.getName(), 1.0F, 1.0F);
}
// Send effect packets to other players
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
if (server != null) {
server.getConfigurationManager().sendToAllNearExcept(player, srcX, srcY, srcZ, 256, player.dimension, new EffectPacket(srcEffect).makePacket());
server.getConfigurationManager().sendToAllNearExcept(player, destX, destY, destZ, 256, player.dimension, new EffectPacket(destEffect).makePacket());
}
} else {
// Client side. Render blink effect.
Minecraft.getMinecraft().sndManager.playSoundFX(Sound.BLINK_OUT.getName(), 1.0F, 1.0F);
srcEffect.perform();
destEffect.perform();
}
return true;
}
|
diff --git a/osgi-int/src/main/org/jboss/osgi/plugins/metadata/OSGiParameters.java b/osgi-int/src/main/org/jboss/osgi/plugins/metadata/OSGiParameters.java
index dca34bca..e0d4a149 100644
--- a/osgi-int/src/main/org/jboss/osgi/plugins/metadata/OSGiParameters.java
+++ b/osgi-int/src/main/org/jboss/osgi/plugins/metadata/OSGiParameters.java
@@ -1,125 +1,126 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., 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.jboss.osgi.plugins.metadata;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.jboss.logging.Logger;
import org.jboss.osgi.spi.metadata.Parameter;
import org.jboss.osgi.spi.metadata.VersionRange;
import static org.osgi.framework.Constants.*;
/**
* OSGi parameter values.
* Util for transforming parameter info to actual useful values.
*
* @author <a href="mailto:[email protected]">Ales Justin</a>
*/
public class OSGiParameters
{
protected static Logger log = Logger.getLogger(OSGiParameters.class);
protected Map<String, Parameter> parameters;
protected Map<String, Object> cachedAttributes;
public OSGiParameters(Map<String, Parameter> parameters)
{
this.parameters = Collections.unmodifiableMap(parameters);
this.cachedAttributes = new HashMap<String, Object>();
}
protected Map<String, Parameter> getParameters()
{
return parameters;
}
public VersionRange getVersion()
{
return get(VERSION_ATTRIBUTE, ValueCreatorUtil.VERSION_RANGE_VC);
}
public String getBundleSymbolicName()
{
return get(BUNDLE_SYMBOLICNAME_ATTRIBUTE, ValueCreatorUtil.STRING_VC);
}
public VersionRange getBundleVersion()
{
return get(BUNDLE_VERSION_ATTRIBUTE, ValueCreatorUtil.VERSION_RANGE_VC);
}
public String getVisibility()
{
return get(VISIBILITY_DIRECTIVE, ValueCreatorUtil.STRING_VC, VISIBILITY_PRIVATE);
}
public String getResolution()
{
return get(RESOLUTION_DIRECTIVE, ValueCreatorUtil.STRING_VC, RESOLUTION_MANDATORY);
}
@SuppressWarnings("unchecked")
protected <T> T get(String key, ValueCreator<T> creator)
{
return get(key, creator, null);
}
@SuppressWarnings("unchecked")
protected <T> T get(String key, ValueCreator<T> creator, T defaultValue)
{
T value = (T)cachedAttributes.get(key);
if (value == null)
{
Parameter parameter = parameters.get(key);
if (parameter != null)
{
Object paramValue = parameter.getValue();
if(parameter.isCollection())
{
if (creator instanceof CollectionValueCreator)
{
CollectionValueCreator<T> cvc = (CollectionValueCreator<T>)creator;
value = cvc.createValue((Collection<String>)paramValue);
}
else
{
log.warn("Unable to create proper value from " + creator + " for parameter: " + parameter);
+ return null;
}
}
else
{
value = creator.createValue(paramValue.toString());
}
cachedAttributes.put(key, value);
}
else if (defaultValue != null)
{
value = defaultValue;
cachedAttributes.put(key, value);
}
}
return value;
}
}
| true | true | protected <T> T get(String key, ValueCreator<T> creator, T defaultValue)
{
T value = (T)cachedAttributes.get(key);
if (value == null)
{
Parameter parameter = parameters.get(key);
if (parameter != null)
{
Object paramValue = parameter.getValue();
if(parameter.isCollection())
{
if (creator instanceof CollectionValueCreator)
{
CollectionValueCreator<T> cvc = (CollectionValueCreator<T>)creator;
value = cvc.createValue((Collection<String>)paramValue);
}
else
{
log.warn("Unable to create proper value from " + creator + " for parameter: " + parameter);
}
}
else
{
value = creator.createValue(paramValue.toString());
}
cachedAttributes.put(key, value);
}
else if (defaultValue != null)
{
value = defaultValue;
cachedAttributes.put(key, value);
}
}
return value;
}
| protected <T> T get(String key, ValueCreator<T> creator, T defaultValue)
{
T value = (T)cachedAttributes.get(key);
if (value == null)
{
Parameter parameter = parameters.get(key);
if (parameter != null)
{
Object paramValue = parameter.getValue();
if(parameter.isCollection())
{
if (creator instanceof CollectionValueCreator)
{
CollectionValueCreator<T> cvc = (CollectionValueCreator<T>)creator;
value = cvc.createValue((Collection<String>)paramValue);
}
else
{
log.warn("Unable to create proper value from " + creator + " for parameter: " + parameter);
return null;
}
}
else
{
value = creator.createValue(paramValue.toString());
}
cachedAttributes.put(key, value);
}
else if (defaultValue != null)
{
value = defaultValue;
cachedAttributes.put(key, value);
}
}
return value;
}
|
diff --git a/src/java/org/apache/hadoop/dfs/DataNode.java b/src/java/org/apache/hadoop/dfs/DataNode.java
index 063f241f7..08587fd56 100644
--- a/src/java/org/apache/hadoop/dfs/DataNode.java
+++ b/src/java/org/apache/hadoop/dfs/DataNode.java
@@ -1,1524 +1,1532 @@
/**
* 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.dfs;
import org.apache.commons.logging.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.ipc.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.metrics.MetricsUtil;
import org.apache.hadoop.net.DNS;
import org.apache.hadoop.net.NodeBase;
import org.apache.hadoop.util.*;
import org.apache.hadoop.util.DiskChecker.DiskErrorException;
import org.apache.hadoop.util.DiskChecker.DiskOutOfSpaceException;
import org.apache.hadoop.mapred.StatusHttpServer;
import org.apache.hadoop.net.NetworkTopology;
import org.apache.hadoop.dfs.BlockCommand;
import org.apache.hadoop.dfs.DatanodeProtocol;
import org.apache.hadoop.fs.FileUtil;
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.hadoop.dfs.FSConstants.StartupOption;
import org.apache.hadoop.metrics.MetricsContext;
import org.apache.hadoop.metrics.MetricsRecord;
import org.apache.hadoop.metrics.Updater;
import org.apache.hadoop.metrics.jvm.JvmMetrics;
/**********************************************************
* DataNode is a class (and program) that stores a set of
* blocks for a DFS deployment. A single deployment can
* have one or many DataNodes. Each DataNode communicates
* regularly with a single NameNode. It also communicates
* with client code and other DataNodes from time to time.
*
* DataNodes store a series of named blocks. The DataNode
* allows client code to read these blocks, or to write new
* block data. The DataNode may also, in response to instructions
* from its NameNode, delete blocks or copy blocks to/from other
* DataNodes.
*
* The DataNode maintains just one critical table:
* block-> stream of bytes (of BLOCK_SIZE or less)
*
* This info is stored on a local disk. The DataNode
* reports the table's contents to the NameNode upon startup
* and every so often afterwards.
*
* DataNodes spend their lives in an endless loop of asking
* the NameNode for something to do. A NameNode cannot connect
* to a DataNode directly; a NameNode simply returns values from
* functions invoked by a DataNode.
*
* DataNodes maintain an open server socket so that client code
* or other DataNodes can read/write data. The host/port for
* this server is reported to the NameNode, which then sends that
* information to clients or other DataNodes that might be interested.
*
**********************************************************/
public class DataNode implements FSConstants, Runnable {
public static final Log LOG = LogFactory.getLog("org.apache.hadoop.dfs.DataNode");
/**
* A buffer size small enough that read/writes while reading headers
* don't result in multiple io calls but reading larger amount of data
* like one checksum size does not result in extra copy.
*/
public static final int SMALL_HDR_BUFFER_SIZE = 64;
/**
* Util method to build socket addr from either:
* <host>:<post>
* <fs>://<host>:<port>/<path>
*/
public static InetSocketAddress createSocketAddr(String target
) throws IOException {
int colonIndex = target.indexOf(':');
if (colonIndex < 0) {
throw new RuntimeException("Not a host:port pair: " + target);
}
String hostname;
int port;
if (!target.contains("/")) {
// must be the old style <host>:<port>
hostname = target.substring(0, colonIndex);
port = Integer.parseInt(target.substring(colonIndex + 1));
} else {
// a new uri
URI addr = new Path(target).toUri();
hostname = addr.getHost();
port = addr.getPort();
}
return new InetSocketAddress(hostname, port);
}
DatanodeProtocol namenode = null;
FSDataset data = null;
DatanodeRegistration dnRegistration = null;
private String networkLoc;
volatile boolean shouldRun = true;
LinkedList<Block> receivedBlockList = new LinkedList<Block>();
int xmitsInProgress = 0;
Daemon dataXceiveServer = null;
long blockReportInterval;
long lastBlockReport = 0;
long lastHeartbeat = 0;
long heartBeatInterval;
private DataStorage storage = null;
private StatusHttpServer infoServer = null;
private DataNodeMetrics myMetrics;
private static InetSocketAddress nameNodeAddr;
private static DataNode datanodeObject = null;
private static Thread dataNodeThread = null;
String machineName;
int defaultBytesPerChecksum = 512;
private static class DataNodeMetrics implements Updater {
private final MetricsRecord metricsRecord;
private int bytesWritten = 0;
private int bytesRead = 0;
private int blocksWritten = 0;
private int blocksRead = 0;
private int blocksReplicated = 0;
private int blocksRemoved = 0;
DataNodeMetrics(Configuration conf) {
String sessionId = conf.get("session.id");
// Initiate reporting of Java VM metrics
JvmMetrics.init("DataNode", sessionId);
// Create record for DataNode metrics
MetricsContext context = MetricsUtil.getContext("dfs");
metricsRecord = MetricsUtil.createRecord(context, "datanode");
metricsRecord.setTag("sessionId", sessionId);
context.registerUpdater(this);
}
/**
* Since this object is a registered updater, this method will be called
* periodically, e.g. every 5 seconds.
*/
public void doUpdates(MetricsContext unused) {
synchronized (this) {
metricsRecord.incrMetric("bytes_read", bytesRead);
metricsRecord.incrMetric("bytes_written", bytesWritten);
metricsRecord.incrMetric("blocks_read", blocksRead);
metricsRecord.incrMetric("blocks_written", blocksWritten);
metricsRecord.incrMetric("blocks_replicated", blocksReplicated);
metricsRecord.incrMetric("blocks_removed", blocksRemoved);
bytesWritten = 0;
bytesRead = 0;
blocksWritten = 0;
blocksRead = 0;
blocksReplicated = 0;
blocksRemoved = 0;
}
metricsRecord.update();
}
synchronized void readBytes(int nbytes) {
bytesRead += nbytes;
}
synchronized void wroteBytes(int nbytes) {
bytesWritten += nbytes;
}
synchronized void readBlocks(int nblocks) {
blocksRead += nblocks;
}
synchronized void wroteBlocks(int nblocks) {
blocksWritten += nblocks;
}
synchronized void replicatedBlocks(int nblocks) {
blocksReplicated += nblocks;
}
synchronized void removedBlocks(int nblocks) {
blocksRemoved += nblocks;
}
}
/**
* Create the DataNode given a configuration and an array of dataDirs.
* 'dataDirs' is where the blocks are stored.
*/
DataNode(Configuration conf,
AbstractList<File> dataDirs) throws IOException {
myMetrics = new DataNodeMetrics(conf);
datanodeObject = this;
try {
startDataNode(conf, dataDirs);
} catch (IOException ie) {
shutdown();
throw ie;
}
}
void startDataNode(Configuration conf,
AbstractList<File> dataDirs
) throws IOException {
// use configured nameserver & interface to get local hostname
machineName = DNS.getDefaultHost(
conf.get("dfs.datanode.dns.interface","default"),
conf.get("dfs.datanode.dns.nameserver","default"));
InetSocketAddress nameNodeAddr = createSocketAddr(
conf.get("fs.default.name", "local"));
this.defaultBytesPerChecksum =
Math.max(conf.getInt("io.bytes.per.checksum", 512), 1);
int tmpPort = conf.getInt("dfs.datanode.port", 50010);
storage = new DataStorage();
// construct registration
this.dnRegistration = new DatanodeRegistration(machineName + ":" + tmpPort);
// connect to name node
this.namenode = (DatanodeProtocol)
RPC.waitForProxy(DatanodeProtocol.class,
DatanodeProtocol.versionID,
nameNodeAddr,
conf);
// get version and id info from the name-node
NamespaceInfo nsInfo = handshake();
// read storage info, lock data dirs and transition fs state if necessary
StartupOption startOpt = getStartupOption(conf);
assert startOpt != null : "Startup option must be set.";
storage.recoverTransitionRead(nsInfo, dataDirs, startOpt);
// adjust
this.dnRegistration.setStorageInfo(storage);
// initialize data node internal structure
this.data = new FSDataset(storage, conf);
// find free port
ServerSocket ss = null;
String bindAddress = conf.get("dfs.datanode.bindAddress", "0.0.0.0");
while (ss == null) {
try {
ss = new ServerSocket(tmpPort, 0, InetAddress.getByName(bindAddress));
LOG.info("Opened server at " + tmpPort);
} catch (IOException ie) {
LOG.info("Could not open server at " + tmpPort + ", trying new port");
tmpPort++;
}
}
// adjust machine name with the actual port
this.dnRegistration.setName(machineName + ":" + tmpPort);
this.dataXceiveServer = new Daemon(new DataXceiveServer(ss));
long blockReportIntervalBasis =
conf.getLong("dfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);
this.blockReportInterval =
blockReportIntervalBasis - new Random().nextInt((int)(blockReportIntervalBasis/10));
this.heartBeatInterval = conf.getLong("dfs.heartbeat.interval", HEARTBEAT_INTERVAL) * 1000L;
DataNode.nameNodeAddr = nameNodeAddr;
//create a servlet to serve full-file content
int infoServerPort = conf.getInt("dfs.datanode.info.port", 50075);
String infoServerBindAddress = conf.get("dfs.datanode.info.bindAddress", "0.0.0.0");
this.infoServer = new StatusHttpServer("datanode", infoServerBindAddress, infoServerPort, true);
this.infoServer.addServlet(null, "/streamFile/*", StreamFile.class);
this.infoServer.start();
// adjust info port
this.dnRegistration.setInfoPort(this.infoServer.getPort());
// get network location
this.networkLoc = conf.get("dfs.datanode.rack");
if (networkLoc == null) // exec network script or set the default rack
networkLoc = getNetworkLoc(conf);
// register datanode
register();
}
private NamespaceInfo handshake() throws IOException {
NamespaceInfo nsInfo = new NamespaceInfo();
while (shouldRun) {
try {
nsInfo = namenode.versionRequest();
break;
} catch(SocketTimeoutException e) { // namenode is busy
LOG.info("Problem connecting to server: " + getNameNodeAddr());
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
}
String errorMsg = null;
// verify build version
if( ! nsInfo.getBuildVersion().equals( Storage.getBuildVersion() )) {
errorMsg = "Incompatible build versions: namenode BV = "
+ nsInfo.getBuildVersion() + "; datanode BV = "
+ Storage.getBuildVersion();
LOG.fatal( errorMsg );
try {
namenode.errorReport( dnRegistration,
DatanodeProtocol.NOTIFY, errorMsg );
} catch( SocketTimeoutException e ) { // namenode is busy
LOG.info("Problem connecting to server: " + getNameNodeAddr());
}
throw new IOException( errorMsg );
}
assert FSConstants.LAYOUT_VERSION == nsInfo.getLayoutVersion() :
"Data-node and name-node layout versions must be the same.";
return nsInfo;
}
/** Return the DataNode object
*
*/
public static DataNode getDataNode() {
return datanodeObject;
}
public InetSocketAddress getNameNodeAddr() {
return nameNodeAddr;
}
/**
* Return the namenode's identifier
*/
public String getNamenode() {
//return namenode.toString();
return "<namenode>";
}
/**
* Register datanode
* <p>
* The datanode needs to register with the namenode on startup in order
* 1) to report which storage it is serving now and
* 2) to receive a registrationID
* issued by the namenode to recognize registered datanodes.
*
* @see FSNamesystem#registerDatanode(DatanodeRegistration,String)
* @throws IOException
*/
private void register() throws IOException {
while(shouldRun) {
try {
// reset name to machineName. Mainly for web interface.
dnRegistration.name = machineName + ":" + dnRegistration.getPort();
dnRegistration = namenode.register(dnRegistration, networkLoc);
break;
} catch(SocketTimeoutException e) { // namenode is busy
LOG.info("Problem connecting to server: " + getNameNodeAddr());
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
}
assert ("".equals(storage.getStorageID())
&& !"".equals(dnRegistration.getStorageID()))
|| storage.getStorageID().equals(dnRegistration.getStorageID()) :
"New storageID can be assigned only if data-node is not formatted";
if (storage.getStorageID().equals("")) {
storage.setStorageID(dnRegistration.getStorageID());
storage.writeAll();
LOG.info("New storage id " + dnRegistration.getStorageID()
+ " is assigned to data-node " + dnRegistration.getName());
}
if(! storage.getStorageID().equals(dnRegistration.getStorageID())) {
throw new IOException("Inconsistent storage IDs. Name-node returned "
+ dnRegistration.getStorageID()
+ ". Expecting " + storage.getStorageID());
}
}
/**
* Shut down this instance of the datanode.
* Returns only after shutdown is complete.
*/
public void shutdown() {
if (infoServer != null) {
try {
infoServer.stop();
} catch (Exception e) {
}
}
this.shouldRun = false;
if (dataXceiveServer != null) {
((DataXceiveServer) this.dataXceiveServer.getRunnable()).kill();
this.dataXceiveServer.interrupt();
}
if(upgradeManager != null)
upgradeManager.shutdownUpgrade();
if (storage != null) {
try {
this.storage.unlockAll();
} catch (IOException ie) {
}
}
if (dataNodeThread != null) {
dataNodeThread.interrupt();
try {
dataNodeThread.join();
} catch (InterruptedException ie) {
}
}
}
/* Check if there is no space in disk or the disk is read-only
* when IOException occurs.
* If so, handle the error */
private void checkDiskError( IOException e ) throws IOException {
if (e.getMessage().startsWith("No space left on device")) {
throw new DiskOutOfSpaceException("No space left on device");
} else {
checkDiskError();
}
}
/* Check if there is no disk space and if so, handle the error*/
private void checkDiskError( ) throws IOException {
try {
data.checkDataDir();
} catch(DiskErrorException de) {
handleDiskError(de.getMessage());
}
}
private void handleDiskError(String errMsgr) {
LOG.warn("DataNode is shutting down.\n" + errMsgr);
try {
namenode.errorReport(
dnRegistration, DatanodeProtocol.DISK_ERROR, errMsgr);
} catch(IOException ignored) {
}
shutdown();
}
private static class Count {
int value = 0;
Count(int init) { value = init; }
synchronized void incr() { value++; }
synchronized void decr() { value--; }
public String toString() { return Integer.toString(value); }
public int getValue() { return value; }
}
Count xceiverCount = new Count(0);
/**
* Main loop for the DataNode. Runs until shutdown,
* forever calling remote NameNode functions.
*/
public void offerService() throws Exception {
LOG.info("using BLOCKREPORT_INTERVAL of " + blockReportInterval + "msec");
//
// Now loop for a long time....
//
while (shouldRun) {
try {
long now = System.currentTimeMillis();
//
// Every so often, send heartbeat or block-report
//
if (now - lastHeartbeat > heartBeatInterval) {
//
// All heartbeat messages include following info:
// -- Datanode name
// -- data transfer port
// -- Total capacity
// -- Bytes remaining
//
DatanodeCommand cmd = namenode.sendHeartbeat(dnRegistration,
data.getCapacity(),
data.getRemaining(),
xmitsInProgress,
xceiverCount.getValue());
//LOG.info("Just sent heartbeat, with name " + localName);
lastHeartbeat = now;
if (!processCommand(cmd))
continue;
}
// check if there are newly received blocks
Block [] blockArray=null;
synchronized(receivedBlockList) {
if (receivedBlockList.size() > 0) {
//
// Send newly-received blockids to namenode
//
blockArray = receivedBlockList.toArray(new Block[receivedBlockList.size()]);
}
}
if (blockArray != null) {
namenode.blockReceived(dnRegistration, blockArray);
synchronized (receivedBlockList) {
for(Block b: blockArray) {
receivedBlockList.remove(b);
}
}
}
// send block report
if (now - lastBlockReport > blockReportInterval) {
//
// Send latest blockinfo report if timer has expired.
// Get back a list of local block(s) that are obsolete
// and can be safely GC'ed.
//
DatanodeCommand cmd = namenode.blockReport(dnRegistration,
data.getBlockReport());
//
// If we have sent the first block report, then wait a random
// time before we start the periodic block reports.
//
if (lastBlockReport == 0) {
lastBlockReport = now - new Random().nextInt((int)(blockReportInterval));
} else {
lastBlockReport = now;
}
processCommand(cmd);
}
//
// There is no work to do; sleep until hearbeat timer elapses,
// or work arrives, and then iterate again.
//
long waitTime = heartBeatInterval - (System.currentTimeMillis() - lastHeartbeat);
synchronized(receivedBlockList) {
if (waitTime > 0 && receivedBlockList.size() == 0) {
try {
receivedBlockList.wait(waitTime);
} catch (InterruptedException ie) {
}
}
} // synchronized
} catch(RemoteException re) {
String reClass = re.getClassName();
if (UnregisteredDatanodeException.class.getName().equals(reClass) ||
DisallowedDatanodeException.class.getName().equals(reClass)) {
LOG.warn("DataNode is shutting down: " +
StringUtils.stringifyException(re));
shutdown();
return;
}
LOG.warn(StringUtils.stringifyException(re));
} catch (IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
} // while (shouldRun)
} // offerService
/**
*
* @param cmd
* @return true if further processing may be required or false otherwise.
* @throws IOException
*/
private boolean processCommand(DatanodeCommand cmd) throws IOException {
if (cmd == null)
return true;
switch(cmd.getAction()) {
case DatanodeProtocol.DNA_TRANSFER:
//
// Send a copy of a block to another datanode
//
BlockCommand bcmd = (BlockCommand)cmd;
transferBlocks(bcmd.getBlocks(), bcmd.getTargets());
break;
case DatanodeProtocol.DNA_INVALIDATE:
//
// Some local block(s) are obsolete and can be
// safely garbage-collected.
//
Block toDelete[] = ((BlockCommand)cmd).getBlocks();
try {
data.invalidate(toDelete);
} catch(IOException e) {
checkDiskError();
throw e;
}
myMetrics.removedBlocks(toDelete.length);
break;
case DatanodeProtocol.DNA_SHUTDOWN:
// shut down the data node
this.shutdown();
return false;
case DatanodeProtocol.DNA_REGISTER:
// namenode requested a registration
register();
lastHeartbeat=0;
lastBlockReport=0;
break;
case DatanodeProtocol.DNA_FINALIZE:
storage.finalizeUpgrade();
break;
case UpgradeCommand.UC_ACTION_START_UPGRADE:
// start distributed upgrade here
processDistributedUpgradeCommand((UpgradeCommand)cmd);
break;
default:
LOG.warn("Unknown DatanodeCommand action: " + cmd.getAction());
}
return true;
}
// Distributed upgrade manager
UpgradeManagerDatanode upgradeManager = new UpgradeManagerDatanode(this);
private void processDistributedUpgradeCommand(UpgradeCommand comm
) throws IOException {
assert upgradeManager != null : "DataNode.upgradeManager is null.";
upgradeManager.processUpgradeCommand(comm);
}
/**
* Start distributed upgrade if it should be initiated by the data-node.
*/
private void startDistributedUpgradeIfNeeded() throws IOException {
UpgradeManagerDatanode um = DataNode.getDataNode().upgradeManager;
assert um != null : "DataNode.upgradeManager is null.";
if(!um.getUpgradeState())
return;
um.setUpgradeState(false, um.getUpgradeVersion());
um.startUpgrade();
return;
}
private void transferBlocks( Block blocks[],
DatanodeInfo xferTargets[][]
) throws IOException {
for (int i = 0; i < blocks.length; i++) {
if (!data.isValidBlock(blocks[i])) {
String errStr = "Can't send invalid block " + blocks[i];
LOG.info(errStr);
namenode.errorReport(dnRegistration,
DatanodeProtocol.INVALID_BLOCK,
errStr);
break;
}
if (xferTargets[i].length > 0) {
LOG.info("Starting thread to transfer block " + blocks[i] + " to " + xferTargets[i]);
new Daemon(new DataTransfer(xferTargets[i], blocks[i])).start();
}
}
}
/**
* Server used for receiving/sending a block of data.
* This is created to listen for requests from clients or
* other DataNodes. This small server does not use the
* Hadoop IPC mechanism.
*/
class DataXceiveServer implements Runnable {
ServerSocket ss;
public DataXceiveServer(ServerSocket ss) {
this.ss = ss;
}
/**
*/
public void run() {
try {
while (shouldRun) {
Socket s = ss.accept();
//s.setSoTimeout(READ_TIMEOUT);
xceiverCount.incr();
new Daemon(new DataXceiver(s)).start();
}
ss.close();
} catch (IOException ie) {
LOG.info("Exiting DataXceiveServer due to " + ie.toString());
}
}
public void kill() {
assert shouldRun == false :
"shoudRun should be set to false before killing";
try {
this.ss.close();
} catch (IOException iex) {
}
}
}
/**
* Thread for processing incoming/outgoing data stream
*/
class DataXceiver implements Runnable {
Socket s;
public DataXceiver(Socket s) {
this.s = s;
LOG.debug("Number of active connections is: "+xceiverCount);
}
/**
* Read/write data from/to the DataXceiveServer.
*/
public void run() {
try {
DataInputStream in = new DataInputStream(
new BufferedInputStream(s.getInputStream(), SMALL_HDR_BUFFER_SIZE));
short version = in.readShort();
if ( version != DATA_TRANFER_VERSION ) {
throw new IOException( "Version Mismatch" );
}
byte op = in.readByte();
switch ( op ) {
case OP_READ_BLOCK:
readBlock( in );
break;
case OP_WRITE_BLOCK:
writeBlock( in );
break;
case OP_READ_METADATA:
readMetadata( in );
default:
System.out.println("Faulty op: " + op);
throw new IOException("Unknown opcode " + op + "in data stream");
}
} catch (Throwable t) {
LOG.error("DataXCeiver", t);
} finally {
try {
xceiverCount.decr();
LOG.debug("Number of active connections is: "+xceiverCount);
s.close();
} catch (IOException ie2) {
}
}
}
/**
* Read a block from the disk
* @param in The stream to read from
* @throws IOException
*/
private void readBlock(DataInputStream in) throws IOException {
//
// Read in the header
//
long blockId = in.readLong();
Block block = new Block( blockId, 0 );
long startOffset = in.readLong();
long length = in.readLong();
try {
//XXX Buffered output stream?
long read = sendBlock(s, block, startOffset, length, null );
myMetrics.readBytes((int)read);
myMetrics.readBlocks(1);
LOG.info("Served block " + block + " to " + s.getInetAddress());
} catch ( SocketException ignored ) {
// Its ok for remote side to close the connection anytime.
myMetrics.readBlocks(1);
} catch ( IOException ioe ) {
/* What exactly should we do here?
* Earlier version shutdown() datanode if there is disk error.
*/
LOG.warn( "Got exception while serving " + block + " to " +
s.getInetAddress() + ": " +
StringUtils.stringifyException(ioe) );
throw ioe;
}
}
/**
* Write a block to disk.
* @param in The stream to read from
* @throws IOException
*/
private void writeBlock(DataInputStream in) throws IOException {
//
// Read in the header
//
DataOutputStream reply = new DataOutputStream(s.getOutputStream());
DataOutputStream out = null;
DataOutputStream checksumOut = null;
Socket mirrorSock = null;
DataOutputStream mirrorOut = null;
DataInputStream mirrorIn = null;
try {
/* We need an estimate for block size to check if the
* disk partition has enough space. For now we just increment
* FSDataset.reserved by configured dfs.block.size
* Other alternative is to include the block size in the header
* sent by DFSClient.
*/
Block block = new Block( in.readLong(), 0 );
int numTargets = in.readInt();
if ( numTargets < 0 ) {
throw new IOException("Mislabelled incoming datastream.");
}
DatanodeInfo targets[] = new DatanodeInfo[numTargets];
for (int i = 0; i < targets.length; i++) {
DatanodeInfo tmp = new DatanodeInfo();
tmp.readFields(in);
targets[i] = tmp;
}
DataChecksum checksum = DataChecksum.newDataChecksum( in );
//
// Open local disk out
//
FSDataset.BlockWriteStreams streams = data.writeToBlock( block );
out = new DataOutputStream(streams.dataOut);
checksumOut = new DataOutputStream(streams.checksumOut);
InetSocketAddress mirrorTarget = null;
String mirrorNode = null;
//
// Open network conn to backup machine, if
// appropriate
//
if (targets.length > 0) {
// Connect to backup machine
mirrorNode = targets[0].getName();
mirrorTarget = createSocketAddr(mirrorNode);
try {
mirrorSock = new Socket();
mirrorSock.connect(mirrorTarget, READ_TIMEOUT);
mirrorSock.setSoTimeout(READ_TIMEOUT);
mirrorOut = new DataOutputStream(
new BufferedOutputStream(mirrorSock.getOutputStream(),
SMALL_HDR_BUFFER_SIZE));
mirrorIn = new DataInputStream( mirrorSock.getInputStream() );
//Copied from DFSClient.java!
mirrorOut.writeShort( DATA_TRANFER_VERSION );
mirrorOut.write( OP_WRITE_BLOCK );
mirrorOut.writeLong( block.getBlockId() );
mirrorOut.writeInt( targets.length - 1 );
for ( int i = 1; i < targets.length; i++ ) {
targets[i].write( mirrorOut );
}
checksum.writeHeader( mirrorOut );
myMetrics.replicatedBlocks(1);
} catch (IOException ie) {
if (mirrorOut != null) {
LOG.info("Exception connecting to mirror " + mirrorNode
+ "\n" + StringUtils.stringifyException(ie));
mirrorOut = null;
}
}
}
// XXX The following code is similar on both sides...
int bytesPerChecksum = checksum.getBytesPerChecksum();
int checksumSize = checksum.getChecksumSize();
byte buf[] = new byte[ bytesPerChecksum + checksumSize ];
long blockLen = 0;
long lastOffset = 0;
long lastLen = 0;
int status = -1;
boolean headerWritten = false;
while ( true ) {
// Read one data chunk in each loop.
long offset = lastOffset + lastLen;
int len = (int) in.readInt();
if ( len < 0 || len > bytesPerChecksum ) {
LOG.warn( "Got wrong length during writeBlock(" +
block + ") from " + s.getRemoteSocketAddress() +
" at offset " + offset + ": " + len +
" expected <= " + bytesPerChecksum );
status = OP_STATUS_ERROR;
break;
}
in.readFully( buf, 0, len + checksumSize );
if ( len > 0 && checksumSize > 0 ) {
/*
* Verification is not included in the initial design.
* For now, it at least catches some bugs. Later, we can
* include this after showing that it does not affect
* performance much.
*/
checksum.update( buf, 0, len );
if ( ! checksum.compare( buf, len ) ) {
throw new IOException( "Unexpected checksum mismatch " +
"while writing " + block +
" from " +
s.getRemoteSocketAddress() );
}
checksum.reset();
}
// First write to remote node before writing locally.
if (mirrorOut != null) {
try {
mirrorOut.writeInt( len );
mirrorOut.write( buf, 0, len + checksumSize );
} catch (IOException ioe) {
LOG.info( "Exception writing to mirror " + mirrorNode +
"\n" + StringUtils.stringifyException(ioe) );
//
// If stream-copy fails, continue
// writing to disk. We shouldn't
// interrupt client write.
//
mirrorOut = null;
}
}
try {
if ( !headerWritten ) {
// First DATA_CHUNK.
// Write the header even if checksumSize is 0.
checksumOut.writeShort( FSDataset.METADATA_VERSION );
checksum.writeHeader( checksumOut );
headerWritten = true;
}
if ( len > 0 ) {
out.write( buf, 0, len );
// Write checksum
checksumOut.write( buf, len, checksumSize );
myMetrics.wroteBytes( len );
+ } else {
+ /* Should we sync() files here? It can add many millisecs of
+ * latency. We did not sync before HADOOP-1134 either.
+ */
+ out.close();
+ out = null;
+ checksumOut.close();
+ checksumOut = null;
}
} catch (IOException iex) {
checkDiskError(iex);
throw iex;
}
if ( len == 0 ) {
// We already have one successful write here. Should we
// wait for response from next target? We will skip for now.
block.setNumBytes( blockLen );
//Does this fsync()?
data.finalizeBlock( block );
myMetrics.wroteBlocks(1);
status = OP_STATUS_SUCCESS;
break;
}
if ( lastLen > 0 && lastLen != bytesPerChecksum ) {
LOG.warn( "Got wrong length during writeBlock(" +
block + ") from " + s.getRemoteSocketAddress() +
" : " + " got " + lastLen + " instead of " +
bytesPerChecksum );
status = OP_STATUS_ERROR;
break;
}
lastOffset = offset;
lastLen = len;
blockLen += len;
}
// done with reading the data.
if ( status == OP_STATUS_SUCCESS ) {
/* Informing the name node could take a long long time!
Should we wait till namenode is informed before responding
with success to the client? For now we don't.
*/
synchronized ( receivedBlockList ) {
receivedBlockList.add( block );
receivedBlockList.notifyAll();
}
String msg = "Received block " + block + " from " +
s.getInetAddress();
if ( mirrorOut != null ) {
//Wait for the remote reply
mirrorOut.flush();
byte result = OP_STATUS_ERROR;
try {
result = mirrorIn.readByte();
} catch ( IOException ignored ) {}
msg += " and " + (( result != OP_STATUS_SUCCESS ) ?
"failed to mirror to " : " mirrored to ") +
mirrorTarget;
mirrorOut = null;
}
LOG.info(msg);
}
if ( status >= 0 ) {
try {
reply.writeByte( status );
reply.flush();
} catch ( IOException ignored ) {}
}
} finally {
try {
if ( out != null )
out.close();
if ( checksumOut != null )
checksumOut.close();
if ( mirrorSock != null )
mirrorSock.close();
} catch (IOException iex) {
shutdown();
throw iex;
}
}
}
/**
* Reads the metadata and sends the data in one 'DATA_CHUNK'
* @param in
*/
void readMetadata(DataInputStream in) throws IOException {
Block block = new Block( in.readLong(), 0 );
InputStream checksumIn = null;
DataOutputStream out = null;
try {
File blockFile = data.getBlockFile( block );
File checksumFile = FSDataset.getMetaFile( blockFile );
checksumIn = new FileInputStream(checksumFile);
long fileSize = checksumFile.length();
if (fileSize >= 1L<<31 || fileSize <= 0) {
throw new IOException("Unexpected size for checksumFile " +
checksumFile);
}
byte [] buf = new byte[(int)fileSize];
FileUtil.readFully(checksumIn, buf, 0, buf.length);
out = new DataOutputStream(s.getOutputStream());
out.writeByte(OP_STATUS_SUCCESS);
out.writeInt(buf.length);
out.write(buf);
//last DATA_CHUNK
out.writeInt(0);
} finally {
FileUtil.closeStream(checksumIn);
}
}
}
/** sendBlock() is used to read block and its metadata and stream
* the data to either a client or to another datanode.
* If argument targets is null, then it is assumed to be replying
* to a client request (OP_BLOCK_READ). Otherwise, we are replicating
* to another datanode.
*
* returns total bytes reads, including crc.
*/
long sendBlock(Socket sock, Block block,
long startOffset, long length, DatanodeInfo targets[] )
throws IOException {
// May be we should just use io.file.buffer.size.
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(sock.getOutputStream(),
SMALL_HDR_BUFFER_SIZE));
DataInputStream in = null;
DataInputStream checksumIn = null;
long totalRead = 0;
/* XXX This will affect inter datanode transfers during
* a CRC upgrade. There should not be any replication
* during crc upgrade since we are in safe mode, right?
*/
boolean corruptChecksumOk = targets == null;
try {
File blockFile = data.getBlockFile( block );
in = new DataInputStream( new FileInputStream( blockFile ) );
File checksumFile = FSDataset.getMetaFile( blockFile );
DataChecksum checksum = null;
if ( !corruptChecksumOk || checksumFile.exists() ) {
checksumIn = new DataInputStream( new FileInputStream(checksumFile) );
//read and handle the common header here. For now just a version
short version = checksumIn.readShort();
if ( version != FSDataset.METADATA_VERSION ) {
LOG.warn( "Wrong version (" + version +
") for metadata file for " + block + " ignoring ..." );
}
checksum = DataChecksum.newDataChecksum( checksumIn ) ;
} else {
LOG.warn( "Could not find metadata file for " + block );
// This only decides the buffer size. Use BUFFER_SIZE?
checksum = DataChecksum.newDataChecksum( DataChecksum.CHECKSUM_NULL,
16*1024 );
}
int bytesPerChecksum = checksum.getBytesPerChecksum();
int checksumSize = checksum.getChecksumSize();
long endOffset = data.getLength( block );
if ( startOffset < 0 || startOffset > endOffset ||
(length + startOffset) > endOffset ) {
String msg = " Offset " + startOffset + " and length " + length +
" don't match block " + block + " ( blockLen " +
endOffset + " )";
LOG.warn( "sendBlock() : " + msg );
if ( targets != null ) {
throw new IOException(msg);
} else {
out.writeShort( OP_STATUS_ERROR_INVALID );
return totalRead;
}
}
byte buf[] = new byte[ bytesPerChecksum + checksumSize ];
long offset = (startOffset - (startOffset % bytesPerChecksum));
if ( length >= 0 ) {
// Make sure endOffset points to end of a checksumed chunk.
long tmpLen = startOffset + length + (startOffset - offset);
if ( tmpLen % bytesPerChecksum != 0 ) {
tmpLen += ( bytesPerChecksum - tmpLen % bytesPerChecksum );
}
if ( tmpLen < endOffset ) {
endOffset = tmpLen;
}
}
// seek to the right offsets
if ( offset > 0 ) {
long checksumSkip = ( offset / bytesPerChecksum ) * checksumSize ;
/* XXX skip() could be very inefficent. Should be seek().
* at least skipFully
*/
if ( in.skip( offset ) != offset ||
( checksumSkip > 0 &&
checksumIn.skip( checksumSkip ) != checksumSkip ) ) {
throw new IOException( "Could not seek to right position while " +
"reading for " + block );
}
}
if ( targets != null ) {
//
// Header info
//
out.writeShort( DATA_TRANFER_VERSION );
out.writeByte( OP_WRITE_BLOCK );
out.writeLong( block.getBlockId() );
out.writeInt(targets.length-1);
for (int i = 1; i < targets.length; i++) {
targets[i].write( out );
}
} else {
out.writeShort( OP_STATUS_SUCCESS );
}
checksum.writeHeader( out );
if ( targets == null ) {
out.writeLong( offset );
}
while ( endOffset >= offset ) {
// Write one data chunk per loop.
int len = (int) Math.min( endOffset - offset, bytesPerChecksum );
if ( len > 0 ) {
in.readFully( buf, 0, len );
totalRead += len;
if ( checksumSize > 0 && checksumIn != null ) {
try {
checksumIn.readFully( buf, len, checksumSize );
totalRead += checksumSize;
} catch ( IOException e ) {
LOG.warn( " Could not read checksum for data at offset " +
offset + " for block " + block + " got : " +
StringUtils.stringifyException(e) );
FileUtil.closeStream( checksumIn );
checksumIn = null;
if ( corruptChecksumOk ) {
// Just fill the array with zeros.
Arrays.fill( buf, len, len + checksumSize, (byte)0 );
} else {
throw e;
}
}
}
}
out.writeInt( len );
out.write( buf, 0, len + checksumSize );
if ( offset == endOffset ) {
out.flush();
// We are not waiting for response from target.
break;
}
offset += len;
}
} finally {
FileUtil.closeStream( checksumIn );
FileUtil.closeStream( in );
FileUtil.closeStream( out );
}
return totalRead;
}
/**
* Used for transferring a block of data. This class
* sends a piece of data to another DataNode.
*/
class DataTransfer implements Runnable {
DatanodeInfo targets[];
Block b;
/**
* Connect to the first item in the target list. Pass along the
* entire target list, the block, and the data.
*/
public DataTransfer(DatanodeInfo targets[], Block b) throws IOException {
this.targets = targets;
this.b = b;
}
/**
* Do the deed, write the bytes
*/
public void run() {
xmitsInProgress++;
Socket sock = null;
try {
InetSocketAddress curTarget =
createSocketAddr(targets[0].getName());
sock = new Socket();
sock.connect(curTarget, READ_TIMEOUT);
sock.setSoTimeout(READ_TIMEOUT);
sendBlock( sock, b, 0, -1, targets );
LOG.info( "Transmitted block " + b + " to " + curTarget );
} catch ( IOException ie ) {
LOG.warn( "Failed to transfer " + b + " to " +
targets[0].getName() + " got " +
StringUtils.stringifyException( ie ) );
} finally {
FileUtil.closeSocket(sock);
xmitsInProgress--;
}
}
}
/**
* No matter what kind of exception we get, keep retrying to offerService().
* That's the loop that connects to the NameNode and provides basic DataNode
* functionality.
*
* Only stop when "shouldRun" is turned off (which can only happen at shutdown).
*/
public void run() {
LOG.info("In DataNode.run, data = " + data);
// start dataXceiveServer
dataXceiveServer.start();
while (shouldRun) {
try {
startDistributedUpgradeIfNeeded();
offerService();
} catch (Exception ex) {
LOG.error("Exception: " + StringUtils.stringifyException(ex));
if (shouldRun) {
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
}
}
// wait for dataXceiveServer to terminate
try {
this.dataXceiveServer.join();
} catch (InterruptedException ie) {
}
LOG.info("Finishing DataNode in: "+data);
}
/** Start datanode daemon.
*/
public static DataNode run(Configuration conf) throws IOException {
String[] dataDirs = conf.getStrings("dfs.data.dir");
DataNode dn = makeInstance(dataDirs, conf);
if (dn != null) {
dataNodeThread = new Thread(dn, "DataNode: [" +
StringUtils.arrayToString(dataDirs) + "]");
dataNodeThread.setDaemon(true); // needed for JUnit testing
dataNodeThread.start();
}
return dn;
}
/** Start a single datanode daemon and wait for it to finish.
* If this thread is specifically interrupted, it will stop waiting.
*/
static DataNode createDataNode(String args[],
Configuration conf) throws IOException {
if (conf == null)
conf = new Configuration();
if (!parseArguments(args, conf)) {
printUsage();
return null;
}
return run(conf);
}
void join() {
if (dataNodeThread != null) {
try {
dataNodeThread.join();
} catch (InterruptedException e) {}
}
}
/**
* Make an instance of DataNode after ensuring that at least one of the
* given data directories (and their parent directories, if necessary)
* can be created.
* @param dataDirs List of directories, where the new DataNode instance should
* keep its files.
* @param conf Configuration instance to use.
* @return DataNode instance for given list of data dirs and conf, or null if
* no directory from this directory list can be created.
* @throws IOException
*/
static DataNode makeInstance(String[] dataDirs, Configuration conf)
throws IOException {
ArrayList<File> dirs = new ArrayList<File>();
for (int i = 0; i < dataDirs.length; i++) {
File data = new File(dataDirs[i]);
try {
DiskChecker.checkDir(data);
dirs.add(data);
} catch(DiskErrorException e) {
LOG.warn("Invalid directory in dfs.data.dir: " + e.getMessage());
}
}
if (dirs.size() > 0)
return new DataNode(conf, dirs);
LOG.error("All directories in dfs.data.dir are invalid.");
return null;
}
public String toString() {
return "DataNode{" +
"data=" + data +
", localName='" + dnRegistration.getName() + "'" +
", storageID='" + dnRegistration.getStorageID() + "'" +
", xmitsInProgress=" + xmitsInProgress +
"}";
}
private static void printUsage() {
System.err.println("Usage: java DataNode");
System.err.println(" [-r, --rack <network location>] |");
System.err.println(" [-rollback]");
}
/**
* Parse and verify command line arguments and set configuration parameters.
*
* @return false if passed argements are incorrect
*/
private static boolean parseArguments(String args[],
Configuration conf) {
int argsLen = (args == null) ? 0 : args.length;
StartupOption startOpt = StartupOption.REGULAR;
String networkLoc = null;
for(int i=0; i < argsLen; i++) {
String cmd = args[i];
if ("-r".equalsIgnoreCase(cmd) || "--rack".equalsIgnoreCase(cmd)) {
if (i==args.length-1)
return false;
networkLoc = args[++i];
if (networkLoc.startsWith("-"))
return false;
} else if ("-rollback".equalsIgnoreCase(cmd)) {
startOpt = StartupOption.ROLLBACK;
} else if ("-regular".equalsIgnoreCase(cmd)) {
startOpt = StartupOption.REGULAR;
} else
return false;
}
if (networkLoc != null)
conf.set("dfs.datanode.rack", NodeBase.normalize(networkLoc));
setStartupOption(conf, startOpt);
return true;
}
private static void setStartupOption(Configuration conf, StartupOption opt) {
conf.set("dfs.datanode.startup", opt.toString());
}
static StartupOption getStartupOption(Configuration conf) {
return StartupOption.valueOf(conf.get("dfs.datanode.startup",
StartupOption.REGULAR.toString()));
}
/* Get the network location by running a script configured in conf */
private static String getNetworkLoc(Configuration conf)
throws IOException {
String locScript = conf.get("dfs.network.script");
if (locScript == null)
return NetworkTopology.DEFAULT_RACK;
LOG.info("Starting to run script to get datanode network location");
Process p = Runtime.getRuntime().exec(locScript);
StringBuffer networkLoc = new StringBuffer();
final BufferedReader inR = new BufferedReader(
new InputStreamReader(p.getInputStream()));
final BufferedReader errR = new BufferedReader(
new InputStreamReader(p.getErrorStream()));
// read & log any error messages from the running script
Thread errThread = new Thread() {
public void start() {
try {
String errLine = errR.readLine();
while(errLine != null) {
LOG.warn("Network script error: "+errLine);
errLine = errR.readLine();
}
} catch(IOException e) {
}
}
};
try {
errThread.start();
// fetch output from the process
String line = inR.readLine();
while(line != null) {
networkLoc.append(line);
line = inR.readLine();
}
try {
// wait for the process to finish
int returnVal = p.waitFor();
// check the exit code
if (returnVal != 0) {
throw new IOException("Process exits with nonzero status: "+locScript);
}
} catch (InterruptedException e) {
throw new IOException(e.getMessage());
} finally {
try {
// make sure that the error thread exits
errThread.join();
} catch (InterruptedException je) {
LOG.warn(StringUtils.stringifyException(je));
}
}
} finally {
// close in & error streams
try {
inR.close();
} catch (IOException ine) {
throw ine;
} finally {
errR.close();
}
}
return networkLoc.toString();
}
/**
*/
public static void main(String args[]) {
try {
StringUtils.startupShutdownMessage(DataNode.class, args, LOG);
DataNode datanode = createDataNode(args, null);
if (datanode != null)
datanode.join();
} catch (Throwable e) {
LOG.error(StringUtils.stringifyException(e));
System.exit(-1);
}
}
}
| true | true | private void writeBlock(DataInputStream in) throws IOException {
//
// Read in the header
//
DataOutputStream reply = new DataOutputStream(s.getOutputStream());
DataOutputStream out = null;
DataOutputStream checksumOut = null;
Socket mirrorSock = null;
DataOutputStream mirrorOut = null;
DataInputStream mirrorIn = null;
try {
/* We need an estimate for block size to check if the
* disk partition has enough space. For now we just increment
* FSDataset.reserved by configured dfs.block.size
* Other alternative is to include the block size in the header
* sent by DFSClient.
*/
Block block = new Block( in.readLong(), 0 );
int numTargets = in.readInt();
if ( numTargets < 0 ) {
throw new IOException("Mislabelled incoming datastream.");
}
DatanodeInfo targets[] = new DatanodeInfo[numTargets];
for (int i = 0; i < targets.length; i++) {
DatanodeInfo tmp = new DatanodeInfo();
tmp.readFields(in);
targets[i] = tmp;
}
DataChecksum checksum = DataChecksum.newDataChecksum( in );
//
// Open local disk out
//
FSDataset.BlockWriteStreams streams = data.writeToBlock( block );
out = new DataOutputStream(streams.dataOut);
checksumOut = new DataOutputStream(streams.checksumOut);
InetSocketAddress mirrorTarget = null;
String mirrorNode = null;
//
// Open network conn to backup machine, if
// appropriate
//
if (targets.length > 0) {
// Connect to backup machine
mirrorNode = targets[0].getName();
mirrorTarget = createSocketAddr(mirrorNode);
try {
mirrorSock = new Socket();
mirrorSock.connect(mirrorTarget, READ_TIMEOUT);
mirrorSock.setSoTimeout(READ_TIMEOUT);
mirrorOut = new DataOutputStream(
new BufferedOutputStream(mirrorSock.getOutputStream(),
SMALL_HDR_BUFFER_SIZE));
mirrorIn = new DataInputStream( mirrorSock.getInputStream() );
//Copied from DFSClient.java!
mirrorOut.writeShort( DATA_TRANFER_VERSION );
mirrorOut.write( OP_WRITE_BLOCK );
mirrorOut.writeLong( block.getBlockId() );
mirrorOut.writeInt( targets.length - 1 );
for ( int i = 1; i < targets.length; i++ ) {
targets[i].write( mirrorOut );
}
checksum.writeHeader( mirrorOut );
myMetrics.replicatedBlocks(1);
} catch (IOException ie) {
if (mirrorOut != null) {
LOG.info("Exception connecting to mirror " + mirrorNode
+ "\n" + StringUtils.stringifyException(ie));
mirrorOut = null;
}
}
}
// XXX The following code is similar on both sides...
int bytesPerChecksum = checksum.getBytesPerChecksum();
int checksumSize = checksum.getChecksumSize();
byte buf[] = new byte[ bytesPerChecksum + checksumSize ];
long blockLen = 0;
long lastOffset = 0;
long lastLen = 0;
int status = -1;
boolean headerWritten = false;
while ( true ) {
// Read one data chunk in each loop.
long offset = lastOffset + lastLen;
int len = (int) in.readInt();
if ( len < 0 || len > bytesPerChecksum ) {
LOG.warn( "Got wrong length during writeBlock(" +
block + ") from " + s.getRemoteSocketAddress() +
" at offset " + offset + ": " + len +
" expected <= " + bytesPerChecksum );
status = OP_STATUS_ERROR;
break;
}
in.readFully( buf, 0, len + checksumSize );
if ( len > 0 && checksumSize > 0 ) {
/*
* Verification is not included in the initial design.
* For now, it at least catches some bugs. Later, we can
* include this after showing that it does not affect
* performance much.
*/
checksum.update( buf, 0, len );
if ( ! checksum.compare( buf, len ) ) {
throw new IOException( "Unexpected checksum mismatch " +
"while writing " + block +
" from " +
s.getRemoteSocketAddress() );
}
checksum.reset();
}
// First write to remote node before writing locally.
if (mirrorOut != null) {
try {
mirrorOut.writeInt( len );
mirrorOut.write( buf, 0, len + checksumSize );
} catch (IOException ioe) {
LOG.info( "Exception writing to mirror " + mirrorNode +
"\n" + StringUtils.stringifyException(ioe) );
//
// If stream-copy fails, continue
// writing to disk. We shouldn't
// interrupt client write.
//
mirrorOut = null;
}
}
try {
if ( !headerWritten ) {
// First DATA_CHUNK.
// Write the header even if checksumSize is 0.
checksumOut.writeShort( FSDataset.METADATA_VERSION );
checksum.writeHeader( checksumOut );
headerWritten = true;
}
if ( len > 0 ) {
out.write( buf, 0, len );
// Write checksum
checksumOut.write( buf, len, checksumSize );
myMetrics.wroteBytes( len );
}
} catch (IOException iex) {
checkDiskError(iex);
throw iex;
}
if ( len == 0 ) {
// We already have one successful write here. Should we
// wait for response from next target? We will skip for now.
block.setNumBytes( blockLen );
//Does this fsync()?
data.finalizeBlock( block );
myMetrics.wroteBlocks(1);
status = OP_STATUS_SUCCESS;
break;
}
if ( lastLen > 0 && lastLen != bytesPerChecksum ) {
LOG.warn( "Got wrong length during writeBlock(" +
block + ") from " + s.getRemoteSocketAddress() +
" : " + " got " + lastLen + " instead of " +
bytesPerChecksum );
status = OP_STATUS_ERROR;
break;
}
lastOffset = offset;
lastLen = len;
blockLen += len;
}
// done with reading the data.
if ( status == OP_STATUS_SUCCESS ) {
/* Informing the name node could take a long long time!
Should we wait till namenode is informed before responding
with success to the client? For now we don't.
*/
synchronized ( receivedBlockList ) {
receivedBlockList.add( block );
receivedBlockList.notifyAll();
}
String msg = "Received block " + block + " from " +
s.getInetAddress();
if ( mirrorOut != null ) {
//Wait for the remote reply
mirrorOut.flush();
byte result = OP_STATUS_ERROR;
try {
result = mirrorIn.readByte();
} catch ( IOException ignored ) {}
msg += " and " + (( result != OP_STATUS_SUCCESS ) ?
"failed to mirror to " : " mirrored to ") +
mirrorTarget;
mirrorOut = null;
}
LOG.info(msg);
}
if ( status >= 0 ) {
try {
reply.writeByte( status );
reply.flush();
} catch ( IOException ignored ) {}
}
} finally {
try {
if ( out != null )
out.close();
if ( checksumOut != null )
checksumOut.close();
if ( mirrorSock != null )
mirrorSock.close();
} catch (IOException iex) {
shutdown();
throw iex;
}
}
}
| private void writeBlock(DataInputStream in) throws IOException {
//
// Read in the header
//
DataOutputStream reply = new DataOutputStream(s.getOutputStream());
DataOutputStream out = null;
DataOutputStream checksumOut = null;
Socket mirrorSock = null;
DataOutputStream mirrorOut = null;
DataInputStream mirrorIn = null;
try {
/* We need an estimate for block size to check if the
* disk partition has enough space. For now we just increment
* FSDataset.reserved by configured dfs.block.size
* Other alternative is to include the block size in the header
* sent by DFSClient.
*/
Block block = new Block( in.readLong(), 0 );
int numTargets = in.readInt();
if ( numTargets < 0 ) {
throw new IOException("Mislabelled incoming datastream.");
}
DatanodeInfo targets[] = new DatanodeInfo[numTargets];
for (int i = 0; i < targets.length; i++) {
DatanodeInfo tmp = new DatanodeInfo();
tmp.readFields(in);
targets[i] = tmp;
}
DataChecksum checksum = DataChecksum.newDataChecksum( in );
//
// Open local disk out
//
FSDataset.BlockWriteStreams streams = data.writeToBlock( block );
out = new DataOutputStream(streams.dataOut);
checksumOut = new DataOutputStream(streams.checksumOut);
InetSocketAddress mirrorTarget = null;
String mirrorNode = null;
//
// Open network conn to backup machine, if
// appropriate
//
if (targets.length > 0) {
// Connect to backup machine
mirrorNode = targets[0].getName();
mirrorTarget = createSocketAddr(mirrorNode);
try {
mirrorSock = new Socket();
mirrorSock.connect(mirrorTarget, READ_TIMEOUT);
mirrorSock.setSoTimeout(READ_TIMEOUT);
mirrorOut = new DataOutputStream(
new BufferedOutputStream(mirrorSock.getOutputStream(),
SMALL_HDR_BUFFER_SIZE));
mirrorIn = new DataInputStream( mirrorSock.getInputStream() );
//Copied from DFSClient.java!
mirrorOut.writeShort( DATA_TRANFER_VERSION );
mirrorOut.write( OP_WRITE_BLOCK );
mirrorOut.writeLong( block.getBlockId() );
mirrorOut.writeInt( targets.length - 1 );
for ( int i = 1; i < targets.length; i++ ) {
targets[i].write( mirrorOut );
}
checksum.writeHeader( mirrorOut );
myMetrics.replicatedBlocks(1);
} catch (IOException ie) {
if (mirrorOut != null) {
LOG.info("Exception connecting to mirror " + mirrorNode
+ "\n" + StringUtils.stringifyException(ie));
mirrorOut = null;
}
}
}
// XXX The following code is similar on both sides...
int bytesPerChecksum = checksum.getBytesPerChecksum();
int checksumSize = checksum.getChecksumSize();
byte buf[] = new byte[ bytesPerChecksum + checksumSize ];
long blockLen = 0;
long lastOffset = 0;
long lastLen = 0;
int status = -1;
boolean headerWritten = false;
while ( true ) {
// Read one data chunk in each loop.
long offset = lastOffset + lastLen;
int len = (int) in.readInt();
if ( len < 0 || len > bytesPerChecksum ) {
LOG.warn( "Got wrong length during writeBlock(" +
block + ") from " + s.getRemoteSocketAddress() +
" at offset " + offset + ": " + len +
" expected <= " + bytesPerChecksum );
status = OP_STATUS_ERROR;
break;
}
in.readFully( buf, 0, len + checksumSize );
if ( len > 0 && checksumSize > 0 ) {
/*
* Verification is not included in the initial design.
* For now, it at least catches some bugs. Later, we can
* include this after showing that it does not affect
* performance much.
*/
checksum.update( buf, 0, len );
if ( ! checksum.compare( buf, len ) ) {
throw new IOException( "Unexpected checksum mismatch " +
"while writing " + block +
" from " +
s.getRemoteSocketAddress() );
}
checksum.reset();
}
// First write to remote node before writing locally.
if (mirrorOut != null) {
try {
mirrorOut.writeInt( len );
mirrorOut.write( buf, 0, len + checksumSize );
} catch (IOException ioe) {
LOG.info( "Exception writing to mirror " + mirrorNode +
"\n" + StringUtils.stringifyException(ioe) );
//
// If stream-copy fails, continue
// writing to disk. We shouldn't
// interrupt client write.
//
mirrorOut = null;
}
}
try {
if ( !headerWritten ) {
// First DATA_CHUNK.
// Write the header even if checksumSize is 0.
checksumOut.writeShort( FSDataset.METADATA_VERSION );
checksum.writeHeader( checksumOut );
headerWritten = true;
}
if ( len > 0 ) {
out.write( buf, 0, len );
// Write checksum
checksumOut.write( buf, len, checksumSize );
myMetrics.wroteBytes( len );
} else {
/* Should we sync() files here? It can add many millisecs of
* latency. We did not sync before HADOOP-1134 either.
*/
out.close();
out = null;
checksumOut.close();
checksumOut = null;
}
} catch (IOException iex) {
checkDiskError(iex);
throw iex;
}
if ( len == 0 ) {
// We already have one successful write here. Should we
// wait for response from next target? We will skip for now.
block.setNumBytes( blockLen );
//Does this fsync()?
data.finalizeBlock( block );
myMetrics.wroteBlocks(1);
status = OP_STATUS_SUCCESS;
break;
}
if ( lastLen > 0 && lastLen != bytesPerChecksum ) {
LOG.warn( "Got wrong length during writeBlock(" +
block + ") from " + s.getRemoteSocketAddress() +
" : " + " got " + lastLen + " instead of " +
bytesPerChecksum );
status = OP_STATUS_ERROR;
break;
}
lastOffset = offset;
lastLen = len;
blockLen += len;
}
// done with reading the data.
if ( status == OP_STATUS_SUCCESS ) {
/* Informing the name node could take a long long time!
Should we wait till namenode is informed before responding
with success to the client? For now we don't.
*/
synchronized ( receivedBlockList ) {
receivedBlockList.add( block );
receivedBlockList.notifyAll();
}
String msg = "Received block " + block + " from " +
s.getInetAddress();
if ( mirrorOut != null ) {
//Wait for the remote reply
mirrorOut.flush();
byte result = OP_STATUS_ERROR;
try {
result = mirrorIn.readByte();
} catch ( IOException ignored ) {}
msg += " and " + (( result != OP_STATUS_SUCCESS ) ?
"failed to mirror to " : " mirrored to ") +
mirrorTarget;
mirrorOut = null;
}
LOG.info(msg);
}
if ( status >= 0 ) {
try {
reply.writeByte( status );
reply.flush();
} catch ( IOException ignored ) {}
}
} finally {
try {
if ( out != null )
out.close();
if ( checksumOut != null )
checksumOut.close();
if ( mirrorSock != null )
mirrorSock.close();
} catch (IOException iex) {
shutdown();
throw iex;
}
}
}
|
diff --git a/src/ru/cubelife/clearworld/ClearWorld.java b/src/ru/cubelife/clearworld/ClearWorld.java
index 15df4d0..5ef731a 100644
--- a/src/ru/cubelife/clearworld/ClearWorld.java
+++ b/src/ru/cubelife/clearworld/ClearWorld.java
@@ -1,87 +1,88 @@
package ru.cubelife.clearworld;
import java.io.File;
import java.util.logging.Logger;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class ClearWorld extends JavaPlugin {
/** Логгер */
private Logger log;
/** Конфиг */
private FileConfiguration cfg;
/** Файл конфига */
private File cfgFile;
/** Время в днях */
private long t;
/** Включено ли? */
public static boolean enabled;
/** Время в миллисекундах */
public static long time;
/** Регенирировать ли? */
public static boolean regen;
/** Вызывается при включении */
public void onEnable() {
enabled = true;
cfgFile = new File(getDataFolder(), "config.yml");
cfg = YamlConfiguration.loadConfiguration(cfgFile);
loadCfg(); // Загружаем настройки
saveCfg(); // Сохраняем настройки
PluginManager pm = getServer().getPluginManager();
if(pm.getPlugin("WorldGuard") != null) {
log("Using WorldGuard!");
} else {
log("WorldGuard not founded! Disabling..");
+ this.setEnabled(false);
}
if(regen) {
if(pm.getPlugin("WorldEdit") != null) {
log("Using WorldEdit!");
} else {
log("WorldEdit not founded! Disabling regeneration..");
regen = false;
saveCfg();
}
}
log = Logger.getLogger("Minecraft");
new AutoCleaner().start(); // Запускает в отдельном потоке AutoCleaner
log("Enabled!");
}
/** Вызывается при выключении */
public void onDisable() {
enabled = false;
log("Disabled!");
}
/** Логирует в консоль */
private void log(String msg) {
log.info("[ClearWorld] " + msg);
}
/** Загружает конфиг */
private void loadCfg() {
t = cfg.getInt("time", 30);
time = (t * 24 * 3600 * 1000);
regen = cfg.getBoolean("regen", false);
}
/** Сохраняет конфиг */
private void saveCfg() {
cfg.set("time", t);
cfg.set("regen", regen);
try {
cfg.save(cfgFile);
} catch (Exception e) { }
}
}
| true | true | public void onEnable() {
enabled = true;
cfgFile = new File(getDataFolder(), "config.yml");
cfg = YamlConfiguration.loadConfiguration(cfgFile);
loadCfg(); // Загружаем настройки
saveCfg(); // Сохраняем настройки
PluginManager pm = getServer().getPluginManager();
if(pm.getPlugin("WorldGuard") != null) {
log("Using WorldGuard!");
} else {
log("WorldGuard not founded! Disabling..");
}
if(regen) {
if(pm.getPlugin("WorldEdit") != null) {
log("Using WorldEdit!");
} else {
log("WorldEdit not founded! Disabling regeneration..");
regen = false;
saveCfg();
}
}
log = Logger.getLogger("Minecraft");
new AutoCleaner().start(); // Запускает в отдельном потоке AutoCleaner
log("Enabled!");
}
| public void onEnable() {
enabled = true;
cfgFile = new File(getDataFolder(), "config.yml");
cfg = YamlConfiguration.loadConfiguration(cfgFile);
loadCfg(); // Загружаем настройки
saveCfg(); // Сохраняем настройки
PluginManager pm = getServer().getPluginManager();
if(pm.getPlugin("WorldGuard") != null) {
log("Using WorldGuard!");
} else {
log("WorldGuard not founded! Disabling..");
this.setEnabled(false);
}
if(regen) {
if(pm.getPlugin("WorldEdit") != null) {
log("Using WorldEdit!");
} else {
log("WorldEdit not founded! Disabling regeneration..");
regen = false;
saveCfg();
}
}
log = Logger.getLogger("Minecraft");
new AutoCleaner().start(); // Запускает в отдельном потоке AutoCleaner
log("Enabled!");
}
|
diff --git a/src/java/org/osjava/norbert/NoRobotClient.java b/src/java/org/osjava/norbert/NoRobotClient.java
index bc42303..76d24b3 100644
--- a/src/java/org/osjava/norbert/NoRobotClient.java
+++ b/src/java/org/osjava/norbert/NoRobotClient.java
@@ -1,244 +1,244 @@
/*
* Copyright (c) 2003-2005, Henri Yandell
* 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 OSJava 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 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 org.osjava.norbert;
import java.io.IOException;
import java.io.StringReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.MalformedURLException;
import java.net.HttpURLConnection;
import java.net.URLConnection;
/**
* A Client which may be used to decide which urls on a website
* may be looked at, according to the norobots specification
* located at:
* http://www.robotstxt.org/wc/norobots-rfc.html
*/
public class NoRobotClient {
private String userAgent;
private RulesEngine rules;
private RulesEngine wildcardRules;
private URL baseUrl;
/**
* Create a Client for a particular user-agent name.
*
* @param userAgent name for the robot
*/
public NoRobotClient(String userAgent) {
this.userAgent = userAgent;
}
/**
* Head to a website and suck in their robots.txt file.
* Note that the URL passed in is for the website and does
* not include the robots.txt file itself.
*
* @param baseUrl of the site
*/
public void parse(URL baseUrl) throws NoRobotException {
this.rules = new RulesEngine();
this.baseUrl = baseUrl;
URL txtUrl = null;
try {
// fetch baseUrl+"robots.txt"
txtUrl = new URL(baseUrl, "robots.txt");
} catch(MalformedURLException murle) {
throw new NoRobotException("Bad URL: "+baseUrl+", robots.txt. ", murle);
}
String txt = null;
try {
txt = loadContent(txtUrl, this.userAgent);
if(txt == null) {
throw new NoRobotException("No content found for: "+txtUrl);
}
} catch(IOException ioe) {
throw new NoRobotException("Unable to get content for: "+txtUrl, ioe);
}
try {
parseText(txt);
} catch(NoRobotException nre) {
throw new NoRobotException("Problem while parsing "+txtUrl, nre);
}
}
public void parseText(String txt) throws NoRobotException {
this.rules = parseTextForUserAgent(txt, this.userAgent);
this.wildcardRules = parseTextForUserAgent(txt, "*");
}
private RulesEngine parseTextForUserAgent(String txt, String userAgent) throws NoRobotException {
RulesEngine engine = new RulesEngine();
// Classic basic parser style, read an element at a time,
// changing a state variable [parsingAllowBlock]
// take each line, one at a time
BufferedReader rdr = new BufferedReader( new StringReader(txt) );
String line = "";
String value = null;
boolean parsingAllowBlock = false;
try {
while( (line = rdr.readLine()) != null ) {
// trim whitespace from either side
line = line.trim();
// ignore startsWith('#')
if(line.startsWith("#")) {
continue;
}
- // if User-agent == userAgent
- // record the rest up until end or next User-agent
+ // if user-agent == userAgent
+ // record the rest up until end or next user-agent
// then quit (? check spec)
- if(line.startsWith("User-agent:")) {
+ if(line.toLowerCase().startsWith("user-agent:")) {
if(parsingAllowBlock) {
// we've just finished reading allows/disallows
if(engine.isEmpty()) {
// multiple user agents in a line, let's
// wait til we get rules
continue;
} else {
break;
}
}
- value = line.substring("User-agent:".length()).trim();
+ value = line.substring("user-agent:".length()).trim();
if(value.equalsIgnoreCase(userAgent)) {
parsingAllowBlock = true;
continue;
}
} else {
// if not, then store if we're currently the user agent
if(parsingAllowBlock) {
if(line.startsWith("Allow:")) {
value = line.substring("Allow:".length()).trim();
value = URLDecoder.decode(value);
engine.allowPath( value );
} else
if(line.startsWith("Disallow:")) {
value = line.substring("Disallow:".length()).trim();
value = URLDecoder.decode(value);
engine.disallowPath( value );
} else {
// ignore
continue;
}
} else {
// ignore
continue;
}
}
}
} catch (IOException ioe) {
// As this is parsing a String, it should not have an IOE
throw new NoRobotException("Problem while parsing text. ", ioe);
}
return engine;
}
/**
* Decide if the parsed website will allow this URL to be
* be seen.
*
* Note that parse(URL) must be called before this method
* is called.
*
* @param url in question
* @return is the url allowed?
*
* @throws IllegalStateException when parse has not been called
*/
public boolean isUrlAllowed(URL url) throws IllegalStateException, IllegalArgumentException {
if(rules == null) {
throw new IllegalStateException("You must call parse before you call this method. ");
}
if( !baseUrl.getHost().equals(url.getHost()) ||
baseUrl.getPort() != url.getPort() ||
!baseUrl.getProtocol().equals(url.getProtocol()) )
{
throw new IllegalArgumentException("Illegal to use a different url, " + url.toExternalForm() +
", for this robots.txt: "+this.baseUrl.toExternalForm());
}
String urlStr = url.toExternalForm().substring( this.baseUrl.toExternalForm().length() - 1);
if("/robots.txt".equals(urlStr)) {
return true;
}
urlStr = URLDecoder.decode( urlStr );
Boolean allowed = this.rules.isAllowed( urlStr );
if(allowed == null) {
allowed = this.wildcardRules.isAllowed( urlStr );
}
if(allowed == null) {
allowed = Boolean.TRUE;
}
return allowed.booleanValue();
}
// INLINE: as such from genjava/gj-core's net package. Simple method
// stolen from Payload too.
private static String loadContent(URL url, String userAgent) throws IOException {
URLConnection urlConn = url.openConnection();
if(urlConn instanceof HttpURLConnection) {
if(userAgent != null) {
((HttpURLConnection)urlConn).addRequestProperty("User-Agent", userAgent);
}
}
InputStream in = urlConn.getInputStream();
BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
StringBuffer buffer = new StringBuffer();
String line = "";
while( (line = rdr.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
in.close();
return buffer.toString();
}
}
| false | true | private RulesEngine parseTextForUserAgent(String txt, String userAgent) throws NoRobotException {
RulesEngine engine = new RulesEngine();
// Classic basic parser style, read an element at a time,
// changing a state variable [parsingAllowBlock]
// take each line, one at a time
BufferedReader rdr = new BufferedReader( new StringReader(txt) );
String line = "";
String value = null;
boolean parsingAllowBlock = false;
try {
while( (line = rdr.readLine()) != null ) {
// trim whitespace from either side
line = line.trim();
// ignore startsWith('#')
if(line.startsWith("#")) {
continue;
}
// if User-agent == userAgent
// record the rest up until end or next User-agent
// then quit (? check spec)
if(line.startsWith("User-agent:")) {
if(parsingAllowBlock) {
// we've just finished reading allows/disallows
if(engine.isEmpty()) {
// multiple user agents in a line, let's
// wait til we get rules
continue;
} else {
break;
}
}
value = line.substring("User-agent:".length()).trim();
if(value.equalsIgnoreCase(userAgent)) {
parsingAllowBlock = true;
continue;
}
} else {
// if not, then store if we're currently the user agent
if(parsingAllowBlock) {
if(line.startsWith("Allow:")) {
value = line.substring("Allow:".length()).trim();
value = URLDecoder.decode(value);
engine.allowPath( value );
} else
if(line.startsWith("Disallow:")) {
value = line.substring("Disallow:".length()).trim();
value = URLDecoder.decode(value);
engine.disallowPath( value );
} else {
// ignore
continue;
}
} else {
// ignore
continue;
}
}
}
} catch (IOException ioe) {
// As this is parsing a String, it should not have an IOE
throw new NoRobotException("Problem while parsing text. ", ioe);
}
return engine;
}
| private RulesEngine parseTextForUserAgent(String txt, String userAgent) throws NoRobotException {
RulesEngine engine = new RulesEngine();
// Classic basic parser style, read an element at a time,
// changing a state variable [parsingAllowBlock]
// take each line, one at a time
BufferedReader rdr = new BufferedReader( new StringReader(txt) );
String line = "";
String value = null;
boolean parsingAllowBlock = false;
try {
while( (line = rdr.readLine()) != null ) {
// trim whitespace from either side
line = line.trim();
// ignore startsWith('#')
if(line.startsWith("#")) {
continue;
}
// if user-agent == userAgent
// record the rest up until end or next user-agent
// then quit (? check spec)
if(line.toLowerCase().startsWith("user-agent:")) {
if(parsingAllowBlock) {
// we've just finished reading allows/disallows
if(engine.isEmpty()) {
// multiple user agents in a line, let's
// wait til we get rules
continue;
} else {
break;
}
}
value = line.substring("user-agent:".length()).trim();
if(value.equalsIgnoreCase(userAgent)) {
parsingAllowBlock = true;
continue;
}
} else {
// if not, then store if we're currently the user agent
if(parsingAllowBlock) {
if(line.startsWith("Allow:")) {
value = line.substring("Allow:".length()).trim();
value = URLDecoder.decode(value);
engine.allowPath( value );
} else
if(line.startsWith("Disallow:")) {
value = line.substring("Disallow:".length()).trim();
value = URLDecoder.decode(value);
engine.disallowPath( value );
} else {
// ignore
continue;
}
} else {
// ignore
continue;
}
}
}
} catch (IOException ioe) {
// As this is parsing a String, it should not have an IOE
throw new NoRobotException("Problem while parsing text. ", ioe);
}
return engine;
}
|
diff --git a/src/com/sunlightlabs/android/congress/notifications/finders/BillNewsFinder.java b/src/com/sunlightlabs/android/congress/notifications/finders/BillNewsFinder.java
index 3afd2323..efb43530 100644
--- a/src/com/sunlightlabs/android/congress/notifications/finders/BillNewsFinder.java
+++ b/src/com/sunlightlabs/android/congress/notifications/finders/BillNewsFinder.java
@@ -1,16 +1,16 @@
package com.sunlightlabs.android.congress.notifications.finders;
import android.content.Intent;
import com.sunlightlabs.android.congress.BillTabs;
import com.sunlightlabs.android.congress.notifications.NotificationEntity;
import com.sunlightlabs.android.congress.utils.Utils;
public class BillNewsFinder extends LegislatorNewsFinder {
@Override
public Intent notificationIntent(NotificationEntity entity) {
- return Utils.billLoadIntent(entity.id, Utils.legislatorTabsIntent()
+ return Utils.billLoadIntent(entity.id, Utils.billTabsIntent()
.putExtra("tab", BillTabs.Tabs.news));
}
}
| true | true | public Intent notificationIntent(NotificationEntity entity) {
return Utils.billLoadIntent(entity.id, Utils.legislatorTabsIntent()
.putExtra("tab", BillTabs.Tabs.news));
}
| public Intent notificationIntent(NotificationEntity entity) {
return Utils.billLoadIntent(entity.id, Utils.billTabsIntent()
.putExtra("tab", BillTabs.Tabs.news));
}
|
diff --git a/amibe/src/org/jcae/mesh/bora/ds/ResultConstraint.java b/amibe/src/org/jcae/mesh/bora/ds/ResultConstraint.java
index 9aa6ec07..68da7cb5 100644
--- a/amibe/src/org/jcae/mesh/bora/ds/ResultConstraint.java
+++ b/amibe/src/org/jcae/mesh/bora/ds/ResultConstraint.java
@@ -1,294 +1,294 @@
/* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD
modeler, Finite element mesher, Plugin architecture.
(C) Copyright 2006, by EADS CRC
This library 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 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
package org.jcae.mesh.bora.ds;
import org.jcae.mesh.bora.algo.*;
import org.jcae.mesh.cad.CADShapeEnum;
import java.util.Iterator;
import java.util.Collection;
import java.lang.reflect.Constructor;
import org.apache.log4j.Logger;
public class ResultConstraint extends Hypothesis
{
private static Logger logger = Logger.getLogger(ResultConstraint.class);
private CADShapeEnum dimension = null;
private AlgoInterface algo = null;
private static Class [] innerClasses = ResultConstraint.class.getDeclaredClasses();
private static HypNone HypNoneInstance = new HypNone();
// Is there a better way to do that?
private void copyHypothesis(Hypothesis h, CADShapeEnum d)
{
dimension = d;
lengthMin = h.lengthMin;
lengthMax = h.lengthMax;
deflection = h.deflection;
lengthBool = h.lengthBool;
numberBool = h.numberBool;
numberMin = h.numberMin;
numberMax = h.numberMax;
elementType = ResultConstraint.impliedType(d, h.elementType);
logger.debug("("+Integer.toHexString(h.hashCode())+") Dim: "+d+" Algo "+h.elementType+" mapped to "+elementType);
}
// Creates a ResultConstraint derived from an Hypothesis
private static ResultConstraint createConstraint(Hypothesis h, CADShapeEnum d)
{
ResultConstraint ret = new ResultConstraint();
ret.copyHypothesis(h, d);
if (ret.elementType == null)
return null;
return ret;
}
// Combines with an Hypothesis for a given dimension
private void combine(Constraint mh, CADShapeEnum d)
{
ResultConstraint that = createConstraint(mh.getHypothesis(), d);
if (that == null)
return;
if (dimension == null)
copyHypothesis(that, d);
- if (elementType != that.elementType)
+ if (!elementType.equals(that.elementType))
{
logger.debug("Element "+elementType+" and "+that.elementType+" differ and are not combined together");
}
double targetLengthMax = lengthMax;
if (targetLengthMax > that.lengthMax)
targetLengthMax = that.lengthMax;
double targetLengthMin = lengthMin;
if (targetLengthMin < that.lengthMin)
targetLengthMin = that.lengthMin;
if (lengthBool && that.lengthBool)
{
if (targetLengthMin > targetLengthMax)
throw new RuntimeException("length min > length max");
lengthMax = targetLengthMax;
lengthMin = targetLengthMin;
}
else
{
lengthBool |= that.lengthBool;
if (targetLengthMin > targetLengthMax)
{
printDirty(mh);
lengthMax = targetLengthMin;
lengthMin = targetLengthMax;
}
}
int targetNumberMax = numberMax;
if (targetNumberMax > that.numberMax)
targetNumberMax = that.numberMax;
int targetNumberMin = numberMin;
if (targetNumberMin < that.numberMin)
targetNumberMin = that.numberMin;
if (numberBool && that.numberBool)
{
if (targetNumberMin > targetNumberMax)
throw new RuntimeException("number min > number max");
numberMax = targetNumberMax;
numberMin = targetNumberMin;
}
else
{
numberBool |= that.numberBool;
if (targetNumberMin > targetNumberMax)
{
printDirty(mh);
numberMax = targetNumberMin;
numberMin = targetNumberMax;
}
}
double targetDefl = deflection;
if (targetDefl > that.deflection)
targetDefl = that.deflection;
deflection = targetDefl;
}
private void printDirty(Constraint mh)
{
logger.warn("Hypothesis not compatible: "+mh+": "+mh.getHypothesis()+" with "+this);
}
/**
* Combines all Hypothesis of a Collection. In order to improve error
* reporting, Constraint objects are passed as arguments instead
* of Hypothesis.
*
* @param mh list of Constraint objects.
* @param d dimension
*/
public static ResultConstraint combineAll(Collection mh, CADShapeEnum d)
{
ResultConstraint ret = null;
if (mh.size() == 0)
return null;
ret = new ResultConstraint();
for (Iterator ita = mh.iterator() ; ita.hasNext(); )
ret.combine((Constraint) ita.next(), d);
if (ret.dimension == null)
ret = null;
return ret;
}
public static HypInterface getAlgo(String elt)
{
HypInterface h = HypNoneInstance;
if (elt == null)
return h;
try {
for (int i = 0; i < innerClasses.length; i++)
{
if (innerClasses[i].getName().equals(ResultConstraint.class.getName()+"$Hyp"+elt))
h = (HypInterface) innerClasses[i].newInstance();
}
} catch (Exception ex) {
ex.printStackTrace();
h = HypNoneInstance;
};
return h;
}
private static String impliedType(CADShapeEnum d, String elt)
{
HypInterface h = getAlgo(elt);
return h.impliedType(d);
}
/**
* Finds the best algorithm suited to constraints defined on a submesh.
*/
public void findAlgorithm()
{
double targetLength = 0.5*(lengthMin+lengthMax);
try {
if (dimension == CADShapeEnum.EDGE)
{
Class [] typeArgs = new Class[] {double.class, double.class, boolean.class};
Constructor cons = UniformLengthDeflection1d.class.getConstructor(typeArgs);
algo = (AlgoInterface) cons.newInstance(new Object [] {new Double(targetLength), new Double(deflection), Boolean.valueOf(true)});
}
else if (dimension == CADShapeEnum.FACE)
{
Class [] typeArgs = new Class[] {double.class, double.class, boolean.class, boolean.class};
Constructor cons = Basic2d.class.getConstructor(typeArgs);
algo = (AlgoInterface) cons.newInstance(new Object [] {new Double(targetLength), new Double(deflection), Boolean.valueOf(true), Boolean.valueOf(true)});
}
else if (dimension == CADShapeEnum.SOLID)
{
Class [] typeArgs = new Class[] {double.class};
Constructor cons = TetGen.class.getConstructor(typeArgs);
algo = (AlgoInterface) cons.newInstance(new Object [] {new Double(targetLength)});
if (!algo.isAvailable())
logger.error("TetGen not available!");
/*
Constructor cons = Netgen.class.getConstructor(typeArgs);
algo = (AlgoInterface) cons.newInstance(new Object [] {new Double(targetLength)});
if (!algo.isAvailable())
logger.error("Netgen not available!");
*/
}
} catch (Exception ex)
{
ex.printStackTrace();
System.exit(1);
}
}
public void applyAlgorithm(BCADGraphCell m)
{
if (algo == null)
findAlgorithm();
if (!algo.isAvailable())
return;
if (!algo.compute(m))
logger.warn("Failed! "+algo);
}
public String toString()
{
String ret = super.toString();
if (algo != null)
ret += "\n"+algo;
return ret;
}
public static class HypNone implements HypInterface
{
public CADShapeEnum dim()
{
return null;
}
public String impliedType(CADShapeEnum d)
{
return null;
}
}
public static class HypE2 implements HypInterface
{
public CADShapeEnum dim()
{
return CADShapeEnum.EDGE;
}
public String impliedType(CADShapeEnum d)
{
if (d == CADShapeEnum.EDGE)
return "E2";
else
return null;
}
}
public static class HypT3 implements HypInterface
{
public CADShapeEnum dim()
{
return CADShapeEnum.FACE;
}
public String impliedType(CADShapeEnum d)
{
if (d == CADShapeEnum.EDGE)
return "E2";
else if (d == CADShapeEnum.FACE)
return "T3";
else
return null;
}
}
public static class HypT4 implements HypInterface
{
public CADShapeEnum dim()
{
return CADShapeEnum.SOLID;
}
public String impliedType(CADShapeEnum d)
{
if (d == CADShapeEnum.EDGE)
return "E2";
else if (d == CADShapeEnum.FACE)
return "T3";
else if (d == CADShapeEnum.SOLID)
return "T4";
else
return null;
}
}
}
| true | true | private void combine(Constraint mh, CADShapeEnum d)
{
ResultConstraint that = createConstraint(mh.getHypothesis(), d);
if (that == null)
return;
if (dimension == null)
copyHypothesis(that, d);
if (elementType != that.elementType)
{
logger.debug("Element "+elementType+" and "+that.elementType+" differ and are not combined together");
}
double targetLengthMax = lengthMax;
if (targetLengthMax > that.lengthMax)
targetLengthMax = that.lengthMax;
double targetLengthMin = lengthMin;
if (targetLengthMin < that.lengthMin)
targetLengthMin = that.lengthMin;
if (lengthBool && that.lengthBool)
{
if (targetLengthMin > targetLengthMax)
throw new RuntimeException("length min > length max");
lengthMax = targetLengthMax;
lengthMin = targetLengthMin;
}
else
{
lengthBool |= that.lengthBool;
if (targetLengthMin > targetLengthMax)
{
printDirty(mh);
lengthMax = targetLengthMin;
lengthMin = targetLengthMax;
}
}
int targetNumberMax = numberMax;
if (targetNumberMax > that.numberMax)
targetNumberMax = that.numberMax;
int targetNumberMin = numberMin;
if (targetNumberMin < that.numberMin)
targetNumberMin = that.numberMin;
if (numberBool && that.numberBool)
{
if (targetNumberMin > targetNumberMax)
throw new RuntimeException("number min > number max");
numberMax = targetNumberMax;
numberMin = targetNumberMin;
}
else
{
numberBool |= that.numberBool;
if (targetNumberMin > targetNumberMax)
{
printDirty(mh);
numberMax = targetNumberMin;
numberMin = targetNumberMax;
}
}
double targetDefl = deflection;
if (targetDefl > that.deflection)
targetDefl = that.deflection;
deflection = targetDefl;
}
| private void combine(Constraint mh, CADShapeEnum d)
{
ResultConstraint that = createConstraint(mh.getHypothesis(), d);
if (that == null)
return;
if (dimension == null)
copyHypothesis(that, d);
if (!elementType.equals(that.elementType))
{
logger.debug("Element "+elementType+" and "+that.elementType+" differ and are not combined together");
}
double targetLengthMax = lengthMax;
if (targetLengthMax > that.lengthMax)
targetLengthMax = that.lengthMax;
double targetLengthMin = lengthMin;
if (targetLengthMin < that.lengthMin)
targetLengthMin = that.lengthMin;
if (lengthBool && that.lengthBool)
{
if (targetLengthMin > targetLengthMax)
throw new RuntimeException("length min > length max");
lengthMax = targetLengthMax;
lengthMin = targetLengthMin;
}
else
{
lengthBool |= that.lengthBool;
if (targetLengthMin > targetLengthMax)
{
printDirty(mh);
lengthMax = targetLengthMin;
lengthMin = targetLengthMax;
}
}
int targetNumberMax = numberMax;
if (targetNumberMax > that.numberMax)
targetNumberMax = that.numberMax;
int targetNumberMin = numberMin;
if (targetNumberMin < that.numberMin)
targetNumberMin = that.numberMin;
if (numberBool && that.numberBool)
{
if (targetNumberMin > targetNumberMax)
throw new RuntimeException("number min > number max");
numberMax = targetNumberMax;
numberMin = targetNumberMin;
}
else
{
numberBool |= that.numberBool;
if (targetNumberMin > targetNumberMax)
{
printDirty(mh);
numberMax = targetNumberMin;
numberMin = targetNumberMax;
}
}
double targetDefl = deflection;
if (targetDefl > that.deflection)
targetDefl = that.deflection;
deflection = targetDefl;
}
|
diff --git a/src/com/nineducks/hereader/ui/NewsItemsFragment.java b/src/com/nineducks/hereader/ui/NewsItemsFragment.java
index e3782d4..6742cf4 100644
--- a/src/com/nineducks/hereader/ui/NewsItemsFragment.java
+++ b/src/com/nineducks/hereader/ui/NewsItemsFragment.java
@@ -1,306 +1,307 @@
package com.nineducks.hereader.ui;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.markupartist.android.widget.ActionBar;
import com.nineducks.hereader.AboutAction;
import com.nineducks.hereader.HEReaderState;
import com.nineducks.hereader.HackfulItemsController;
import com.nineducks.hereader.HackfulReaderActivity;
import com.nineducks.hereader.ItemsLoadedListener;
import com.nineducks.hereader.LoadAskItemsAction;
import com.nineducks.hereader.LoadFrontpageItemsAction;
import com.nineducks.hereader.LoadNewItemsAction;
import com.nineducks.hereader.NewsItemsLoaderTask;
import com.nineducks.hereader.R;
import com.nineducks.util.rss.HEMessage;
public class NewsItemsFragment
extends ListFragment
implements ItemsLoadedListener, HackfulItemsController,
AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener,
DialogInterface.OnClickListener{
public static final String SAVED_ITEMS_KEY = "saved_items";
public static final String SAVED_ITEMS_SOURCE_KEY = "saved_items_source";
private List<ListFragmentItem> items = new ArrayList<ListFragmentItem>();
private boolean mDualPane = true;
private HEMessagesAdapter adapter = null;
private WebView webView = null;
private FrameLayout webViewContainer;
private int currentItemsSource;
private int currentPage = 1;
private ActionBar actionBar;
private int currentPosition = -1;
private int clickedPosition = -1;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d("hereader", "entering NewsItemsFragment.onActivityCreated");
super.onActivityCreated(savedInstanceState);
initUI();
getListView().setHapticFeedbackEnabled(true);
getListView().setLongClickable(true);
getListView().setOnItemClickListener(this);
getListView().setOnItemLongClickListener(this);
if (savedInstanceState != null &&
savedInstanceState.containsKey(NewsItemsFragment.SAVED_ITEMS_KEY) &&
savedInstanceState.containsKey(NewsItemsFragment.SAVED_ITEMS_SOURCE_KEY)) {
List<ListFragmentItem> items = (List<ListFragmentItem>) savedInstanceState.getSerializable(NewsItemsFragment.SAVED_ITEMS_KEY);
int itemsSource = savedInstanceState.getInt(NewsItemsFragment.SAVED_ITEMS_SOURCE_KEY);
putItems(items, itemsSource);
} else {
if (savedInstanceState == null)
Log.d("hereader", "savend instancestate null");
loadFrontpageItems();
}
Log.d("hereader", "leaving NewsItemsFragment.onActivityCreated");
}
private void initUI() {
Log.d("hereader", "Creating UI");
webViewContainer = (FrameLayout) getActivity().findViewById(R.id.webview_container);
mDualPane = webViewContainer != null && webViewContainer.getVisibility() == View.VISIBLE;
actionBar = (ActionBar) getActivity().findViewById(R.id.action_bar);
actionBar.setHomeIcon(R.drawable.hackful_icon);
actionBar.addAction(new LoadFrontpageItemsAction(HackfulReaderActivity.getContext(), this));
actionBar.addAction(new LoadNewItemsAction(HackfulReaderActivity.getContext(), this));
actionBar.addAction(new LoadAskItemsAction(HackfulReaderActivity.getContext(), this));
actionBar.addAction(new AboutAction(HackfulReaderActivity.getContext(), this));
if (mDualPane || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
actionBar.setTitle(R.string.app_name);
}
if (mDualPane) {
if (webView == null) {
Log.d("hereader", "WebView is null, creating new instance");
final ActionBar actionB = actionBar;
webView = new WebView(getActivity());
webView.setId(R.id.webview_id);
webView.getSettings().setJavaScriptEnabled(true);
- webView.getSettings().setBuiltInZoomControls(true);
+ webView.getSettings().setSupportZoom(true);
+ //webView.getSettings().setBuiltInZoomControls(false);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
actionB.setProgressBarVisibility(View.GONE);
}
}
});
}
webViewContainer.addView(webView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
Log.d("hereader", "UI created");
}
private void showDetails(int position, URL itemUrl) {
Log.d("hereader", "entering NewsItemsFragment.showDetails");
if (mDualPane) {
Log.d("hereader", "Is dual pane");
if (currentPosition >= 0) {
items.get(currentPosition).setSelected(false);
}
currentPosition = position;
items.get(currentPosition).setSelected(true);
actionBar.setProgressBarVisibility(View.VISIBLE);
webView.stopLoading();
webView.loadUrl(itemUrl.toString());
adapter.notifyDataSetChanged();
Log.d("hereader", "WebView loadUrl invoked");
} else {
Log.d("hereader", "Is single pane");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(itemUrl.toString()));
startActivity(intent);
Log.d("hereader", "Intent launched for single pane");
}
Log.d("hereader", "leaving NewsItemsFragment.showDetails");
}
@Override
public void onItemsLoaded(List<HEMessage> items) {
Log.d("hereader", "received notification from NewsItemsLoaderTask");
if (items != null) {
this.items.addAll(transformItems(items));
if (adapter == null) {
adapter = new HEMessagesAdapter(getActivity(), R.layout.item, this.items);
setListAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
actionBar.setProgressBarVisibility(View.GONE);
getListView().setSelectionAfterHeaderView();
} else {
Toast.makeText(getActivity(), R.string.connection_error, 7).show();
}
}
public boolean isDualPane() {
return mDualPane;
}
private void loadItems(String source) {
Log.d("hereader", "entering NewsItemsFragment.loadItems");
if (actionBar != null) {
actionBar.setProgressBarVisibility(View.VISIBLE);
}
NewsItemsLoaderTask task = new NewsItemsLoaderTask();
task.addNewsItemsLoadedListener(this);
task.setContext(getActivity().getApplicationContext());
task.execute(source, getString(R.string.he_namespace));
Log.d("hereader", "leaving NewsItemsFragment.loadItems");
}
@Override
public void loadFrontpageItems() {
currentItemsSource = R.string.frontpage_feed;
items.clear();
if (adapter != null) {
adapter.clear();
}
loadItems(getString(R.string.frontpage_feed));
}
@Override
public void loadNewItems() {
currentItemsSource = R.string.new_feed;
items.clear();
if (adapter != null) {
adapter.clear();
}
loadItems(getString(R.string.new_feed));
}
@Override
public void loadAskItems() {
currentItemsSource = R.string.ask_feed;
items.clear();
if (adapter != null) {
adapter.clear();
}
loadItems(getString(R.string.ask_feed));
}
@Override
public void loadMoreItems() {
actionBar.setProgressBarVisibility(View.VISIBLE);
switch (currentItemsSource) {
case R.string.frontpage_feed:
break;
case R.string.new_feed:
break;
}
}
@Override
public List<ListFragmentItem> getItems() {
return items;
}
@Override
public void putItems(List<ListFragmentItem> items, int itemsSource) {
this.items = items;
currentItemsSource = itemsSource;
}
@Override
public int getItemsSource() {
return currentItemsSource;
}
@Override
public HEReaderState getCurrentState() {
return new HEReaderState(currentItemsSource, items, currentPage);
}
@Override
public void setCurrentState(HEReaderState state) {
currentItemsSource = state.getCurrentSource();
items = state.getItems();
currentPage = state.getCurrentPage();
adapter.notifyDataSetChanged();
}
@Override
public void onDetach() {
if (mDualPane) {
webViewContainer.removeView(webView);
}
super.onDetach();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
private List<ListFragmentItem> transformItems(List<HEMessage> items) {
List<ListFragmentItem> result = new ArrayList<ListFragmentItem>();
for(HEMessage msg : items) {
result.add(new ListFragmentItem(msg, false));
}
return result;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("hereader", "saving instance state");
outState.putSerializable(SAVED_ITEMS_KEY, (Serializable) items);
outState.putInt(SAVED_ITEMS_SOURCE_KEY, currentItemsSource);
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
getListView().performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
clickedPosition = position;
getActivity().showDialog(R.id.open_dialog);
return true;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
URL itemUrl = items.get(position).getHEMessage().getLink();
clickedPosition = position;
showDetails(position, itemUrl);
}
@Override
public void onClick(DialogInterface dialog, int item) {
String selected = getResources().getStringArray(R.array.open_dialog_options)[item];
URL url = null;
if (selected.equals(getResources().getString(R.string.open_link))) {
url = items.get(clickedPosition).getHEMessage().getLink();
} else if (selected.equals(getResources().getString(R.string.open_post))) {
url = items.get(clickedPosition).getHEMessage().getGuid();
}
if (url != null) {
showDetails(clickedPosition, url);
}
}
}
| true | true | private void initUI() {
Log.d("hereader", "Creating UI");
webViewContainer = (FrameLayout) getActivity().findViewById(R.id.webview_container);
mDualPane = webViewContainer != null && webViewContainer.getVisibility() == View.VISIBLE;
actionBar = (ActionBar) getActivity().findViewById(R.id.action_bar);
actionBar.setHomeIcon(R.drawable.hackful_icon);
actionBar.addAction(new LoadFrontpageItemsAction(HackfulReaderActivity.getContext(), this));
actionBar.addAction(new LoadNewItemsAction(HackfulReaderActivity.getContext(), this));
actionBar.addAction(new LoadAskItemsAction(HackfulReaderActivity.getContext(), this));
actionBar.addAction(new AboutAction(HackfulReaderActivity.getContext(), this));
if (mDualPane || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
actionBar.setTitle(R.string.app_name);
}
if (mDualPane) {
if (webView == null) {
Log.d("hereader", "WebView is null, creating new instance");
final ActionBar actionB = actionBar;
webView = new WebView(getActivity());
webView.setId(R.id.webview_id);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
actionB.setProgressBarVisibility(View.GONE);
}
}
});
}
webViewContainer.addView(webView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
Log.d("hereader", "UI created");
}
| private void initUI() {
Log.d("hereader", "Creating UI");
webViewContainer = (FrameLayout) getActivity().findViewById(R.id.webview_container);
mDualPane = webViewContainer != null && webViewContainer.getVisibility() == View.VISIBLE;
actionBar = (ActionBar) getActivity().findViewById(R.id.action_bar);
actionBar.setHomeIcon(R.drawable.hackful_icon);
actionBar.addAction(new LoadFrontpageItemsAction(HackfulReaderActivity.getContext(), this));
actionBar.addAction(new LoadNewItemsAction(HackfulReaderActivity.getContext(), this));
actionBar.addAction(new LoadAskItemsAction(HackfulReaderActivity.getContext(), this));
actionBar.addAction(new AboutAction(HackfulReaderActivity.getContext(), this));
if (mDualPane || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
actionBar.setTitle(R.string.app_name);
}
if (mDualPane) {
if (webView == null) {
Log.d("hereader", "WebView is null, creating new instance");
final ActionBar actionB = actionBar;
webView = new WebView(getActivity());
webView.setId(R.id.webview_id);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
//webView.getSettings().setBuiltInZoomControls(false);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
actionB.setProgressBarVisibility(View.GONE);
}
}
});
}
webViewContainer.addView(webView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
Log.d("hereader", "UI created");
}
|
diff --git a/src/main/java/pl/psnc/dl/wf4ever/portal/pages/SparqlEndpointPage.java b/src/main/java/pl/psnc/dl/wf4ever/portal/pages/SparqlEndpointPage.java
index 6303093..7881569 100644
--- a/src/main/java/pl/psnc/dl/wf4ever/portal/pages/SparqlEndpointPage.java
+++ b/src/main/java/pl/psnc/dl/wf4ever/portal/pages/SparqlEndpointPage.java
@@ -1,223 +1,223 @@
package pl.psnc.dl.wf4ever.portal.pages;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.protocol.http.RequestUtils;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import pl.psnc.dl.wf4ever.portal.PortalApplication;
import pl.psnc.dl.wf4ever.portal.pages.util.MyAjaxButton;
import pl.psnc.dl.wf4ever.portal.pages.util.MyComponentFeedbackPanel;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
public class SparqlEndpointPage
extends TemplatePage
{
private static final long serialVersionUID = 1L;
private String query;
private String url;
private String result;
@SuppressWarnings("serial")
public SparqlEndpointPage(final PageParameters parameters)
{
super(parameters);
add(new MyFeedbackPanel("feedbackPanel"));
Form< ? > form = new Form<Void>("form");
add(form);
final TextArea<String> queryTA = new TextArea<String>("query", new PropertyModel<String>(this, "query")) {
@Override
protected void onValid()
{
add(AttributeModifier.remove("style"));
};
@Override
protected void onInvalid()
{
add(AttributeModifier.replace("style", "border-color: #EE5F5B"));
};
};
queryTA.setRequired(true);
queryTA.setOutputMarkupId(true);
form.add(queryTA);
final Panel queryFeedback = new MyComponentFeedbackPanel("queryFeedback", queryTA);
queryFeedback.setOutputMarkupId(true);
form.add(queryFeedback);
final Label urlLabel = new Label("url", new PropertyModel<String>(this, "url"));
urlLabel.setOutputMarkupId(true);
form.add(urlLabel);
final Label resultLabel = new Label("result", new PropertyModel<String>(this, "result"));
resultLabel.setOutputMarkupId(true);
form.add(resultLabel);
form.add(new MyAjaxButton("execute", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form< ? > form)
{
super.onSubmit(target, form);
Client client = Client.create();
try {
WebResource webResource = client.resource(getEndpointUrl().toString());
- String response = webResource.header("Content-type", "application/x-turtle").get(String.class);
+ String response = webResource.accept("application/x-turtle").get(String.class);
setResult(response);
}
catch (Exception e) {
error(e.getMessage());
}
target.add(queryTA);
target.add(queryFeedback);
target.add(resultLabel);
}
@Override
protected void onError(AjaxRequestTarget target, Form< ? > form)
{
super.onError(target, form);
target.add(queryTA);
target.add(queryFeedback);
}
});
form.add(new MyAjaxButton("generateURL", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form< ? > form)
{
super.onSubmit(target, form);
try {
setUrl(getEndpointUrl().toString());
}
catch (MalformedURLException | URISyntaxException e) {
error(e.getMessage());
}
target.add(queryTA);
target.add(queryFeedback);
target.add(urlLabel);
}
@Override
protected void onError(AjaxRequestTarget target, Form< ? > form)
{
super.onError(target, form);
target.add(queryTA);
target.add(queryFeedback);
target.add(urlLabel);
}
});
}
protected URL getEndpointUrl()
throws URISyntaxException, MalformedURLException
{
URI uri = ((PortalApplication) getApplication()).getSparqlEndpointURL().toURI();
return new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), "query=" + query, uri.getFragment()).toURL();
}
/**
* Get an absoulte URL for a Page and parameters. E.g.
* http://localhost/wicket/Page?param1=value
*
* @param pageClass
* Page Class
* @param parameters
* Params
* @param <C>
* Page Class
* @return Absolute Url
*/
public static <C extends Page> String getAbsoluteUrl(final Class<C> pageClass, final PageParameters parameters)
{
CharSequence resetUrl = RequestCycle.get().urlFor(pageClass, parameters);
String abs = RequestUtils.toAbsolutePath("/", resetUrl.toString());
final Url url = Url.parse(abs);
return RequestCycle.get().getUrlRenderer().renderFullUrl(url);
}
/**
* @return the query
*/
public String getQuery()
{
return query;
}
/**
* @param query
* the query to set
*/
public void setQuery(String query)
{
this.query = query;
}
/**
* @return the result
*/
public String getResult()
{
return result;
}
/**
* @param result
* the result to set
*/
public void setResult(String result)
{
this.result = result;
}
/**
* @return the url
*/
public String getUrl()
{
return url;
}
/**
* @param url
* the url to set
*/
public void setUrl(String url)
{
this.url = url;
}
}
| true | true | public SparqlEndpointPage(final PageParameters parameters)
{
super(parameters);
add(new MyFeedbackPanel("feedbackPanel"));
Form< ? > form = new Form<Void>("form");
add(form);
final TextArea<String> queryTA = new TextArea<String>("query", new PropertyModel<String>(this, "query")) {
@Override
protected void onValid()
{
add(AttributeModifier.remove("style"));
};
@Override
protected void onInvalid()
{
add(AttributeModifier.replace("style", "border-color: #EE5F5B"));
};
};
queryTA.setRequired(true);
queryTA.setOutputMarkupId(true);
form.add(queryTA);
final Panel queryFeedback = new MyComponentFeedbackPanel("queryFeedback", queryTA);
queryFeedback.setOutputMarkupId(true);
form.add(queryFeedback);
final Label urlLabel = new Label("url", new PropertyModel<String>(this, "url"));
urlLabel.setOutputMarkupId(true);
form.add(urlLabel);
final Label resultLabel = new Label("result", new PropertyModel<String>(this, "result"));
resultLabel.setOutputMarkupId(true);
form.add(resultLabel);
form.add(new MyAjaxButton("execute", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form< ? > form)
{
super.onSubmit(target, form);
Client client = Client.create();
try {
WebResource webResource = client.resource(getEndpointUrl().toString());
String response = webResource.header("Content-type", "application/x-turtle").get(String.class);
setResult(response);
}
catch (Exception e) {
error(e.getMessage());
}
target.add(queryTA);
target.add(queryFeedback);
target.add(resultLabel);
}
@Override
protected void onError(AjaxRequestTarget target, Form< ? > form)
{
super.onError(target, form);
target.add(queryTA);
target.add(queryFeedback);
}
});
form.add(new MyAjaxButton("generateURL", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form< ? > form)
{
super.onSubmit(target, form);
try {
setUrl(getEndpointUrl().toString());
}
catch (MalformedURLException | URISyntaxException e) {
error(e.getMessage());
}
target.add(queryTA);
target.add(queryFeedback);
target.add(urlLabel);
}
@Override
protected void onError(AjaxRequestTarget target, Form< ? > form)
{
super.onError(target, form);
target.add(queryTA);
target.add(queryFeedback);
target.add(urlLabel);
}
});
}
| public SparqlEndpointPage(final PageParameters parameters)
{
super(parameters);
add(new MyFeedbackPanel("feedbackPanel"));
Form< ? > form = new Form<Void>("form");
add(form);
final TextArea<String> queryTA = new TextArea<String>("query", new PropertyModel<String>(this, "query")) {
@Override
protected void onValid()
{
add(AttributeModifier.remove("style"));
};
@Override
protected void onInvalid()
{
add(AttributeModifier.replace("style", "border-color: #EE5F5B"));
};
};
queryTA.setRequired(true);
queryTA.setOutputMarkupId(true);
form.add(queryTA);
final Panel queryFeedback = new MyComponentFeedbackPanel("queryFeedback", queryTA);
queryFeedback.setOutputMarkupId(true);
form.add(queryFeedback);
final Label urlLabel = new Label("url", new PropertyModel<String>(this, "url"));
urlLabel.setOutputMarkupId(true);
form.add(urlLabel);
final Label resultLabel = new Label("result", new PropertyModel<String>(this, "result"));
resultLabel.setOutputMarkupId(true);
form.add(resultLabel);
form.add(new MyAjaxButton("execute", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form< ? > form)
{
super.onSubmit(target, form);
Client client = Client.create();
try {
WebResource webResource = client.resource(getEndpointUrl().toString());
String response = webResource.accept("application/x-turtle").get(String.class);
setResult(response);
}
catch (Exception e) {
error(e.getMessage());
}
target.add(queryTA);
target.add(queryFeedback);
target.add(resultLabel);
}
@Override
protected void onError(AjaxRequestTarget target, Form< ? > form)
{
super.onError(target, form);
target.add(queryTA);
target.add(queryFeedback);
}
});
form.add(new MyAjaxButton("generateURL", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form< ? > form)
{
super.onSubmit(target, form);
try {
setUrl(getEndpointUrl().toString());
}
catch (MalformedURLException | URISyntaxException e) {
error(e.getMessage());
}
target.add(queryTA);
target.add(queryFeedback);
target.add(urlLabel);
}
@Override
protected void onError(AjaxRequestTarget target, Form< ? > form)
{
super.onError(target, form);
target.add(queryTA);
target.add(queryFeedback);
target.add(urlLabel);
}
});
}
|
diff --git a/src/com/dmdirc/addons/ui_swing/framemanager/tree/TreeFrameManager.java b/src/com/dmdirc/addons/ui_swing/framemanager/tree/TreeFrameManager.java
index 922dd9bb..1bf62969 100644
--- a/src/com/dmdirc/addons/ui_swing/framemanager/tree/TreeFrameManager.java
+++ b/src/com/dmdirc/addons/ui_swing/framemanager/tree/TreeFrameManager.java
@@ -1,453 +1,454 @@
/*
* Copyright (c) 2006-2011 DMDirc Developers
*
* 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.
*/
package com.dmdirc.addons.ui_swing.framemanager.tree;
import com.dmdirc.FrameContainer;
import com.dmdirc.addons.ui_swing.SwingController;
import com.dmdirc.addons.ui_swing.UIUtilities;
import com.dmdirc.addons.ui_swing.components.TreeScroller;
import com.dmdirc.addons.ui_swing.components.frames.TextFrame;
import com.dmdirc.addons.ui_swing.framemanager.FrameManager;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.interfaces.FrameInfoListener;
import com.dmdirc.interfaces.NotificationListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.ui.WindowManager;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import net.miginfocom.swing.MigLayout;
/**
* Manages open windows in the application in a tree style view.
*/
public final class TreeFrameManager implements FrameManager,
Serializable, ConfigChangeListener, NotificationListener,
FrameInfoListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 5;
/** display tree. */
private Tree tree;
/** data model. */
private TreeViewModel model;
/** node storage, used for adding and deleting nodes correctly. */
private final Map<FrameContainer, TreeViewNode> nodes;
/** UI Controller. */
private SwingController controller;
/** Tree scroller. */
private TreeScroller scroller;
/** creates a new instance of the TreeFrameManager. */
public TreeFrameManager() {
nodes = new HashMap<FrameContainer, TreeViewNode>();
}
/** {@inheritDoc} */
@Override
public boolean canPositionVertically() {
return true;
}
/** {@inheritDoc} */
@Override
public boolean canPositionHorizontally() {
return false;
}
/** {@inheritDoc} */
@Override
public void setParent(final JComponent parent) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final JScrollPane scrollPane = new JScrollPane(tree);
scrollPane.setAutoscrolls(true);
scrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
parent.setVisible(false);
parent.setLayout(new MigLayout("ins 0, fill"));
parent.add(scrollPane, "grow");
parent.setFocusable(false);
parent.setVisible(true);
setColours();
redoTreeView();
}
});
}
/** {@inheritDoc} */
@Override
public void setController(final SwingController controller) {
this.controller = controller;
UIUtilities.invokeLater(new Runnable() {
@Override
public void run() {
model = new TreeViewModel(new TreeViewNode(null, null));
tree = new Tree(TreeFrameManager.this, model,
TreeFrameManager.this.controller);
tree.setCellRenderer(new TreeViewTreeCellRenderer(
TreeFrameManager.this));
tree.setVisible(true);
IdentityManager.getGlobalConfig().addChangeListener("treeview",
TreeFrameManager.this);
IdentityManager.getGlobalConfig().addChangeListener("ui",
"sortrootwindows", TreeFrameManager.this);
IdentityManager.getGlobalConfig().addChangeListener("ui",
"sortchildwindows", TreeFrameManager.this);
IdentityManager.getGlobalConfig().addChangeListener("ui",
"backgroundcolour", TreeFrameManager.this);
IdentityManager.getGlobalConfig().addChangeListener("ui",
"foregroundcolour", TreeFrameManager.this);
}
});
}
/** {@inheritDoc} */
@Override
public void windowAdded(final TextFrame parent, final TextFrame window) {
if (nodes.containsKey(window.getContainer())) {
return;
}
if (parent == null) {
addWindow(model.getRootNode(), window.getContainer());
} else {
addWindow(nodes.get(parent.getContainer()), window.getContainer());
}
}
/** {@inheritDoc} */
@Override
public void windowDeleted(final TextFrame parent, final TextFrame window) {
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
if (nodes == null || nodes.get(window.getContainer()) == null) {
return;
}
final DefaultMutableTreeNode node =
nodes.get(window.getContainer());
if (node.getLevel() == 0) {
Logger.appError(ErrorLevel.MEDIUM,
"delServer triggered for root node"
+ node.toString(),
new IllegalArgumentException());
} else {
model.removeNodeFromParent(nodes.get(window.getContainer()));
}
synchronized (nodes) {
nodes.remove(window.getContainer());
}
window.getContainer().removeFrameInfoListener(
TreeFrameManager.this);
window.getContainer().removeNotificationListener(
TreeFrameManager.this);
}
});
}
/**
* Adds a window to the frame container.
*
* @param parent Parent node
* @param window Window to add
*/
public void addWindow(final TreeViewNode parent,
final FrameContainer window) {
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final NodeLabel label = new NodeLabel(window);
final TreeViewNode node = new TreeViewNode(label, window);
synchronized (nodes) {
nodes.put(window, node);
}
if (parent == null) {
model.insertNodeInto(node, model.getRootNode());
} else {
model.insertNodeInto(node, parent);
}
tree.expandPath(new TreePath(node.getPath()).getParentPath());
final Rectangle view =
tree.getRowBounds(tree.getRowForPath(new TreePath(node.
getPath())));
if (view != null) {
tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(),
0, 0));
}
window.addFrameInfoListener(TreeFrameManager.this);
window.addNotificationListener(TreeFrameManager.this);
node.getLabel().notificationSet(window, window.getNotification());
+ node.getLabel().iconChanged(window, window.getIcon());
}
});
}
/**
* Returns the tree for this frame manager.
*
* @return Tree for the manager
*/
public JTree getTree() {
return tree;
}
/**
* Checks for and sets a rollover node.
*
* @param event event to check
*/
protected void checkRollover(final MouseEvent event) {
NodeLabel node = null;
if (event != null && tree.getNodeForLocation(event.getX(), event.getY()) != null) {
node = tree.getNodeForLocation(event.getX(), event.getY()).getLabel();
}
synchronized (nodes) {
for (TreeViewNode treeNode : nodes.values()) {
final NodeLabel label = treeNode.getLabel();
label.setRollover(label == node);
}
}
tree.repaint();
}
/** Sets treeview colours. */
private void setColours() {
tree.setBackground(IdentityManager.getGlobalConfig().getOptionColour(
"treeview", "backgroundcolour",
"ui", "backgroundcolour"));
tree.setForeground(IdentityManager.getGlobalConfig().getOptionColour(
"treeview", "foregroundcolour",
"ui", "foregroundcolour"));
tree.repaint();
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
if ("sortrootwindows".equals(key) || "sortchildwindows".equals(key)) {
redoTreeView();
} else {
setColours();
}
}
/**
* Starts the tree from scratch taking into account new sort orders.
*/
private void redoTreeView() {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
((DefaultTreeModel) tree.getModel()).setRoot(null);
((DefaultTreeModel) tree.getModel()).setRoot(new TreeViewNode(
null, null));
if (scroller != null) {
scroller.unregister();
}
scroller = new TreeTreeScroller(controller, tree);
for (FrameContainer window
: WindowManager.getWindowManager().getRootWindows()) {
addWindow(null, window);
final Collection<FrameContainer> childWindows = window
.getChildren();
for (FrameContainer childWindow : childWindows) {
addWindow(nodes.get(window), childWindow);
}
}
if (controller.getMainFrame() != null
&& controller.getMainFrame().getActiveFrame() != null) {
selectionChanged(controller.getMainFrame().getActiveFrame());
}
}
});
}
/** {@inheritDoc} */
@Override
public void selectionChanged(final TextFrame window) {
synchronized (nodes) {
final Collection<TreeViewNode> collection =
new ArrayList<TreeViewNode>(nodes.values());
for (TreeViewNode treeNode : collection) {
final NodeLabel label = treeNode.getLabel();
label.selectionChanged(window);
}
}
if (window != null) {
UIUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final TreeNode[] treePath =
((DefaultTreeModel) tree.getModel()).getPathToRoot(
nodes.get(window.getContainer()));
if (treePath != null && treePath.length > 0) {
final TreePath path = new TreePath(treePath);
if (path != null) {
tree.setTreePath(path);
tree.scrollPathToVisible(path);
}
}
}
});
}
}
/** {@inheritDoc} */
@Override
public void notificationSet(final FrameContainer window, final Color colour) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
synchronized (nodes) {
final TreeViewNode node = nodes.get(window);
if (window != null && node != null) {
final NodeLabel label = node.getLabel();
if (label != null) {
label.notificationSet(window, colour);
tree.repaint();
}
}
}
}
});
}
/** {@inheritDoc} */
@Override
public void notificationCleared(final FrameContainer window) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
synchronized (nodes) {
final TreeViewNode node = nodes.get(window);
if (window != null && node != null) {
final NodeLabel label = node.getLabel();
if (label != null) {
label.notificationCleared(window);
tree.repaint();
}
}
}
}
});
}
/** {@inheritDoc} */
@Override
public void iconChanged(final FrameContainer window, final String icon) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
synchronized (nodes) {
final TreeViewNode node = nodes.get(window);
if (node != null) {
final NodeLabel label = node.getLabel();
if (label != null) {
label.iconChanged(window, icon);
tree.repaint();
}
}
}
}
});
}
/** {@inheritDoc} */
@Override
public void nameChanged(final FrameContainer window, final String name) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
synchronized (nodes) {
final TreeViewNode node = nodes.get(window);
if (node != null) {
final NodeLabel label = node.getLabel();
if (label != null) {
label.nameChanged(window, name);
tree.repaint();
}
}
}
}
});
}
/** {@inheritDoc} */
@Override
public void titleChanged(final FrameContainer window, final String title) {
// Do nothing
}
}
| true | true | public void addWindow(final TreeViewNode parent,
final FrameContainer window) {
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final NodeLabel label = new NodeLabel(window);
final TreeViewNode node = new TreeViewNode(label, window);
synchronized (nodes) {
nodes.put(window, node);
}
if (parent == null) {
model.insertNodeInto(node, model.getRootNode());
} else {
model.insertNodeInto(node, parent);
}
tree.expandPath(new TreePath(node.getPath()).getParentPath());
final Rectangle view =
tree.getRowBounds(tree.getRowForPath(new TreePath(node.
getPath())));
if (view != null) {
tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(),
0, 0));
}
window.addFrameInfoListener(TreeFrameManager.this);
window.addNotificationListener(TreeFrameManager.this);
node.getLabel().notificationSet(window, window.getNotification());
}
});
}
| public void addWindow(final TreeViewNode parent,
final FrameContainer window) {
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final NodeLabel label = new NodeLabel(window);
final TreeViewNode node = new TreeViewNode(label, window);
synchronized (nodes) {
nodes.put(window, node);
}
if (parent == null) {
model.insertNodeInto(node, model.getRootNode());
} else {
model.insertNodeInto(node, parent);
}
tree.expandPath(new TreePath(node.getPath()).getParentPath());
final Rectangle view =
tree.getRowBounds(tree.getRowForPath(new TreePath(node.
getPath())));
if (view != null) {
tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(),
0, 0));
}
window.addFrameInfoListener(TreeFrameManager.this);
window.addNotificationListener(TreeFrameManager.this);
node.getLabel().notificationSet(window, window.getNotification());
node.getLabel().iconChanged(window, window.getIcon());
}
});
}
|
diff --git a/src/Kode/GUI.java b/src/Kode/GUI.java
index a13b72b..fba6fc1 100644
--- a/src/Kode/GUI.java
+++ b/src/Kode/GUI.java
@@ -1,198 +1,198 @@
package Kode;
import java.awt.*;
import javax.swing.*;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
public class GUI extends JFrame {
//Alle komponenter
private BrettRute bakgrunn = new BrettRute("src/Kode/Bilder/ramme.png");
private JMenuBar menuBar = new JMenuBar();
private Sjakk sjakk = new Sjakk();
private Timer timerS;
private Timer timerH;
private JTextArea textarea = new JTextArea(10, 12);
private JTextArea textarea2 = new JTextArea(10, 12);
private JScrollPane scrollpane = new JScrollPane(textarea);
private JScrollPane scrollpane2 = new JScrollPane(textarea2);
private Container contentPane = getContentPane();
private SpringLayout layout = new SpringLayout();
SjakkListener sjakkL = new SjakkListener() {
@Override
public void sjakkReceived(SjakkEvent event) {
if (event.lag() == 1) {
timerS.resume();
timerH.pause();
textarea.setText(sjakk.getHvitLogg());
} else if (event.lag() == 2) {
timerS.pause();
timerH.resume();
textarea2.setText(sjakk.getSvartLogg());
}
}
};
public GUI(String tittel) {
//Ramme
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle(tittel);
contentPane.setLayout(layout);
setJMenuBar(menuBar);
sjakk = new Sjakk();
sjakk.addSjakkListener(sjakkL);
timerS = new Timer();
timerH = new Timer();
scrollpane = new JScrollPane(textarea);
scrollpane2 = new JScrollPane(textarea2);
bakgrunn.setPreferredSize(new Dimension(920, 650));
add(scrollpane);
add(sjakk);
add(scrollpane2);
add(timerS);
add(timerH);
//add(bakgrunn);
layout.putConstraint(SpringLayout.WEST, scrollpane, 23, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, scrollpane, 20, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, scrollpane2, 20, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, scrollpane2, 920, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.EAST, sjakk, 840, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, sjakk, 30, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, timerS, 190, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, timerS, 64, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, timerH, 190, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, timerH, 970, SpringLayout.WEST, contentPane);
//Menybar
JMenu file = new JMenu("Fil");
JMenu settings = new JMenu("Innstillinger");
JMenu credits = new JMenu("Credits");
JMenu help = new JMenu("Hjelp");
menuBar.add(file);
menuBar.add(settings);
menuBar.add(credits);
menuBar.add(help);
menuBar.setBorder(null);
//Knapper til menybar
JMenuItem Nyttspill = new JMenuItem("Nytt Spill", new ImageIcon("src/Kode/Bilder/nyttspill1.png"));
Nyttspill.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.SHIFT_MASK));
JMenuItem Avslutt = new JMenuItem("Avslutt", new ImageIcon("src/Kode/Bilder/avslutt.png"));
JMenuItem Save = new JMenuItem("Lagre spill", new ImageIcon("src/Kode/Bilder/mac.png"));
JMenuItem Load = new JMenuItem("Åpne spill", new ImageIcon("src/Kode/Bilder/Load Icon.png"));
Save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
Load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
JRadioButtonMenuItem Meme = new JRadioButtonMenuItem("Meme-sjakk");
JRadioButtonMenuItem Vanlig = new JRadioButtonMenuItem("Vanlig sjakk");
Meme.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.SHIFT_MASK));
Vanlig.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.SHIFT_MASK));
Avslutt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.SHIFT_MASK));
JMenuItem Utviklere = new JMenuItem("Utviklere");
ButtonGroup bg = new ButtonGroup();
bg.add(Meme);
bg.add(Vanlig);
file.add(Nyttspill);
file.add(Save);
file.add(Load);
file.add(Avslutt);
settings.add(Meme);
settings.add(Vanlig);
credits.add(Utviklere);
//Logg
textarea.setEditable(false);
textarea2.setEditable(false);
//textarea.setOpaque(false);
//scrollpane.setOpaque(false);
//scrollpane.getViewport().setOpaque(false);
scrollpane.setBorder(null);
//textarea2.setOpaque(false);
//scrollpane2.setOpaque(false);
//scrollpane2.getViewport().setOpaque(false);
scrollpane2.setBorder(null);
//Lyttere
Nyttspill.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset();
}
});
Avslutt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Utviklere.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
- JOptionPane.showMessageDialog(null, "Copyright © 2003–2011 Andreas Henrik Michael Lars. \nAll rights reserved.", "MemeChess",3, new ImageIcon("src/Kode/Bilder/trollfaceW.png"));
+ JOptionPane.showMessageDialog(null, "Copyright © 2003–2011 Andreas Kalstad, Henrik Reitan, Michael Olsen, Lars Kristoffer Sagmo. \nAll rights reserved.", "MemeChess",3, new ImageIcon("src/Kode/Bilder/trollfaceW.png"));
}
});
Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.tilTabell();
}
});
Load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.fraTabell();
sjakk.refresh();
}
});
Meme.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.endreUI(1);
}
});
Vanlig.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.endreUI(2);
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void reset(){
remove(sjakk);
remove(scrollpane);
remove(scrollpane2);
textarea.setText("");
textarea2.setText("");
repaint();
menuBar.remove(timerS);
menuBar.remove(timerH);
sjakk = new Sjakk();
timerS = new Timer();
timerH = new Timer();
scrollpane = new JScrollPane(textarea);
scrollpane2 = new JScrollPane(textarea2);
add(sjakk);
sjakk.addSjakkListener(sjakkL);
add(scrollpane, SpringLayout.WEST);
add(scrollpane2, SpringLayout.EAST);
layout.putConstraint(SpringLayout.WEST, scrollpane, 0, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, sjakk, 152, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, scrollpane2, 755, SpringLayout.WEST, contentPane);
setVisible(true);
}
}
| true | true | public GUI(String tittel) {
//Ramme
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle(tittel);
contentPane.setLayout(layout);
setJMenuBar(menuBar);
sjakk = new Sjakk();
sjakk.addSjakkListener(sjakkL);
timerS = new Timer();
timerH = new Timer();
scrollpane = new JScrollPane(textarea);
scrollpane2 = new JScrollPane(textarea2);
bakgrunn.setPreferredSize(new Dimension(920, 650));
add(scrollpane);
add(sjakk);
add(scrollpane2);
add(timerS);
add(timerH);
//add(bakgrunn);
layout.putConstraint(SpringLayout.WEST, scrollpane, 23, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, scrollpane, 20, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, scrollpane2, 20, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, scrollpane2, 920, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.EAST, sjakk, 840, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, sjakk, 30, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, timerS, 190, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, timerS, 64, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, timerH, 190, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, timerH, 970, SpringLayout.WEST, contentPane);
//Menybar
JMenu file = new JMenu("Fil");
JMenu settings = new JMenu("Innstillinger");
JMenu credits = new JMenu("Credits");
JMenu help = new JMenu("Hjelp");
menuBar.add(file);
menuBar.add(settings);
menuBar.add(credits);
menuBar.add(help);
menuBar.setBorder(null);
//Knapper til menybar
JMenuItem Nyttspill = new JMenuItem("Nytt Spill", new ImageIcon("src/Kode/Bilder/nyttspill1.png"));
Nyttspill.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.SHIFT_MASK));
JMenuItem Avslutt = new JMenuItem("Avslutt", new ImageIcon("src/Kode/Bilder/avslutt.png"));
JMenuItem Save = new JMenuItem("Lagre spill", new ImageIcon("src/Kode/Bilder/mac.png"));
JMenuItem Load = new JMenuItem("Åpne spill", new ImageIcon("src/Kode/Bilder/Load Icon.png"));
Save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
Load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
JRadioButtonMenuItem Meme = new JRadioButtonMenuItem("Meme-sjakk");
JRadioButtonMenuItem Vanlig = new JRadioButtonMenuItem("Vanlig sjakk");
Meme.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.SHIFT_MASK));
Vanlig.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.SHIFT_MASK));
Avslutt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.SHIFT_MASK));
JMenuItem Utviklere = new JMenuItem("Utviklere");
ButtonGroup bg = new ButtonGroup();
bg.add(Meme);
bg.add(Vanlig);
file.add(Nyttspill);
file.add(Save);
file.add(Load);
file.add(Avslutt);
settings.add(Meme);
settings.add(Vanlig);
credits.add(Utviklere);
//Logg
textarea.setEditable(false);
textarea2.setEditable(false);
//textarea.setOpaque(false);
//scrollpane.setOpaque(false);
//scrollpane.getViewport().setOpaque(false);
scrollpane.setBorder(null);
//textarea2.setOpaque(false);
//scrollpane2.setOpaque(false);
//scrollpane2.getViewport().setOpaque(false);
scrollpane2.setBorder(null);
//Lyttere
Nyttspill.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset();
}
});
Avslutt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Utviklere.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Copyright © 2003–2011 Andreas Henrik Michael Lars. \nAll rights reserved.", "MemeChess",3, new ImageIcon("src/Kode/Bilder/trollfaceW.png"));
}
});
Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.tilTabell();
}
});
Load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.fraTabell();
sjakk.refresh();
}
});
Meme.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.endreUI(1);
}
});
Vanlig.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.endreUI(2);
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
| public GUI(String tittel) {
//Ramme
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle(tittel);
contentPane.setLayout(layout);
setJMenuBar(menuBar);
sjakk = new Sjakk();
sjakk.addSjakkListener(sjakkL);
timerS = new Timer();
timerH = new Timer();
scrollpane = new JScrollPane(textarea);
scrollpane2 = new JScrollPane(textarea2);
bakgrunn.setPreferredSize(new Dimension(920, 650));
add(scrollpane);
add(sjakk);
add(scrollpane2);
add(timerS);
add(timerH);
//add(bakgrunn);
layout.putConstraint(SpringLayout.WEST, scrollpane, 23, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, scrollpane, 20, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, scrollpane2, 20, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, scrollpane2, 920, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.EAST, sjakk, 840, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, sjakk, 30, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, timerS, 190, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, timerS, 64, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, timerH, 190, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, timerH, 970, SpringLayout.WEST, contentPane);
//Menybar
JMenu file = new JMenu("Fil");
JMenu settings = new JMenu("Innstillinger");
JMenu credits = new JMenu("Credits");
JMenu help = new JMenu("Hjelp");
menuBar.add(file);
menuBar.add(settings);
menuBar.add(credits);
menuBar.add(help);
menuBar.setBorder(null);
//Knapper til menybar
JMenuItem Nyttspill = new JMenuItem("Nytt Spill", new ImageIcon("src/Kode/Bilder/nyttspill1.png"));
Nyttspill.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.SHIFT_MASK));
JMenuItem Avslutt = new JMenuItem("Avslutt", new ImageIcon("src/Kode/Bilder/avslutt.png"));
JMenuItem Save = new JMenuItem("Lagre spill", new ImageIcon("src/Kode/Bilder/mac.png"));
JMenuItem Load = new JMenuItem("Åpne spill", new ImageIcon("src/Kode/Bilder/Load Icon.png"));
Save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
Load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
JRadioButtonMenuItem Meme = new JRadioButtonMenuItem("Meme-sjakk");
JRadioButtonMenuItem Vanlig = new JRadioButtonMenuItem("Vanlig sjakk");
Meme.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.SHIFT_MASK));
Vanlig.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.SHIFT_MASK));
Avslutt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.SHIFT_MASK));
JMenuItem Utviklere = new JMenuItem("Utviklere");
ButtonGroup bg = new ButtonGroup();
bg.add(Meme);
bg.add(Vanlig);
file.add(Nyttspill);
file.add(Save);
file.add(Load);
file.add(Avslutt);
settings.add(Meme);
settings.add(Vanlig);
credits.add(Utviklere);
//Logg
textarea.setEditable(false);
textarea2.setEditable(false);
//textarea.setOpaque(false);
//scrollpane.setOpaque(false);
//scrollpane.getViewport().setOpaque(false);
scrollpane.setBorder(null);
//textarea2.setOpaque(false);
//scrollpane2.setOpaque(false);
//scrollpane2.getViewport().setOpaque(false);
scrollpane2.setBorder(null);
//Lyttere
Nyttspill.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset();
}
});
Avslutt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Utviklere.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Copyright © 2003–2011 Andreas Kalstad, Henrik Reitan, Michael Olsen, Lars Kristoffer Sagmo. \nAll rights reserved.", "MemeChess",3, new ImageIcon("src/Kode/Bilder/trollfaceW.png"));
}
});
Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.tilTabell();
}
});
Load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.fraTabell();
sjakk.refresh();
}
});
Meme.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.endreUI(1);
}
});
Vanlig.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sjakk.endreUI(2);
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
|
diff --git a/trunk/jbehave/core/src/com/thoughtworks/jbehave/core/responsibility/NotifyingResponsibilityVerifier.java b/trunk/jbehave/core/src/com/thoughtworks/jbehave/core/responsibility/NotifyingResponsibilityVerifier.java
index e7c1215d..e5d96f69 100644
--- a/trunk/jbehave/core/src/com/thoughtworks/jbehave/core/responsibility/NotifyingResponsibilityVerifier.java
+++ b/trunk/jbehave/core/src/com/thoughtworks/jbehave/core/responsibility/NotifyingResponsibilityVerifier.java
@@ -1,45 +1,45 @@
/*
* Created on 12-Aug-2004
*
* (c) 2003-2004 ThoughtWorks Ltd
*
* See license.txt for license details
*/
package com.thoughtworks.jbehave.core.responsibility;
import java.lang.reflect.Method;
import com.thoughtworks.jbehave.core.Listener;
import com.thoughtworks.jbehave.core.exception.JBehaveFrameworkError;
/**
* @author <a href="mailto:[email protected]">Dan North</a>
*/
public class NotifyingResponsibilityVerifier implements ResponsibilityVerifier {
/**
* Verify an individual responsibility.
*
* The {@link Listener} is alerted before and after the verification,
* with calls to {@link Listener#responsibilityVerificationStarting(Method)
* responsibilityVerificationStarting(this)} and
* {@link Listener#responsibilityVerificationEnding(Result, Object)
* responsibilityVerificationEnding(result)} respectively.
*/
public Result verifyResponsibility(Listener listener, Method method, Object instance) {
try {
listener.responsibilityVerificationStarting(method);
Result result = doVerifyResponsibility(method, instance);
- listener.responsibilityVerificationEnding(result, instance);
+ result = listener.responsibilityVerificationEnding(result, instance);
return result;
} catch (Exception e) {
System.out.println("Problem verifying " + method);
throw new JBehaveFrameworkError(e);
}
}
protected Result doVerifyResponsibility(Method method, Object instance) {
return new Result(method.getDeclaringClass().getName(), method.getName());
}
}
| true | true | public Result verifyResponsibility(Listener listener, Method method, Object instance) {
try {
listener.responsibilityVerificationStarting(method);
Result result = doVerifyResponsibility(method, instance);
listener.responsibilityVerificationEnding(result, instance);
return result;
} catch (Exception e) {
System.out.println("Problem verifying " + method);
throw new JBehaveFrameworkError(e);
}
}
| public Result verifyResponsibility(Listener listener, Method method, Object instance) {
try {
listener.responsibilityVerificationStarting(method);
Result result = doVerifyResponsibility(method, instance);
result = listener.responsibilityVerificationEnding(result, instance);
return result;
} catch (Exception e) {
System.out.println("Problem verifying " + method);
throw new JBehaveFrameworkError(e);
}
}
|
diff --git a/src/main/java/com/googlecode/wmbutil/messages/XmlPayload.java b/src/main/java/com/googlecode/wmbutil/messages/XmlPayload.java
index 42cc732..d9c403a 100644
--- a/src/main/java/com/googlecode/wmbutil/messages/XmlPayload.java
+++ b/src/main/java/com/googlecode/wmbutil/messages/XmlPayload.java
@@ -1,290 +1,290 @@
/*
* Copyright 2007 (C) Callista Enterprise.
*
* 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.googlecode.wmbutil.messages;
import com.googlecode.wmbutil.NiceMbException;
import com.googlecode.wmbutil.util.ElementUtil;
import com.googlecode.wmbutil.util.XmlUtil;
import com.ibm.broker.plugin.MbElement;
import com.ibm.broker.plugin.MbException;
import com.ibm.broker.plugin.MbMessage;
import com.ibm.broker.plugin.MbXMLNS;
import com.ibm.broker.plugin.MbXMLNSC;
/**
* Helper class for working with XML messages.
*
*/
public class XmlPayload extends Payload {
private static final String DEFAULT_PARSER = "XMLNS";
private XmlElement docElm;
/**
* Wraps a payload
*
* @param msg The message containing the XML payload
* @param readOnly Specifies whether the payload will be wrapped as read only or not.
* @return XML payload found in the message
* @throws MbException
*/
public static XmlPayload wrap(MbMessage msg, boolean readOnly) throws MbException {
MbElement elm = locateXmlBody(msg);
if (elm == null) {
throw new NiceMbException("Failed to find XML payload");
}
return new XmlPayload(elm, readOnly);
}
/**
* Creates an XMLNS payload as the last child, even if one already exists
*
* @param msg The message where to create an XML payload
* @return A newly created XML payload
* @throws MbException
*/
public static XmlPayload create(MbMessage msg) throws MbException {
return create(msg, DEFAULT_PARSER);
}
/**
* Creates a payload as the last child, even if one already exists
*
* @param msg The message where to create an XML payload
* @param parser Specifies the payload parser
* @return A newly created XML payload
* @throws MbException
*/
public static XmlPayload create(MbMessage msg, String parser) throws MbException {
MbElement elm = msg.getRootElement().createElementAsLastChild(parser);
return new XmlPayload(elm, false);
}
/**
* Wraps or creates a payload as the last child, even if one already exists
*
* @param msg The message where to look for/create an XML payload
* @return An XML payload, existent or newly created
* @throws MbException
*/
public static XmlPayload wrapOrCreate(MbMessage msg) throws MbException {
return wrapOrCreate(msg, DEFAULT_PARSER);
}
/**
* Wraps or creates a payload as the last child, even if one already exists
*
* @param msg The message where to look for/create an XML payload
* @param parser Specifies the parser when creating a new payload
* @return An XML payload, existent or newly created
* @throws MbException
*/
public static XmlPayload wrapOrCreate(MbMessage msg, String parser) throws MbException {
if (has(msg)) {
return wrap(msg, false);
} else {
return create(msg, parser);
}
}
/**
* Removes (detaches) the first XML payload
*
* @param msg The message containing the XML payload
* @return The detached payload
* @throws MbException
*/
public static XmlPayload remove(MbMessage msg) throws MbException {
MbElement elm = locateXmlBody(msg);
if (elm != null) {
elm.detach();
return new XmlPayload(elm, true);
} else {
throw new NiceMbException("Failed to find XML payload");
}
}
/**
* Checks if a message contains an XML payload
*
* @param msg The message to check
* @return True if there's an XML payload in the message
* @throws MbException
*/
public static boolean has(MbMessage msg) throws MbException {
MbElement elm = locateXmlBody(msg);
return elm != null;
}
/**
* Locates the XML body in a message
*
* @param msg The message to check
* @return The XML body element of the message
* @throws MbException
*/
private static MbElement locateXmlBody(MbMessage msg) throws MbException {
MbElement elm = msg.getRootElement().getFirstElementByPath("/XMLNSC");
if (elm == null) {
elm = msg.getRootElement().getFirstElementByPath("/XMLNS");
}
if (elm == null) {
elm = msg.getRootElement().getFirstElementByPath("/XML");
}
if (elm == null) {
elm = msg.getRootElement().getFirstElementByPath("/MRM");
}
return elm;
}
/**
* Class constructor
*
* @param elm
* @param readOnly Specifies whether the payload is readonly
* @throws MbException
*/
private XmlPayload(MbElement elm, boolean readOnly) throws MbException {
super(elm, readOnly);
if (ElementUtil.isMRM(getMbElement())) {
docElm = new XmlElement(getMbElement(), isReadOnly());
} else {
MbElement child = getMbElement().getFirstChild();
while (child != null) {
// find first and only element
if (XmlUtil.isElement(child)) {
docElm = new XmlElement(child, isReadOnly());
break;
}
child = child.getNextSibling();
}
}
}
/**
* Returns the root element
*
* @return The root element
* @throws MbException
*/
public XmlElement getRootElement() {
return docElm;
}
/**
* Creates a root element (without a namespace)
*
* @param name The root element name
* @return The root element
* @throws MbException
*/
public XmlElement createRootElement(String name) throws MbException {
return createRootElement(null, name);
}
/**
* Creates a root element (with a namespace)
*
* @param ns Element name space
* @param name The root element name
* @return The root element
* @throws MbException
*/
public XmlElement createRootElement(String ns, String name) throws MbException {
checkReadOnly();
MbElement elm;
if (ElementUtil.isMRM(getMbElement())) {
// for MRM, don't generate a root element
elm = getMbElement();
} else {
elm = getMbElement().createElementAsLastChild(
XmlUtil.getFolderElementType(getMbElement()));
elm.setName(name);
if (ns != null) {
elm.setNamespace(ns);
}
}
docElm = new XmlElement(elm, isReadOnly());
return docElm;
}
/**
* Declares a namespace in the root element
*
* @param prefix What prefix to use
* @param ns The namespace string
* @throws MbException
*/
public void declareNamespace(String prefix, String ns) throws MbException {
checkReadOnly();
if (ElementUtil.isXML(docElm.getMbElement()) || ElementUtil.isXMLNS(docElm.getMbElement())
|| ElementUtil.isXMLNSC(docElm.getMbElement())) {
docElm.getMbElement().createElementAsFirstChild(MbXMLNS.NAMESPACE_DECL, prefix, ns)
.setNamespace("xmlns");
}
}
/**
* Creates an XML declaration in the payload even if one exists
*
* @param version XML version
* @param encoding XML encoding
* @param standalone Specifies whether standalone should be set to yes or no
* @throws MbException
*/
- public void createXmlDeclaration(String version, String encoding, Boolean standalone) throws MbException {
+ public void createXmlDeclaration(String version, String encoding, boolean standalone) throws MbException {
checkReadOnly();
MbElement elm = getMbElement();
if (ElementUtil.isXMLNSC(elm)) {
MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNSC.XML_DECLARATION);
xmlDecl.setName("XmlDeclaration");
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Version", version);
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Encoding", encoding);
if (standalone) {
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "yes");
} else {
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "no");
}
} else if (ElementUtil.isXML(elm) || ElementUtil.isXMLNS(elm)) {
MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNS.XML_DECL);
xmlDecl.setName("XmlDeclaration");
xmlDecl.createElementAsLastChild(MbXMLNS.VERSION, "version", version);
xmlDecl.createElementAsLastChild(MbXMLNS.ENCODING, "encoding", encoding);
if (standalone) {
xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "standalone", "yes");
} else {
xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "Standalone", "no");
}
} else {
throw new NiceMbException("Failed to create XML declaration for parser " + XmlUtil.getFolderElementType(elm));
}
}
}
| true | true | public void createXmlDeclaration(String version, String encoding, Boolean standalone) throws MbException {
checkReadOnly();
MbElement elm = getMbElement();
if (ElementUtil.isXMLNSC(elm)) {
MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNSC.XML_DECLARATION);
xmlDecl.setName("XmlDeclaration");
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Version", version);
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Encoding", encoding);
if (standalone) {
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "yes");
} else {
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "no");
}
} else if (ElementUtil.isXML(elm) || ElementUtil.isXMLNS(elm)) {
MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNS.XML_DECL);
xmlDecl.setName("XmlDeclaration");
xmlDecl.createElementAsLastChild(MbXMLNS.VERSION, "version", version);
xmlDecl.createElementAsLastChild(MbXMLNS.ENCODING, "encoding", encoding);
if (standalone) {
xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "standalone", "yes");
} else {
xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "Standalone", "no");
}
} else {
throw new NiceMbException("Failed to create XML declaration for parser " + XmlUtil.getFolderElementType(elm));
}
}
| public void createXmlDeclaration(String version, String encoding, boolean standalone) throws MbException {
checkReadOnly();
MbElement elm = getMbElement();
if (ElementUtil.isXMLNSC(elm)) {
MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNSC.XML_DECLARATION);
xmlDecl.setName("XmlDeclaration");
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Version", version);
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Encoding", encoding);
if (standalone) {
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "yes");
} else {
xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "no");
}
} else if (ElementUtil.isXML(elm) || ElementUtil.isXMLNS(elm)) {
MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNS.XML_DECL);
xmlDecl.setName("XmlDeclaration");
xmlDecl.createElementAsLastChild(MbXMLNS.VERSION, "version", version);
xmlDecl.createElementAsLastChild(MbXMLNS.ENCODING, "encoding", encoding);
if (standalone) {
xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "standalone", "yes");
} else {
xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "Standalone", "no");
}
} else {
throw new NiceMbException("Failed to create XML declaration for parser " + XmlUtil.getFolderElementType(elm));
}
}
|
diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java
index 570c8d155..976ccd981 100644
--- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java
+++ b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java
@@ -1,114 +1,114 @@
/* ====================================================================
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.poi.hwpf.converter;
import java.io.File;
import java.io.FilenameFilter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hwpf.HWPFDocumentCore;
public class TestWordToConverterSuite
{
/**
* YK: a quick hack to exclude failing documents from the suite.
*/
private static List<String> failingFiles = Arrays.asList();
public static Test suite()
{
- TestSuite suite = new TestSuite();
+ TestSuite suite = new TestSuite(TestWordToConverterSuite.class.getName());
File directory = POIDataSamples.getDocumentInstance().getFile(
"../document" );
for ( final File child : directory.listFiles( new FilenameFilter()
{
public boolean accept( File dir, String name )
{
return name.endsWith( ".doc" ) && !failingFiles.contains( name );
}
} ) )
{
final String name = child.getName();
suite.addTest( new TestCase( name + " [FO]" )
{
public void runTest() throws Exception
{
test( child, false );
}
} );
suite.addTest( new TestCase( name + " [HTML]" )
{
public void runTest() throws Exception
{
test( child, true );
}
} );
}
return suite;
}
protected static void test( File child, boolean html ) throws Exception
{
HWPFDocumentCore hwpfDocument;
try
{
hwpfDocument = AbstractWordUtils.loadDoc( child );
}
catch ( Exception exc )
{
// unable to parse file -- not WordToFoConverter fault
return;
}
WordToFoConverter wordToFoConverter = new WordToFoConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument() );
wordToFoConverter.processDocument( hwpfDocument );
StringWriter stringWriter = new StringWriter();
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" );
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.transform(
new DOMSource( wordToFoConverter.getDocument() ),
new StreamResult( stringWriter ) );
if ( html )
transformer.setOutputProperty( OutputKeys.METHOD, "html" );
// no exceptions
}
}
| true | true | public static Test suite()
{
TestSuite suite = new TestSuite();
File directory = POIDataSamples.getDocumentInstance().getFile(
"../document" );
for ( final File child : directory.listFiles( new FilenameFilter()
{
public boolean accept( File dir, String name )
{
return name.endsWith( ".doc" ) && !failingFiles.contains( name );
}
} ) )
{
final String name = child.getName();
suite.addTest( new TestCase( name + " [FO]" )
{
public void runTest() throws Exception
{
test( child, false );
}
} );
suite.addTest( new TestCase( name + " [HTML]" )
{
public void runTest() throws Exception
{
test( child, true );
}
} );
}
return suite;
}
| public static Test suite()
{
TestSuite suite = new TestSuite(TestWordToConverterSuite.class.getName());
File directory = POIDataSamples.getDocumentInstance().getFile(
"../document" );
for ( final File child : directory.listFiles( new FilenameFilter()
{
public boolean accept( File dir, String name )
{
return name.endsWith( ".doc" ) && !failingFiles.contains( name );
}
} ) )
{
final String name = child.getName();
suite.addTest( new TestCase( name + " [FO]" )
{
public void runTest() throws Exception
{
test( child, false );
}
} );
suite.addTest( new TestCase( name + " [HTML]" )
{
public void runTest() throws Exception
{
test( child, true );
}
} );
}
return suite;
}
|
diff --git a/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryParser.java b/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryParser.java
index 6dac8aa27..df87abb4a 100644
--- a/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryParser.java
+++ b/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryParser.java
@@ -1,302 +1,305 @@
/*
* Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package ae3.service.structuredquery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.gxa.properties.AtlasProperties;
import uk.ac.ebi.gxa.utils.EscapeUtil;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static uk.ac.ebi.gxa.utils.EscapeUtil.parseNumber;
/**
* HTPP structured query parser for front-end interface and rest API
* @author pashky
*/
public class AtlasStructuredQueryParser {
private static final Logger log = LoggerFactory.getLogger(AtlasStructuredQueryParser.class);
private static final String PARAM_EXPRESSION = "fexp_";
private static final String PARAM_MINEXPERIMENTS = "fmex_";
private static final String PARAM_FACTOR = "fact_";
private static final String PARAM_FACTORVALUE = "fval_";
private static final String PARAM_GENE = "gval_";
private static final String PARAM_GENENOT = "gnot_";
private static final String PARAM_GENEPROP = "gprop_";
private static final String PARAM_SPECIE = "specie_";
private static final String PARAM_START = "p";
private static final String PARAM_EXPAND = "fexp";
/**
* Finds all available parameters' names starting with prefix and ending with some number
* @param httpRequest HTTP request object to process
* @param prefix string prefix
* @return list of available suffixes, ordered numerically (if they can be converted to integer) or lexicographically
*/
public static List<String> findPrefixParamsSuffixes(final HttpServletRequest httpRequest, final String prefix)
{
List<String> result = new ArrayList<String>();
@SuppressWarnings("unchecked")
Enumeration<String> e = httpRequest.getParameterNames();
while(e.hasMoreElements()) {
String v = e.nextElement();
if(v.startsWith(prefix))
result.add(v.replace(prefix, ""));
}
Collections.sort(result, new Comparator<String>() {
public int compare(String o1, String o2) {
try {
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
} catch(NumberFormatException e) {
return o1.compareTo(o2);
}
}
});
return result;
}
/**
* Extract list of reuqested species search strings
* @param httpRequest HTTP request
* @return list of request strings
*/
@SuppressWarnings("unchecked")
private static List<String> parseSpecies(final HttpServletRequest httpRequest)
{
List<String> result = new ArrayList<String>();
for(String p : findPrefixParamsSuffixes(httpRequest, PARAM_SPECIE)) {
String value = httpRequest.getParameter(PARAM_SPECIE + p);
if(value.length() == 0)
// "any" value found, return magic empty list
return Collections.emptyList();
else
result.add(value);
}
return result;
}
/**
* Extract list of experimental conditions from request
* @param httpRequest HTTP request
* @return list of experiment conditions
*/
private static List<ExpFactorQueryCondition> parseExpFactorConditions(final HttpServletRequest httpRequest)
{
List<ExpFactorQueryCondition> result = new ArrayList<ExpFactorQueryCondition>();
for(String id : findPrefixParamsSuffixes(httpRequest, PARAM_FACTOR)) {
ExpFactorQueryCondition condition = new ExpFactorQueryCondition();
try {
condition.setExpression(QueryExpression.parseFuzzyString(httpRequest.getParameter(PARAM_EXPRESSION + id)));
condition.setMinExperiments(EscapeUtil.parseNumber(httpRequest.getParameter(PARAM_MINEXPERIMENTS + id), 1, 1, Integer.MAX_VALUE));
String factor = httpRequest.getParameter(PARAM_FACTOR + id);
if(factor == null)
throw new IllegalArgumentException("Empty factor name rowid:" + id);
condition.setFactor(factor);
String value = httpRequest.getParameter(PARAM_FACTORVALUE + id);
List<String> values = value != null ? EscapeUtil.parseQuotedList(value) : new ArrayList<String>();
condition.setFactorValues(values);
result.add(condition);
} catch (IllegalArgumentException e) {
// Ignore this one, may be better stop future handling
log.error("Unable to parse and condition. Ignoring it.", e);
}
}
return result;
}
/**
* Extract list of gene condtitions from request
* @param httpRequest HTTP request
* @return list of gene conditions
*/
private static List<GeneQueryCondition> parseGeneConditions(final HttpServletRequest httpRequest)
{
List<GeneQueryCondition> result = new ArrayList<GeneQueryCondition>();
for(String id : findPrefixParamsSuffixes(httpRequest, PARAM_GENEPROP)) {
GeneQueryCondition condition = new GeneQueryCondition();
try {
String not = httpRequest.getParameter(PARAM_GENENOT + id);
condition.setNegated(not != null && !"".equals(not) && !"0".equals(not));
String factor = httpRequest.getParameter(PARAM_GENEPROP + id);
if(factor == null)
throw new IllegalArgumentException("Empty gene property name rowid:" + id);
condition.setFactor(factor);
String value = httpRequest.getParameter(PARAM_GENE + id);
List<String> values = value != null ? EscapeUtil.parseQuotedList(value) : new ArrayList<String>();
if(values.size() > 0)
{
condition.setFactorValues(values);
result.add(condition);
}
} catch (IllegalArgumentException e) {
// Ignore this one, may be better stop future handling
log.error("Unable to parse and condition. Ignoring it.", e);
}
}
return result;
}
/**
* Extract list of columns to expand in heatmap view
* @param httpRequest HTTP request
* @return list of factors to be expanded in view
*/
static private Set<String> parseExpandColumns(final HttpServletRequest httpRequest)
{
String[] values = httpRequest.getParameterValues(PARAM_EXPAND);
Set<String> result = new HashSet<String>();
if(values != null && values.length > 0)
{
result.addAll(Arrays.asList(values));
}
return result;
}
/**
* Extract view type (heatmap or list) for structured query result
* @param s view type parameter string
* @return view type
*/
static private ViewType parseViewType(String s) {
try {
if("list".equals(s))
return ViewType.LIST;
} catch (Exception e) { // skip
}
return ViewType.HEATMAP;
}
/**
* Parse HTTP request parameters provided by interactive javascript code and build AtlasStructuredQuery structure
* @param httpRequest HTTP servlet request
* @return query object made of successfully parsed conditions
*/
static public AtlasStructuredQuery parseRequest(final HttpServletRequest httpRequest,
final AtlasProperties atlasProperties) {
AtlasStructuredQuery request = new AtlasStructuredQuery();
request.setGeneConditions(parseGeneConditions(httpRequest));
request.setSpecies(parseSpecies(httpRequest));
request.setConditions(parseExpFactorConditions(httpRequest));
request.setViewType(parseViewType(httpRequest.getParameter("view")));
if(!request.isNone()){
if(request.getViewType() == ViewType.HEATMAP)
request.setRowsPerPage(atlasProperties.getQueryPageSize());
else{
request.setRowsPerPage(atlasProperties.getQueryListSize());
request.setExpsPerGene(atlasProperties.getQueryExperimentsPerGene());
}
}
String start = httpRequest.getParameter(PARAM_START);
try {
request.setStart(Integer.valueOf(start) * request.getRowsPerPage());
} catch(Exception e) {
request.setStart(0);
}
request.setExpandColumns(parseExpandColumns(httpRequest));
return request;
}
/**
* Parse REST API URL into AtlasStructuredQuery. For format of this URL please refer to REST API documentation.
* @param request HTTP request
* @param properties collection of all available gene properties to check against
* @param factors collection of available factors to check against
* @return query object made of successfully parsed conditions
*/
static public AtlasStructuredQuery parseRestRequest(HttpServletRequest request, Collection<String> properties, Collection<String> factors) {
AtlasStructuredQueryBuilder qb = new AtlasStructuredQueryBuilder();
qb.viewAs(ViewType.LIST);
Pattern pexpr = Pattern.compile("^(any|non|up|d(ow)?n|up([Oo]r)?[Dd](ow)?n|up([Oo]nly)|d(ow)?n([Oo]nly)?)([0-9]*)In(.*)$");
Pattern geneExpr = Pattern.compile("^gene(.*)(:?Is(:?Not)?)?$");
for(Object e : request.getParameterMap().entrySet()) {
String name = ((Map.Entry)e).getKey().toString();
for(String v : ((String[])((Map.Entry)e).getValue())) {
Matcher m;
if((m = geneExpr.matcher(name)).matches()) {
boolean not = name.endsWith("Not");
String propName = m.group(1).toLowerCase();
- if(propName.startsWith("any"))
+ if(propName.startsWith("any") ||
+ // If no property was specified after gene and before Is (e.g. propName == "is" or propName == "isnot"),
+ // this is equivalent to "any" factor query, i.e. geneIsNot=cell+cycle == geneAnyIsNot=cell+cycle
+ propName.startsWith("is"))
propName = "";
else if(propName.length() > 0)
for(String p : properties)
if(p.equalsIgnoreCase(propName))
propName = p;
qb.andGene(propName, !not, EscapeUtil.parseQuotedList(v));
} else if((m = pexpr.matcher(name)).matches()) {
QueryExpression qexp = QueryExpression.parseFuzzyString(m.group(1));
int minExp = EscapeUtil.parseNumber(m.group(8), 1, 1, Integer.MAX_VALUE);
String factName = m.group(9).toLowerCase();
if(factName.startsWith("any"))
factName = "";
else if(factName.length() > 0)
for(String p : factors)
if(p.equalsIgnoreCase(factName))
factName = p;
qb.andExprIn(factName, qexp, minExp, EscapeUtil.parseQuotedList(v));
} else if(name.equalsIgnoreCase("species")) {
qb.andSpecies(v);
} else if(name.equalsIgnoreCase("rows")) {
qb.rowsPerPage(parseNumber(v, 10, 1, 200));
} else if(name.equalsIgnoreCase("start")) {
qb.startFrom(parseNumber(v, 0, 0, Integer.MAX_VALUE));
} else if(name.equalsIgnoreCase("viewAs")) {
try {
qb.viewAs(ViewType.valueOf(v.toUpperCase()));
} catch(Exception ee) {
// do nothing
}
}
}
}
qb.expsPerGene(Integer.MAX_VALUE);
return qb.query();
}
}
| true | true | static public AtlasStructuredQuery parseRestRequest(HttpServletRequest request, Collection<String> properties, Collection<String> factors) {
AtlasStructuredQueryBuilder qb = new AtlasStructuredQueryBuilder();
qb.viewAs(ViewType.LIST);
Pattern pexpr = Pattern.compile("^(any|non|up|d(ow)?n|up([Oo]r)?[Dd](ow)?n|up([Oo]nly)|d(ow)?n([Oo]nly)?)([0-9]*)In(.*)$");
Pattern geneExpr = Pattern.compile("^gene(.*)(:?Is(:?Not)?)?$");
for(Object e : request.getParameterMap().entrySet()) {
String name = ((Map.Entry)e).getKey().toString();
for(String v : ((String[])((Map.Entry)e).getValue())) {
Matcher m;
if((m = geneExpr.matcher(name)).matches()) {
boolean not = name.endsWith("Not");
String propName = m.group(1).toLowerCase();
if(propName.startsWith("any"))
propName = "";
else if(propName.length() > 0)
for(String p : properties)
if(p.equalsIgnoreCase(propName))
propName = p;
qb.andGene(propName, !not, EscapeUtil.parseQuotedList(v));
} else if((m = pexpr.matcher(name)).matches()) {
QueryExpression qexp = QueryExpression.parseFuzzyString(m.group(1));
int minExp = EscapeUtil.parseNumber(m.group(8), 1, 1, Integer.MAX_VALUE);
String factName = m.group(9).toLowerCase();
if(factName.startsWith("any"))
factName = "";
else if(factName.length() > 0)
for(String p : factors)
if(p.equalsIgnoreCase(factName))
factName = p;
qb.andExprIn(factName, qexp, minExp, EscapeUtil.parseQuotedList(v));
} else if(name.equalsIgnoreCase("species")) {
qb.andSpecies(v);
} else if(name.equalsIgnoreCase("rows")) {
qb.rowsPerPage(parseNumber(v, 10, 1, 200));
} else if(name.equalsIgnoreCase("start")) {
qb.startFrom(parseNumber(v, 0, 0, Integer.MAX_VALUE));
} else if(name.equalsIgnoreCase("viewAs")) {
try {
qb.viewAs(ViewType.valueOf(v.toUpperCase()));
} catch(Exception ee) {
// do nothing
}
}
}
}
qb.expsPerGene(Integer.MAX_VALUE);
return qb.query();
}
| static public AtlasStructuredQuery parseRestRequest(HttpServletRequest request, Collection<String> properties, Collection<String> factors) {
AtlasStructuredQueryBuilder qb = new AtlasStructuredQueryBuilder();
qb.viewAs(ViewType.LIST);
Pattern pexpr = Pattern.compile("^(any|non|up|d(ow)?n|up([Oo]r)?[Dd](ow)?n|up([Oo]nly)|d(ow)?n([Oo]nly)?)([0-9]*)In(.*)$");
Pattern geneExpr = Pattern.compile("^gene(.*)(:?Is(:?Not)?)?$");
for(Object e : request.getParameterMap().entrySet()) {
String name = ((Map.Entry)e).getKey().toString();
for(String v : ((String[])((Map.Entry)e).getValue())) {
Matcher m;
if((m = geneExpr.matcher(name)).matches()) {
boolean not = name.endsWith("Not");
String propName = m.group(1).toLowerCase();
if(propName.startsWith("any") ||
// If no property was specified after gene and before Is (e.g. propName == "is" or propName == "isnot"),
// this is equivalent to "any" factor query, i.e. geneIsNot=cell+cycle == geneAnyIsNot=cell+cycle
propName.startsWith("is"))
propName = "";
else if(propName.length() > 0)
for(String p : properties)
if(p.equalsIgnoreCase(propName))
propName = p;
qb.andGene(propName, !not, EscapeUtil.parseQuotedList(v));
} else if((m = pexpr.matcher(name)).matches()) {
QueryExpression qexp = QueryExpression.parseFuzzyString(m.group(1));
int minExp = EscapeUtil.parseNumber(m.group(8), 1, 1, Integer.MAX_VALUE);
String factName = m.group(9).toLowerCase();
if(factName.startsWith("any"))
factName = "";
else if(factName.length() > 0)
for(String p : factors)
if(p.equalsIgnoreCase(factName))
factName = p;
qb.andExprIn(factName, qexp, minExp, EscapeUtil.parseQuotedList(v));
} else if(name.equalsIgnoreCase("species")) {
qb.andSpecies(v);
} else if(name.equalsIgnoreCase("rows")) {
qb.rowsPerPage(parseNumber(v, 10, 1, 200));
} else if(name.equalsIgnoreCase("start")) {
qb.startFrom(parseNumber(v, 0, 0, Integer.MAX_VALUE));
} else if(name.equalsIgnoreCase("viewAs")) {
try {
qb.viewAs(ViewType.valueOf(v.toUpperCase()));
} catch(Exception ee) {
// do nothing
}
}
}
}
qb.expsPerGene(Integer.MAX_VALUE);
return qb.query();
}
|
diff --git a/helloworld/src/Smallint.java b/helloworld/src/Smallint.java
index ffb4914..2ca23d7 100644
--- a/helloworld/src/Smallint.java
+++ b/helloworld/src/Smallint.java
@@ -1,7 +1,10 @@
public class Smallint {
public int getSmallest (int a, int b){
+ if (a < b){
return a;
+ }
+ return b;
}
}
| false | true | public int getSmallest (int a, int b){
return a;
}
| public int getSmallest (int a, int b){
if (a < b){
return a;
}
return b;
}
|
diff --git a/src/main/java/org/mybatis/spring/SqlSessionTemplate.java b/src/main/java/org/mybatis/spring/SqlSessionTemplate.java
index bc3c1bbd..938c9252 100644
--- a/src/main/java/org/mybatis/spring/SqlSessionTemplate.java
+++ b/src/main/java/org/mybatis/spring/SqlSessionTemplate.java
@@ -1,380 +1,385 @@
/*
* Copyright 2010-2013 the original author or authors.
*
* 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 org.mybatis.spring;
import static java.lang.reflect.Proxy.newProxyInstance;
import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable;
import static org.mybatis.spring.SqlSessionUtils.closeSqlSession;
import static org.mybatis.spring.SqlSessionUtils.getSqlSession;
import static org.mybatis.spring.SqlSessionUtils.isSqlSessionTransactional;
import static org.springframework.util.Assert.notNull;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.executor.BatchResult;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.dao.support.PersistenceExceptionTranslator;
/**
* Thread safe, Spring managed, {@code SqlSession} that works with Spring
* transaction management to ensure that that the actual SqlSession used is the
* one associated with the current Spring transaction. In addition, it manages
* the session life-cycle, including closing, committing or rolling back the
* session as necessary based on the Spring transaction configuration.
* <p>
* The template needs a SqlSessionFactory to create SqlSessions, passed as a
* constructor argument. It also can be constructed indicating the executor type
* to be used, if not, the default executor type, defined in the session factory
* will be used.
* <p>
* This template converts MyBatis PersistenceExceptions into unchecked
* DataAccessExceptions, using, by default, a {@code MyBatisExceptionTranslator}.
* <p>
* Because SqlSessionTemplate is thread safe, a single instance can be shared
* by all DAOs; there should also be a small memory savings by doing this. This
* pattern can be used in Spring configuration files as follows:
*
* <pre class="code">
* {@code
* <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
* <constructor-arg ref="sqlSessionFactory" />
* </bean>
* }
* </pre>
*
* @author Putthibong Boonbong
* @author Hunter Presnall
* @author Eduardo Macarron
*
* @see SqlSessionFactory
* @see MyBatisExceptionTranslator
* @version $Id$
*/
public class SqlSessionTemplate implements SqlSession {
private final SqlSessionFactory sqlSessionFactory;
private final ExecutorType executorType;
private final SqlSession sqlSessionProxy;
private final PersistenceExceptionTranslator exceptionTranslator;
/**
* Constructs a Spring managed SqlSession with the {@code SqlSessionFactory}
* provided as an argument.
*
* @param sqlSessionFactory
*/
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
}
/**
* Constructs a Spring managed SqlSession with the {@code SqlSessionFactory}
* provided as an argument and the given {@code ExecutorType}
* {@code ExecutorType} cannot be changed once the {@code SqlSessionTemplate}
* is constructed.
*
* @param sqlSessionFactory
* @param executorType
*/
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
this(sqlSessionFactory, executorType,
new MyBatisExceptionTranslator(
sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true));
}
/**
* Constructs a Spring managed {@code SqlSession} with the given
* {@code SqlSessionFactory} and {@code ExecutorType}.
* A custom {@code SQLExceptionTranslator} can be provided as an
* argument so any {@code PersistenceException} thrown by MyBatis
* can be custom translated to a {@code RuntimeException}
* The {@code SQLExceptionTranslator} can also be null and thus no
* exception translation will be done and MyBatis exceptions will be
* thrown
*
* @param sqlSessionFactory
* @param executorType
* @param exceptionTranslator
*/
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
PersistenceExceptionTranslator exceptionTranslator) {
notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
notNull(executorType, "Property 'executorType' is required");
this.sqlSessionFactory = sqlSessionFactory;
this.executorType = executorType;
this.exceptionTranslator = exceptionTranslator;
this.sqlSessionProxy = (SqlSession) newProxyInstance(
SqlSessionFactory.class.getClassLoader(),
new Class[] { SqlSession.class },
new SqlSessionInterceptor());
}
public SqlSessionFactory getSqlSessionFactory() {
return this.sqlSessionFactory;
}
public ExecutorType getExecutorType() {
return this.executorType;
}
public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {
return this.exceptionTranslator;
}
/**
* {@inheritDoc}
*/
public <T> T selectOne(String statement) {
return this.sqlSessionProxy.<T> selectOne(statement);
}
/**
* {@inheritDoc}
*/
public <T> T selectOne(String statement, Object parameter) {
return this.sqlSessionProxy.<T> selectOne(statement, parameter);
}
/**
* {@inheritDoc}
*/
public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey);
}
/**
* {@inheritDoc}
*/
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey);
}
/**
* {@inheritDoc}
*/
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds);
}
/**
* {@inheritDoc}
*/
public <E> List<E> selectList(String statement) {
return this.sqlSessionProxy.<E> selectList(statement);
}
/**
* {@inheritDoc}
*/
public <E> List<E> selectList(String statement, Object parameter) {
return this.sqlSessionProxy.<E> selectList(statement, parameter);
}
/**
* {@inheritDoc}
*/
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds);
}
/**
* {@inheritDoc}
*/
public void select(String statement, ResultHandler handler) {
this.sqlSessionProxy.select(statement, handler);
}
/**
* {@inheritDoc}
*/
public void select(String statement, Object parameter, ResultHandler handler) {
this.sqlSessionProxy.select(statement, parameter, handler);
}
/**
* {@inheritDoc}
*/
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
this.sqlSessionProxy.select(statement, parameter, rowBounds, handler);
}
/**
* {@inheritDoc}
*/
public int insert(String statement) {
return this.sqlSessionProxy.insert(statement);
}
/**
* {@inheritDoc}
*/
public int insert(String statement, Object parameter) {
return this.sqlSessionProxy.insert(statement, parameter);
}
/**
* {@inheritDoc}
*/
public int update(String statement) {
return this.sqlSessionProxy.update(statement);
}
/**
* {@inheritDoc}
*/
public int update(String statement, Object parameter) {
return this.sqlSessionProxy.update(statement, parameter);
}
/**
* {@inheritDoc}
*/
public int delete(String statement) {
return this.sqlSessionProxy.delete(statement);
}
/**
* {@inheritDoc}
*/
public int delete(String statement, Object parameter) {
return this.sqlSessionProxy.delete(statement, parameter);
}
/**
* {@inheritDoc}
*/
public <T> T getMapper(Class<T> type) {
return getConfiguration().getMapper(type, this);
}
/**
* {@inheritDoc}
*/
public void commit() {
throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void commit(boolean force) {
throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void rollback() {
throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void rollback(boolean force) {
throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void close() {
throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void clearCache() {
this.sqlSessionProxy.clearCache();
}
/**
* {@inheritDoc}
*
*/
public Configuration getConfiguration() {
return this.sqlSessionFactory.getConfiguration();
}
/**
* {@inheritDoc}
*/
public Connection getConnection() {
return this.sqlSessionProxy.getConnection();
}
/**
* {@inheritDoc}
*
* @since 1.0.2
*
*/
public List<BatchResult> flushStatements() {
return this.sqlSessionProxy.flushStatements();
}
/**
* Proxy needed to route MyBatis method calls to the proper SqlSession got
* from Spring's Transaction Manager
* It also unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to
* pass a {@code PersistenceException} to the {@code PersistenceExceptionTranslator}.
*/
private class SqlSessionInterceptor implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- final SqlSession sqlSession = getSqlSession(
+ SqlSession sqlSession = getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
// force commit even on non-dirty sessions because some databases require
// a commit/rollback before calling close()
sqlSession.commit(true);
}
return result;
} catch (Throwable t) {
Throwable unwrapped = unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
+ // release the connection to avoid a deadlock if the translator is no loaded. See issue #22
+ closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
+ sqlSession = null;
Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
if (translated != null) {
unwrapped = translated;
}
}
throw unwrapped;
} finally {
- closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
+ if (sqlSession != null) {
+ closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
+ }
}
}
}
}
| false | true | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final SqlSession sqlSession = getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
// force commit even on non-dirty sessions because some databases require
// a commit/rollback before calling close()
sqlSession.commit(true);
}
return result;
} catch (Throwable t) {
Throwable unwrapped = unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
if (translated != null) {
unwrapped = translated;
}
}
throw unwrapped;
} finally {
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
}
}
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
SqlSession sqlSession = getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
// force commit even on non-dirty sessions because some databases require
// a commit/rollback before calling close()
sqlSession.commit(true);
}
return result;
} catch (Throwable t) {
Throwable unwrapped = unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
// release the connection to avoid a deadlock if the translator is no loaded. See issue #22
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
sqlSession = null;
Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
if (translated != null) {
unwrapped = translated;
}
}
throw unwrapped;
} finally {
if (sqlSession != null) {
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
}
}
}
|
diff --git a/emulator/src/vidhrdw/pengo.java b/emulator/src/vidhrdw/pengo.java
index c563900..21e1e44 100644
--- a/emulator/src/vidhrdw/pengo.java
+++ b/emulator/src/vidhrdw/pengo.java
@@ -1,294 +1,294 @@
/*
* ported to v0.36
* using automatic conversion tool v0.04 + manual conversion
* converted at : 29-05-2013 18:29:30
*
* THIS FILE IS 100% PORTED!!!
*
*/
package vidhrdw;
import static arcadeflex.libc_old.*;
import static arcadeflex.libc.*;
import static mame.driverH.*;
import static vidhrdw.generic.*;
import static mame.osdependH.*;
import static mame.mame.*;
import static mame.drawgfxH.*;
import static mame.drawgfx.*;
public class pengo
{
public static int gfx_bank;
public static int flipscreen;
public static int xoffsethack;
static int TOTAL_COLORS(int gfxn)
{
return Machine.gfx[gfxn].total_colors * Machine.gfx[gfxn].color_granularity;
}
static rectangle spritevisiblearea = new rectangle
(
2*8, 34*8-1,
0*8, 28*8-1
);
public static VhConvertColorPromPtr pacman_vh_convert_color_prom = new VhConvertColorPromPtr() { public void handler(UByte []palette, char []colortable, UBytePtr color_prom)
{
int i;
//#define TOTAL_COLORS(gfxn) (Machine.gfx[gfxn].total_colors * Machine.gfx[gfxn].color_granularity)
//#define COLOR(gfxn,offs) (colortable[Machine.drv.gfxdecodeinfo[gfxn].color_codes_start + offs])
//UBytePtr palette= new UBytePtr(palette_table);
int p_inc=0;
for (i = 0;i < Machine.drv.total_colors;i++)
{
int bit0,bit1,bit2;
/* red component */
bit0 = (color_prom.read() >> 0) & 0x01;
bit1 = (color_prom.read() >> 1) & 0x01;
bit2 = (color_prom.read() >> 2) & 0x01;
palette[p_inc++].set((char)(0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2));
/* green component */
bit0 = (color_prom.read() >> 3) & 0x01;
bit1 = (color_prom.read() >> 4) & 0x01;
bit2 = (color_prom.read() >> 5) & 0x01;
palette[p_inc++].set((char)(0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2));
/* blue component */
bit0 = 0;
bit1 = (color_prom.read() >> 6) & 0x01;
bit2 = (color_prom.read() >> 7) & 0x01;
palette[p_inc++].set((char)(0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2));
color_prom.inc();
}
color_prom.inc(0x10);//color_prom += 0x10;
/* color_prom now points to the beginning of the lookup table */
/* character lookup table */
/* sprites use the same color lookup table as characters */
for (i = 0;i < TOTAL_COLORS(0);i++)
colortable[Machine.drv.gfxdecodeinfo[0].color_codes_start + i]=(char)(color_prom.readinc() & 0x0f);
}};
public static VhConvertColorPromPtr pengo_vh_convert_color_prom = new VhConvertColorPromPtr() { public void handler(UByte []palette, char []colortable, UBytePtr color_prom)
{
int i;
//#define TOTAL_COLORS(gfxn) (Machine.gfx[gfxn].total_colors * Machine.gfx[gfxn].color_granularity)
//#define COLOR(gfxn,offs) (colortable[Machine.drv.gfxdecodeinfo[gfxn].color_codes_start + offs])
int p_inc=0;
for (i = 0;i < Machine.drv.total_colors;i++)
{
int bit0,bit1,bit2;
/* red component */
bit0 = (color_prom.read() >> 0) & 0x01;
bit1 = (color_prom.read() >> 1) & 0x01;
bit2 = (color_prom.read() >> 2) & 0x01;
palette[p_inc++].set((char)(0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2));
/* green component */
bit0 = (color_prom.read() >> 3) & 0x01;
bit1 = (color_prom.read() >> 4) & 0x01;
bit2 = (color_prom.read() >> 5) & 0x01;
palette[p_inc++].set((char)(0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2));
/* blue component */
bit0 = 0;
bit1 = (color_prom.read() >> 6) & 0x01;
bit2 = (color_prom.read() >> 7) & 0x01;
palette[p_inc++].set((char)(0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2));
color_prom.inc();
}
/* color_prom now points to the beginning of the lookup table */
/* character lookup table */
/* sprites use the same color lookup table as characters */
for (i = 0;i < TOTAL_COLORS(0);i++)
colortable[Machine.drv.gfxdecodeinfo[0].color_codes_start + i]=(char)(color_prom.readinc() & 0x0f);
color_prom.inc(0x80); //color_prom += 0x80;
/* second bank character lookup table */
/* sprites use the same color lookup table as characters */
for (i = 0;i < TOTAL_COLORS(2);i++)
{
if (color_prom.read()!=0)
{
colortable[Machine.drv.gfxdecodeinfo[2].color_codes_start + i]=(char)((color_prom.read() & 0x0f) +0x10);/* second palette bank */
}
else
{
colortable[Machine.drv.gfxdecodeinfo[2].color_codes_start + i]=0;/* preserve transparency */
}
color_prom.inc();
}
}};
/***************************************************************************
Start the video hardware emulation.
***************************************************************************/
public static VhStartPtr pengo_vh_start = new VhStartPtr() { public int handler()
{
gfx_bank = 0;
xoffsethack = 0;
return generic_vh_start.handler();
} };
public static VhStartPtr pacman_vh_start = new VhStartPtr() { public int handler()
{
gfx_bank = 0;
/* In the Pac Man based games (NOT Pengo) the first two sprites must be offset */
/* one pixel to the left to get a more correct placement */
xoffsethack = 1;
return generic_vh_start.handler();
} };
public static WriteHandlerPtr pengo_gfxbank_w = new WriteHandlerPtr() { public void handler(int offset, int data)
{
/* the Pengo hardware can set independently the palette bank, color lookup */
/* table, and chars/sprites. However the game always set them together (and */
/* the only place where this is used is the intro screen) so I don't bother */
/* emulating the whole thing. */
if (gfx_bank != (data & 1))
{
gfx_bank = data & 1;
memset(dirtybuffer,1,videoram_size[0]);
}
} };
public static WriteHandlerPtr pengo_flipscreen_w = new WriteHandlerPtr() { public void handler(int offset, int data)
{
if (flipscreen != (data & 1))
{
flipscreen = data & 1;
memset(dirtybuffer,1,videoram_size[0]);
}
} };
/***************************************************************************
Draw the game screen in the given osd_bitmap.
Do NOT call osd_update_display() from this function, it will be called by
the main emulation engine.
***************************************************************************/
public static VhUpdatePtr pengo_vh_screenrefresh = new VhUpdatePtr() { public void handler(osd_bitmap bitmap,int full_refresh)
{
int offs;
for (offs = videoram_size[0] - 1; offs > 0; offs--)
{
if (dirtybuffer[offs]!=0)
{
int mx,my,sx,sy;
dirtybuffer[offs] = 0;
mx = offs % 32;
my = offs / 32;
if (my < 2)
{
if (mx < 2 || mx >= 30) continue; /* not visible */
sx = my + 34;
sy = mx - 2;
}
else if (my >= 30)
{
if (mx < 2 || mx >= 30) continue; /* not visible */
sx = my - 30;
sy = mx - 2;
}
else
{
sx = mx + 2;
sy = my - 2;
}
if (flipscreen != 0)
{
sx = 35 - sx;
sy = 27 - sy;
}
drawgfx(tmpbitmap,Machine.gfx[gfx_bank*2],
videoram.read(offs),
- colorram.read(offs) & 0x1f,
+ (int)(colorram.read(offs) & 0x1f),
flipscreen,flipscreen,
sx*8,sy*8,
Machine.drv.visible_area,TRANSPARENCY_NONE,0);
}
}
copybitmap(bitmap,tmpbitmap,0,0,0,0,Machine.drv.visible_area,TRANSPARENCY_NONE,0);
/* Draw the sprites. Note that it is important to draw them exactly in this */
/* order, to have the correct priorities. */
for (offs = spriteram_size[0] - 2;offs > 2*2;offs -= 2)
{
int sx,sy;
sx = 272 - spriteram_2.read(offs + 1);
sy = spriteram_2.read(offs) - 31;
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 1,spriteram.read(offs) & 2,
sx,sy,
spritevisiblearea,TRANSPARENCY_COLOR,0);
/* also plot the sprite with wraparound (tunnel in Crush Roller) */
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 1,spriteram.read(offs) & 2,
sx - 256,sy,
spritevisiblearea,TRANSPARENCY_COLOR,0);
}
/* In the Pac Man based games (NOT Pengo) the first two sprites must be offset */
/* one pixel to the left to get a more correct placement */
for (offs = 2*2;offs >= 0;offs -= 2)
{
int sx,sy;
sx = 272 - spriteram_2.read(offs + 1);
sy = spriteram_2.read(offs) - 31;
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 1,spriteram.read(offs) & 2,
sx,sy + xoffsethack,
spritevisiblearea,TRANSPARENCY_COLOR,0);
/* also plot the sprite with wraparound (tunnel in Crush Roller) */
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 2,spriteram.read(offs) & 1,
sx - 256,sy + xoffsethack,
spritevisiblearea,TRANSPARENCY_COLOR,0);
}
}};
}
| true | true | public static VhUpdatePtr pengo_vh_screenrefresh = new VhUpdatePtr() { public void handler(osd_bitmap bitmap,int full_refresh)
{
int offs;
for (offs = videoram_size[0] - 1; offs > 0; offs--)
{
if (dirtybuffer[offs]!=0)
{
int mx,my,sx,sy;
dirtybuffer[offs] = 0;
mx = offs % 32;
my = offs / 32;
if (my < 2)
{
if (mx < 2 || mx >= 30) continue; /* not visible */
sx = my + 34;
sy = mx - 2;
}
else if (my >= 30)
{
if (mx < 2 || mx >= 30) continue; /* not visible */
sx = my - 30;
sy = mx - 2;
}
else
{
sx = mx + 2;
sy = my - 2;
}
if (flipscreen != 0)
{
sx = 35 - sx;
sy = 27 - sy;
}
drawgfx(tmpbitmap,Machine.gfx[gfx_bank*2],
videoram.read(offs),
colorram.read(offs) & 0x1f,
flipscreen,flipscreen,
sx*8,sy*8,
Machine.drv.visible_area,TRANSPARENCY_NONE,0);
}
}
copybitmap(bitmap,tmpbitmap,0,0,0,0,Machine.drv.visible_area,TRANSPARENCY_NONE,0);
/* Draw the sprites. Note that it is important to draw them exactly in this */
/* order, to have the correct priorities. */
for (offs = spriteram_size[0] - 2;offs > 2*2;offs -= 2)
{
int sx,sy;
sx = 272 - spriteram_2.read(offs + 1);
sy = spriteram_2.read(offs) - 31;
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 1,spriteram.read(offs) & 2,
sx,sy,
spritevisiblearea,TRANSPARENCY_COLOR,0);
/* also plot the sprite with wraparound (tunnel in Crush Roller) */
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 1,spriteram.read(offs) & 2,
sx - 256,sy,
spritevisiblearea,TRANSPARENCY_COLOR,0);
}
/* In the Pac Man based games (NOT Pengo) the first two sprites must be offset */
/* one pixel to the left to get a more correct placement */
for (offs = 2*2;offs >= 0;offs -= 2)
{
int sx,sy;
sx = 272 - spriteram_2.read(offs + 1);
sy = spriteram_2.read(offs) - 31;
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 1,spriteram.read(offs) & 2,
sx,sy + xoffsethack,
spritevisiblearea,TRANSPARENCY_COLOR,0);
/* also plot the sprite with wraparound (tunnel in Crush Roller) */
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 2,spriteram.read(offs) & 1,
sx - 256,sy + xoffsethack,
spritevisiblearea,TRANSPARENCY_COLOR,0);
}
}};
| public static VhUpdatePtr pengo_vh_screenrefresh = new VhUpdatePtr() { public void handler(osd_bitmap bitmap,int full_refresh)
{
int offs;
for (offs = videoram_size[0] - 1; offs > 0; offs--)
{
if (dirtybuffer[offs]!=0)
{
int mx,my,sx,sy;
dirtybuffer[offs] = 0;
mx = offs % 32;
my = offs / 32;
if (my < 2)
{
if (mx < 2 || mx >= 30) continue; /* not visible */
sx = my + 34;
sy = mx - 2;
}
else if (my >= 30)
{
if (mx < 2 || mx >= 30) continue; /* not visible */
sx = my - 30;
sy = mx - 2;
}
else
{
sx = mx + 2;
sy = my - 2;
}
if (flipscreen != 0)
{
sx = 35 - sx;
sy = 27 - sy;
}
drawgfx(tmpbitmap,Machine.gfx[gfx_bank*2],
videoram.read(offs),
(int)(colorram.read(offs) & 0x1f),
flipscreen,flipscreen,
sx*8,sy*8,
Machine.drv.visible_area,TRANSPARENCY_NONE,0);
}
}
copybitmap(bitmap,tmpbitmap,0,0,0,0,Machine.drv.visible_area,TRANSPARENCY_NONE,0);
/* Draw the sprites. Note that it is important to draw them exactly in this */
/* order, to have the correct priorities. */
for (offs = spriteram_size[0] - 2;offs > 2*2;offs -= 2)
{
int sx,sy;
sx = 272 - spriteram_2.read(offs + 1);
sy = spriteram_2.read(offs) - 31;
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 1,spriteram.read(offs) & 2,
sx,sy,
spritevisiblearea,TRANSPARENCY_COLOR,0);
/* also plot the sprite with wraparound (tunnel in Crush Roller) */
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 1,spriteram.read(offs) & 2,
sx - 256,sy,
spritevisiblearea,TRANSPARENCY_COLOR,0);
}
/* In the Pac Man based games (NOT Pengo) the first two sprites must be offset */
/* one pixel to the left to get a more correct placement */
for (offs = 2*2;offs >= 0;offs -= 2)
{
int sx,sy;
sx = 272 - spriteram_2.read(offs + 1);
sy = spriteram_2.read(offs) - 31;
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 1,spriteram.read(offs) & 2,
sx,sy + xoffsethack,
spritevisiblearea,TRANSPARENCY_COLOR,0);
/* also plot the sprite with wraparound (tunnel in Crush Roller) */
drawgfx(bitmap,Machine.gfx[gfx_bank*2+1],
spriteram.read(offs) >> 2,
spriteram.read(offs + 1) & 0x1f,
spriteram.read(offs) & 2,spriteram.read(offs) & 1,
sx - 256,sy + xoffsethack,
spritevisiblearea,TRANSPARENCY_COLOR,0);
}
}};
|
diff --git a/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java b/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java
index a3d6f75e4..4b5379ac1 100644
--- a/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java
+++ b/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java
@@ -1,758 +1,760 @@
/* I2PTunnel is GPL'ed (with the exception mentioned in I2PTunnel.java)
* (c) 2003 - 2004 mihi
*/
package net.i2p.i2ptunnel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import net.i2p.I2PAppContext;
import net.i2p.I2PException;
import net.i2p.client.streaming.I2PSocket;
import net.i2p.client.streaming.I2PSocketOptions;
import net.i2p.data.DataFormatException;
import net.i2p.data.Destination;
import net.i2p.util.EventDispatcher;
import net.i2p.util.FileUtil;
import net.i2p.util.Log;
/**
* Act as a mini HTTP proxy, handling various different types of requests,
* forwarding them through I2P appropriately, and displaying the reply. Supported
* request formats are: <pre>
* $method http://$site[$port]/$path $protocolVersion
* or
* $method $path $protocolVersion\nHost: $site
* or
* $method http://i2p/$site/$path $protocolVersion
* or
* $method /$site/$path $protocolVersion
* </pre>
*
* If the $site resolves with the I2P naming service, then it is directed towards
* that eepsite, otherwise it is directed towards this client's outproxy (typically
* "squid.i2p"). Only HTTP is supported (no HTTPS, ftp, mailto, etc). Both GET
* and POST have been tested, though other $methods should work.
*
*/
public class I2PTunnelHTTPClient extends I2PTunnelClientBase implements Runnable {
private static final Log _log = new Log(I2PTunnelHTTPClient.class);
private List proxyList;
private HashMap addressHelpers = new HashMap();
private final static byte[] ERR_REQUEST_DENIED =
("HTTP/1.1 403 Access Denied\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n"+
"\r\n"+
"<html><body><H1>I2P ERROR: REQUEST DENIED</H1>"+
"You attempted to connect to a non-I2P website or location.<BR>")
.getBytes();
private final static byte[] ERR_DESTINATION_UNKNOWN =
("HTTP/1.1 503 Service Unavailable\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n"+
"\r\n"+
"<html><body><H1>I2P ERROR: DESTINATION NOT FOUND</H1>"+
"That I2P Destination was not found. Perhaps you pasted in the "+
"wrong BASE64 I2P Destination or the link you are following is "+
"bad. The host (or the WWW proxy, if you're using one) could also "+
"be temporarily offline. You may want to <b>retry</b>. "+
"Could not find the following Destination:<BR><BR><div>")
.getBytes();
private final static byte[] ERR_TIMEOUT =
("HTTP/1.1 504 Gateway Timeout\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n\r\n"+
"<html><body><H1>I2P ERROR: TIMEOUT</H1>"+
"That Destination was reachable, but timed out getting a "+
"response. This is likely a temporary error, so you should simply "+
"try to refresh, though if the problem persists, the remote "+
"destination may have issues. Could not get a response from "+
"the following Destination:<BR><BR>")
.getBytes();
private final static byte[] ERR_NO_OUTPROXY =
("HTTP/1.1 503 Service Unavailable\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n"+
"\r\n"+
"<html><body><H1>I2P ERROR: No outproxy found</H1>"+
"Your request was for a site outside of I2P, but you have no "+
"HTTP outproxy configured. Please configure an outproxy in I2PTunnel")
.getBytes();
private final static byte[] ERR_AHELPER_CONFLICT =
("HTTP/1.1 409 Conflict\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n"+
"\r\n"+
"<html><body><H1>I2P ERROR: Destination key conflict</H1>"+
"The addresshelper link you followed specifies a different destination key "+
"than a host entry in your host database. "+
"Someone could be trying to impersonate another eepsite, "+
"or people have given two eepsites identical names.<P/>"+
"You can resolve the conflict by considering which key you trust, "+
"and either discarding the addresshelper link, "+
"discarding the host entry from your host database, "+
"or naming one of them differently.<P/>")
.getBytes();
private final static byte[] ERR_BAD_PROTOCOL =
("HTTP/1.1 403 Bad Protocol\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n"+
"\r\n"+
"<html><body><H1>I2P ERROR: NON-HTTP PROTOCOL</H1>"+
"The request uses a bad protocol. "+
"The I2P HTTP Proxy supports http:// requests ONLY. Other protocols such as https:// and ftp:// are not allowed.<BR>")
.getBytes();
private final static byte[] ERR_LOCALHOST =
("HTTP/1.1 403 Access Denied\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n"+
"\r\n"+
"<html><body><H1>I2P ERROR: REQUEST DENIED</H1>"+
"Your browser is misconfigured. Do not use the proxy to access the router console or other localhost destinations.<BR>")
.getBytes();
private final static int MAX_POSTBYTES = 20*1024*1024; // arbitrary but huge - all in memory, no temp file
private final static byte[] ERR_MAXPOST =
("HTTP/1.1 503 Bad POST\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n"+
"\r\n"+
"<html><body><H1>I2P ERROR: REQUEST DENIED</H1>"+
"The maximum POST size is " + MAX_POSTBYTES + " bytes.<BR>")
.getBytes();
/** used to assign unique IDs to the threads / clients. no logic or functionality */
private static volatile long __clientId = 0;
/**
* @throws IllegalArgumentException if the I2PTunnel does not contain
* valid config to contact the router
*/
public I2PTunnelHTTPClient(int localPort, Logging l, boolean ownDest,
String wwwProxy, EventDispatcher notifyThis,
I2PTunnel tunnel) throws IllegalArgumentException {
super(localPort, ownDest, l, notifyThis, "HTTPHandler " + (++__clientId), tunnel);
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openHTTPClientResult", "error");
return;
}
proxyList = new ArrayList();
if (wwwProxy != null) {
StringTokenizer tok = new StringTokenizer(wwwProxy, ",");
while (tok.hasMoreTokens())
proxyList.add(tok.nextToken().trim());
}
setName(getLocalPort() + " -> HTTPClient [WWW outproxy list: " + wwwProxy + "]");
startRunning();
notifyEvent("openHTTPClientResult", "ok");
}
private String getPrefix(long requestId) { return "Client[" + _clientId + "/" + requestId + "]: "; }
private String selectProxy() {
synchronized (proxyList) {
int size = proxyList.size();
if (size <= 0) {
if (_log.shouldLog(Log.INFO))
_log.info("Proxy list is empty - no outproxy available");
l.log("Proxy list is emtpy - no outproxy available");
return null;
}
int index = I2PAppContext.getGlobalContext().random().nextInt(size);
String proxy = (String)proxyList.get(index);
return proxy;
}
}
private static final int DEFAULT_READ_TIMEOUT = 60*1000;
/**
* create the default options (using the default timeout, etc)
*
*/
protected I2PSocketOptions getDefaultOptions() {
Properties defaultOpts = getTunnel().getClientOptions();
if (!defaultOpts.contains(I2PSocketOptions.PROP_READ_TIMEOUT))
defaultOpts.setProperty(I2PSocketOptions.PROP_READ_TIMEOUT, ""+DEFAULT_READ_TIMEOUT);
//if (!defaultOpts.contains("i2p.streaming.inactivityTimeout"))
// defaultOpts.setProperty("i2p.streaming.inactivityTimeout", ""+DEFAULT_READ_TIMEOUT);
I2PSocketOptions opts = sockMgr.buildOptions(defaultOpts);
if (!defaultOpts.containsKey(I2PSocketOptions.PROP_CONNECT_TIMEOUT))
opts.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
return opts;
}
/**
* create the default options (using the default timeout, etc)
*
*/
protected I2PSocketOptions getDefaultOptions(Properties overrides) {
Properties defaultOpts = getTunnel().getClientOptions();
defaultOpts.putAll(overrides);
if (!defaultOpts.contains(I2PSocketOptions.PROP_READ_TIMEOUT))
defaultOpts.setProperty(I2PSocketOptions.PROP_READ_TIMEOUT, ""+DEFAULT_READ_TIMEOUT);
if (!defaultOpts.contains("i2p.streaming.inactivityTimeout"))
defaultOpts.setProperty("i2p.streaming.inactivityTimeout", ""+DEFAULT_READ_TIMEOUT);
I2PSocketOptions opts = sockMgr.buildOptions(defaultOpts);
if (!defaultOpts.containsKey(I2PSocketOptions.PROP_CONNECT_TIMEOUT))
opts.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
return opts;
}
private static final boolean DEFAULT_GZIP = true;
// all default to false
public static final String PROP_REFERER = "i2ptunnel.httpclient.sendReferer";
public static final String PROP_USER_AGENT = "i2ptunnel.httpclient.sendUserAgent";
public static final String PROP_VIA = "i2ptunnel.httpclient.sendVia";
private static long __requestId = 0;
protected void clientConnectionRun(Socket s) {
OutputStream out = null;
String targetRequest = null;
boolean usingWWWProxy = false;
String currentProxy = null;
long requestId = ++__requestId;
try {
out = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream(), "ISO-8859-1"));
String line, method = null, protocol = null, host = null, destination = null;
StringBuffer newRequest = new StringBuffer();
int ahelper = 0;
while ((line = br.readLine()) != null) {
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Line=[" + line + "]");
String lowercaseLine = line.toLowerCase();
if (lowercaseLine.startsWith("connection: ") ||
lowercaseLine.startsWith("keep-alive: ") ||
lowercaseLine.startsWith("proxy-connection: "))
continue;
if (method == null) { // first line (GET /base64/realaddr)
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Method is null for [" + line + "]");
line = line.trim();
int pos = line.indexOf(" ");
if (pos == -1) break;
method = line.substring(0, pos);
String request = line.substring(pos + 1);
if (request.startsWith("/") && getTunnel().getClientOptions().getProperty("i2ptunnel.noproxy") != null) {
request = "http://i2p" + request;
} else if (request.startsWith("/eepproxy/")) {
// /eepproxy/foo.i2p/bar/baz.html HTTP/1.0
String subRequest = request.substring("/eepproxy/".length());
int protopos = subRequest.indexOf(" ");
String uri = subRequest.substring(0, protopos);
if (uri.indexOf("/") == -1) {
uri = uri + "/";
}
// "http://" + "foo.i2p/bar/baz.html" + " HTTP/1.0"
request = "http://" + uri + subRequest.substring(protopos);
}
pos = request.indexOf("//");
if (pos == -1) {
method = null;
break;
}
protocol = request.substring(0, pos + 2);
request = request.substring(pos + 2);
targetRequest = request;
pos = request.indexOf("/");
if (pos == -1) {
method = null;
break;
}
host = request.substring(0, pos);
// Quick hack for foo.bar.i2p
if (host.toLowerCase().endsWith(".i2p")) {
// Destination gets the host name
destination = host;
// Host becomes the destination key
host = getHostName(destination);
int pos2;
if ((pos2 = request.indexOf("?")) != -1) {
// Try to find an address helper in the fragments
// and split the request into it's component parts for rebuilding later
String ahelperKey = null;
boolean ahelperConflict = false;
String fragments = request.substring(pos2 + 1);
String uriPath = request.substring(0, pos2);
pos2 = fragments.indexOf(" ");
String protocolVersion = fragments.substring(pos2 + 1);
String urlEncoding = "";
fragments = fragments.substring(0, pos2);
String initialFragments = fragments;
fragments = fragments + "&";
String fragment;
while(fragments.length() > 0) {
pos2 = fragments.indexOf("&");
fragment = fragments.substring(0, pos2);
fragments = fragments.substring(pos2 + 1);
// Fragment looks like addresshelper key
if (fragment.startsWith("i2paddresshelper=")) {
pos2 = fragment.indexOf("=");
ahelperKey = fragment.substring(pos2 + 1);
// Key contains data, lets not ignore it
if (ahelperKey != null) {
// Host resolvable only with addresshelper
if ( (host == null) || ("i2p".equals(host)) )
{
// Cannot check, use addresshelper key
addressHelpers.put(destination,ahelperKey);
} else {
// Host resolvable from database, verify addresshelper key
// Silently bypass correct keys, otherwise alert
if (!host.equals(ahelperKey))
{
// Conflict: handle when URL reconstruction done
ahelperConflict = true;
if (_log.shouldLog(Log.WARN))
_log.warn(getPrefix(requestId) + "Addresshelper key conflict for site [" + destination + "], trusted key [" + host + "], specified key [" + ahelperKey + "].");
}
}
}
} else {
// Other fragments, just pass along
// Append each fragment to urlEncoding
if ("".equals(urlEncoding)) {
urlEncoding = "?" + fragment;
} else {
urlEncoding = urlEncoding + "&" + fragment;
}
}
}
// Reconstruct the request minus the i2paddresshelper GET var
request = uriPath + urlEncoding + " " + protocolVersion;
// Did addresshelper key conflict?
if (ahelperConflict)
{
String str;
byte[] header;
str = FileUtil.readTextFile("docs/ahelper-conflict-header.ht", 100, true);
if (str != null) header = str.getBytes();
else header = ERR_AHELPER_CONFLICT;
if (out != null) {
long alias = I2PAppContext.getGlobalContext().random().nextLong();
String trustedURL = protocol + uriPath + urlEncoding;
String conflictURL = protocol + alias + ".i2p/?" + initialFragments;
out.write(header);
out.write(("To visit the destination in your host database, click <a href=\"" + trustedURL + "\">here</a>. To visit the conflicting addresshelper link by temporarily giving it a random alias, click <a href=\"" + conflictURL + "\">here</a>.<P/>").getBytes());
out.write("</div><p><i>I2P HTTP Proxy Server<br>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
}
String addressHelper = (String) addressHelpers.get(destination);
if (addressHelper != null) {
destination = addressHelper;
host = getHostName(destination);
ahelper = 1;
}
line = method + " " + request.substring(pos);
} else if (host.indexOf(".") != -1) {
// The request must be forwarded to a WWW proxy
if (_log.shouldLog(Log.DEBUG))
_log.debug("Before selecting outproxy for " + host);
currentProxy = selectProxy();
if (_log.shouldLog(Log.DEBUG))
_log.debug("After selecting outproxy for " + host + ": " + currentProxy);
if (currentProxy == null) {
if (_log.shouldLog(Log.WARN))
_log.warn(getPrefix(requestId) + "Host wants to be outproxied, but we dont have any!");
l.log("No HTTP outproxy found for the request.");
if (out != null) {
out.write(ERR_NO_OUTPROXY);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
destination = currentProxy;
usingWWWProxy = true;
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Host doesnt end with .i2p and it contains a period [" + host + "]: wwwProxy!");
} else if (host.toLowerCase().startsWith("localhost:")) {
if (out != null) {
out.write(ERR_LOCALHOST);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
} else {
request = request.substring(pos + 1);
pos = request.indexOf("/");
if (pos < 0) {
l.log("Invalid request url [" + request + "]");
if (out != null) {
out.write(ERR_REQUEST_DENIED);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
destination = request.substring(0, pos);
line = method + " " + request.substring(pos);
}
boolean isValid = usingWWWProxy || isSupportedAddress(host, protocol);
if (!isValid) {
if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "notValid(" + host + ")");
method = null;
destination = null;
break;
} else if (!usingWWWProxy) {
if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "host=getHostName(" + destination + ")");
host = getHostName(destination); // hide original host
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug(getPrefix(requestId) + "METHOD:" + method + ":");
_log.debug(getPrefix(requestId) + "PROTOC:" + protocol + ":");
_log.debug(getPrefix(requestId) + "HOST :" + host + ":");
_log.debug(getPrefix(requestId) + "DEST :" + destination + ":");
}
} else {
if (lowercaseLine.startsWith("host: ") && !usingWWWProxy) {
line = "Host: " + host;
if (_log.shouldLog(Log.INFO))
_log.info(getPrefix(requestId) + "Setting host = " + host);
} else if (lowercaseLine.startsWith("user-agent: ") &&
!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue()) {
line = null;
continue;
} else if (lowercaseLine.startsWith("accept")) {
// strip the accept-blah headers, as they vary dramatically from
// browser to browser
line = null;
continue;
} else if (lowercaseLine.startsWith("referer: ") &&
!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_REFERER)).booleanValue()) {
// Shouldn't we be more specific, like accepting in-site referers ?
//line = "Referer: i2p";
line = null;
continue; // completely strip the line
} else if (lowercaseLine.startsWith("via: ") &&
!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_VIA)).booleanValue()) {
//line = "Via: i2p";
line = null;
continue; // completely strip the line
} else if (lowercaseLine.startsWith("from: ")) {
//line = "From: i2p";
line = null;
continue; // completely strip the line
}
}
if (line.length() == 0) {
String ok = getTunnel().getClientOptions().getProperty("i2ptunnel.gzip");
boolean gzip = DEFAULT_GZIP;
if (ok != null)
gzip = Boolean.valueOf(ok).booleanValue();
if (gzip) {
// according to rfc2616 s14.3, this *should* force identity, even if
// an explicit q=0 for gzip doesn't. tested against orion.i2p, and it
// seems to work.
newRequest.append("Accept-Encoding: \r\n");
newRequest.append("X-Accept-Encoding: x-i2p-gzip;q=1.0, identity;q=0.5, deflate;q=0, gzip;q=0, *;q=0\r\n");
}
if (!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue())
newRequest.append("User-Agent: MYOB/6.66 (AN/ON)\r\n");
newRequest.append("Connection: close\r\n\r\n");
break;
} else {
newRequest.append(line.trim()).append("\r\n"); // HTTP spec
}
}
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "NewRequest header: [" + newRequest.toString() + "]");
int postbytes = 0;
while (br.ready()) { // empty the buffer (POST requests)
int i = br.read();
if (i != -1) {
newRequest.append((char) i);
if (++postbytes > MAX_POSTBYTES) {
if (out != null) {
out.write(ERR_MAXPOST);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
}
}
if (method == null || destination == null) {
l.log("No HTTP method found in the request.");
if (out != null) {
if ("http://".equalsIgnoreCase(protocol))
out.write(ERR_REQUEST_DENIED);
else
out.write(ERR_BAD_PROTOCOL);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Destination: " + destination);
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
- l.log("Could not resolve " + destination + ".");
+ //l.log("Could not resolve " + destination + ".");
if (_log.shouldLog(Log.WARN))
_log.warn("Unable to resolve " + destination + " (proxy? " + usingWWWProxy + ", request: " + targetRequest);
String str;
byte[] header;
boolean showAddrHelper = false;
if (usingWWWProxy)
str = FileUtil.readTextFile("docs/dnfp-header.ht", 100, true);
else if(ahelper != 0)
str = FileUtil.readTextFile("docs/dnfb-header.ht", 100, true);
+ else if (destination.length() == 60 && destination.endsWith(".b32.i2p"))
+ str = FileUtil.readTextFile("docs/dnf-header.ht", 100, true);
else {
str = FileUtil.readTextFile("docs/dnfh-header.ht", 100, true);
showAddrHelper = true;
}
if (str != null)
header = str.getBytes();
else
header = ERR_DESTINATION_UNKNOWN;
writeErrorMessage(header, out, targetRequest, usingWWWProxy, destination, showAddrHelper);
s.close();
return;
}
String remoteID;
Properties opts = new Properties();
//opts.setProperty("i2p.streaming.inactivityTimeout", ""+120*1000);
// 1 == disconnect. see ConnectionOptions in the new streaming lib, which i
// dont want to hard link to here
//opts.setProperty("i2p.streaming.inactivityTimeoutAction", ""+1);
I2PSocket i2ps = createI2PSocket(dest, getDefaultOptions(opts));
byte[] data = newRequest.toString().getBytes("ISO-8859-1");
Runnable onTimeout = new OnTimeout(s, s.getOutputStream(), targetRequest, usingWWWProxy, currentProxy, requestId);
I2PTunnelRunner runner = new I2PTunnelHTTPClientRunner(s, i2ps, sockLock, data, mySockets, onTimeout);
} catch (SocketException ex) {
_log.info(getPrefix(requestId) + "Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
} catch (IOException ex) {
_log.info(getPrefix(requestId) + "Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
} catch (I2PException ex) {
_log.info("getPrefix(requestId) + Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
} catch (OutOfMemoryError oom) { // mainly for huge POSTs
IOException ex = new IOException("OOM (in POST?)");
_log.info("getPrefix(requestId) + Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
}
}
private final static String getHostName(String host) {
if (host == null) return null;
try {
Destination dest = I2PTunnel.destFromName(host);
if (dest == null) return "i2p";
return dest.toBase64();
} catch (DataFormatException dfe) {
return "i2p";
}
}
private class OnTimeout implements Runnable {
private Socket _socket;
private OutputStream _out;
private String _target;
private boolean _usingProxy;
private String _wwwProxy;
private long _requestId;
public OnTimeout(Socket s, OutputStream out, String target, boolean usingProxy, String wwwProxy, long id) {
_socket = s;
_out = out;
_target = target;
_usingProxy = usingProxy;
_wwwProxy = wwwProxy;
_requestId = id;
}
public void run() {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Timeout occured requesting " + _target);
handleHTTPClientException(new RuntimeException("Timeout"), _out,
_target, _usingProxy, _wwwProxy, _requestId);
closeSocket(_socket);
}
}
private static String jumpServers[] = {
"http://i2host.i2p/cgi-bin/i2hostjump?",
// "http://orion.i2p/jump/",
"http://stats.i2p/cgi-bin/jump.cgi?a=",
// "http://trevorreznik.i2p/cgi-bin/jump.php?hostname=",
"http://i2jump.i2p/"
};
private static void writeErrorMessage(byte[] errMessage, OutputStream out, String targetRequest,
boolean usingWWWProxy, String wwwProxy, boolean showAddrHelper) throws IOException {
if (out != null) {
out.write(errMessage);
if (targetRequest != null) {
int protopos = targetRequest.indexOf(" ");
String uri = null;
if (protopos >= 0)
uri = targetRequest.substring(0, protopos);
else
uri = targetRequest;
out.write("<a href=\"http://".getBytes());
out.write(uri.getBytes());
out.write("\">http://".getBytes());
out.write(uri.getBytes());
out.write("</a>".getBytes());
if (usingWWWProxy) out.write(("<br>WWW proxy: " + wwwProxy).getBytes());
if (showAddrHelper) {
out.write("<br><br>Click a link below to look for an address helper by using a \"jump\" service:<br>".getBytes());
for (int i = 0; i < jumpServers.length; i++) {
// Skip jump servers we don't know
String jumphost = jumpServers[i].substring(7); // "http://"
jumphost = jumphost.substring(0, jumphost.indexOf('/'));
try {
Destination dest = I2PTunnel.destFromName(jumphost);
if (dest == null) continue;
} catch (DataFormatException dfe) {
continue;
}
out.write("<br><a href=\"".getBytes());
out.write(jumpServers[i].getBytes());
out.write(uri.getBytes());
out.write("\">".getBytes());
out.write(jumpServers[i].getBytes());
out.write(uri.getBytes());
out.write("</a>".getBytes());
}
}
}
out.write("</div><p><i>I2P HTTP Proxy Server<br>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
}
private void handleHTTPClientException(Exception ex, OutputStream out, String targetRequest,
boolean usingWWWProxy, String wwwProxy, long requestId) {
if (_log.shouldLog(Log.WARN))
_log.warn(getPrefix(requestId) + "Error sending to " + wwwProxy + " (proxy? " + usingWWWProxy + ", request: " + targetRequest, ex);
if (out != null) {
try {
String str;
byte[] header;
if (usingWWWProxy)
str = FileUtil.readTextFile("docs/dnfp-header.ht", 100, true);
else
str = FileUtil.readTextFile("docs/dnf-header.ht", 100, true);
if (str != null)
header = str.getBytes();
else
header = ERR_DESTINATION_UNKNOWN;
writeErrorMessage(header, out, targetRequest, usingWWWProxy, wwwProxy, false);
} catch (IOException ioe) {
_log.warn(getPrefix(requestId) + "Error writing out the 'destination was unknown' " + "message", ioe);
}
} else {
_log.warn(getPrefix(requestId) + "Client disconnected before we could say that destination " + "was unknown", ex);
}
}
private final static String SUPPORTED_HOSTS[] = { "i2p", "www.i2p.com", "i2p."};
private boolean isSupportedAddress(String host, String protocol) {
if ((host == null) || (protocol == null)) return false;
boolean found = false;
String lcHost = host.toLowerCase();
for (int i = 0; i < SUPPORTED_HOSTS.length; i++) {
if (SUPPORTED_HOSTS[i].equals(lcHost)) {
found = true;
break;
}
}
if (!found) {
try {
Destination d = I2PTunnel.destFromName(host);
if (d == null) return false;
} catch (DataFormatException dfe) {
}
}
return protocol.equalsIgnoreCase("http://");
}
}
| false | true | protected void clientConnectionRun(Socket s) {
OutputStream out = null;
String targetRequest = null;
boolean usingWWWProxy = false;
String currentProxy = null;
long requestId = ++__requestId;
try {
out = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream(), "ISO-8859-1"));
String line, method = null, protocol = null, host = null, destination = null;
StringBuffer newRequest = new StringBuffer();
int ahelper = 0;
while ((line = br.readLine()) != null) {
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Line=[" + line + "]");
String lowercaseLine = line.toLowerCase();
if (lowercaseLine.startsWith("connection: ") ||
lowercaseLine.startsWith("keep-alive: ") ||
lowercaseLine.startsWith("proxy-connection: "))
continue;
if (method == null) { // first line (GET /base64/realaddr)
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Method is null for [" + line + "]");
line = line.trim();
int pos = line.indexOf(" ");
if (pos == -1) break;
method = line.substring(0, pos);
String request = line.substring(pos + 1);
if (request.startsWith("/") && getTunnel().getClientOptions().getProperty("i2ptunnel.noproxy") != null) {
request = "http://i2p" + request;
} else if (request.startsWith("/eepproxy/")) {
// /eepproxy/foo.i2p/bar/baz.html HTTP/1.0
String subRequest = request.substring("/eepproxy/".length());
int protopos = subRequest.indexOf(" ");
String uri = subRequest.substring(0, protopos);
if (uri.indexOf("/") == -1) {
uri = uri + "/";
}
// "http://" + "foo.i2p/bar/baz.html" + " HTTP/1.0"
request = "http://" + uri + subRequest.substring(protopos);
}
pos = request.indexOf("//");
if (pos == -1) {
method = null;
break;
}
protocol = request.substring(0, pos + 2);
request = request.substring(pos + 2);
targetRequest = request;
pos = request.indexOf("/");
if (pos == -1) {
method = null;
break;
}
host = request.substring(0, pos);
// Quick hack for foo.bar.i2p
if (host.toLowerCase().endsWith(".i2p")) {
// Destination gets the host name
destination = host;
// Host becomes the destination key
host = getHostName(destination);
int pos2;
if ((pos2 = request.indexOf("?")) != -1) {
// Try to find an address helper in the fragments
// and split the request into it's component parts for rebuilding later
String ahelperKey = null;
boolean ahelperConflict = false;
String fragments = request.substring(pos2 + 1);
String uriPath = request.substring(0, pos2);
pos2 = fragments.indexOf(" ");
String protocolVersion = fragments.substring(pos2 + 1);
String urlEncoding = "";
fragments = fragments.substring(0, pos2);
String initialFragments = fragments;
fragments = fragments + "&";
String fragment;
while(fragments.length() > 0) {
pos2 = fragments.indexOf("&");
fragment = fragments.substring(0, pos2);
fragments = fragments.substring(pos2 + 1);
// Fragment looks like addresshelper key
if (fragment.startsWith("i2paddresshelper=")) {
pos2 = fragment.indexOf("=");
ahelperKey = fragment.substring(pos2 + 1);
// Key contains data, lets not ignore it
if (ahelperKey != null) {
// Host resolvable only with addresshelper
if ( (host == null) || ("i2p".equals(host)) )
{
// Cannot check, use addresshelper key
addressHelpers.put(destination,ahelperKey);
} else {
// Host resolvable from database, verify addresshelper key
// Silently bypass correct keys, otherwise alert
if (!host.equals(ahelperKey))
{
// Conflict: handle when URL reconstruction done
ahelperConflict = true;
if (_log.shouldLog(Log.WARN))
_log.warn(getPrefix(requestId) + "Addresshelper key conflict for site [" + destination + "], trusted key [" + host + "], specified key [" + ahelperKey + "].");
}
}
}
} else {
// Other fragments, just pass along
// Append each fragment to urlEncoding
if ("".equals(urlEncoding)) {
urlEncoding = "?" + fragment;
} else {
urlEncoding = urlEncoding + "&" + fragment;
}
}
}
// Reconstruct the request minus the i2paddresshelper GET var
request = uriPath + urlEncoding + " " + protocolVersion;
// Did addresshelper key conflict?
if (ahelperConflict)
{
String str;
byte[] header;
str = FileUtil.readTextFile("docs/ahelper-conflict-header.ht", 100, true);
if (str != null) header = str.getBytes();
else header = ERR_AHELPER_CONFLICT;
if (out != null) {
long alias = I2PAppContext.getGlobalContext().random().nextLong();
String trustedURL = protocol + uriPath + urlEncoding;
String conflictURL = protocol + alias + ".i2p/?" + initialFragments;
out.write(header);
out.write(("To visit the destination in your host database, click <a href=\"" + trustedURL + "\">here</a>. To visit the conflicting addresshelper link by temporarily giving it a random alias, click <a href=\"" + conflictURL + "\">here</a>.<P/>").getBytes());
out.write("</div><p><i>I2P HTTP Proxy Server<br>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
}
String addressHelper = (String) addressHelpers.get(destination);
if (addressHelper != null) {
destination = addressHelper;
host = getHostName(destination);
ahelper = 1;
}
line = method + " " + request.substring(pos);
} else if (host.indexOf(".") != -1) {
// The request must be forwarded to a WWW proxy
if (_log.shouldLog(Log.DEBUG))
_log.debug("Before selecting outproxy for " + host);
currentProxy = selectProxy();
if (_log.shouldLog(Log.DEBUG))
_log.debug("After selecting outproxy for " + host + ": " + currentProxy);
if (currentProxy == null) {
if (_log.shouldLog(Log.WARN))
_log.warn(getPrefix(requestId) + "Host wants to be outproxied, but we dont have any!");
l.log("No HTTP outproxy found for the request.");
if (out != null) {
out.write(ERR_NO_OUTPROXY);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
destination = currentProxy;
usingWWWProxy = true;
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Host doesnt end with .i2p and it contains a period [" + host + "]: wwwProxy!");
} else if (host.toLowerCase().startsWith("localhost:")) {
if (out != null) {
out.write(ERR_LOCALHOST);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
} else {
request = request.substring(pos + 1);
pos = request.indexOf("/");
if (pos < 0) {
l.log("Invalid request url [" + request + "]");
if (out != null) {
out.write(ERR_REQUEST_DENIED);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
destination = request.substring(0, pos);
line = method + " " + request.substring(pos);
}
boolean isValid = usingWWWProxy || isSupportedAddress(host, protocol);
if (!isValid) {
if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "notValid(" + host + ")");
method = null;
destination = null;
break;
} else if (!usingWWWProxy) {
if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "host=getHostName(" + destination + ")");
host = getHostName(destination); // hide original host
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug(getPrefix(requestId) + "METHOD:" + method + ":");
_log.debug(getPrefix(requestId) + "PROTOC:" + protocol + ":");
_log.debug(getPrefix(requestId) + "HOST :" + host + ":");
_log.debug(getPrefix(requestId) + "DEST :" + destination + ":");
}
} else {
if (lowercaseLine.startsWith("host: ") && !usingWWWProxy) {
line = "Host: " + host;
if (_log.shouldLog(Log.INFO))
_log.info(getPrefix(requestId) + "Setting host = " + host);
} else if (lowercaseLine.startsWith("user-agent: ") &&
!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue()) {
line = null;
continue;
} else if (lowercaseLine.startsWith("accept")) {
// strip the accept-blah headers, as they vary dramatically from
// browser to browser
line = null;
continue;
} else if (lowercaseLine.startsWith("referer: ") &&
!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_REFERER)).booleanValue()) {
// Shouldn't we be more specific, like accepting in-site referers ?
//line = "Referer: i2p";
line = null;
continue; // completely strip the line
} else if (lowercaseLine.startsWith("via: ") &&
!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_VIA)).booleanValue()) {
//line = "Via: i2p";
line = null;
continue; // completely strip the line
} else if (lowercaseLine.startsWith("from: ")) {
//line = "From: i2p";
line = null;
continue; // completely strip the line
}
}
if (line.length() == 0) {
String ok = getTunnel().getClientOptions().getProperty("i2ptunnel.gzip");
boolean gzip = DEFAULT_GZIP;
if (ok != null)
gzip = Boolean.valueOf(ok).booleanValue();
if (gzip) {
// according to rfc2616 s14.3, this *should* force identity, even if
// an explicit q=0 for gzip doesn't. tested against orion.i2p, and it
// seems to work.
newRequest.append("Accept-Encoding: \r\n");
newRequest.append("X-Accept-Encoding: x-i2p-gzip;q=1.0, identity;q=0.5, deflate;q=0, gzip;q=0, *;q=0\r\n");
}
if (!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue())
newRequest.append("User-Agent: MYOB/6.66 (AN/ON)\r\n");
newRequest.append("Connection: close\r\n\r\n");
break;
} else {
newRequest.append(line.trim()).append("\r\n"); // HTTP spec
}
}
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "NewRequest header: [" + newRequest.toString() + "]");
int postbytes = 0;
while (br.ready()) { // empty the buffer (POST requests)
int i = br.read();
if (i != -1) {
newRequest.append((char) i);
if (++postbytes > MAX_POSTBYTES) {
if (out != null) {
out.write(ERR_MAXPOST);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
}
}
if (method == null || destination == null) {
l.log("No HTTP method found in the request.");
if (out != null) {
if ("http://".equalsIgnoreCase(protocol))
out.write(ERR_REQUEST_DENIED);
else
out.write(ERR_BAD_PROTOCOL);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Destination: " + destination);
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
l.log("Could not resolve " + destination + ".");
if (_log.shouldLog(Log.WARN))
_log.warn("Unable to resolve " + destination + " (proxy? " + usingWWWProxy + ", request: " + targetRequest);
String str;
byte[] header;
boolean showAddrHelper = false;
if (usingWWWProxy)
str = FileUtil.readTextFile("docs/dnfp-header.ht", 100, true);
else if(ahelper != 0)
str = FileUtil.readTextFile("docs/dnfb-header.ht", 100, true);
else {
str = FileUtil.readTextFile("docs/dnfh-header.ht", 100, true);
showAddrHelper = true;
}
if (str != null)
header = str.getBytes();
else
header = ERR_DESTINATION_UNKNOWN;
writeErrorMessage(header, out, targetRequest, usingWWWProxy, destination, showAddrHelper);
s.close();
return;
}
String remoteID;
Properties opts = new Properties();
//opts.setProperty("i2p.streaming.inactivityTimeout", ""+120*1000);
// 1 == disconnect. see ConnectionOptions in the new streaming lib, which i
// dont want to hard link to here
//opts.setProperty("i2p.streaming.inactivityTimeoutAction", ""+1);
I2PSocket i2ps = createI2PSocket(dest, getDefaultOptions(opts));
byte[] data = newRequest.toString().getBytes("ISO-8859-1");
Runnable onTimeout = new OnTimeout(s, s.getOutputStream(), targetRequest, usingWWWProxy, currentProxy, requestId);
I2PTunnelRunner runner = new I2PTunnelHTTPClientRunner(s, i2ps, sockLock, data, mySockets, onTimeout);
} catch (SocketException ex) {
_log.info(getPrefix(requestId) + "Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
} catch (IOException ex) {
_log.info(getPrefix(requestId) + "Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
} catch (I2PException ex) {
_log.info("getPrefix(requestId) + Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
} catch (OutOfMemoryError oom) { // mainly for huge POSTs
IOException ex = new IOException("OOM (in POST?)");
_log.info("getPrefix(requestId) + Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
}
}
| protected void clientConnectionRun(Socket s) {
OutputStream out = null;
String targetRequest = null;
boolean usingWWWProxy = false;
String currentProxy = null;
long requestId = ++__requestId;
try {
out = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream(), "ISO-8859-1"));
String line, method = null, protocol = null, host = null, destination = null;
StringBuffer newRequest = new StringBuffer();
int ahelper = 0;
while ((line = br.readLine()) != null) {
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Line=[" + line + "]");
String lowercaseLine = line.toLowerCase();
if (lowercaseLine.startsWith("connection: ") ||
lowercaseLine.startsWith("keep-alive: ") ||
lowercaseLine.startsWith("proxy-connection: "))
continue;
if (method == null) { // first line (GET /base64/realaddr)
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Method is null for [" + line + "]");
line = line.trim();
int pos = line.indexOf(" ");
if (pos == -1) break;
method = line.substring(0, pos);
String request = line.substring(pos + 1);
if (request.startsWith("/") && getTunnel().getClientOptions().getProperty("i2ptunnel.noproxy") != null) {
request = "http://i2p" + request;
} else if (request.startsWith("/eepproxy/")) {
// /eepproxy/foo.i2p/bar/baz.html HTTP/1.0
String subRequest = request.substring("/eepproxy/".length());
int protopos = subRequest.indexOf(" ");
String uri = subRequest.substring(0, protopos);
if (uri.indexOf("/") == -1) {
uri = uri + "/";
}
// "http://" + "foo.i2p/bar/baz.html" + " HTTP/1.0"
request = "http://" + uri + subRequest.substring(protopos);
}
pos = request.indexOf("//");
if (pos == -1) {
method = null;
break;
}
protocol = request.substring(0, pos + 2);
request = request.substring(pos + 2);
targetRequest = request;
pos = request.indexOf("/");
if (pos == -1) {
method = null;
break;
}
host = request.substring(0, pos);
// Quick hack for foo.bar.i2p
if (host.toLowerCase().endsWith(".i2p")) {
// Destination gets the host name
destination = host;
// Host becomes the destination key
host = getHostName(destination);
int pos2;
if ((pos2 = request.indexOf("?")) != -1) {
// Try to find an address helper in the fragments
// and split the request into it's component parts for rebuilding later
String ahelperKey = null;
boolean ahelperConflict = false;
String fragments = request.substring(pos2 + 1);
String uriPath = request.substring(0, pos2);
pos2 = fragments.indexOf(" ");
String protocolVersion = fragments.substring(pos2 + 1);
String urlEncoding = "";
fragments = fragments.substring(0, pos2);
String initialFragments = fragments;
fragments = fragments + "&";
String fragment;
while(fragments.length() > 0) {
pos2 = fragments.indexOf("&");
fragment = fragments.substring(0, pos2);
fragments = fragments.substring(pos2 + 1);
// Fragment looks like addresshelper key
if (fragment.startsWith("i2paddresshelper=")) {
pos2 = fragment.indexOf("=");
ahelperKey = fragment.substring(pos2 + 1);
// Key contains data, lets not ignore it
if (ahelperKey != null) {
// Host resolvable only with addresshelper
if ( (host == null) || ("i2p".equals(host)) )
{
// Cannot check, use addresshelper key
addressHelpers.put(destination,ahelperKey);
} else {
// Host resolvable from database, verify addresshelper key
// Silently bypass correct keys, otherwise alert
if (!host.equals(ahelperKey))
{
// Conflict: handle when URL reconstruction done
ahelperConflict = true;
if (_log.shouldLog(Log.WARN))
_log.warn(getPrefix(requestId) + "Addresshelper key conflict for site [" + destination + "], trusted key [" + host + "], specified key [" + ahelperKey + "].");
}
}
}
} else {
// Other fragments, just pass along
// Append each fragment to urlEncoding
if ("".equals(urlEncoding)) {
urlEncoding = "?" + fragment;
} else {
urlEncoding = urlEncoding + "&" + fragment;
}
}
}
// Reconstruct the request minus the i2paddresshelper GET var
request = uriPath + urlEncoding + " " + protocolVersion;
// Did addresshelper key conflict?
if (ahelperConflict)
{
String str;
byte[] header;
str = FileUtil.readTextFile("docs/ahelper-conflict-header.ht", 100, true);
if (str != null) header = str.getBytes();
else header = ERR_AHELPER_CONFLICT;
if (out != null) {
long alias = I2PAppContext.getGlobalContext().random().nextLong();
String trustedURL = protocol + uriPath + urlEncoding;
String conflictURL = protocol + alias + ".i2p/?" + initialFragments;
out.write(header);
out.write(("To visit the destination in your host database, click <a href=\"" + trustedURL + "\">here</a>. To visit the conflicting addresshelper link by temporarily giving it a random alias, click <a href=\"" + conflictURL + "\">here</a>.<P/>").getBytes());
out.write("</div><p><i>I2P HTTP Proxy Server<br>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
}
String addressHelper = (String) addressHelpers.get(destination);
if (addressHelper != null) {
destination = addressHelper;
host = getHostName(destination);
ahelper = 1;
}
line = method + " " + request.substring(pos);
} else if (host.indexOf(".") != -1) {
// The request must be forwarded to a WWW proxy
if (_log.shouldLog(Log.DEBUG))
_log.debug("Before selecting outproxy for " + host);
currentProxy = selectProxy();
if (_log.shouldLog(Log.DEBUG))
_log.debug("After selecting outproxy for " + host + ": " + currentProxy);
if (currentProxy == null) {
if (_log.shouldLog(Log.WARN))
_log.warn(getPrefix(requestId) + "Host wants to be outproxied, but we dont have any!");
l.log("No HTTP outproxy found for the request.");
if (out != null) {
out.write(ERR_NO_OUTPROXY);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
destination = currentProxy;
usingWWWProxy = true;
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Host doesnt end with .i2p and it contains a period [" + host + "]: wwwProxy!");
} else if (host.toLowerCase().startsWith("localhost:")) {
if (out != null) {
out.write(ERR_LOCALHOST);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
} else {
request = request.substring(pos + 1);
pos = request.indexOf("/");
if (pos < 0) {
l.log("Invalid request url [" + request + "]");
if (out != null) {
out.write(ERR_REQUEST_DENIED);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
destination = request.substring(0, pos);
line = method + " " + request.substring(pos);
}
boolean isValid = usingWWWProxy || isSupportedAddress(host, protocol);
if (!isValid) {
if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "notValid(" + host + ")");
method = null;
destination = null;
break;
} else if (!usingWWWProxy) {
if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "host=getHostName(" + destination + ")");
host = getHostName(destination); // hide original host
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug(getPrefix(requestId) + "METHOD:" + method + ":");
_log.debug(getPrefix(requestId) + "PROTOC:" + protocol + ":");
_log.debug(getPrefix(requestId) + "HOST :" + host + ":");
_log.debug(getPrefix(requestId) + "DEST :" + destination + ":");
}
} else {
if (lowercaseLine.startsWith("host: ") && !usingWWWProxy) {
line = "Host: " + host;
if (_log.shouldLog(Log.INFO))
_log.info(getPrefix(requestId) + "Setting host = " + host);
} else if (lowercaseLine.startsWith("user-agent: ") &&
!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue()) {
line = null;
continue;
} else if (lowercaseLine.startsWith("accept")) {
// strip the accept-blah headers, as they vary dramatically from
// browser to browser
line = null;
continue;
} else if (lowercaseLine.startsWith("referer: ") &&
!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_REFERER)).booleanValue()) {
// Shouldn't we be more specific, like accepting in-site referers ?
//line = "Referer: i2p";
line = null;
continue; // completely strip the line
} else if (lowercaseLine.startsWith("via: ") &&
!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_VIA)).booleanValue()) {
//line = "Via: i2p";
line = null;
continue; // completely strip the line
} else if (lowercaseLine.startsWith("from: ")) {
//line = "From: i2p";
line = null;
continue; // completely strip the line
}
}
if (line.length() == 0) {
String ok = getTunnel().getClientOptions().getProperty("i2ptunnel.gzip");
boolean gzip = DEFAULT_GZIP;
if (ok != null)
gzip = Boolean.valueOf(ok).booleanValue();
if (gzip) {
// according to rfc2616 s14.3, this *should* force identity, even if
// an explicit q=0 for gzip doesn't. tested against orion.i2p, and it
// seems to work.
newRequest.append("Accept-Encoding: \r\n");
newRequest.append("X-Accept-Encoding: x-i2p-gzip;q=1.0, identity;q=0.5, deflate;q=0, gzip;q=0, *;q=0\r\n");
}
if (!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue())
newRequest.append("User-Agent: MYOB/6.66 (AN/ON)\r\n");
newRequest.append("Connection: close\r\n\r\n");
break;
} else {
newRequest.append(line.trim()).append("\r\n"); // HTTP spec
}
}
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "NewRequest header: [" + newRequest.toString() + "]");
int postbytes = 0;
while (br.ready()) { // empty the buffer (POST requests)
int i = br.read();
if (i != -1) {
newRequest.append((char) i);
if (++postbytes > MAX_POSTBYTES) {
if (out != null) {
out.write(ERR_MAXPOST);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
}
}
if (method == null || destination == null) {
l.log("No HTTP method found in the request.");
if (out != null) {
if ("http://".equalsIgnoreCase(protocol))
out.write(ERR_REQUEST_DENIED);
else
out.write(ERR_BAD_PROTOCOL);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
if (_log.shouldLog(Log.DEBUG))
_log.debug(getPrefix(requestId) + "Destination: " + destination);
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
//l.log("Could not resolve " + destination + ".");
if (_log.shouldLog(Log.WARN))
_log.warn("Unable to resolve " + destination + " (proxy? " + usingWWWProxy + ", request: " + targetRequest);
String str;
byte[] header;
boolean showAddrHelper = false;
if (usingWWWProxy)
str = FileUtil.readTextFile("docs/dnfp-header.ht", 100, true);
else if(ahelper != 0)
str = FileUtil.readTextFile("docs/dnfb-header.ht", 100, true);
else if (destination.length() == 60 && destination.endsWith(".b32.i2p"))
str = FileUtil.readTextFile("docs/dnf-header.ht", 100, true);
else {
str = FileUtil.readTextFile("docs/dnfh-header.ht", 100, true);
showAddrHelper = true;
}
if (str != null)
header = str.getBytes();
else
header = ERR_DESTINATION_UNKNOWN;
writeErrorMessage(header, out, targetRequest, usingWWWProxy, destination, showAddrHelper);
s.close();
return;
}
String remoteID;
Properties opts = new Properties();
//opts.setProperty("i2p.streaming.inactivityTimeout", ""+120*1000);
// 1 == disconnect. see ConnectionOptions in the new streaming lib, which i
// dont want to hard link to here
//opts.setProperty("i2p.streaming.inactivityTimeoutAction", ""+1);
I2PSocket i2ps = createI2PSocket(dest, getDefaultOptions(opts));
byte[] data = newRequest.toString().getBytes("ISO-8859-1");
Runnable onTimeout = new OnTimeout(s, s.getOutputStream(), targetRequest, usingWWWProxy, currentProxy, requestId);
I2PTunnelRunner runner = new I2PTunnelHTTPClientRunner(s, i2ps, sockLock, data, mySockets, onTimeout);
} catch (SocketException ex) {
_log.info(getPrefix(requestId) + "Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
} catch (IOException ex) {
_log.info(getPrefix(requestId) + "Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
} catch (I2PException ex) {
_log.info("getPrefix(requestId) + Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
} catch (OutOfMemoryError oom) { // mainly for huge POSTs
IOException ex = new IOException("OOM (in POST?)");
_log.info("getPrefix(requestId) + Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);
closeSocket(s);
}
}
|
diff --git a/tools/pldt/org.eclipse.ptp.pldt.mpi.core/src/org/eclipse/ptp/pldt/mpi/core/actions/RunAnalyseMPIcommandHandler.java b/tools/pldt/org.eclipse.ptp.pldt.mpi.core/src/org/eclipse/ptp/pldt/mpi/core/actions/RunAnalyseMPIcommandHandler.java
index 9debb1003..37629c0cc 100644
--- a/tools/pldt/org.eclipse.ptp.pldt.mpi.core/src/org/eclipse/ptp/pldt/mpi/core/actions/RunAnalyseMPIcommandHandler.java
+++ b/tools/pldt/org.eclipse.ptp.pldt.mpi.core/src/org/eclipse/ptp/pldt/mpi/core/actions/RunAnalyseMPIcommandHandler.java
@@ -1,122 +1,122 @@
/**********************************************************************
* Copyright (c) 2007,2010 IBM 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ptp.pldt.mpi.core.actions;
import java.lang.reflect.Method;
import java.util.List;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.c.GCCLanguage;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.GPPLanguage;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.ptp.pldt.common.CommonPlugin;
import org.eclipse.ptp.pldt.common.ScanReturn;
import org.eclipse.ptp.pldt.common.actions.RunAnalyseHandlerBase;
import org.eclipse.ptp.pldt.common.util.ViewActivator;
import org.eclipse.ptp.pldt.mpi.core.MPIArtifactMarkingVisitor;
import org.eclipse.ptp.pldt.mpi.core.MpiIDs;
import org.eclipse.ptp.pldt.mpi.core.MpiPlugin;
import org.eclipse.ptp.pldt.mpi.core.analysis.MpiCASTVisitor;
import org.eclipse.ptp.pldt.mpi.core.analysis.MpiCPPASTVisitor;
/**
* @author tibbitts
*
*/
public class RunAnalyseMPIcommandHandler extends RunAnalyseHandlerBase
{
/**
* Constructor for the "Run Analysis" action
*/
public RunAnalyseMPIcommandHandler() {
super("MPI", new MPIArtifactMarkingVisitor(MpiIDs.MARKER_ID), MpiIDs.MARKER_ID); //$NON-NLS-1$
}
/**
* Returns MPI analysis artifacts for file
*
* @param file
* @param includes
* MPI include paths
* @return
*/
@Override
public ScanReturn doArtifactAnalysis(final ITranslationUnit tu, final List<String> includes) {
final ScanReturn msr = new ScanReturn();
final String fileName = tu.getElementName();
ILanguage lang;
boolean allowPrefixOnlyMatch = MpiPlugin.getDefault().getPreferenceStore()
.getBoolean(MpiIDs.MPI_RECOGNIZE_APIS_BY_PREFIX_ALONE);
try {
lang = tu.getLanguage();
// long startTime = System.currentTimeMillis();
IASTTranslationUnit atu = getAST(tu); // use index; was tu.getAST();
// long endTime = System.currentTimeMillis();
// System.out.println("RunAnalyseMPICommandHandler: time to build AST for "+tu+": "+(endTime-startTime)/1000.0+" sec");
String languageID = lang.getId();
if (languageID.equals(GCCLanguage.ID) || languageID.equals(GPPLanguage.ID)) {
// null IASTTranslationUnit when we're doing C/C++ means we should quit.
// but want to continue to see if this is a fortran file we are analyzing.
if (atu == null) {// this is null for Fortran file during JUnit testing.
- System.out.println("RunAnalyseMPICommandHandler.doArtifactAnalysis(), atu is null (testing?)");
+ System.out.println("RunAnalyseMPICommandHandler.doArtifactAnalysis(), atu is null (Fortran testing?)");
return msr;
}
}
if (languageID.equals(GCCLanguage.ID)) {// C
atu.accept(new MpiCASTVisitor(includes, fileName, allowPrefixOnlyMatch, msr));
}
else if (languageID.equals(GPPLanguage.ID)) { // C++
atu.accept(new MpiCPPASTVisitor(includes, fileName, allowPrefixOnlyMatch, msr));
}
else {
// Attempt to handle Fortran
// Instantiate using reflection to avoid static Photran dependencies
try {
Class<?> c = Class.forName("org.eclipse.ptp.pldt.mpi.core.actions.AnalyseMPIFortranHandler");
Method method = c.getMethod("run", String.class, ITranslationUnit.class, String.class, ScanReturn.class);
method.invoke(c.newInstance(), languageID, tu, fileName, msr);
} catch (Exception e) {
System.err.println("RunAnalyseMPIcommandHandler.doArtifactAnalysis: Photran not installed");
}
}
} catch (CoreException e) {
e.printStackTrace();
CommonPlugin
.log(IStatus.ERROR,
"RunAnalyseMPICommandHandler.getAST():Error setting up visitor for project " + tu.getCProject() + " error=" + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
return msr;
}
@Override
protected List<String> getIncludePath() {
return MpiPlugin.getDefault().getMpiIncludeDirs();
}
@Override
protected void activateArtifactView() {
ViewActivator.activateView(MpiIDs.MPI_VIEW_ID);
}
@Override
public boolean areIncludePathsNeeded() {
boolean allowPrefixOnlyMatch = MpiPlugin.getDefault().getPreferenceStore()
.getBoolean(MpiIDs.MPI_RECOGNIZE_APIS_BY_PREFIX_ALONE);
return !allowPrefixOnlyMatch;
}
}
| true | true | public ScanReturn doArtifactAnalysis(final ITranslationUnit tu, final List<String> includes) {
final ScanReturn msr = new ScanReturn();
final String fileName = tu.getElementName();
ILanguage lang;
boolean allowPrefixOnlyMatch = MpiPlugin.getDefault().getPreferenceStore()
.getBoolean(MpiIDs.MPI_RECOGNIZE_APIS_BY_PREFIX_ALONE);
try {
lang = tu.getLanguage();
// long startTime = System.currentTimeMillis();
IASTTranslationUnit atu = getAST(tu); // use index; was tu.getAST();
// long endTime = System.currentTimeMillis();
// System.out.println("RunAnalyseMPICommandHandler: time to build AST for "+tu+": "+(endTime-startTime)/1000.0+" sec");
String languageID = lang.getId();
if (languageID.equals(GCCLanguage.ID) || languageID.equals(GPPLanguage.ID)) {
// null IASTTranslationUnit when we're doing C/C++ means we should quit.
// but want to continue to see if this is a fortran file we are analyzing.
if (atu == null) {// this is null for Fortran file during JUnit testing.
System.out.println("RunAnalyseMPICommandHandler.doArtifactAnalysis(), atu is null (testing?)");
return msr;
}
}
if (languageID.equals(GCCLanguage.ID)) {// C
atu.accept(new MpiCASTVisitor(includes, fileName, allowPrefixOnlyMatch, msr));
}
else if (languageID.equals(GPPLanguage.ID)) { // C++
atu.accept(new MpiCPPASTVisitor(includes, fileName, allowPrefixOnlyMatch, msr));
}
else {
// Attempt to handle Fortran
// Instantiate using reflection to avoid static Photran dependencies
try {
Class<?> c = Class.forName("org.eclipse.ptp.pldt.mpi.core.actions.AnalyseMPIFortranHandler");
Method method = c.getMethod("run", String.class, ITranslationUnit.class, String.class, ScanReturn.class);
method.invoke(c.newInstance(), languageID, tu, fileName, msr);
} catch (Exception e) {
System.err.println("RunAnalyseMPIcommandHandler.doArtifactAnalysis: Photran not installed");
}
}
} catch (CoreException e) {
e.printStackTrace();
CommonPlugin
.log(IStatus.ERROR,
"RunAnalyseMPICommandHandler.getAST():Error setting up visitor for project " + tu.getCProject() + " error=" + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
return msr;
}
| public ScanReturn doArtifactAnalysis(final ITranslationUnit tu, final List<String> includes) {
final ScanReturn msr = new ScanReturn();
final String fileName = tu.getElementName();
ILanguage lang;
boolean allowPrefixOnlyMatch = MpiPlugin.getDefault().getPreferenceStore()
.getBoolean(MpiIDs.MPI_RECOGNIZE_APIS_BY_PREFIX_ALONE);
try {
lang = tu.getLanguage();
// long startTime = System.currentTimeMillis();
IASTTranslationUnit atu = getAST(tu); // use index; was tu.getAST();
// long endTime = System.currentTimeMillis();
// System.out.println("RunAnalyseMPICommandHandler: time to build AST for "+tu+": "+(endTime-startTime)/1000.0+" sec");
String languageID = lang.getId();
if (languageID.equals(GCCLanguage.ID) || languageID.equals(GPPLanguage.ID)) {
// null IASTTranslationUnit when we're doing C/C++ means we should quit.
// but want to continue to see if this is a fortran file we are analyzing.
if (atu == null) {// this is null for Fortran file during JUnit testing.
System.out.println("RunAnalyseMPICommandHandler.doArtifactAnalysis(), atu is null (Fortran testing?)");
return msr;
}
}
if (languageID.equals(GCCLanguage.ID)) {// C
atu.accept(new MpiCASTVisitor(includes, fileName, allowPrefixOnlyMatch, msr));
}
else if (languageID.equals(GPPLanguage.ID)) { // C++
atu.accept(new MpiCPPASTVisitor(includes, fileName, allowPrefixOnlyMatch, msr));
}
else {
// Attempt to handle Fortran
// Instantiate using reflection to avoid static Photran dependencies
try {
Class<?> c = Class.forName("org.eclipse.ptp.pldt.mpi.core.actions.AnalyseMPIFortranHandler");
Method method = c.getMethod("run", String.class, ITranslationUnit.class, String.class, ScanReturn.class);
method.invoke(c.newInstance(), languageID, tu, fileName, msr);
} catch (Exception e) {
System.err.println("RunAnalyseMPIcommandHandler.doArtifactAnalysis: Photran not installed");
}
}
} catch (CoreException e) {
e.printStackTrace();
CommonPlugin
.log(IStatus.ERROR,
"RunAnalyseMPICommandHandler.getAST():Error setting up visitor for project " + tu.getCProject() + " error=" + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
return msr;
}
|
diff --git a/src/main/java/ch/entwine/weblounge/contentrepository/impl/fs/FileSystemContentRepository.java b/src/main/java/ch/entwine/weblounge/contentrepository/impl/fs/FileSystemContentRepository.java
index 5557081bd..6fb0c5583 100644
--- a/src/main/java/ch/entwine/weblounge/contentrepository/impl/fs/FileSystemContentRepository.java
+++ b/src/main/java/ch/entwine/weblounge/contentrepository/impl/fs/FileSystemContentRepository.java
@@ -1,723 +1,723 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2003 - 2011 The Weblounge Team
* http://entwinemedia.com/weblounge
*
* 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 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 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, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.entwine.weblounge.contentrepository.impl.fs;
import ch.entwine.weblounge.common.content.MalformedResourceURIException;
import ch.entwine.weblounge.common.content.Resource;
import ch.entwine.weblounge.common.content.ResourceContent;
import ch.entwine.weblounge.common.content.ResourceReader;
import ch.entwine.weblounge.common.content.ResourceURI;
import ch.entwine.weblounge.common.content.ResourceUtils;
import ch.entwine.weblounge.common.content.repository.ContentRepositoryException;
import ch.entwine.weblounge.common.impl.util.config.ConfigurationUtils;
import ch.entwine.weblounge.common.language.Language;
import ch.entwine.weblounge.common.site.Site;
import ch.entwine.weblounge.common.url.PathUtils;
import ch.entwine.weblounge.common.url.UrlUtils;
import ch.entwine.weblounge.contentrepository.ResourceSerializer;
import ch.entwine.weblounge.contentrepository.ResourceSerializerFactory;
import ch.entwine.weblounge.contentrepository.VersionedContentRepositoryIndex;
import ch.entwine.weblounge.contentrepository.impl.AbstractWritableContentRepository;
import ch.entwine.weblounge.contentrepository.impl.index.ContentRepositoryIndex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Dictionary;
import java.util.Set;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
/**
* Implementation of a content repository that lives on a filesystem.
*/
public class FileSystemContentRepository extends AbstractWritableContentRepository implements ManagedService {
/** The logging facility */
private static final Logger logger = LoggerFactory.getLogger(FileSystemContentRepository.class);
/** The repository type */
public static final String TYPE = "ch.entwine.weblounge.contentrepository.filesystem";
/** Prefix for repository configuration keys */
private static final String CONF_PREFIX = "contentrepository.fs.";
/** Configuration key for the repository's root directory */
public static final String OPT_ROOT_DIR = CONF_PREFIX + "root";
/** Name of the system property containing the root directory */
public static final String PROP_ROOT_DIR = "weblounge.sitesdatadir";
/** Default directory root directory name */
public static final String ROOT_DIR_DEFAULT = "sites-data";
/** Name of the index path element right below the repository root */
public static final String INDEX_PATH = "index";
/** The repository storage root directory */
protected File repositoryRoot = null;
/** The repository root directory */
protected File repositorySiteRoot = null;
/** The root directory for the temporary bundle index */
protected File idxRootDir = null;
/** The document builder factory */
protected final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
/** The xml transformer factory */
protected final TransformerFactory transformerFactory = TransformerFactory.newInstance();
/**
* Creates a new instance of the file system content repository.
*/
public FileSystemContentRepository() {
super(TYPE);
}
/**
* {@inheritDoc}
*
* @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
*/
@SuppressWarnings("rawtypes")
public void updated(Dictionary properties) throws ConfigurationException {
// Detect the filesystem root directory
String fsRootDir = null;
if (StringUtils.isNotBlank(System.getProperty(PROP_ROOT_DIR)))
fsRootDir = System.getProperty(PROP_ROOT_DIR);
else if (properties != null && StringUtils.isNotBlank((String) properties.get(OPT_ROOT_DIR)))
fsRootDir = (String) properties.get(OPT_ROOT_DIR);
else
fsRootDir = PathUtils.concat(System.getProperty("java.io.tmpdir"), ROOT_DIR_DEFAULT);
repositoryRoot = new File(fsRootDir);
if (site != null)
repositorySiteRoot = new File(repositoryRoot, site.getIdentifier());
logger.debug("Content repository storage root is located at {}", repositoryRoot);
// Make sure we can create a temporary index
try {
FileUtils.forceMkdir(repositoryRoot);
} catch (IOException e) {
throw new ConfigurationException(OPT_ROOT_DIR, "Unable to create repository storage at " + repositoryRoot, e);
}
logger.debug("Content repository configured");
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository#connect(ch.entwine.weblounge.common.site.Site)
*/
@Override
public void connect(Site site) throws ContentRepositoryException {
repositorySiteRoot = new File(repositoryRoot, site.getIdentifier());
logger.debug("Content repository root is located at {}", repositorySiteRoot);
// Make sure we can create a temporary index
idxRootDir = new File(repositorySiteRoot, INDEX_PATH);
try {
FileUtils.forceMkdir(idxRootDir);
} catch (IOException e) {
throw new ContentRepositoryException("Unable to create site index at " + idxRootDir, e);
}
// Tell the super implementation
super.connect(site);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.content.repository.WritableContentRepository#index()
*/
public void index() throws ContentRepositoryException {
// Temporary path for rebuilt site
boolean success = true;
try {
// Clear the current index, which might be null if the site has not been
// started yet.
if (index == null)
index = loadIndex();
index.clear();
logger.info("Creating site index '{}'...", site);
long time = System.currentTimeMillis();
long resourceCount = 0;
// Index each and every known resource type
Set<ResourceSerializer<?, ?>> serializers = ResourceSerializerFactory.getSerializers();
if (serializers == null) {
logger.warn("Unable to index {} while no resource serializers are registered", this);
return;
}
for (ResourceSerializer<?, ?> serializer : serializers) {
long added = index(serializer.getType());
if (added > 0)
logger.info("Added {} {}s to index", added, serializer.getType().toLowerCase());
resourceCount += added;
}
if (resourceCount > 0) {
time = System.currentTimeMillis() - time;
logger.info("Site index populated in {} ms", ConfigurationUtils.toHumanReadableDuration(time));
logger.info("{} resources added to index", resourceCount);
}
} catch (IOException e) {
success = false;
throw new ContentRepositoryException("Error while writing to index", e);
} catch (MalformedResourceURIException e) {
success = false;
throw new ContentRepositoryException("Error while reading resource uri for index", e);
} finally {
if (!success) {
try {
index.clear();
} catch (IOException e) {
logger.error("Error while trying to cleanup after failed indexing operation", e);
}
}
}
}
/**
* This method indexes a certain type of resources and expects the resources
* to be located in a subdirectory of the site directory named
* <tt><resourceType>s<tt>.
*
* @param resourceType
* the resource type
* @return the number of resources that were indexed
* @throws IOException
* if accessing a file fails
*/
protected long index(String resourceType) throws IOException {
// Temporary path for rebuilt site
String resourceDirectory = resourceType + "s";
String homePath = UrlUtils.concat(repositorySiteRoot.getAbsolutePath(), resourceDirectory);
File resourcesRootDirectory = new File(homePath);
FileUtils.forceMkdir(resourcesRootDirectory);
if (resourcesRootDirectory.list().length == 0) {
logger.debug("No {}s found to index", resourceType);
return 0;
}
logger.info("Populating site index '{}' with {}s...", site, resourceType);
ResourceSerializer<?, ?> serializer = ResourceSerializerFactory.getSerializerByType(resourceType);
if (serializer == null) {
logger.warn("Unable to index resources of type '{}': no resource serializer found", resourceType);
return 0;
}
// Clear previews directory
logger.info("Removing cached preview images");
File previewsDir = new File(PathUtils.concat(System.getProperty("java.io.tmpdir"), "sites", site.getIdentifier(), "images"));
FileUtils.deleteQuietly(previewsDir);
File restructuredResources = new File(repositorySiteRoot, "." + resourceDirectory);
long resourceCount = 0;
long resourceVersionCount = 0;
boolean restructured = false;
try {
Stack<File> uris = new Stack<File>();
uris.push(resourcesRootDirectory);
while (!uris.empty()) {
File dir = uris.pop();
File[] files = dir.listFiles(new FileFilter() {
public boolean accept(File path) {
if (path.getName().startsWith("."))
return false;
return path.isDirectory() || path.getName().endsWith(".xml");
}
});
if (files == null || files.length == 0)
continue;
for (File f : files) {
if (f.isDirectory()) {
uris.push(f);
} else {
try {
Resource<?> resource = null;
ResourceURI uri = null;
ResourceReader<?, ?> reader = serializer.getReader();
InputStream is = null;
boolean foundResource = false;
// Read the resource
try {
is = new FileInputStream(f);
resource = reader.read(is, site);
if (resource == null) {
logger.warn("Unkown error loading {}", f);
continue;
}
uri = resource.getURI();
} catch (Throwable t) {
logger.error("Error loading {}: {}", f, t.getMessage());
continue;
} finally {
IOUtils.closeQuietly(is);
}
index.add(resource);
resourceVersionCount++;
// Make sure the resource is in the correct place
File expectedFile = uriToFile(uri);
String tempPath = expectedFile.getAbsolutePath().substring(homePath.length());
File indexedFile = new File(restructuredResources, tempPath);
FileUtils.copyFile(f, indexedFile);
if (!f.equals(expectedFile)) {
restructured = true;
}
// See if there are files that need to be copied as well. We add
// the "found" flag in case that there are multiple versions of
// this resource (we don't want to copy the files more than once).
if (!foundResource) {
for (ResourceContent c : resource.contents()) {
if (c.getFilename() == null)
throw new IllegalStateException("Found content without filename in " + resource);
Language l = c.getLanguage();
String filename = l.getIdentifier() + "." + FilenameUtils.getExtension(c.getFilename());
String srcFile = PathUtils.concat(f.getParentFile().getAbsolutePath(), filename);
String destFile = PathUtils.concat(indexedFile.getParentFile().getAbsolutePath(), filename);
FileUtils.copyFile(new File(srcFile), new File(destFile));
}
logger.info("Adding {} {} to site index", resourceType, uri.toString());
resourceCount++;
foundResource = true;
}
// Create the previews
- logger.info("Creating preview images");
+ logger.debug("Creating preview images");
createPreviews(resource);
} catch (Throwable t) {
logger.error("Error indexing {} {}: {}", new Object[] {
resourceType,
f,
t.getMessage() });
}
}
}
}
// Move restructured resources in place
if (restructured) {
String oldResourcesDirectory = resourceDirectory + "-old";
File movedOldResources = new File(repositorySiteRoot, oldResourcesDirectory);
if (movedOldResources.exists()) {
for (int i = 1; i < Integer.MAX_VALUE; i++) {
movedOldResources = new File(repositorySiteRoot, oldResourcesDirectory + " " + i);
if (!movedOldResources.exists())
break;
}
}
FileUtils.moveDirectory(resourcesRootDirectory, movedOldResources);
FileUtils.moveDirectory(restructuredResources, resourcesRootDirectory);
}
// Log the work
if (resourceCount > 0) {
logger.info("{} {}s and {} revisions added to index", new Object[] {
resourceCount,
resourceType,
resourceVersionCount - resourceCount });
}
} finally {
if (restructuredResources.exists()) {
FileUtils.deleteQuietly(restructuredResources);
}
}
return resourceCount;
}
/**
* Returns the root directory for this repository.
* <p>
* The root is either equal to the repository's filesystem root or, in case
* this repository hosts multiple sites, to the filesystem root + a uri.
*
* @return the repository root directory
*/
public File getRootDirectory() {
return repositorySiteRoot;
}
/**
* Returns the <code>File</code> object that is represented by
* <code>uri</code> or <code>null</code> if the resource does not exist on the
* filesystem.
*
* @param uri
* the resource uri
* @return the file
*/
protected File uriToFile(ResourceURI uri) throws IOException {
StringBuffer path = new StringBuffer(repositorySiteRoot.getAbsolutePath());
if (uri.getType() == null)
throw new IllegalArgumentException("Resource uri has no type");
path.append("/").append(uri.getType()).append("s");
String id = null;
if (uri.getIdentifier() != null) {
id = uri.getIdentifier();
} else {
id = index.getIdentifier(uri);
if (id == null) {
logger.debug("Uri '{}' is not part of the repository index", uri);
return null;
}
}
if (uri.getVersion() < 0) {
logger.warn("Resource {} has no version");
}
// Build the path
path = appendIdToPath(id, path);
path.append(File.separatorChar);
path.append(uri.getVersion());
path.append(File.separatorChar);
// Add the document name
path.append(ResourceUtils.getDocument(Resource.LIVE));
return new File(path.toString());
}
/**
* Returns the <code>File</code> object that is represented by
* <code>uri</code> and <code>content</code> or <code>null</code> if the
* resource or the resource content does not exist on the filesystem.
*
* @param uri
* the resource uri
* @param content
* the resource content
* @return the content file
* @throws IOException
* if the file cannot be accessed not exist
*/
protected File uriToContentFile(ResourceURI uri, ResourceContent content)
throws IOException {
File resourceDirectory = uriToDirectory(uri);
File resourceRevisionDirectory = new File(resourceDirectory, Long.toString(uri.getVersion()));
// Construct the filename
String fileName = content.getLanguage().getIdentifier();
String fileExtension = FilenameUtils.getExtension(content.getFilename());
if (!"".equals(fileExtension)) {
fileName += "." + fileExtension;
}
File contentFile = new File(resourceRevisionDirectory, fileName);
return contentFile;
}
/**
* Returns the resource uri's parent directory or <code>null</code> if the
* directory does not exist on the filesystem.
*
* @param uri
* the resource uri
* @return the parent directory
*/
protected File uriToDirectory(ResourceURI uri) throws IOException {
StringBuffer path = new StringBuffer(repositorySiteRoot.getAbsolutePath());
if (uri.getType() == null)
throw new IllegalArgumentException("Resource uri has no type");
path.append("/").append(uri.getType()).append("s");
String id = null;
if (uri.getIdentifier() != null) {
id = uri.getIdentifier();
} else {
id = index.getIdentifier(uri);
if (id == null) {
logger.warn("Uri '{}' is not part of the repository index", uri);
return null;
}
}
path = appendIdToPath(uri.getIdentifier(), path);
return new File(path.toString());
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
if (repositorySiteRoot != null)
return repositorySiteRoot.hashCode();
else
return super.hashCode();
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof FileSystemContentRepository) {
FileSystemContentRepository repo = (FileSystemContentRepository) obj;
if (repositorySiteRoot != null) {
return repositorySiteRoot.equals(repo.getRootDirectory());
} else {
return super.equals(obj);
}
}
return false;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return repositorySiteRoot.getAbsolutePath();
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository#loadResource()
*/
@Override
protected InputStream openStreamToResource(ResourceURI uri)
throws IOException {
if (uri.getType() == null) {
uri.setType(index.getType(uri));
}
File resourceFile = uriToFile(uri);
if (resourceFile == null || !resourceFile.isFile())
return null;
return new FileInputStream(resourceFile);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository#openStreamToResourceContent(ch.entwine.weblounge.common.content.ResourceURI,
* ch.entwine.weblounge.common.language.Language)
*/
@Override
protected InputStream openStreamToResourceContent(ResourceURI uri,
Language language) throws IOException {
File resourceFile = uriToFile(uri);
if (resourceFile == null)
return null;
// Look for the localized file
File resourceDirectory = resourceFile.getParentFile();
final String filenamePrefix = language.getIdentifier() + ".";
File[] localizedFiles = resourceDirectory.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isFile() && f.getName().startsWith(filenamePrefix);
}
});
// Make sure everything looks consistent
if (localizedFiles.length == 0)
return null;
else if (localizedFiles.length > 1)
logger.warn("Inconsistencies found in resource {} content {}", language, uri);
// Finally return the content
return new FileInputStream(localizedFiles[0]);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.contentrepository.impl.AbstractWritableContentRepository#deleteResource(ch.entwine.weblounge.common.content.ResourceURI,
* long[])
*/
@Override
protected void deleteResource(ResourceURI uri, long[] revisions)
throws IOException {
// Remove the resources
File resourceDir = uriToDirectory(uri);
for (long r : revisions) {
File f = new File(resourceDir, Long.toString(r));
if (f.exists()) {
try {
FileUtils.deleteDirectory(f);
} catch (IOException e) {
throw new IOException("Unable to delete revision " + r + " of resource " + uri + " located at " + f + " from repository");
}
}
}
// Remove the resource directory itself if there are no more resources
try {
File f = resourceDir;
while (!uri.getType().equals(f.getName()) && f.listFiles().length == 0) {
FileUtils.deleteDirectory(f);
f = f.getParentFile();
}
} catch (IOException e) {
throw new IOException("Unable to delete directory for resource " + uri, e);
}
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.contentrepository.impl.AbstractWritableContentRepository#storeResource(ch.entwine.weblounge.common.content.resource.Resource)
*/
@Override
protected <T extends ResourceContent, R extends Resource<T>> R storeResource(
R resource) throws IOException {
File resourceUrl = uriToFile(resource.getURI());
InputStream is = null;
OutputStream os = null;
try {
FileUtils.forceMkdir(resourceUrl.getParentFile());
if (!resourceUrl.exists())
resourceUrl.createNewFile();
is = new ByteArrayInputStream(resource.toXml().getBytes("utf-8"));
os = new FileOutputStream(resourceUrl);
IOUtils.copy(is, os);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
return resource;
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.contentrepository.impl.AbstractWritableContentRepository#storeResourceContent(ch.entwine.weblounge.common.content.ResourceURI,
* ch.entwine.weblounge.common.content.ResourceContent,
* java.io.InputStream)
*/
@Override
protected <T extends ResourceContent> T storeResourceContent(ResourceURI uri,
T content, InputStream is) throws IOException {
File contentFile = uriToContentFile(uri, content);
OutputStream os = null;
try {
FileUtils.forceMkdir(contentFile.getParentFile());
if (!contentFile.exists())
contentFile.createNewFile();
os = new FileOutputStream(contentFile);
IOUtils.copyLarge(is, os);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
// Set the size
content.setSize(contentFile.length());
return content;
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.contentrepository.impl.AbstractWritableContentRepository#deleteResourceContent(ch.entwine.weblounge.common.content.ResourceURI,
* ch.entwine.weblounge.common.content.ResourceContent)
*/
protected <T extends ResourceContent> void deleteResourceContent(
ResourceURI uri, T content) throws IOException {
File contentFile = uriToContentFile(uri, content);
if (contentFile == null)
throw new IOException("Resource content " + contentFile + " does not exist");
FileUtils.deleteQuietly(contentFile);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository#loadIndex()
*/
@Override
protected ContentRepositoryIndex loadIndex() throws IOException,
ContentRepositoryException {
logger.debug("Trying to load site index from {}", idxRootDir);
// Is this a new index?
boolean created = !idxRootDir.exists() || idxRootDir.list().length == 0;
FileUtils.forceMkdir(idxRootDir);
// Add content if there is any
index = new FileSystemContentRepositoryIndex(idxRootDir);
// Create the index if there is nothing in place so far
if (index.getResourceCount() <= 0) {
index();
}
// Make sure the version matches the implementation
else if (index.getIndexVersion() != VersionedContentRepositoryIndex.INDEX_VERSION) {
logger.warn("Index version does not match implementation, triggering reindex");
index();
}
// Is there an existing index?
if (created) {
logger.info("Created site index at {}", idxRootDir);
} else {
long resourceCount = index.getResourceCount();
long resourceVersionCount = index.getRevisionCount();
logger.info("Loaded site index with {} resources and {} revisions from {}", new Object[] {
resourceCount,
resourceVersionCount - resourceCount,
idxRootDir });
}
return index;
}
}
| true | true | protected long index(String resourceType) throws IOException {
// Temporary path for rebuilt site
String resourceDirectory = resourceType + "s";
String homePath = UrlUtils.concat(repositorySiteRoot.getAbsolutePath(), resourceDirectory);
File resourcesRootDirectory = new File(homePath);
FileUtils.forceMkdir(resourcesRootDirectory);
if (resourcesRootDirectory.list().length == 0) {
logger.debug("No {}s found to index", resourceType);
return 0;
}
logger.info("Populating site index '{}' with {}s...", site, resourceType);
ResourceSerializer<?, ?> serializer = ResourceSerializerFactory.getSerializerByType(resourceType);
if (serializer == null) {
logger.warn("Unable to index resources of type '{}': no resource serializer found", resourceType);
return 0;
}
// Clear previews directory
logger.info("Removing cached preview images");
File previewsDir = new File(PathUtils.concat(System.getProperty("java.io.tmpdir"), "sites", site.getIdentifier(), "images"));
FileUtils.deleteQuietly(previewsDir);
File restructuredResources = new File(repositorySiteRoot, "." + resourceDirectory);
long resourceCount = 0;
long resourceVersionCount = 0;
boolean restructured = false;
try {
Stack<File> uris = new Stack<File>();
uris.push(resourcesRootDirectory);
while (!uris.empty()) {
File dir = uris.pop();
File[] files = dir.listFiles(new FileFilter() {
public boolean accept(File path) {
if (path.getName().startsWith("."))
return false;
return path.isDirectory() || path.getName().endsWith(".xml");
}
});
if (files == null || files.length == 0)
continue;
for (File f : files) {
if (f.isDirectory()) {
uris.push(f);
} else {
try {
Resource<?> resource = null;
ResourceURI uri = null;
ResourceReader<?, ?> reader = serializer.getReader();
InputStream is = null;
boolean foundResource = false;
// Read the resource
try {
is = new FileInputStream(f);
resource = reader.read(is, site);
if (resource == null) {
logger.warn("Unkown error loading {}", f);
continue;
}
uri = resource.getURI();
} catch (Throwable t) {
logger.error("Error loading {}: {}", f, t.getMessage());
continue;
} finally {
IOUtils.closeQuietly(is);
}
index.add(resource);
resourceVersionCount++;
// Make sure the resource is in the correct place
File expectedFile = uriToFile(uri);
String tempPath = expectedFile.getAbsolutePath().substring(homePath.length());
File indexedFile = new File(restructuredResources, tempPath);
FileUtils.copyFile(f, indexedFile);
if (!f.equals(expectedFile)) {
restructured = true;
}
// See if there are files that need to be copied as well. We add
// the "found" flag in case that there are multiple versions of
// this resource (we don't want to copy the files more than once).
if (!foundResource) {
for (ResourceContent c : resource.contents()) {
if (c.getFilename() == null)
throw new IllegalStateException("Found content without filename in " + resource);
Language l = c.getLanguage();
String filename = l.getIdentifier() + "." + FilenameUtils.getExtension(c.getFilename());
String srcFile = PathUtils.concat(f.getParentFile().getAbsolutePath(), filename);
String destFile = PathUtils.concat(indexedFile.getParentFile().getAbsolutePath(), filename);
FileUtils.copyFile(new File(srcFile), new File(destFile));
}
logger.info("Adding {} {} to site index", resourceType, uri.toString());
resourceCount++;
foundResource = true;
}
// Create the previews
logger.info("Creating preview images");
createPreviews(resource);
} catch (Throwable t) {
logger.error("Error indexing {} {}: {}", new Object[] {
resourceType,
f,
t.getMessage() });
}
}
}
}
// Move restructured resources in place
if (restructured) {
String oldResourcesDirectory = resourceDirectory + "-old";
File movedOldResources = new File(repositorySiteRoot, oldResourcesDirectory);
if (movedOldResources.exists()) {
for (int i = 1; i < Integer.MAX_VALUE; i++) {
movedOldResources = new File(repositorySiteRoot, oldResourcesDirectory + " " + i);
if (!movedOldResources.exists())
break;
}
}
FileUtils.moveDirectory(resourcesRootDirectory, movedOldResources);
FileUtils.moveDirectory(restructuredResources, resourcesRootDirectory);
}
// Log the work
if (resourceCount > 0) {
logger.info("{} {}s and {} revisions added to index", new Object[] {
resourceCount,
resourceType,
resourceVersionCount - resourceCount });
}
} finally {
if (restructuredResources.exists()) {
FileUtils.deleteQuietly(restructuredResources);
}
}
return resourceCount;
}
| protected long index(String resourceType) throws IOException {
// Temporary path for rebuilt site
String resourceDirectory = resourceType + "s";
String homePath = UrlUtils.concat(repositorySiteRoot.getAbsolutePath(), resourceDirectory);
File resourcesRootDirectory = new File(homePath);
FileUtils.forceMkdir(resourcesRootDirectory);
if (resourcesRootDirectory.list().length == 0) {
logger.debug("No {}s found to index", resourceType);
return 0;
}
logger.info("Populating site index '{}' with {}s...", site, resourceType);
ResourceSerializer<?, ?> serializer = ResourceSerializerFactory.getSerializerByType(resourceType);
if (serializer == null) {
logger.warn("Unable to index resources of type '{}': no resource serializer found", resourceType);
return 0;
}
// Clear previews directory
logger.info("Removing cached preview images");
File previewsDir = new File(PathUtils.concat(System.getProperty("java.io.tmpdir"), "sites", site.getIdentifier(), "images"));
FileUtils.deleteQuietly(previewsDir);
File restructuredResources = new File(repositorySiteRoot, "." + resourceDirectory);
long resourceCount = 0;
long resourceVersionCount = 0;
boolean restructured = false;
try {
Stack<File> uris = new Stack<File>();
uris.push(resourcesRootDirectory);
while (!uris.empty()) {
File dir = uris.pop();
File[] files = dir.listFiles(new FileFilter() {
public boolean accept(File path) {
if (path.getName().startsWith("."))
return false;
return path.isDirectory() || path.getName().endsWith(".xml");
}
});
if (files == null || files.length == 0)
continue;
for (File f : files) {
if (f.isDirectory()) {
uris.push(f);
} else {
try {
Resource<?> resource = null;
ResourceURI uri = null;
ResourceReader<?, ?> reader = serializer.getReader();
InputStream is = null;
boolean foundResource = false;
// Read the resource
try {
is = new FileInputStream(f);
resource = reader.read(is, site);
if (resource == null) {
logger.warn("Unkown error loading {}", f);
continue;
}
uri = resource.getURI();
} catch (Throwable t) {
logger.error("Error loading {}: {}", f, t.getMessage());
continue;
} finally {
IOUtils.closeQuietly(is);
}
index.add(resource);
resourceVersionCount++;
// Make sure the resource is in the correct place
File expectedFile = uriToFile(uri);
String tempPath = expectedFile.getAbsolutePath().substring(homePath.length());
File indexedFile = new File(restructuredResources, tempPath);
FileUtils.copyFile(f, indexedFile);
if (!f.equals(expectedFile)) {
restructured = true;
}
// See if there are files that need to be copied as well. We add
// the "found" flag in case that there are multiple versions of
// this resource (we don't want to copy the files more than once).
if (!foundResource) {
for (ResourceContent c : resource.contents()) {
if (c.getFilename() == null)
throw new IllegalStateException("Found content without filename in " + resource);
Language l = c.getLanguage();
String filename = l.getIdentifier() + "." + FilenameUtils.getExtension(c.getFilename());
String srcFile = PathUtils.concat(f.getParentFile().getAbsolutePath(), filename);
String destFile = PathUtils.concat(indexedFile.getParentFile().getAbsolutePath(), filename);
FileUtils.copyFile(new File(srcFile), new File(destFile));
}
logger.info("Adding {} {} to site index", resourceType, uri.toString());
resourceCount++;
foundResource = true;
}
// Create the previews
logger.debug("Creating preview images");
createPreviews(resource);
} catch (Throwable t) {
logger.error("Error indexing {} {}: {}", new Object[] {
resourceType,
f,
t.getMessage() });
}
}
}
}
// Move restructured resources in place
if (restructured) {
String oldResourcesDirectory = resourceDirectory + "-old";
File movedOldResources = new File(repositorySiteRoot, oldResourcesDirectory);
if (movedOldResources.exists()) {
for (int i = 1; i < Integer.MAX_VALUE; i++) {
movedOldResources = new File(repositorySiteRoot, oldResourcesDirectory + " " + i);
if (!movedOldResources.exists())
break;
}
}
FileUtils.moveDirectory(resourcesRootDirectory, movedOldResources);
FileUtils.moveDirectory(restructuredResources, resourcesRootDirectory);
}
// Log the work
if (resourceCount > 0) {
logger.info("{} {}s and {} revisions added to index", new Object[] {
resourceCount,
resourceType,
resourceVersionCount - resourceCount });
}
} finally {
if (restructuredResources.exists()) {
FileUtils.deleteQuietly(restructuredResources);
}
}
return resourceCount;
}
|
diff --git a/src/me/libraryaddict/Hungergames/Kits/Spiderman.java b/src/me/libraryaddict/Hungergames/Kits/Spiderman.java
index ef97776..2b86163 100644
--- a/src/me/libraryaddict/Hungergames/Kits/Spiderman.java
+++ b/src/me/libraryaddict/Hungergames/Kits/Spiderman.java
@@ -1,95 +1,96 @@
package me.libraryaddict.Hungergames.Kits;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import me.libraryaddict.Hungergames.Hungergames;
import me.libraryaddict.Hungergames.Managers.KitManager;
import me.libraryaddict.Hungergames.Types.HungergamesApi;
public class Spiderman implements Listener {
private KitManager kits = HungergamesApi.getKitManager();
private Hungergames hg = HungergamesApi.getHungergames();
private HashMap<String, ArrayList<Long>> cooldown = new HashMap<String, ArrayList<Long>>();
@EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent event) {
if (event.getEntityType() == EntityType.SNOWBALL) {
if (event.getEntity().getShooter() != null && event.getEntity().getShooter() instanceof Player) {
Player p = (Player) event.getEntity().getShooter();
if (!kits.hasAbility(p, "Spiderman"))
return;
ArrayList<Long> cooldowns;
if (cooldown.containsKey(p.getName()))
cooldowns = cooldown.get(p.getName());
else {
cooldowns = new ArrayList<Long>();
cooldown.put(p.getName(), cooldowns);
}
if (cooldowns.size() == 3) {
if (cooldowns.get(0) >= System.currentTimeMillis()) {
event.setCancelled(true);
+ p.updateInventory();
p.sendMessage(ChatColor.BLUE + "Your web shooters havn't refilled yet! Wait "
+ (((cooldowns.get(0) - System.currentTimeMillis()) / 1000) + 1) + " seconds!");
kits.addItem(p, new ItemStack(Material.SNOW_BALL));
return;
}
cooldowns.remove(0);
}
event.getEntity().setMetadata("Spiderball", new FixedMetadataValue(hg, "Spiderball"));
cooldowns.add(System.currentTimeMillis() + 30000);
}
}
}
@EventHandler
public void onProjectileHit(ProjectileHitEvent event) {
if (event.getEntity().hasMetadata("Spiderball")) {
Location loc = event.getEntity().getLocation();
int x = new Random().nextInt(2) - 1;
int z = new Random().nextInt(2) - 1;
for (int y = 0; y < 2; y++)
for (int xx = 0; xx < 2; xx++)
for (int zz = 0; zz < 2; zz++) {
Block b = loc.clone().add(x + xx, y, z + zz).getBlock();
if (b.getType() == Material.AIR)
b.setType(Material.WEB);
}
event.getEntity().remove();
}
}
private boolean isWeb(Location loc) {
if (loc.getBlock().getType() == Material.WEB)
return true;
return loc.clone().add(0, 1, 0).getBlock().getType() == Material.WEB;
}
@EventHandler
public void onMove(PlayerMoveEvent event) {
if (kits.hasAbility(event.getPlayer(), "Spiderman")) {
if (isWeb(event.getFrom()) || isWeb(event.getTo())) {
event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 40, 1), true);
}
}
}
}
| true | true | public void onProjectileLaunch(ProjectileLaunchEvent event) {
if (event.getEntityType() == EntityType.SNOWBALL) {
if (event.getEntity().getShooter() != null && event.getEntity().getShooter() instanceof Player) {
Player p = (Player) event.getEntity().getShooter();
if (!kits.hasAbility(p, "Spiderman"))
return;
ArrayList<Long> cooldowns;
if (cooldown.containsKey(p.getName()))
cooldowns = cooldown.get(p.getName());
else {
cooldowns = new ArrayList<Long>();
cooldown.put(p.getName(), cooldowns);
}
if (cooldowns.size() == 3) {
if (cooldowns.get(0) >= System.currentTimeMillis()) {
event.setCancelled(true);
p.sendMessage(ChatColor.BLUE + "Your web shooters havn't refilled yet! Wait "
+ (((cooldowns.get(0) - System.currentTimeMillis()) / 1000) + 1) + " seconds!");
kits.addItem(p, new ItemStack(Material.SNOW_BALL));
return;
}
cooldowns.remove(0);
}
event.getEntity().setMetadata("Spiderball", new FixedMetadataValue(hg, "Spiderball"));
cooldowns.add(System.currentTimeMillis() + 30000);
}
}
}
| public void onProjectileLaunch(ProjectileLaunchEvent event) {
if (event.getEntityType() == EntityType.SNOWBALL) {
if (event.getEntity().getShooter() != null && event.getEntity().getShooter() instanceof Player) {
Player p = (Player) event.getEntity().getShooter();
if (!kits.hasAbility(p, "Spiderman"))
return;
ArrayList<Long> cooldowns;
if (cooldown.containsKey(p.getName()))
cooldowns = cooldown.get(p.getName());
else {
cooldowns = new ArrayList<Long>();
cooldown.put(p.getName(), cooldowns);
}
if (cooldowns.size() == 3) {
if (cooldowns.get(0) >= System.currentTimeMillis()) {
event.setCancelled(true);
p.updateInventory();
p.sendMessage(ChatColor.BLUE + "Your web shooters havn't refilled yet! Wait "
+ (((cooldowns.get(0) - System.currentTimeMillis()) / 1000) + 1) + " seconds!");
kits.addItem(p, new ItemStack(Material.SNOW_BALL));
return;
}
cooldowns.remove(0);
}
event.getEntity().setMetadata("Spiderball", new FixedMetadataValue(hg, "Spiderball"));
cooldowns.add(System.currentTimeMillis() + 30000);
}
}
}
|
diff --git a/src/powercrystals/minefactoryreloaded/modhelpers/vanilla/Vanilla.java b/src/powercrystals/minefactoryreloaded/modhelpers/vanilla/Vanilla.java
index 93be4e54..48cbd2b1 100644
--- a/src/powercrystals/minefactoryreloaded/modhelpers/vanilla/Vanilla.java
+++ b/src/powercrystals/minefactoryreloaded/modhelpers/vanilla/Vanilla.java
@@ -1,276 +1,275 @@
package powercrystals.minefactoryreloaded.modhelpers.vanilla;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.item.EntityMinecartHopper;
import net.minecraft.entity.item.EntityTNTPrimed;
import net.minecraft.entity.monster.EntityBlaze;
import net.minecraft.entity.monster.EntityCaveSpider;
import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.monster.EntityGhast;
import net.minecraft.entity.monster.EntityMagmaCube;
import net.minecraft.entity.monster.EntitySlime;
import net.minecraft.entity.monster.EntitySpider;
import net.minecraft.entity.monster.EntityWitch;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.passive.EntityChicken;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.entity.passive.EntityMooshroom;
import net.minecraft.entity.passive.EntityOcelot;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.entity.passive.EntitySquid;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import powercrystals.minefactoryreloaded.MFRRegistry;
import powercrystals.minefactoryreloaded.MineFactoryReloadedCore;
import powercrystals.minefactoryreloaded.api.FertilizerType;
import powercrystals.minefactoryreloaded.api.HarvestType;
import powercrystals.minefactoryreloaded.api.MobDrop;
import powercrystals.minefactoryreloaded.farmables.egghandlers.VanillaEggHandler;
import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableCocoa;
import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableCropPlant;
import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableGiantMushroom;
import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableGrass;
import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableNetherWart;
import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableRubberSapling;
import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableSapling;
import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizableStemPlants;
import powercrystals.minefactoryreloaded.farmables.fertilizables.FertilizerStandard;
import powercrystals.minefactoryreloaded.farmables.grindables.GrindableSheep;
import powercrystals.minefactoryreloaded.farmables.grindables.GrindableSkeleton;
import powercrystals.minefactoryreloaded.farmables.grindables.GrindableStandard;
import powercrystals.minefactoryreloaded.farmables.grindables.GrindableZombiePigman;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableCocoa;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableCropPlant;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableMushroom;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableNetherWart;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableShrub;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableStandard;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableStemPlant;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableTreeLeaves;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableVine;
import powercrystals.minefactoryreloaded.farmables.harvestables.HarvestableWood;
import powercrystals.minefactoryreloaded.farmables.plantables.PlantableCocoa;
import powercrystals.minefactoryreloaded.farmables.plantables.PlantableCropPlant;
import powercrystals.minefactoryreloaded.farmables.plantables.PlantableNetherWart;
import powercrystals.minefactoryreloaded.farmables.plantables.PlantableStandard;
import powercrystals.minefactoryreloaded.farmables.ranchables.RanchableCow;
import powercrystals.minefactoryreloaded.farmables.ranchables.RanchableMooshroom;
import powercrystals.minefactoryreloaded.farmables.ranchables.RanchableSheep;
import powercrystals.minefactoryreloaded.farmables.ranchables.RanchableSquid;
import powercrystals.minefactoryreloaded.farmables.safarinethandlers.EntityAgeableHandler;
import powercrystals.minefactoryreloaded.farmables.safarinethandlers.EntityLivingHandler;
import powercrystals.minefactoryreloaded.farmables.safarinethandlers.SheepHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
@Mod(modid = "MFReloaded|CompatVanilla", name = "MFR Compat: Vanilla", version = MineFactoryReloadedCore.version, dependencies = "after:MFReloaded")
@NetworkMod(clientSideRequired = false, serverSideRequired = false)
public class Vanilla
{
@Init
public void load(FMLInitializationEvent event)
{
MFRRegistry.registerPlantable(new PlantableStandard(Block.sapling.blockID, Block.sapling.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Item.pumpkinSeeds.itemID, Block.pumpkinStem.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Item.melonSeeds.itemID, Block.melonStem.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Block.mushroomBrown.blockID, Block.mushroomBrown.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Block.mushroomRed.blockID, Block.mushroomRed.blockID));
MFRRegistry.registerPlantable(new PlantableCropPlant(Item.seeds.itemID, Block.crops.blockID));
MFRRegistry.registerPlantable(new PlantableCropPlant(Item.carrot.itemID, Block.carrot.blockID));
MFRRegistry.registerPlantable(new PlantableCropPlant(Item.potato.itemID, Block.potato.blockID));
MFRRegistry.registerPlantable(new PlantableNetherWart());
MFRRegistry.registerPlantable(new PlantableCocoa());
MFRRegistry.registerPlantable(new PlantableStandard(MineFactoryReloadedCore.rubberSaplingBlock.blockID, MineFactoryReloadedCore.rubberSaplingBlock.blockID));
MFRRegistry.registerHarvestable(new HarvestableWood());
MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(Block.leaves.blockID));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.reed.blockID, HarvestType.LeaveBottom));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.cactus.blockID, HarvestType.LeaveBottom));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.plantRed.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.plantYellow.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableShrub(Block.tallGrass.blockID));
MFRRegistry.registerHarvestable(new HarvestableShrub(Block.deadBush.blockID));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.mushroomCapBrown.blockID, HarvestType.Tree));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.mushroomCapRed.blockID, HarvestType.Tree));
MFRRegistry.registerHarvestable(new HarvestableMushroom(Block.mushroomBrown.blockID));
MFRRegistry.registerHarvestable(new HarvestableMushroom(Block.mushroomRed.blockID));
MFRRegistry.registerHarvestable(new HarvestableStemPlant(Block.pumpkin.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableStemPlant(Block.melon.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableCropPlant(Block.crops.blockID));
MFRRegistry.registerHarvestable(new HarvestableCropPlant(Block.carrot.blockID));
MFRRegistry.registerHarvestable(new HarvestableCropPlant(Block.potato.blockID));
MFRRegistry.registerHarvestable(new HarvestableVine());
MFRRegistry.registerHarvestable(new HarvestableNetherWart());
MFRRegistry.registerHarvestable(new HarvestableCocoa());
MFRRegistry.registerHarvestable(new HarvestableStandard(MineFactoryReloadedCore.rubberWoodBlock.blockID, HarvestType.Tree));
MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(MineFactoryReloadedCore.rubberLeavesBlock.blockID));
MFRRegistry.registerFertilizable(new FertilizableSapling(Block.sapling.blockID));
MFRRegistry.registerFertilizable(new FertilizableCropPlant(Block.crops.blockID));
MFRRegistry.registerFertilizable(new FertilizableCropPlant(Block.carrot.blockID));
MFRRegistry.registerFertilizable(new FertilizableCropPlant(Block.potato.blockID));
MFRRegistry.registerFertilizable(new FertilizableGiantMushroom(Block.mushroomBrown.blockID));
MFRRegistry.registerFertilizable(new FertilizableGiantMushroom(Block.mushroomRed.blockID));
MFRRegistry.registerFertilizable(new FertilizableStemPlants(Block.pumpkinStem.blockID));
MFRRegistry.registerFertilizable(new FertilizableStemPlants(Block.melonStem.blockID));
MFRRegistry.registerFertilizable(new FertilizableNetherWart());
MFRRegistry.registerFertilizable(new FertilizableCocoa());
MFRRegistry.registerFertilizable(new FertilizableGrass());
MFRRegistry.registerFertilizable(new FertilizableRubberSapling());
MFRRegistry.registerFertilizer(new FertilizerStandard(MineFactoryReloadedCore.fertilizerItem.itemID, 0));
if(MineFactoryReloadedCore.enableBonemealFertilizing.getBoolean(false))
{
MFRRegistry.registerFertilizer(new FertilizerStandard(Item.dyePowder.itemID, 15));
}
else
{
MFRRegistry.registerFertilizer(new FertilizerStandard(Item.dyePowder.itemID, 15, FertilizerType.Grass));
}
MFRRegistry.registerRanchable(new RanchableCow());
MFRRegistry.registerRanchable(new RanchableMooshroom());
MFRRegistry.registerRanchable(new RanchableSheep());
MFRRegistry.registerRanchable(new RanchableSquid());
MFRRegistry.registerGrindable(new GrindableStandard(EntityChicken.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.feather)),
new MobDrop(10, new ItemStack(Item.chickenRaw)),
new MobDrop(10, new ItemStack(Item.egg))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityCow.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.leather)),
new MobDrop(10, new ItemStack(Item.beefRaw))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityMooshroom.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.leather)),
new MobDrop(10, new ItemStack(Item.beefRaw))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityOcelot.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.fishRaw)),
new MobDrop(10, new ItemStack(Item.silk))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityPig.class, new ItemStack(Item.porkRaw)));
MFRRegistry.registerGrindable(new GrindableSheep());
MFRRegistry.registerGrindable(new GrindableStandard(EntitySquid.class, new ItemStack(Item.dyePowder)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityEnderman.class, new ItemStack(Item.enderPearl)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityWolf.class, new ItemStack(Item.bone)));
MFRRegistry.registerGrindable(new GrindableZombiePigman());
MFRRegistry.registerGrindable(new GrindableStandard(EntityBlaze.class, new ItemStack(Item.blazeRod)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityCaveSpider.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.silk)),
new MobDrop(10, new ItemStack(Item.spiderEye))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityCreeper.class, new ItemStack(Item.gunpowder)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityGhast.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.gunpowder)),
new MobDrop(2, new ItemStack(Item.ghastTear))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityMagmaCube.class, new ItemStack(Item.magmaCream)));
MFRRegistry.registerGrindable(new GrindableSkeleton());
MFRRegistry.registerGrindable(new GrindableStandard(EntitySlime.class, new ItemStack(Item.slimeBall)));
MFRRegistry.registerGrindable(new GrindableStandard(EntitySpider.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.silk)),
new MobDrop(10, new ItemStack(Item.spiderEye))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityWitch.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.glassBottle, 2)),
new MobDrop(10, new ItemStack(Item.lightStoneDust, 2)),
new MobDrop(10, new ItemStack(Item.gunpowder, 2)),
new MobDrop(10, new ItemStack(Item.redstone, 2)),
new MobDrop(10, new ItemStack(Item.spiderEye, 2)),
new MobDrop(10, new ItemStack(Item.stick, 2)),
new MobDrop(10, new ItemStack(Item.sugar, 2))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityZombie.class, new ItemStack(Item.rottenFlesh)));
MFRRegistry.registerSludgeDrop(25, new ItemStack(Block.sand));
MFRRegistry.registerSludgeDrop(20, new ItemStack(Block.dirt));
MFRRegistry.registerSludgeDrop(15, new ItemStack(Item.clay, 4));
MFRRegistry.registerSludgeDrop(1, new ItemStack(Block.slowSand));
MFRRegistry.registerBreederFood(EntityChicken.class, new ItemStack(Item.seeds));
MFRRegistry.registerBreederFood(EntityWolf.class, new ItemStack(Item.porkCooked));
MFRRegistry.registerBreederFood(EntityOcelot.class, new ItemStack(Item.fishRaw));
MFRRegistry.registerBreederFood(EntityPig.class, new ItemStack(Item.carrot));
MFRRegistry.registerSafariNetHandler(new EntityLivingHandler());
MFRRegistry.registerSafariNetHandler(new EntityAgeableHandler());
MFRRegistry.registerSafariNetHandler(new SheepHandler());
MFRRegistry.registerMobEggHandler(new VanillaEggHandler());
MFRRegistry.registerRubberTreeBiome("Swampland");
MFRRegistry.registerRubberTreeBiome("Forest");
MFRRegistry.registerRubberTreeBiome("Taiga");
MFRRegistry.registerRubberTreeBiome("TaigaHills");
MFRRegistry.registerRubberTreeBiome("Jungle");
MFRRegistry.registerRubberTreeBiome("JungleHills");
MFRRegistry.registerSafariNetBlacklist(EntityDragon.class);
MFRRegistry.registerSafariNetBlacklist(EntityWither.class);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityMooshroom.class), 20);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntitySlime.class), 20);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityCow.class), 100);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityChicken.class), 100);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityWitch.class), 10);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityGhast.class), 15);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityPig.class), 100);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityCreeper.class), 25);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntitySquid.class), 30);
- MFRRegistry.registerVillagerTradeMob(prepareMob(EntityOcelot.class), 40);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityMinecartHopper.class), 15);
NBTTagCompound chargedCreeper = prepareMob(EntityCreeper.class);
chargedCreeper.setBoolean("powered", true);
chargedCreeper.setShort("Fuse", (short)120);
MFRRegistry.registerVillagerTradeMob(chargedCreeper, 5);
NBTTagCompound armedTNT = prepareMob(EntityTNTPrimed.class);
armedTNT.setByte("Fuse", (byte)120);
MFRRegistry.registerVillagerTradeMob(armedTNT, 5);
}
private NBTTagCompound prepareMob(Class<? extends Entity> entity)
{
NBTTagCompound c = null;
try
{
Entity e = (Entity)entity.getConstructor(new Class[] {World.class}).newInstance(new Object[] { null });
if(e instanceof EntityLiving)
{
((EntityLiving)e).initCreature();
}
c = new NBTTagCompound();
e.writeToNBT(c);
e.addEntityID(c);
}
catch(Exception e)
{
e.printStackTrace();
}
return c;
}
}
| true | true | public void load(FMLInitializationEvent event)
{
MFRRegistry.registerPlantable(new PlantableStandard(Block.sapling.blockID, Block.sapling.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Item.pumpkinSeeds.itemID, Block.pumpkinStem.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Item.melonSeeds.itemID, Block.melonStem.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Block.mushroomBrown.blockID, Block.mushroomBrown.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Block.mushroomRed.blockID, Block.mushroomRed.blockID));
MFRRegistry.registerPlantable(new PlantableCropPlant(Item.seeds.itemID, Block.crops.blockID));
MFRRegistry.registerPlantable(new PlantableCropPlant(Item.carrot.itemID, Block.carrot.blockID));
MFRRegistry.registerPlantable(new PlantableCropPlant(Item.potato.itemID, Block.potato.blockID));
MFRRegistry.registerPlantable(new PlantableNetherWart());
MFRRegistry.registerPlantable(new PlantableCocoa());
MFRRegistry.registerPlantable(new PlantableStandard(MineFactoryReloadedCore.rubberSaplingBlock.blockID, MineFactoryReloadedCore.rubberSaplingBlock.blockID));
MFRRegistry.registerHarvestable(new HarvestableWood());
MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(Block.leaves.blockID));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.reed.blockID, HarvestType.LeaveBottom));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.cactus.blockID, HarvestType.LeaveBottom));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.plantRed.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.plantYellow.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableShrub(Block.tallGrass.blockID));
MFRRegistry.registerHarvestable(new HarvestableShrub(Block.deadBush.blockID));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.mushroomCapBrown.blockID, HarvestType.Tree));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.mushroomCapRed.blockID, HarvestType.Tree));
MFRRegistry.registerHarvestable(new HarvestableMushroom(Block.mushroomBrown.blockID));
MFRRegistry.registerHarvestable(new HarvestableMushroom(Block.mushroomRed.blockID));
MFRRegistry.registerHarvestable(new HarvestableStemPlant(Block.pumpkin.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableStemPlant(Block.melon.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableCropPlant(Block.crops.blockID));
MFRRegistry.registerHarvestable(new HarvestableCropPlant(Block.carrot.blockID));
MFRRegistry.registerHarvestable(new HarvestableCropPlant(Block.potato.blockID));
MFRRegistry.registerHarvestable(new HarvestableVine());
MFRRegistry.registerHarvestable(new HarvestableNetherWart());
MFRRegistry.registerHarvestable(new HarvestableCocoa());
MFRRegistry.registerHarvestable(new HarvestableStandard(MineFactoryReloadedCore.rubberWoodBlock.blockID, HarvestType.Tree));
MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(MineFactoryReloadedCore.rubberLeavesBlock.blockID));
MFRRegistry.registerFertilizable(new FertilizableSapling(Block.sapling.blockID));
MFRRegistry.registerFertilizable(new FertilizableCropPlant(Block.crops.blockID));
MFRRegistry.registerFertilizable(new FertilizableCropPlant(Block.carrot.blockID));
MFRRegistry.registerFertilizable(new FertilizableCropPlant(Block.potato.blockID));
MFRRegistry.registerFertilizable(new FertilizableGiantMushroom(Block.mushroomBrown.blockID));
MFRRegistry.registerFertilizable(new FertilizableGiantMushroom(Block.mushroomRed.blockID));
MFRRegistry.registerFertilizable(new FertilizableStemPlants(Block.pumpkinStem.blockID));
MFRRegistry.registerFertilizable(new FertilizableStemPlants(Block.melonStem.blockID));
MFRRegistry.registerFertilizable(new FertilizableNetherWart());
MFRRegistry.registerFertilizable(new FertilizableCocoa());
MFRRegistry.registerFertilizable(new FertilizableGrass());
MFRRegistry.registerFertilizable(new FertilizableRubberSapling());
MFRRegistry.registerFertilizer(new FertilizerStandard(MineFactoryReloadedCore.fertilizerItem.itemID, 0));
if(MineFactoryReloadedCore.enableBonemealFertilizing.getBoolean(false))
{
MFRRegistry.registerFertilizer(new FertilizerStandard(Item.dyePowder.itemID, 15));
}
else
{
MFRRegistry.registerFertilizer(new FertilizerStandard(Item.dyePowder.itemID, 15, FertilizerType.Grass));
}
MFRRegistry.registerRanchable(new RanchableCow());
MFRRegistry.registerRanchable(new RanchableMooshroom());
MFRRegistry.registerRanchable(new RanchableSheep());
MFRRegistry.registerRanchable(new RanchableSquid());
MFRRegistry.registerGrindable(new GrindableStandard(EntityChicken.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.feather)),
new MobDrop(10, new ItemStack(Item.chickenRaw)),
new MobDrop(10, new ItemStack(Item.egg))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityCow.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.leather)),
new MobDrop(10, new ItemStack(Item.beefRaw))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityMooshroom.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.leather)),
new MobDrop(10, new ItemStack(Item.beefRaw))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityOcelot.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.fishRaw)),
new MobDrop(10, new ItemStack(Item.silk))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityPig.class, new ItemStack(Item.porkRaw)));
MFRRegistry.registerGrindable(new GrindableSheep());
MFRRegistry.registerGrindable(new GrindableStandard(EntitySquid.class, new ItemStack(Item.dyePowder)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityEnderman.class, new ItemStack(Item.enderPearl)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityWolf.class, new ItemStack(Item.bone)));
MFRRegistry.registerGrindable(new GrindableZombiePigman());
MFRRegistry.registerGrindable(new GrindableStandard(EntityBlaze.class, new ItemStack(Item.blazeRod)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityCaveSpider.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.silk)),
new MobDrop(10, new ItemStack(Item.spiderEye))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityCreeper.class, new ItemStack(Item.gunpowder)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityGhast.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.gunpowder)),
new MobDrop(2, new ItemStack(Item.ghastTear))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityMagmaCube.class, new ItemStack(Item.magmaCream)));
MFRRegistry.registerGrindable(new GrindableSkeleton());
MFRRegistry.registerGrindable(new GrindableStandard(EntitySlime.class, new ItemStack(Item.slimeBall)));
MFRRegistry.registerGrindable(new GrindableStandard(EntitySpider.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.silk)),
new MobDrop(10, new ItemStack(Item.spiderEye))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityWitch.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.glassBottle, 2)),
new MobDrop(10, new ItemStack(Item.lightStoneDust, 2)),
new MobDrop(10, new ItemStack(Item.gunpowder, 2)),
new MobDrop(10, new ItemStack(Item.redstone, 2)),
new MobDrop(10, new ItemStack(Item.spiderEye, 2)),
new MobDrop(10, new ItemStack(Item.stick, 2)),
new MobDrop(10, new ItemStack(Item.sugar, 2))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityZombie.class, new ItemStack(Item.rottenFlesh)));
MFRRegistry.registerSludgeDrop(25, new ItemStack(Block.sand));
MFRRegistry.registerSludgeDrop(20, new ItemStack(Block.dirt));
MFRRegistry.registerSludgeDrop(15, new ItemStack(Item.clay, 4));
MFRRegistry.registerSludgeDrop(1, new ItemStack(Block.slowSand));
MFRRegistry.registerBreederFood(EntityChicken.class, new ItemStack(Item.seeds));
MFRRegistry.registerBreederFood(EntityWolf.class, new ItemStack(Item.porkCooked));
MFRRegistry.registerBreederFood(EntityOcelot.class, new ItemStack(Item.fishRaw));
MFRRegistry.registerBreederFood(EntityPig.class, new ItemStack(Item.carrot));
MFRRegistry.registerSafariNetHandler(new EntityLivingHandler());
MFRRegistry.registerSafariNetHandler(new EntityAgeableHandler());
MFRRegistry.registerSafariNetHandler(new SheepHandler());
MFRRegistry.registerMobEggHandler(new VanillaEggHandler());
MFRRegistry.registerRubberTreeBiome("Swampland");
MFRRegistry.registerRubberTreeBiome("Forest");
MFRRegistry.registerRubberTreeBiome("Taiga");
MFRRegistry.registerRubberTreeBiome("TaigaHills");
MFRRegistry.registerRubberTreeBiome("Jungle");
MFRRegistry.registerRubberTreeBiome("JungleHills");
MFRRegistry.registerSafariNetBlacklist(EntityDragon.class);
MFRRegistry.registerSafariNetBlacklist(EntityWither.class);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityMooshroom.class), 20);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntitySlime.class), 20);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityCow.class), 100);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityChicken.class), 100);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityWitch.class), 10);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityGhast.class), 15);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityPig.class), 100);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityCreeper.class), 25);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntitySquid.class), 30);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityOcelot.class), 40);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityMinecartHopper.class), 15);
NBTTagCompound chargedCreeper = prepareMob(EntityCreeper.class);
chargedCreeper.setBoolean("powered", true);
chargedCreeper.setShort("Fuse", (short)120);
MFRRegistry.registerVillagerTradeMob(chargedCreeper, 5);
NBTTagCompound armedTNT = prepareMob(EntityTNTPrimed.class);
armedTNT.setByte("Fuse", (byte)120);
MFRRegistry.registerVillagerTradeMob(armedTNT, 5);
}
| public void load(FMLInitializationEvent event)
{
MFRRegistry.registerPlantable(new PlantableStandard(Block.sapling.blockID, Block.sapling.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Item.pumpkinSeeds.itemID, Block.pumpkinStem.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Item.melonSeeds.itemID, Block.melonStem.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Block.mushroomBrown.blockID, Block.mushroomBrown.blockID));
MFRRegistry.registerPlantable(new PlantableStandard(Block.mushroomRed.blockID, Block.mushroomRed.blockID));
MFRRegistry.registerPlantable(new PlantableCropPlant(Item.seeds.itemID, Block.crops.blockID));
MFRRegistry.registerPlantable(new PlantableCropPlant(Item.carrot.itemID, Block.carrot.blockID));
MFRRegistry.registerPlantable(new PlantableCropPlant(Item.potato.itemID, Block.potato.blockID));
MFRRegistry.registerPlantable(new PlantableNetherWart());
MFRRegistry.registerPlantable(new PlantableCocoa());
MFRRegistry.registerPlantable(new PlantableStandard(MineFactoryReloadedCore.rubberSaplingBlock.blockID, MineFactoryReloadedCore.rubberSaplingBlock.blockID));
MFRRegistry.registerHarvestable(new HarvestableWood());
MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(Block.leaves.blockID));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.reed.blockID, HarvestType.LeaveBottom));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.cactus.blockID, HarvestType.LeaveBottom));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.plantRed.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.plantYellow.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableShrub(Block.tallGrass.blockID));
MFRRegistry.registerHarvestable(new HarvestableShrub(Block.deadBush.blockID));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.mushroomCapBrown.blockID, HarvestType.Tree));
MFRRegistry.registerHarvestable(new HarvestableStandard(Block.mushroomCapRed.blockID, HarvestType.Tree));
MFRRegistry.registerHarvestable(new HarvestableMushroom(Block.mushroomBrown.blockID));
MFRRegistry.registerHarvestable(new HarvestableMushroom(Block.mushroomRed.blockID));
MFRRegistry.registerHarvestable(new HarvestableStemPlant(Block.pumpkin.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableStemPlant(Block.melon.blockID, HarvestType.Normal));
MFRRegistry.registerHarvestable(new HarvestableCropPlant(Block.crops.blockID));
MFRRegistry.registerHarvestable(new HarvestableCropPlant(Block.carrot.blockID));
MFRRegistry.registerHarvestable(new HarvestableCropPlant(Block.potato.blockID));
MFRRegistry.registerHarvestable(new HarvestableVine());
MFRRegistry.registerHarvestable(new HarvestableNetherWart());
MFRRegistry.registerHarvestable(new HarvestableCocoa());
MFRRegistry.registerHarvestable(new HarvestableStandard(MineFactoryReloadedCore.rubberWoodBlock.blockID, HarvestType.Tree));
MFRRegistry.registerHarvestable(new HarvestableTreeLeaves(MineFactoryReloadedCore.rubberLeavesBlock.blockID));
MFRRegistry.registerFertilizable(new FertilizableSapling(Block.sapling.blockID));
MFRRegistry.registerFertilizable(new FertilizableCropPlant(Block.crops.blockID));
MFRRegistry.registerFertilizable(new FertilizableCropPlant(Block.carrot.blockID));
MFRRegistry.registerFertilizable(new FertilizableCropPlant(Block.potato.blockID));
MFRRegistry.registerFertilizable(new FertilizableGiantMushroom(Block.mushroomBrown.blockID));
MFRRegistry.registerFertilizable(new FertilizableGiantMushroom(Block.mushroomRed.blockID));
MFRRegistry.registerFertilizable(new FertilizableStemPlants(Block.pumpkinStem.blockID));
MFRRegistry.registerFertilizable(new FertilizableStemPlants(Block.melonStem.blockID));
MFRRegistry.registerFertilizable(new FertilizableNetherWart());
MFRRegistry.registerFertilizable(new FertilizableCocoa());
MFRRegistry.registerFertilizable(new FertilizableGrass());
MFRRegistry.registerFertilizable(new FertilizableRubberSapling());
MFRRegistry.registerFertilizer(new FertilizerStandard(MineFactoryReloadedCore.fertilizerItem.itemID, 0));
if(MineFactoryReloadedCore.enableBonemealFertilizing.getBoolean(false))
{
MFRRegistry.registerFertilizer(new FertilizerStandard(Item.dyePowder.itemID, 15));
}
else
{
MFRRegistry.registerFertilizer(new FertilizerStandard(Item.dyePowder.itemID, 15, FertilizerType.Grass));
}
MFRRegistry.registerRanchable(new RanchableCow());
MFRRegistry.registerRanchable(new RanchableMooshroom());
MFRRegistry.registerRanchable(new RanchableSheep());
MFRRegistry.registerRanchable(new RanchableSquid());
MFRRegistry.registerGrindable(new GrindableStandard(EntityChicken.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.feather)),
new MobDrop(10, new ItemStack(Item.chickenRaw)),
new MobDrop(10, new ItemStack(Item.egg))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityCow.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.leather)),
new MobDrop(10, new ItemStack(Item.beefRaw))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityMooshroom.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.leather)),
new MobDrop(10, new ItemStack(Item.beefRaw))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityOcelot.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.fishRaw)),
new MobDrop(10, new ItemStack(Item.silk))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityPig.class, new ItemStack(Item.porkRaw)));
MFRRegistry.registerGrindable(new GrindableSheep());
MFRRegistry.registerGrindable(new GrindableStandard(EntitySquid.class, new ItemStack(Item.dyePowder)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityEnderman.class, new ItemStack(Item.enderPearl)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityWolf.class, new ItemStack(Item.bone)));
MFRRegistry.registerGrindable(new GrindableZombiePigman());
MFRRegistry.registerGrindable(new GrindableStandard(EntityBlaze.class, new ItemStack(Item.blazeRod)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityCaveSpider.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.silk)),
new MobDrop(10, new ItemStack(Item.spiderEye))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityCreeper.class, new ItemStack(Item.gunpowder)));
MFRRegistry.registerGrindable(new GrindableStandard(EntityGhast.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.gunpowder)),
new MobDrop(2, new ItemStack(Item.ghastTear))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityMagmaCube.class, new ItemStack(Item.magmaCream)));
MFRRegistry.registerGrindable(new GrindableSkeleton());
MFRRegistry.registerGrindable(new GrindableStandard(EntitySlime.class, new ItemStack(Item.slimeBall)));
MFRRegistry.registerGrindable(new GrindableStandard(EntitySpider.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.silk)),
new MobDrop(10, new ItemStack(Item.spiderEye))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityWitch.class, new MobDrop[]
{
new MobDrop(10, new ItemStack(Item.glassBottle, 2)),
new MobDrop(10, new ItemStack(Item.lightStoneDust, 2)),
new MobDrop(10, new ItemStack(Item.gunpowder, 2)),
new MobDrop(10, new ItemStack(Item.redstone, 2)),
new MobDrop(10, new ItemStack(Item.spiderEye, 2)),
new MobDrop(10, new ItemStack(Item.stick, 2)),
new MobDrop(10, new ItemStack(Item.sugar, 2))
}));
MFRRegistry.registerGrindable(new GrindableStandard(EntityZombie.class, new ItemStack(Item.rottenFlesh)));
MFRRegistry.registerSludgeDrop(25, new ItemStack(Block.sand));
MFRRegistry.registerSludgeDrop(20, new ItemStack(Block.dirt));
MFRRegistry.registerSludgeDrop(15, new ItemStack(Item.clay, 4));
MFRRegistry.registerSludgeDrop(1, new ItemStack(Block.slowSand));
MFRRegistry.registerBreederFood(EntityChicken.class, new ItemStack(Item.seeds));
MFRRegistry.registerBreederFood(EntityWolf.class, new ItemStack(Item.porkCooked));
MFRRegistry.registerBreederFood(EntityOcelot.class, new ItemStack(Item.fishRaw));
MFRRegistry.registerBreederFood(EntityPig.class, new ItemStack(Item.carrot));
MFRRegistry.registerSafariNetHandler(new EntityLivingHandler());
MFRRegistry.registerSafariNetHandler(new EntityAgeableHandler());
MFRRegistry.registerSafariNetHandler(new SheepHandler());
MFRRegistry.registerMobEggHandler(new VanillaEggHandler());
MFRRegistry.registerRubberTreeBiome("Swampland");
MFRRegistry.registerRubberTreeBiome("Forest");
MFRRegistry.registerRubberTreeBiome("Taiga");
MFRRegistry.registerRubberTreeBiome("TaigaHills");
MFRRegistry.registerRubberTreeBiome("Jungle");
MFRRegistry.registerRubberTreeBiome("JungleHills");
MFRRegistry.registerSafariNetBlacklist(EntityDragon.class);
MFRRegistry.registerSafariNetBlacklist(EntityWither.class);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityMooshroom.class), 20);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntitySlime.class), 20);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityCow.class), 100);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityChicken.class), 100);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityWitch.class), 10);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityGhast.class), 15);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityPig.class), 100);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityCreeper.class), 25);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntitySquid.class), 30);
MFRRegistry.registerVillagerTradeMob(prepareMob(EntityMinecartHopper.class), 15);
NBTTagCompound chargedCreeper = prepareMob(EntityCreeper.class);
chargedCreeper.setBoolean("powered", true);
chargedCreeper.setShort("Fuse", (short)120);
MFRRegistry.registerVillagerTradeMob(chargedCreeper, 5);
NBTTagCompound armedTNT = prepareMob(EntityTNTPrimed.class);
armedTNT.setByte("Fuse", (byte)120);
MFRRegistry.registerVillagerTradeMob(armedTNT, 5);
}
|
diff --git a/test/jdbc/Connection/ConnTest1.java b/test/jdbc/Connection/ConnTest1.java
index ab32232b..2370d74b 100755
--- a/test/jdbc/Connection/ConnTest1.java
+++ b/test/jdbc/Connection/ConnTest1.java
@@ -1,49 +1,50 @@
//Test connection default rollback mechanism
//close the connection without committing the transaction
import java.sql.*;
public class ConnTest1
{
public static void main(String[] args)
{
try
{
Class.forName("csql.jdbc.JdbcSqlDriver");
Connection con = DriverManager.getConnection("jdbc:csql", "root", "manager");
+ con.setAutoCommit( false );
Statement cStmt = con.createStatement();
int ret =0;
cStmt.execute("CREATE TABLE T1 (f1 integer, f2 char (20));");
PreparedStatement stmt = null;
stmt = con.prepareStatement("INSERT INTO T1 VALUES (?, ?);");
int count=0;
for (int i =0 ; i< 10 ; i++) {
stmt.setInt(1, i);
stmt.setString(2, String.valueOf(i+100));
ret = stmt.executeUpdate();
if (ret !=1) break;
count++;
}
con.close();
System.out.println("Total tuples inserted "+ count);
con = DriverManager.getConnection("jdbc:csql", "root", "manager");
cStmt = con.createStatement();
System.out.println("Listing tuples:");
ResultSet rs = cStmt.executeQuery("SELECT * from T1;");
count =0;
while (rs.next())
{
System.out.println("Tuple value is " + rs.getInt(1)+ " "+ rs.getString(2));
count++;
}
System.out.println("Total tuples selected "+ count);
rs.close();
con.commit();
cStmt.execute("DROP TABLE T1;");
con.close();
}catch(Exception e) {
System.out.println("Exception in Test: "+e);
e.getStackTrace();
}
}
}
| true | true | public static void main(String[] args)
{
try
{
Class.forName("csql.jdbc.JdbcSqlDriver");
Connection con = DriverManager.getConnection("jdbc:csql", "root", "manager");
Statement cStmt = con.createStatement();
int ret =0;
cStmt.execute("CREATE TABLE T1 (f1 integer, f2 char (20));");
PreparedStatement stmt = null;
stmt = con.prepareStatement("INSERT INTO T1 VALUES (?, ?);");
int count=0;
for (int i =0 ; i< 10 ; i++) {
stmt.setInt(1, i);
stmt.setString(2, String.valueOf(i+100));
ret = stmt.executeUpdate();
if (ret !=1) break;
count++;
}
con.close();
System.out.println("Total tuples inserted "+ count);
con = DriverManager.getConnection("jdbc:csql", "root", "manager");
cStmt = con.createStatement();
System.out.println("Listing tuples:");
ResultSet rs = cStmt.executeQuery("SELECT * from T1;");
count =0;
while (rs.next())
{
System.out.println("Tuple value is " + rs.getInt(1)+ " "+ rs.getString(2));
count++;
}
System.out.println("Total tuples selected "+ count);
rs.close();
con.commit();
cStmt.execute("DROP TABLE T1;");
con.close();
}catch(Exception e) {
System.out.println("Exception in Test: "+e);
e.getStackTrace();
}
}
| public static void main(String[] args)
{
try
{
Class.forName("csql.jdbc.JdbcSqlDriver");
Connection con = DriverManager.getConnection("jdbc:csql", "root", "manager");
con.setAutoCommit( false );
Statement cStmt = con.createStatement();
int ret =0;
cStmt.execute("CREATE TABLE T1 (f1 integer, f2 char (20));");
PreparedStatement stmt = null;
stmt = con.prepareStatement("INSERT INTO T1 VALUES (?, ?);");
int count=0;
for (int i =0 ; i< 10 ; i++) {
stmt.setInt(1, i);
stmt.setString(2, String.valueOf(i+100));
ret = stmt.executeUpdate();
if (ret !=1) break;
count++;
}
con.close();
System.out.println("Total tuples inserted "+ count);
con = DriverManager.getConnection("jdbc:csql", "root", "manager");
cStmt = con.createStatement();
System.out.println("Listing tuples:");
ResultSet rs = cStmt.executeQuery("SELECT * from T1;");
count =0;
while (rs.next())
{
System.out.println("Tuple value is " + rs.getInt(1)+ " "+ rs.getString(2));
count++;
}
System.out.println("Total tuples selected "+ count);
rs.close();
con.commit();
cStmt.execute("DROP TABLE T1;");
con.close();
}catch(Exception e) {
System.out.println("Exception in Test: "+e);
e.getStackTrace();
}
}
|
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/ui/eclipse/editors/CoordinatorEditor.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/ui/eclipse/editors/CoordinatorEditor.java
index fe19bcdc..ecbd8be3 100644
--- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/ui/eclipse/editors/CoordinatorEditor.java
+++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/ui/eclipse/editors/CoordinatorEditor.java
@@ -1,573 +1,572 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* 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.
******************************************************************************/
package de.tuilmenau.ics.fog.ui.eclipse.editors;
import java.rmi.RemoteException;
import java.text.Collator;
import java.util.Locale;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import de.tuilmenau.ics.fog.eclipse.ui.editors.EditorInput;
import de.tuilmenau.ics.fog.facade.Description;
import de.tuilmenau.ics.fog.facade.Name;
import de.tuilmenau.ics.fog.facade.RequirementsException;
import de.tuilmenau.ics.fog.facade.RoutingException;
import de.tuilmenau.ics.fog.facade.Signature;
import de.tuilmenau.ics.fog.packets.hierarchical.TopologyEnvelope.FIBEntry;
import de.tuilmenau.ics.fog.routing.Route;
import de.tuilmenau.ics.fog.routing.hierarchical.Coordinator;
import de.tuilmenau.ics.fog.routing.hierarchical.CoordinatorCEPDemultiplexed;
import de.tuilmenau.ics.fog.routing.hierarchical.ElectionProcess;
import de.tuilmenau.ics.fog.routing.hierarchical.ElectionProcess.ElectionManager;
import de.tuilmenau.ics.fog.routing.hierarchical.HRMConfig;
import de.tuilmenau.ics.fog.routing.hierarchical.clusters.AttachedCluster;
import de.tuilmenau.ics.fog.routing.hierarchical.clusters.Cluster;
import de.tuilmenau.ics.fog.routing.hierarchical.clusters.ClusterDummy;
import de.tuilmenau.ics.fog.routing.hierarchical.clusters.ClusterManager;
import de.tuilmenau.ics.fog.routing.hierarchical.clusters.IntermediateCluster;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID;
import de.tuilmenau.ics.fog.ui.Logging;
/**
* Editor for showing and editing the internals of a bus.
*/
public class CoordinatorEditor extends EditorPart
{
private Coordinator mCoordinator = null;
private Composite mShell = null;
private ScrolledComposite mScroller = null;
private Composite mContainer = null;
public CoordinatorEditor()
{
}
@Override
public void createPartControl(Composite parent)
{
mShell = parent;
mShell.setLayout(new FillLayout());
mScroller = new ScrolledComposite(mShell, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
mContainer = new Composite(mScroller, SWT.NONE);
mScroller.setContent(mContainer);
GridLayout tLayout = new GridLayout(1, true);
mContainer.setLayout(tLayout);
for(int i = 0; i <= HRMConfig.Routing.HIERARCHY_LEVEL_AMOUNT; i++) {
Logging.log(this, "Amount of found clusters: " + mCoordinator.getClusters().size());
int j = -1;
for(Cluster tCluster : mCoordinator.getClusters()) {
j++;
Logging.log(this, "Printing cluster " + j + ": " + tCluster.toString());
if( !(tCluster instanceof AttachedCluster) && tCluster.getLevel() == i) {
printCluster(tCluster);
}
}
}
Text overviewText = new Text(mContainer, SWT.BORDER);;
overviewText.setText("Approved signatures: " + mCoordinator.getApprovedSignatures());
int j = 0;
final Table tMappingTable = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnHRMID = new TableColumn(tMappingTable, SWT.NONE, 0);
tColumnHRMID.setText("HRMID");
TableColumn tColumnNextHop = new TableColumn(tMappingTable, SWT.NONE, 1);
tColumnNextHop.setText("next hop");
TableColumn tColumnNextCluster = new TableColumn(tMappingTable, SWT.NONE, 2);
tColumnNextCluster.setText("next cluster");
TableColumn tColumnFarthestCluster = new TableColumn(tMappingTable, SWT.NONE, 3);
tColumnFarthestCluster.setText("farthest cluster");
TableColumn tColumnRoute = new TableColumn(tMappingTable, SWT.NONE, 4);
tColumnRoute.setText("route");
TableColumn tColumnOrigin = new TableColumn(tMappingTable, SWT.NONE, 5);
tColumnOrigin.setText("origin");
if(mCoordinator.getHRS().getRoutingTable() != null && !mCoordinator.getHRS().getRoutingTable().isEmpty()) {
for(HRMID tHRMID : mCoordinator.getHRS().getRoutingTable().keySet()) {
TableItem item = new TableItem(tMappingTable, SWT.NONE, j);
item.setText(0, tHRMID != null ? tHRMID.toString() : "");
item.setText(1, mCoordinator.getHRS().getFIBEntry(tHRMID).getNextHop() != null ? mCoordinator.getHRS().getFIBEntry(tHRMID).getNextHop().toString() : "UNKNOWN");
item.setText(2, mCoordinator.getHRS().getFIBEntry(tHRMID).getNextCluster()!=null && mCoordinator.getCluster(mCoordinator.getHRS().getFIBEntry(tHRMID).getNextCluster()) != null ? mCoordinator.getCluster(mCoordinator.getHRS().getFIBEntry(tHRMID).getNextCluster()).toString() : "UNKNOWN");
item.setText(3, mCoordinator.getHRS().getFIBEntry(tHRMID).getFarthestClusterInDirection()!=null && mCoordinator.getCluster(mCoordinator.getHRS().getFIBEntry(tHRMID).getFarthestClusterInDirection()) != null ? mCoordinator.getCluster(mCoordinator.getHRS().getFIBEntry(tHRMID).getFarthestClusterInDirection()).toString() : "UNKNOWN");
item.setText(4, mCoordinator.getHRS().getFIBEntry(tHRMID).getRouteToTarget()!=null ? mCoordinator.getHRS().getFIBEntry(tHRMID).getRouteToTarget().toString() : "UNKNOWN");
item.setText(5, mCoordinator.getHRS().getFIBEntry(tHRMID).getSignature()!=null ? mCoordinator.getHRS().getFIBEntry(tHRMID).getSignature().toString() : "UNKNOWN");
j++;
}
}
TableColumn[] columns = tMappingTable.getColumns();
for(int k=0; k<columns.length; k++) columns[k].pack();
tMappingTable.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
tMappingTable.setHeaderVisible(true);
tMappingTable.setLinesVisible(true);
tColumnHRMID.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
// sort column 2
TableItem[] items = tMappingTable.getItems();
Collator collator = Collator.getInstance(Locale.getDefault());
for (int i = 1; i < items.length; i++) {
String value1 = items[i].getText(1);
for (int j = 0; j < i; j++) {
String value2 = items[j].getText(1);
if (collator.compare(value1, value2) < 0) {
String[] values = { items[i].getText(0),
items[i].getText(1) };
items[i].dispose();
TableItem item = new TableItem(tMappingTable, SWT.NONE, j);
item.setText(values);
items = tMappingTable.getItems();
break;
}
}
}
}
});
mContainer.setSize(mContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
public class ElectionOnClusterListener implements Listener
{
private IntermediateCluster mCluster = null;
public ElectionOnClusterListener(IntermediateCluster pCluster)
{
super();
mCluster = pCluster;
}
@Override
public void handleEvent(Event event)
{
ElectionManager.getElectionManager().getElectionProcess(mCluster.getLevel(), mCluster.getClusterID()).start();
}
}
public class ElectionOnAllClustersListener implements Listener
{
private IntermediateCluster mCluster = null;
public ElectionOnAllClustersListener(IntermediateCluster pCluster)
{
super();
mCluster = pCluster;
}
@Override
public void handleEvent(Event event)
{
Logging.log("Available Election Processes: ");
for(ElectionProcess tProcess : ElectionManager.getElectionManager().getAllElections()) {
Logging.log(tProcess.toString());
}
for(ElectionProcess tProcess : ElectionManager.getElectionManager().getProcessesOnLevel(mCluster.getLevel())) {
boolean tStartProcess=true;
for(Cluster tCluster : tProcess.getParticipatingClusters()) {
for(CoordinatorCEPDemultiplexed tCEP : tCluster.getParticipatingCEPs()) {
if(tCEP.isEdgeCEP()) {
tStartProcess = false;
}
}
}
if(tStartProcess) {
tProcess.start();
}
}
}
}
public class AbovePreparationOnAllClustersListener implements Listener
{
private IntermediateCluster mCluster = null;
public AbovePreparationOnAllClustersListener(IntermediateCluster pCluster)
{
super();
mCluster = pCluster;
}
@Override
public void handleEvent(Event event)
{
Logging.log("Available Election Processes: ");
for(ElectionProcess tProcess : ElectionManager.getElectionManager().getAllElections()) {
Logging.log(tProcess.toString());
}
for(ElectionProcess tProcess : ElectionManager.getElectionManager().getProcessesOnLevel(mCluster.getLevel())) {
synchronized(tProcess) {
tProcess.notifyAll();
}
}
}
}
public class AbovePreparationOnClusterListener implements Listener
{
private IntermediateCluster mCluster = null;
public AbovePreparationOnClusterListener(IntermediateCluster pCluster)
{
super();
mCluster = pCluster;
}
@Override
public void handleEvent(Event event)
{
synchronized(ElectionManager.getElectionManager().getElectionProcess(mCluster.getLevel(), mCluster.getClusterID())) {
ElectionManager.getElectionManager().getElectionProcess(mCluster.getLevel(), mCluster.getClusterID()).notifyAll();
}
}
}
public class AddressDistributionListener implements Listener
{
private IntermediateCluster mCluster = null;
public AddressDistributionListener(IntermediateCluster pCluster)
{
super();
mCluster = pCluster;
}
@Override
public void handleEvent(Event event)
{
final ClusterManager tManager = new ClusterManager(mCluster, mCluster.getLevel()+1, new HRMID(0));
new Thread() {
public void run()
{
try {
tManager.distributeAddresses();
} catch (RoutingException e) {
e.printStackTrace();
} catch (RequirementsException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}.start();
}
}
public void printCluster(Cluster pCluster)
{
Text overviewText = new Text(mContainer, SWT.BORDER);;
overviewText.setText(pCluster.toString());
if(pCluster instanceof IntermediateCluster) {
ToolBar tToolbar = new ToolBar(mContainer, SWT.NONE);
ToolItem toolItem1 = new ToolItem(tToolbar, SWT.PUSH);
toolItem1.setText("Election");
ToolItem toolItem2 = new ToolItem(tToolbar, SWT.PUSH);
toolItem2.setText("Elect(all)");
ToolItem toolItem3 = new ToolItem(tToolbar, SWT.PUSH);
toolItem3.setText("Prepare Above");
ToolItem toolItem4 = new ToolItem(tToolbar, SWT.PUSH);
toolItem4.setText("Prepare Above (all)");
ToolItem toolItem5 = new ToolItem(tToolbar, SWT.PUSH);
toolItem5.setText("Distribute Addresses");
toolItem1.addListener(SWT.Selection, new ElectionOnClusterListener((IntermediateCluster)pCluster));
toolItem2.addListener(SWT.Selection, new ElectionOnAllClustersListener((IntermediateCluster)pCluster));
toolItem3.addListener(SWT.Selection, new AbovePreparationOnClusterListener((IntermediateCluster)pCluster));
toolItem4.addListener(SWT.Selection, new AbovePreparationOnAllClustersListener((IntermediateCluster)pCluster));
toolItem5.addListener(SWT.Selection, new AddressDistributionListener((IntermediateCluster)pCluster));
tToolbar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
}
Table tTable = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnCoordinator = new TableColumn(tTable, SWT.NONE, 0);
tColumnCoordinator.setText("Coordinator");
TableColumn tColumnCEP = new TableColumn(tTable, SWT.NONE, 1);
tColumnCEP.setText("Connection Endpoint");
TableColumn tColumnTargetCovered = new TableColumn(tTable, SWT.NONE, 2);
tColumnTargetCovered.setText("Target Covered");
TableColumn tColumnPartofCluster = new TableColumn(tTable, SWT.NONE, 3);
tColumnPartofCluster.setText("Part of Cluster");
TableColumn tColumnPeerPriority = new TableColumn(tTable, SWT.NONE, 4);
tColumnPeerPriority.setText("Peer Priority");
TableColumn tColumnNegotiator = new TableColumn(tTable, SWT.NONE, 5);
tColumnNegotiator.setText("Negotiatoting Cluster");
TableColumn tColumnAnnouncerNegotiator = new TableColumn(tTable, SWT.NONE, 6);
tColumnAnnouncerNegotiator.setText("Announcers negotiator");
TableColumn tColumnRoute = new TableColumn(tTable, SWT.NONE, 7);
tColumnRoute.setText("route");
TableColumn tColumnBorder = new TableColumn(tTable, SWT.NONE, 8);
tColumnBorder.setText("received BNA");
tTable.setHeaderVisible(true);
tTable.setLinesVisible(true);
- int j = -1;
+ int j = 0;
Logging.log(this, "Amount of participating CEPs is " + pCluster.getParticipatingCEPs().size());
for(CoordinatorCEPDemultiplexed tCEP : pCluster.getParticipatingCEPs()) {
- j++;
Logging.log(this, "Printing table item number " + j);
TableItem item = new TableItem(tTable, SWT.NONE, j);
item.setText(0, (pCluster.getCoordinatorSignature() != null ? pCluster.getCoordinatorSignature().toString() : ""));
Name tPeerAddress = tCEP.getPeerName();
item.setText(1, tPeerAddress.toString());
item.setText(2, tCEP.hasRequestedCoordinator() ? Boolean.toString(tCEP.knowsCoordinator()) : "UNKNOWN");
item.setText(3, Boolean.toString(tCEP.isPartOfMyCluster()));
item.setText(4, (tCEP.getPeerPriority() != 0 ? Float.toString(tCEP.getPeerPriority()) : "UNKNOWN"));
item.setText(5, (tCEP.getRemoteCluster() != null ? tCEP.getRemoteCluster().toString() : "UNKNOWN"));
if(tCEP.getRemoteCluster() != null && tCEP.getRemoteCluster() instanceof AttachedCluster && ((AttachedCluster)tCEP.getRemoteCluster()).getAnnouncedCEP(tCEP.getRemoteCluster()) != null && ((AttachedCluster)tCEP.getRemoteCluster()).getAnnouncedCEP(tCEP.getRemoteCluster()).getRemoteCluster() != null) {
item.setText(6, ((AttachedCluster)tCEP.getRemoteCluster()).getAnnouncedCEP(tCEP.getRemoteCluster()).getRemoteCluster().toString());
}
Route tRoute = null;
Name tSource = null;
Name tTarget = null;
try {
tSource = tCEP.getSourceName();
tTarget = tCEP.getPeerName();
if(tSource != null && tTarget != null) {
tRoute = mCoordinator.getHRS().getRoute(tCEP.getCoordinator().getPhysicalNode().getCentralFN(), tTarget, new Description(), tCEP.getCoordinator().getPhysicalNode().getIdentity());
} else {
tRoute = new Route();
}
} catch (RoutingException tExc) {
Logging.err(this, "Unable to compute route to " + tTarget, tExc);
} catch (RequirementsException tExc) {
Logging.err(this, "Unable to fulfill requirements for route calculation to " + tTarget, tExc);
}
item.setText(7, (tRoute != null ? tRoute.toString() : "UNKNOWN"));
item.setText(8, Boolean.toString(tCEP.receivedBorderNodeAnnouncement()));
++j;
}
TableColumn[] cols = tTable.getColumns();
for(int k=0; k<cols.length; k++) cols[k].pack();
tTable.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
if((pCluster instanceof IntermediateCluster && ((IntermediateCluster)pCluster).getTopologyEnvelope()!= null && ((IntermediateCluster)pCluster).getTopologyEnvelope().getEntries() != null) || (pCluster instanceof ClusterManager && ((ClusterManager)pCluster).getTopologyEnvelope()!= null && ((ClusterManager)pCluster).getTopologyEnvelope().getEntries() != null) ) {
Table tFIB = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnDestination = new TableColumn(tFIB, SWT.NONE, 0);
tColumnDestination.setText("destination");
TableColumn tColumnForwardingCluster = new TableColumn(tFIB, SWT.NONE, 1);
tColumnForwardingCluster.setText("forwarding cluster");
TableColumn tColumnFarthestCluster = new TableColumn(tFIB, SWT.NONE, 2);
tColumnFarthestCluster.setText("farthest cluster");
TableColumn tColumnNextHop = new TableColumn(tFIB, SWT.NONE, 3);
tColumnNextHop.setText("next hop");
TableColumn tColumnProposedRoute = new TableColumn(tFIB, SWT.NONE, 4);
tColumnProposedRoute.setText("proposed route");
TableColumn tColumnOrigin = new TableColumn(tFIB, SWT.NONE, 5);
tColumnOrigin.setText("origin");
j=0;
if(pCluster instanceof IntermediateCluster) {
for(FIBEntry tEntry: ((IntermediateCluster)pCluster).getTopologyEnvelope().getEntries()) {
TableItem tItem = new TableItem(tFIB, SWT.NONE, j);
tItem.setText(0, (tEntry.getDestination() != null ? tEntry.getDestination().toString() : "UNKNOWN"));
tItem.setText(1, (tEntry.getNextCluster() != null && mCoordinator.getCluster(tEntry.getNextCluster()) != null ? mCoordinator.getCluster(tEntry.getNextCluster()).toString() : tEntry.getNextCluster().toString()));
ClusterDummy tDummy = tEntry.getFarthestClusterInDirection();
Cluster tFarthestCluster = null;
if(tDummy != null) {
tFarthestCluster = mCoordinator.getCluster(tEntry.getFarthestClusterInDirection());
}
tItem.setText(2, (tFarthestCluster != null ? tFarthestCluster.toString() : "UNKNOWN"));
tItem.setText(3, (tEntry.getNextHop() != null ? tEntry.getNextHop().toString() : "UNKNOWN"));
tItem.setText(4, (tEntry.getRouteToTarget() != null ? tEntry.getRouteToTarget().toString() : "UNKNOWN"));
tItem.setText(5, (tEntry.getSignature() != null ? tEntry.getSignature().toString() : "UNKNOWN"));
j++;
}
} else if(pCluster instanceof ClusterManager) {
for(FIBEntry tEntry: ((ClusterManager)pCluster).getTopologyEnvelope().getEntries()) {
TableItem tItem = new TableItem(tFIB, SWT.NONE, j);
tItem.setText(0, (tEntry.getDestination() != null ? tEntry.getDestination().toString() : "UNKNOWN"));
tItem.setText(1, (tEntry.getNextCluster() != null && mCoordinator.getCluster(tEntry.getNextCluster()) != null ? mCoordinator.getCluster(tEntry.getNextCluster()).toString() : tEntry.getNextCluster().toString()));
ClusterDummy tDummy = tEntry.getFarthestClusterInDirection();
Cluster tFarthestCluster = null;
if(tDummy != null) {
tFarthestCluster = mCoordinator.getCluster(tEntry.getFarthestClusterInDirection());
}
tItem.setText(2, (tFarthestCluster != null ? tFarthestCluster.toString() : "UNKNOWN"));
tItem.setText(3, (tEntry.getNextHop() != null ? tEntry.getNextHop().toString() : "UNKNOWN"));
String tTargetString = (tEntry.getRouteToTarget() != null ? tEntry.getRouteToTarget().toString() : null);
if(tTargetString == null) {
tTargetString = ((ClusterManager)pCluster).getPathToCoordinator(((ClusterManager)pCluster).getManagedCluster(), pCluster.getCoordinator().getCluster(tEntry.getNextCluster())).toString();
}
tItem.setText(4, (tEntry.getRouteToTarget() != null ? tEntry.getRouteToTarget().toString() : "UNKNOWN"));
tItem.setText(5, (tEntry.getSignature() != null ? tEntry.getSignature().toString() : "UNKNOWN"));
j++;
}
}
tFIB.setHeaderVisible(true);
tFIB.setLinesVisible(true);
TableColumn[] columns = tFIB.getColumns();
for(int k=0; k<columns.length; k++) columns[k].pack();
tFIB.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
}
if(pCluster instanceof ClusterManager) {
if(pCluster.getLevel() == 3) {
mCoordinator.getLogger().log(this, "Will print cluster manager");
}
j=0;
Table tMappingTable = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnHRMID = new TableColumn(tMappingTable, SWT.NONE, 0);
tColumnHRMID.setText("HRMID");
TableColumn tClumnMappedEntry = new TableColumn(tMappingTable, SWT.NONE, 1);
tClumnMappedEntry.setText("mapped entity");
TableColumn tColumnProvidedPath = new TableColumn(tMappingTable, SWT.NONE, 2);
tColumnProvidedPath.setText("provided path");
TableColumn tColumnSignature = new TableColumn(tMappingTable, SWT.NONE, 3);
tColumnSignature.setText("signature");
if(((ClusterManager)pCluster).getMappings() != null && !((ClusterManager)pCluster).getMappings().isEmpty()) {
for(HRMID tHRMID : ((ClusterManager)pCluster).getMappings().keySet()) {
TableItem item = new TableItem(tMappingTable, SWT.NONE, j);
item.setText(0, tHRMID != null ? tHRMID.toString() : "");
item.setText(1, ((ClusterManager)pCluster).getVirtualNodeFromHRMID(tHRMID) != null ? ((ClusterManager)pCluster).getVirtualNodeFromHRMID(tHRMID).toString() : "" );
item.setText(2, ((ClusterManager)pCluster).getPathFromHRMID(tHRMID) != null ? ((ClusterManager)pCluster).getPathFromHRMID(tHRMID).toString(): "UNKNOWN");
Signature tOrigin = null;
if(((ClusterManager)pCluster).getTopologyEnvelope() != null && ((ClusterManager)pCluster).getTopologyEnvelope().getEntries() != null) {
for(FIBEntry tEntry : ((ClusterManager)pCluster).getTopologyEnvelope().getEntries()) {
if(tEntry.equals(tHRMID)) {
tOrigin = tEntry.getSignature();
}
}
}
item.setText(3, tOrigin != null ? tOrigin.toString() : "UNKNOWN");
j++;
}
}
TableColumn[] columns = tMappingTable.getColumns();
for(int k=0; k<columns.length; k++) columns[k].pack();
tMappingTable.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
tMappingTable.setHeaderVisible(true);
tMappingTable.setLinesVisible(true);
}
Label separator = new Label (mContainer, SWT.SEPARATOR | SWT.HORIZONTAL);
separator.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
separator.setVisible(true);
}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException
{
setSite(site);
setInput(input);
// get selected object to show in editor
Object inputObject;
if(input instanceof EditorInput) {
inputObject = ((EditorInput) input).getObj();
} else {
inputObject = null;
}
Logging.log(this, "init editor for " +inputObject + " (class=" +inputObject.getClass() +")");
if(inputObject != null) {
// update title of editor
setTitle(inputObject.toString());
if(inputObject instanceof Coordinator) {
mCoordinator = (Coordinator) inputObject;
} else {
throw new PartInitException("Invalid input object " +inputObject +". Bus expected.");
}
setPartName(mCoordinator.toString());
} else {
throw new PartInitException("No input for editor.");
}
}
@Override
public void doSave(IProgressMonitor arg0)
{
}
@Override
public void doSaveAs()
{
}
@Override
public boolean isDirty()
{
return false;
}
@Override
public boolean isSaveAsAllowed()
{
return false;
}
@Override
public void setFocus()
{
}
@Override
public Object getAdapter(Class required)
{
if(this.getClass().equals(required)) return this;
Object res = super.getAdapter(required);
if(res == null) {
res = Platform.getAdapterManager().getAdapter(this, required);
if(res == null) res = Platform.getAdapterManager().getAdapter(mCoordinator, required);
}
return res;
}
public String toString()
{
return this.getClass().getSimpleName() + "@" + this.hashCode();
}
}
| false | true | public void printCluster(Cluster pCluster)
{
Text overviewText = new Text(mContainer, SWT.BORDER);;
overviewText.setText(pCluster.toString());
if(pCluster instanceof IntermediateCluster) {
ToolBar tToolbar = new ToolBar(mContainer, SWT.NONE);
ToolItem toolItem1 = new ToolItem(tToolbar, SWT.PUSH);
toolItem1.setText("Election");
ToolItem toolItem2 = new ToolItem(tToolbar, SWT.PUSH);
toolItem2.setText("Elect(all)");
ToolItem toolItem3 = new ToolItem(tToolbar, SWT.PUSH);
toolItem3.setText("Prepare Above");
ToolItem toolItem4 = new ToolItem(tToolbar, SWT.PUSH);
toolItem4.setText("Prepare Above (all)");
ToolItem toolItem5 = new ToolItem(tToolbar, SWT.PUSH);
toolItem5.setText("Distribute Addresses");
toolItem1.addListener(SWT.Selection, new ElectionOnClusterListener((IntermediateCluster)pCluster));
toolItem2.addListener(SWT.Selection, new ElectionOnAllClustersListener((IntermediateCluster)pCluster));
toolItem3.addListener(SWT.Selection, new AbovePreparationOnClusterListener((IntermediateCluster)pCluster));
toolItem4.addListener(SWT.Selection, new AbovePreparationOnAllClustersListener((IntermediateCluster)pCluster));
toolItem5.addListener(SWT.Selection, new AddressDistributionListener((IntermediateCluster)pCluster));
tToolbar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
}
Table tTable = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnCoordinator = new TableColumn(tTable, SWT.NONE, 0);
tColumnCoordinator.setText("Coordinator");
TableColumn tColumnCEP = new TableColumn(tTable, SWT.NONE, 1);
tColumnCEP.setText("Connection Endpoint");
TableColumn tColumnTargetCovered = new TableColumn(tTable, SWT.NONE, 2);
tColumnTargetCovered.setText("Target Covered");
TableColumn tColumnPartofCluster = new TableColumn(tTable, SWT.NONE, 3);
tColumnPartofCluster.setText("Part of Cluster");
TableColumn tColumnPeerPriority = new TableColumn(tTable, SWT.NONE, 4);
tColumnPeerPriority.setText("Peer Priority");
TableColumn tColumnNegotiator = new TableColumn(tTable, SWT.NONE, 5);
tColumnNegotiator.setText("Negotiatoting Cluster");
TableColumn tColumnAnnouncerNegotiator = new TableColumn(tTable, SWT.NONE, 6);
tColumnAnnouncerNegotiator.setText("Announcers negotiator");
TableColumn tColumnRoute = new TableColumn(tTable, SWT.NONE, 7);
tColumnRoute.setText("route");
TableColumn tColumnBorder = new TableColumn(tTable, SWT.NONE, 8);
tColumnBorder.setText("received BNA");
tTable.setHeaderVisible(true);
tTable.setLinesVisible(true);
int j = -1;
Logging.log(this, "Amount of participating CEPs is " + pCluster.getParticipatingCEPs().size());
for(CoordinatorCEPDemultiplexed tCEP : pCluster.getParticipatingCEPs()) {
j++;
Logging.log(this, "Printing table item number " + j);
TableItem item = new TableItem(tTable, SWT.NONE, j);
item.setText(0, (pCluster.getCoordinatorSignature() != null ? pCluster.getCoordinatorSignature().toString() : ""));
Name tPeerAddress = tCEP.getPeerName();
item.setText(1, tPeerAddress.toString());
item.setText(2, tCEP.hasRequestedCoordinator() ? Boolean.toString(tCEP.knowsCoordinator()) : "UNKNOWN");
item.setText(3, Boolean.toString(tCEP.isPartOfMyCluster()));
item.setText(4, (tCEP.getPeerPriority() != 0 ? Float.toString(tCEP.getPeerPriority()) : "UNKNOWN"));
item.setText(5, (tCEP.getRemoteCluster() != null ? tCEP.getRemoteCluster().toString() : "UNKNOWN"));
if(tCEP.getRemoteCluster() != null && tCEP.getRemoteCluster() instanceof AttachedCluster && ((AttachedCluster)tCEP.getRemoteCluster()).getAnnouncedCEP(tCEP.getRemoteCluster()) != null && ((AttachedCluster)tCEP.getRemoteCluster()).getAnnouncedCEP(tCEP.getRemoteCluster()).getRemoteCluster() != null) {
item.setText(6, ((AttachedCluster)tCEP.getRemoteCluster()).getAnnouncedCEP(tCEP.getRemoteCluster()).getRemoteCluster().toString());
}
Route tRoute = null;
Name tSource = null;
Name tTarget = null;
try {
tSource = tCEP.getSourceName();
tTarget = tCEP.getPeerName();
if(tSource != null && tTarget != null) {
tRoute = mCoordinator.getHRS().getRoute(tCEP.getCoordinator().getPhysicalNode().getCentralFN(), tTarget, new Description(), tCEP.getCoordinator().getPhysicalNode().getIdentity());
} else {
tRoute = new Route();
}
} catch (RoutingException tExc) {
Logging.err(this, "Unable to compute route to " + tTarget, tExc);
} catch (RequirementsException tExc) {
Logging.err(this, "Unable to fulfill requirements for route calculation to " + tTarget, tExc);
}
item.setText(7, (tRoute != null ? tRoute.toString() : "UNKNOWN"));
item.setText(8, Boolean.toString(tCEP.receivedBorderNodeAnnouncement()));
++j;
}
TableColumn[] cols = tTable.getColumns();
for(int k=0; k<cols.length; k++) cols[k].pack();
tTable.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
if((pCluster instanceof IntermediateCluster && ((IntermediateCluster)pCluster).getTopologyEnvelope()!= null && ((IntermediateCluster)pCluster).getTopologyEnvelope().getEntries() != null) || (pCluster instanceof ClusterManager && ((ClusterManager)pCluster).getTopologyEnvelope()!= null && ((ClusterManager)pCluster).getTopologyEnvelope().getEntries() != null) ) {
Table tFIB = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnDestination = new TableColumn(tFIB, SWT.NONE, 0);
tColumnDestination.setText("destination");
TableColumn tColumnForwardingCluster = new TableColumn(tFIB, SWT.NONE, 1);
tColumnForwardingCluster.setText("forwarding cluster");
TableColumn tColumnFarthestCluster = new TableColumn(tFIB, SWT.NONE, 2);
tColumnFarthestCluster.setText("farthest cluster");
TableColumn tColumnNextHop = new TableColumn(tFIB, SWT.NONE, 3);
tColumnNextHop.setText("next hop");
TableColumn tColumnProposedRoute = new TableColumn(tFIB, SWT.NONE, 4);
tColumnProposedRoute.setText("proposed route");
TableColumn tColumnOrigin = new TableColumn(tFIB, SWT.NONE, 5);
tColumnOrigin.setText("origin");
j=0;
if(pCluster instanceof IntermediateCluster) {
for(FIBEntry tEntry: ((IntermediateCluster)pCluster).getTopologyEnvelope().getEntries()) {
TableItem tItem = new TableItem(tFIB, SWT.NONE, j);
tItem.setText(0, (tEntry.getDestination() != null ? tEntry.getDestination().toString() : "UNKNOWN"));
tItem.setText(1, (tEntry.getNextCluster() != null && mCoordinator.getCluster(tEntry.getNextCluster()) != null ? mCoordinator.getCluster(tEntry.getNextCluster()).toString() : tEntry.getNextCluster().toString()));
ClusterDummy tDummy = tEntry.getFarthestClusterInDirection();
Cluster tFarthestCluster = null;
if(tDummy != null) {
tFarthestCluster = mCoordinator.getCluster(tEntry.getFarthestClusterInDirection());
}
tItem.setText(2, (tFarthestCluster != null ? tFarthestCluster.toString() : "UNKNOWN"));
tItem.setText(3, (tEntry.getNextHop() != null ? tEntry.getNextHop().toString() : "UNKNOWN"));
tItem.setText(4, (tEntry.getRouteToTarget() != null ? tEntry.getRouteToTarget().toString() : "UNKNOWN"));
tItem.setText(5, (tEntry.getSignature() != null ? tEntry.getSignature().toString() : "UNKNOWN"));
j++;
}
} else if(pCluster instanceof ClusterManager) {
for(FIBEntry tEntry: ((ClusterManager)pCluster).getTopologyEnvelope().getEntries()) {
TableItem tItem = new TableItem(tFIB, SWT.NONE, j);
tItem.setText(0, (tEntry.getDestination() != null ? tEntry.getDestination().toString() : "UNKNOWN"));
tItem.setText(1, (tEntry.getNextCluster() != null && mCoordinator.getCluster(tEntry.getNextCluster()) != null ? mCoordinator.getCluster(tEntry.getNextCluster()).toString() : tEntry.getNextCluster().toString()));
ClusterDummy tDummy = tEntry.getFarthestClusterInDirection();
Cluster tFarthestCluster = null;
if(tDummy != null) {
tFarthestCluster = mCoordinator.getCluster(tEntry.getFarthestClusterInDirection());
}
tItem.setText(2, (tFarthestCluster != null ? tFarthestCluster.toString() : "UNKNOWN"));
tItem.setText(3, (tEntry.getNextHop() != null ? tEntry.getNextHop().toString() : "UNKNOWN"));
String tTargetString = (tEntry.getRouteToTarget() != null ? tEntry.getRouteToTarget().toString() : null);
if(tTargetString == null) {
tTargetString = ((ClusterManager)pCluster).getPathToCoordinator(((ClusterManager)pCluster).getManagedCluster(), pCluster.getCoordinator().getCluster(tEntry.getNextCluster())).toString();
}
tItem.setText(4, (tEntry.getRouteToTarget() != null ? tEntry.getRouteToTarget().toString() : "UNKNOWN"));
tItem.setText(5, (tEntry.getSignature() != null ? tEntry.getSignature().toString() : "UNKNOWN"));
j++;
}
}
tFIB.setHeaderVisible(true);
tFIB.setLinesVisible(true);
TableColumn[] columns = tFIB.getColumns();
for(int k=0; k<columns.length; k++) columns[k].pack();
tFIB.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
}
if(pCluster instanceof ClusterManager) {
if(pCluster.getLevel() == 3) {
mCoordinator.getLogger().log(this, "Will print cluster manager");
}
j=0;
Table tMappingTable = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnHRMID = new TableColumn(tMappingTable, SWT.NONE, 0);
tColumnHRMID.setText("HRMID");
TableColumn tClumnMappedEntry = new TableColumn(tMappingTable, SWT.NONE, 1);
tClumnMappedEntry.setText("mapped entity");
TableColumn tColumnProvidedPath = new TableColumn(tMappingTable, SWT.NONE, 2);
tColumnProvidedPath.setText("provided path");
TableColumn tColumnSignature = new TableColumn(tMappingTable, SWT.NONE, 3);
tColumnSignature.setText("signature");
if(((ClusterManager)pCluster).getMappings() != null && !((ClusterManager)pCluster).getMappings().isEmpty()) {
for(HRMID tHRMID : ((ClusterManager)pCluster).getMappings().keySet()) {
TableItem item = new TableItem(tMappingTable, SWT.NONE, j);
item.setText(0, tHRMID != null ? tHRMID.toString() : "");
item.setText(1, ((ClusterManager)pCluster).getVirtualNodeFromHRMID(tHRMID) != null ? ((ClusterManager)pCluster).getVirtualNodeFromHRMID(tHRMID).toString() : "" );
item.setText(2, ((ClusterManager)pCluster).getPathFromHRMID(tHRMID) != null ? ((ClusterManager)pCluster).getPathFromHRMID(tHRMID).toString(): "UNKNOWN");
Signature tOrigin = null;
if(((ClusterManager)pCluster).getTopologyEnvelope() != null && ((ClusterManager)pCluster).getTopologyEnvelope().getEntries() != null) {
for(FIBEntry tEntry : ((ClusterManager)pCluster).getTopologyEnvelope().getEntries()) {
if(tEntry.equals(tHRMID)) {
tOrigin = tEntry.getSignature();
}
}
}
item.setText(3, tOrigin != null ? tOrigin.toString() : "UNKNOWN");
j++;
}
}
TableColumn[] columns = tMappingTable.getColumns();
for(int k=0; k<columns.length; k++) columns[k].pack();
tMappingTable.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
tMappingTable.setHeaderVisible(true);
tMappingTable.setLinesVisible(true);
}
Label separator = new Label (mContainer, SWT.SEPARATOR | SWT.HORIZONTAL);
separator.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
separator.setVisible(true);
}
| public void printCluster(Cluster pCluster)
{
Text overviewText = new Text(mContainer, SWT.BORDER);;
overviewText.setText(pCluster.toString());
if(pCluster instanceof IntermediateCluster) {
ToolBar tToolbar = new ToolBar(mContainer, SWT.NONE);
ToolItem toolItem1 = new ToolItem(tToolbar, SWT.PUSH);
toolItem1.setText("Election");
ToolItem toolItem2 = new ToolItem(tToolbar, SWT.PUSH);
toolItem2.setText("Elect(all)");
ToolItem toolItem3 = new ToolItem(tToolbar, SWT.PUSH);
toolItem3.setText("Prepare Above");
ToolItem toolItem4 = new ToolItem(tToolbar, SWT.PUSH);
toolItem4.setText("Prepare Above (all)");
ToolItem toolItem5 = new ToolItem(tToolbar, SWT.PUSH);
toolItem5.setText("Distribute Addresses");
toolItem1.addListener(SWT.Selection, new ElectionOnClusterListener((IntermediateCluster)pCluster));
toolItem2.addListener(SWT.Selection, new ElectionOnAllClustersListener((IntermediateCluster)pCluster));
toolItem3.addListener(SWT.Selection, new AbovePreparationOnClusterListener((IntermediateCluster)pCluster));
toolItem4.addListener(SWT.Selection, new AbovePreparationOnAllClustersListener((IntermediateCluster)pCluster));
toolItem5.addListener(SWT.Selection, new AddressDistributionListener((IntermediateCluster)pCluster));
tToolbar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
}
Table tTable = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnCoordinator = new TableColumn(tTable, SWT.NONE, 0);
tColumnCoordinator.setText("Coordinator");
TableColumn tColumnCEP = new TableColumn(tTable, SWT.NONE, 1);
tColumnCEP.setText("Connection Endpoint");
TableColumn tColumnTargetCovered = new TableColumn(tTable, SWT.NONE, 2);
tColumnTargetCovered.setText("Target Covered");
TableColumn tColumnPartofCluster = new TableColumn(tTable, SWT.NONE, 3);
tColumnPartofCluster.setText("Part of Cluster");
TableColumn tColumnPeerPriority = new TableColumn(tTable, SWT.NONE, 4);
tColumnPeerPriority.setText("Peer Priority");
TableColumn tColumnNegotiator = new TableColumn(tTable, SWT.NONE, 5);
tColumnNegotiator.setText("Negotiatoting Cluster");
TableColumn tColumnAnnouncerNegotiator = new TableColumn(tTable, SWT.NONE, 6);
tColumnAnnouncerNegotiator.setText("Announcers negotiator");
TableColumn tColumnRoute = new TableColumn(tTable, SWT.NONE, 7);
tColumnRoute.setText("route");
TableColumn tColumnBorder = new TableColumn(tTable, SWT.NONE, 8);
tColumnBorder.setText("received BNA");
tTable.setHeaderVisible(true);
tTable.setLinesVisible(true);
int j = 0;
Logging.log(this, "Amount of participating CEPs is " + pCluster.getParticipatingCEPs().size());
for(CoordinatorCEPDemultiplexed tCEP : pCluster.getParticipatingCEPs()) {
Logging.log(this, "Printing table item number " + j);
TableItem item = new TableItem(tTable, SWT.NONE, j);
item.setText(0, (pCluster.getCoordinatorSignature() != null ? pCluster.getCoordinatorSignature().toString() : ""));
Name tPeerAddress = tCEP.getPeerName();
item.setText(1, tPeerAddress.toString());
item.setText(2, tCEP.hasRequestedCoordinator() ? Boolean.toString(tCEP.knowsCoordinator()) : "UNKNOWN");
item.setText(3, Boolean.toString(tCEP.isPartOfMyCluster()));
item.setText(4, (tCEP.getPeerPriority() != 0 ? Float.toString(tCEP.getPeerPriority()) : "UNKNOWN"));
item.setText(5, (tCEP.getRemoteCluster() != null ? tCEP.getRemoteCluster().toString() : "UNKNOWN"));
if(tCEP.getRemoteCluster() != null && tCEP.getRemoteCluster() instanceof AttachedCluster && ((AttachedCluster)tCEP.getRemoteCluster()).getAnnouncedCEP(tCEP.getRemoteCluster()) != null && ((AttachedCluster)tCEP.getRemoteCluster()).getAnnouncedCEP(tCEP.getRemoteCluster()).getRemoteCluster() != null) {
item.setText(6, ((AttachedCluster)tCEP.getRemoteCluster()).getAnnouncedCEP(tCEP.getRemoteCluster()).getRemoteCluster().toString());
}
Route tRoute = null;
Name tSource = null;
Name tTarget = null;
try {
tSource = tCEP.getSourceName();
tTarget = tCEP.getPeerName();
if(tSource != null && tTarget != null) {
tRoute = mCoordinator.getHRS().getRoute(tCEP.getCoordinator().getPhysicalNode().getCentralFN(), tTarget, new Description(), tCEP.getCoordinator().getPhysicalNode().getIdentity());
} else {
tRoute = new Route();
}
} catch (RoutingException tExc) {
Logging.err(this, "Unable to compute route to " + tTarget, tExc);
} catch (RequirementsException tExc) {
Logging.err(this, "Unable to fulfill requirements for route calculation to " + tTarget, tExc);
}
item.setText(7, (tRoute != null ? tRoute.toString() : "UNKNOWN"));
item.setText(8, Boolean.toString(tCEP.receivedBorderNodeAnnouncement()));
++j;
}
TableColumn[] cols = tTable.getColumns();
for(int k=0; k<cols.length; k++) cols[k].pack();
tTable.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
if((pCluster instanceof IntermediateCluster && ((IntermediateCluster)pCluster).getTopologyEnvelope()!= null && ((IntermediateCluster)pCluster).getTopologyEnvelope().getEntries() != null) || (pCluster instanceof ClusterManager && ((ClusterManager)pCluster).getTopologyEnvelope()!= null && ((ClusterManager)pCluster).getTopologyEnvelope().getEntries() != null) ) {
Table tFIB = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnDestination = new TableColumn(tFIB, SWT.NONE, 0);
tColumnDestination.setText("destination");
TableColumn tColumnForwardingCluster = new TableColumn(tFIB, SWT.NONE, 1);
tColumnForwardingCluster.setText("forwarding cluster");
TableColumn tColumnFarthestCluster = new TableColumn(tFIB, SWT.NONE, 2);
tColumnFarthestCluster.setText("farthest cluster");
TableColumn tColumnNextHop = new TableColumn(tFIB, SWT.NONE, 3);
tColumnNextHop.setText("next hop");
TableColumn tColumnProposedRoute = new TableColumn(tFIB, SWT.NONE, 4);
tColumnProposedRoute.setText("proposed route");
TableColumn tColumnOrigin = new TableColumn(tFIB, SWT.NONE, 5);
tColumnOrigin.setText("origin");
j=0;
if(pCluster instanceof IntermediateCluster) {
for(FIBEntry tEntry: ((IntermediateCluster)pCluster).getTopologyEnvelope().getEntries()) {
TableItem tItem = new TableItem(tFIB, SWT.NONE, j);
tItem.setText(0, (tEntry.getDestination() != null ? tEntry.getDestination().toString() : "UNKNOWN"));
tItem.setText(1, (tEntry.getNextCluster() != null && mCoordinator.getCluster(tEntry.getNextCluster()) != null ? mCoordinator.getCluster(tEntry.getNextCluster()).toString() : tEntry.getNextCluster().toString()));
ClusterDummy tDummy = tEntry.getFarthestClusterInDirection();
Cluster tFarthestCluster = null;
if(tDummy != null) {
tFarthestCluster = mCoordinator.getCluster(tEntry.getFarthestClusterInDirection());
}
tItem.setText(2, (tFarthestCluster != null ? tFarthestCluster.toString() : "UNKNOWN"));
tItem.setText(3, (tEntry.getNextHop() != null ? tEntry.getNextHop().toString() : "UNKNOWN"));
tItem.setText(4, (tEntry.getRouteToTarget() != null ? tEntry.getRouteToTarget().toString() : "UNKNOWN"));
tItem.setText(5, (tEntry.getSignature() != null ? tEntry.getSignature().toString() : "UNKNOWN"));
j++;
}
} else if(pCluster instanceof ClusterManager) {
for(FIBEntry tEntry: ((ClusterManager)pCluster).getTopologyEnvelope().getEntries()) {
TableItem tItem = new TableItem(tFIB, SWT.NONE, j);
tItem.setText(0, (tEntry.getDestination() != null ? tEntry.getDestination().toString() : "UNKNOWN"));
tItem.setText(1, (tEntry.getNextCluster() != null && mCoordinator.getCluster(tEntry.getNextCluster()) != null ? mCoordinator.getCluster(tEntry.getNextCluster()).toString() : tEntry.getNextCluster().toString()));
ClusterDummy tDummy = tEntry.getFarthestClusterInDirection();
Cluster tFarthestCluster = null;
if(tDummy != null) {
tFarthestCluster = mCoordinator.getCluster(tEntry.getFarthestClusterInDirection());
}
tItem.setText(2, (tFarthestCluster != null ? tFarthestCluster.toString() : "UNKNOWN"));
tItem.setText(3, (tEntry.getNextHop() != null ? tEntry.getNextHop().toString() : "UNKNOWN"));
String tTargetString = (tEntry.getRouteToTarget() != null ? tEntry.getRouteToTarget().toString() : null);
if(tTargetString == null) {
tTargetString = ((ClusterManager)pCluster).getPathToCoordinator(((ClusterManager)pCluster).getManagedCluster(), pCluster.getCoordinator().getCluster(tEntry.getNextCluster())).toString();
}
tItem.setText(4, (tEntry.getRouteToTarget() != null ? tEntry.getRouteToTarget().toString() : "UNKNOWN"));
tItem.setText(5, (tEntry.getSignature() != null ? tEntry.getSignature().toString() : "UNKNOWN"));
j++;
}
}
tFIB.setHeaderVisible(true);
tFIB.setLinesVisible(true);
TableColumn[] columns = tFIB.getColumns();
for(int k=0; k<columns.length; k++) columns[k].pack();
tFIB.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
}
if(pCluster instanceof ClusterManager) {
if(pCluster.getLevel() == 3) {
mCoordinator.getLogger().log(this, "Will print cluster manager");
}
j=0;
Table tMappingTable = new Table(mContainer, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TableColumn tColumnHRMID = new TableColumn(tMappingTable, SWT.NONE, 0);
tColumnHRMID.setText("HRMID");
TableColumn tClumnMappedEntry = new TableColumn(tMappingTable, SWT.NONE, 1);
tClumnMappedEntry.setText("mapped entity");
TableColumn tColumnProvidedPath = new TableColumn(tMappingTable, SWT.NONE, 2);
tColumnProvidedPath.setText("provided path");
TableColumn tColumnSignature = new TableColumn(tMappingTable, SWT.NONE, 3);
tColumnSignature.setText("signature");
if(((ClusterManager)pCluster).getMappings() != null && !((ClusterManager)pCluster).getMappings().isEmpty()) {
for(HRMID tHRMID : ((ClusterManager)pCluster).getMappings().keySet()) {
TableItem item = new TableItem(tMappingTable, SWT.NONE, j);
item.setText(0, tHRMID != null ? tHRMID.toString() : "");
item.setText(1, ((ClusterManager)pCluster).getVirtualNodeFromHRMID(tHRMID) != null ? ((ClusterManager)pCluster).getVirtualNodeFromHRMID(tHRMID).toString() : "" );
item.setText(2, ((ClusterManager)pCluster).getPathFromHRMID(tHRMID) != null ? ((ClusterManager)pCluster).getPathFromHRMID(tHRMID).toString(): "UNKNOWN");
Signature tOrigin = null;
if(((ClusterManager)pCluster).getTopologyEnvelope() != null && ((ClusterManager)pCluster).getTopologyEnvelope().getEntries() != null) {
for(FIBEntry tEntry : ((ClusterManager)pCluster).getTopologyEnvelope().getEntries()) {
if(tEntry.equals(tHRMID)) {
tOrigin = tEntry.getSignature();
}
}
}
item.setText(3, tOrigin != null ? tOrigin.toString() : "UNKNOWN");
j++;
}
}
TableColumn[] columns = tMappingTable.getColumns();
for(int k=0; k<columns.length; k++) columns[k].pack();
tMappingTable.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
tMappingTable.setHeaderVisible(true);
tMappingTable.setLinesVisible(true);
}
Label separator = new Label (mContainer, SWT.SEPARATOR | SWT.HORIZONTAL);
separator.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
separator.setVisible(true);
}
|
diff --git a/src/master/src/org/drftpd/vfs/DirectoryHandle.java b/src/master/src/org/drftpd/vfs/DirectoryHandle.java
index 518637b8..2011f888 100644
--- a/src/master/src/org/drftpd/vfs/DirectoryHandle.java
+++ b/src/master/src/org/drftpd/vfs/DirectoryHandle.java
@@ -1,979 +1,980 @@
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD 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.
*
* DrFTPD 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 DrFTPD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.drftpd.vfs;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.drftpd.GlobalContext;
import org.drftpd.exceptions.FileExistsException;
import org.drftpd.io.PermissionDeniedException;
import org.drftpd.master.RemoteSlave;
import org.drftpd.slave.LightRemoteInode;
import org.drftpd.usermanager.User;
/**
* @author zubov
* @version $Id$
*/
public class DirectoryHandle extends InodeHandle implements
DirectoryHandleInterface {
public DirectoryHandle(String path) {
super(path);
}
/**
* @param reason
* @throws FileNotFoundException if this Directory does not exist
*/
public void abortAllTransfers(String reason) throws FileNotFoundException {
for (FileHandle file : getFilesUnchecked()) {
try {
file.abortTransfers(reason);
} catch (FileNotFoundException e) {
}
}
}
/**
* Returns a DirectoryHandle for a possibly non-existant directory in this path
* No verification to its existence is made
* @param name
* @return
*/
public DirectoryHandle getNonExistentDirectoryHandle(String name) {
if (name.startsWith(VirtualFileSystem.separator)) {
// absolute path, easy to handle
return new DirectoryHandle(name);
}
// path must be relative
return new DirectoryHandle(getPath() + VirtualFileSystem.separator + name);
}
/**
* Returns a LinkHandle for a possibly non-existant directory in this path
* No verification to its existence is made
* @param name
* @return
*/
public LinkHandle getNonExistentLinkHandle(String name) {
return new LinkHandle(getPath() + VirtualFileSystem.separator + name);
}
/**
* @see org.drftpd.vfs.InodleHandle#getInode()
*/
@Override
public VirtualFileSystemDirectory getInode()
throws FileNotFoundException {
VirtualFileSystemInode inode = super.getInode();
if (inode instanceof VirtualFileSystemDirectory) {
return (VirtualFileSystemDirectory) inode;
}
throw new ClassCastException(
"DirectoryHandle object pointing to Inode:" + inode);
}
/**
* @return all InodeHandles inside this dir.
* @throws FileNotFoundException
*/
public Set<InodeHandle> getInodeHandles(User user) throws FileNotFoundException {
Set<InodeHandle> inodes = getInodeHandlesUnchecked();
for (Iterator<InodeHandle> iter = inodes.iterator(); iter.hasNext();) {
InodeHandle inode = iter.next();
try {
checkHiddenPath(inode, user);
} catch (FileNotFoundException e) {
// file is hidden or a race just happened.
iter.remove();
}
}
return inodes;
}
/**
* @return all InodeHandles inside this dir.
* @throws FileNotFoundException
*/
public Set<InodeHandle> getInodeHandlesUnchecked() throws FileNotFoundException {
return getInode().getInodes();
}
public ArrayList<FileHandle> getAllFilesRecursiveUnchecked() {
ArrayList<FileHandle> files = new ArrayList<FileHandle>();
try {
for (InodeHandle inode : getInodeHandlesUnchecked()) {
if (inode.isFile()) {
files.add((FileHandle) inode);
} else if (inode.isDirectory()) {
files.addAll(((DirectoryHandle)inode).getAllFilesRecursiveUnchecked());
}
}
} catch (FileNotFoundException e) {
// oh well, we just won't have any files to add
}
return files;
}
/**
* This method *does* check for hidden paths.
* @return a set containing only the files of this dir.
* (no links or directories included.)
* @throws FileNotFoundException
*/
public Set<FileHandle> getFiles(User user) throws FileNotFoundException {
return getFilesUnchecked(getInodeHandles(user));
}
/**
* This method *does* check for hidden paths.
* @return a sorted set containing only the files of this dir.
* (no links or directories included.)
* @throws FileNotFoundException
*/
public Set<FileHandle> getSortedFiles(User user) throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandles(user));
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getFilesUnchecked(sortedInodes);
}
/**
* This method does not check for hidden paths.
* @return a set containing only the files of this dir.
* (no links or directories included.)
* @throws FileNotFoundException
*/
public Set<FileHandle> getFilesUnchecked() throws FileNotFoundException {
return getFilesUnchecked(getInodeHandlesUnchecked());
}
/**
* This method does not check for hidden paths.
* @return a sorted set containing only the files of this dir.
* (no links or directories included.)
* @throws FileNotFoundException
*/
public Set<FileHandle> getSortedFilesUnchecked() throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getFilesUnchecked(sortedInodes);
}
private Set<FileHandle> getFilesUnchecked(Collection<InodeHandle> inodes) throws FileNotFoundException {
Set<FileHandle> set = new LinkedHashSet<FileHandle>();
for (InodeHandle handle : getInode().getInodes()) {
if (handle instanceof FileHandle) {
set.add((FileHandle) handle);
}
}
return set;
}
/**.
* This method *does* check for hiddens paths.
* @return a set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getDirectories(User user) throws FileNotFoundException {
return getDirectoriesUnchecked(getInodeHandles(user));
}
/**.
* This method *does* check for hiddens paths.
* @return a sorted set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getSortedDirectories(User user) throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandles(user));
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getDirectoriesUnchecked(sortedInodes);
}
/**
* This method does not check for hiddens paths.
* @return a set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getDirectoriesUnchecked() throws FileNotFoundException {
return getDirectoriesUnchecked(getInodeHandlesUnchecked());
}
/**
* This method does not check for hiddens paths.
* @return a sorted set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getSortedDirectoriesUnchecked() throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getDirectoriesUnchecked(sortedInodes);
}
/**
* This method iterates through the given Collection, removing non-Directory objects.
* @return a set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
private Set<DirectoryHandle> getDirectoriesUnchecked(Collection<InodeHandle> inodes)
throws FileNotFoundException {
Set<DirectoryHandle> set = new LinkedHashSet<DirectoryHandle>();
for (InodeHandle handle : inodes) {
if (handle instanceof DirectoryHandle) {
set.add((DirectoryHandle) handle);
}
}
return set;
}
/**
* This method *does* check for hiddens paths.
* @return a set containing only the links of this dir.
* (no directories or files included.)
* @throws FileNotFoundException
*/
public Set<LinkHandle> getLinks(User user) throws FileNotFoundException {
return getLinksUnchecked(getInodeHandles(user));
}
/**
* This method *does* check for hiddens paths.
* @return a sorted set containing only the links of this dir.
* (no directories or files included.)
* @throws FileNotFoundException
*/
public Set<LinkHandle> getSortedLinks(User user) throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandles(user));
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getLinksUnchecked(sortedInodes);
}
/**
* This method does not check for hiddens paths.
* @return a set containing only the links of this dir.
* (no directories or files included.)
* @throws FileNotFoundException
*/
public Set<LinkHandle> getLinksUnchecked() throws FileNotFoundException {
return getLinksUnchecked(getInodeHandlesUnchecked());
}
/**
* This method does not check for hiddens paths.
* @return a sorted set containing only the links of this dir.
* (no directories or files included.)
* @throws FileNotFoundException
*/
public Set<LinkHandle> getSortedLinksUnchecked() throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getLinksUnchecked(sortedInodes);
}
private Set<LinkHandle> getLinksUnchecked(Collection<InodeHandle> inodes) {
Set<LinkHandle> set = new LinkedHashSet<LinkHandle>();
for (Iterator<InodeHandle> iter = inodes.iterator(); iter
.hasNext();) {
InodeHandle handle = iter.next();
if (handle instanceof LinkHandle) {
set.add((LinkHandle) handle);
}
}
return set;
}
/**
* @return true if the dir has offline files.
* @throws FileNotFoundException
*/
public boolean hasOfflineFiles() throws FileNotFoundException {
return getOfflineFiles().size() != 0;
}
/**
* @return a set containing only the offline files of this dir.
* @throws FileNotFoundException
*/
private Set<FileHandle> getOfflineFiles() throws FileNotFoundException {
Set<FileHandle> allFiles = getFilesUnchecked();
Set<FileHandle> offlineFiles = new LinkedHashSet<FileHandle>(allFiles.size());
for (FileHandle file : allFiles) {
if (!file.isAvailable())
offlineFiles.add(file);
}
return offlineFiles;
}
/**
* @param name
* @throws FileNotFoundException
*/
public InodeHandle getInodeHandle(String name, User user) throws FileNotFoundException {
InodeHandle inode = getInodeHandleUnchecked(name);
checkHiddenPath(inode, user);
return inode;
}
public InodeHandle getInodeHandleUnchecked(String name) throws FileNotFoundException {
VirtualFileSystemInode inode = getInode().getInodeByName(name);
if (inode.isDirectory()) {
return new DirectoryHandle(inode.getPath());
} else if (inode.isFile()) {
return new FileHandle(inode.getPath());
} else if (inode.isLink()) {
return new LinkHandle(inode.getPath());
}
throw new IllegalStateException(
"Not a directory, file, or link -- punt");
}
public DirectoryHandle getDirectory(String name, User user)
throws FileNotFoundException, ObjectNotValidException {
DirectoryHandle dir = getDirectoryUnchecked(name);
checkHiddenPath(dir, user);
return dir;
}
public DirectoryHandle getDirectoryUnchecked(String name)
throws FileNotFoundException, ObjectNotValidException {
if (name.equals(VirtualFileSystem.separator)) {
return new DirectoryHandle("/");
}
logger.debug("getDirectory(" + name + ")");
if (name.equals("..")) {
return getParent();
} else if (name.startsWith("../")) {
// strip off the ../
return getParent().getDirectoryUnchecked(name.substring(3));
} else if (name.equals(".")) {
return this;
} else if (name.startsWith("./")) {
return getDirectoryUnchecked(name.substring(2));
}
InodeHandle handle = getInodeHandleUnchecked(name);
if (handle.isDirectory()) {
return (DirectoryHandle) handle;
}
if (handle.isLink()) {
return ((LinkHandle) handle).getTargetDirectoryUnchecked();
}
throw new ObjectNotValidException(name + " is not a directory");
}
public FileHandle getFile(String name, User user) throws FileNotFoundException, ObjectNotValidException {
FileHandle file = getFileUnchecked(name);
checkHiddenPath(file.getParent(), user);
return file;
}
public FileHandle getFileUnchecked(String name) throws FileNotFoundException,
ObjectNotValidException {
InodeHandle handle = getInodeHandleUnchecked(name);
if (handle.isFile()) {
return (FileHandle) handle;
} else if (handle.isLink()) {
LinkHandle link = (LinkHandle) handle;
return link.getTargetFileUnchecked();
}
throw new ObjectNotValidException(name + " is not a file");
}
public LinkHandle getLink(String name, User user) throws FileNotFoundException,
ObjectNotValidException {
LinkHandle link = getLinkUnchecked(name);
checkHiddenPath(link.getTargetInode(user), user);
return link;
}
public LinkHandle getLinkUnchecked(String name) throws FileNotFoundException,
ObjectNotValidException {
InodeHandle handle = getInodeHandleUnchecked(name);
if (handle.isLink()) {
return (LinkHandle) handle;
}
throw new ObjectNotValidException(name + " is not a link");
}
private void createRemergedFile(LightRemoteInode lrf, RemoteSlave rslave,
boolean collision) throws IOException {
String name = lrf.getName();
if (collision) {
name = lrf.getName() + ".collision." + rslave.getName();
rslave.simpleRename(getPath() + lrf.getPath(), getPath(), name);
}
FileHandle newFile = createFileUnchecked(name, "drftpd", "drftpd",
rslave, lrf.lastModified(), true);
newFile.setSize(lrf.length());
//newFile.setCheckSum(rslave.getCheckSumForPath(newFile.getPath()));
// TODO Implement a Checksum queue on remerge
newFile.setCheckSum(0);
}
public void remerge(List<LightRemoteInode> files, RemoteSlave rslave, long lastModified)
throws IOException {
Iterator<LightRemoteInode> sourceIter = files.iterator();
// source comes pre-sorted from the slave
List<InodeHandle> destinationList = null;
try {
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
} catch (FileNotFoundException e) {
// create directory for merging
getParent().createDirectoryRecursive(getName(), true);
// lets try this again, this time, if it doesn't work, we throw an
// IOException up the chain
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
}
try {
// Update the last modified on the dir, this allows us to get a correct
// timestamp on higher level dirs created recursively when remerging a
// lower level. Additionally if the same dir exists on multiple slaves it
// ensures we use the latest timestamp for the dir from all slaves in the
// VFS
compareAndUpdateLastModified(lastModified);
} catch (FileNotFoundException e) {
// Not sure this should be able to happen, for now log an error
logger.error("Directory not found but was there a second ago!",e);
}
Collections.sort(destinationList,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
Iterator<InodeHandle> destinationIter = destinationList.iterator();
LightRemoteInode source = null;
InodeHandle destination = null;
if (sourceIter.hasNext()) {
source = sourceIter.next();
}
if (destinationIter.hasNext()) {
destination = destinationIter.next();
}
while (true) {
/*logger.debug("loop, [destination="
+ (destination == null ? "null" : destination.getName())
+ "][source="
+ (source == null ? "null" : source.getName()) + "]");
*/
// source & destination are set at the "next to process" one OR are
// null and at the end of that list
// case1 : source list is out, remove slave from all remaining
// files/directories
if (source == null) {
while (destination != null) {
// can removeSlave()'s from all types of Inodes, no type
// checking needed
destination.removeSlave(rslave);
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
}
// all done, both lists are empty
return;
}
// case2: destination list is out, add files
if (destination == null) {
while (source != null) {
if (source.isFile()) {
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
- source
- + ".isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
+ source.getName()
+ + " from slave " + rslave.getName() +
+ " isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
// all done, both lists are empty
return;
}
// both source and destination are non-null
// we don't know which one is first alphabetically
int compare = source.getName().compareToIgnoreCase(
destination.getName());
// compare is < 0, source comes before destination
// compare is > 0, source comes after destination
// compare is == 0, they have the same name
if (compare < 0) {
// add the file
createRemergedFile(source, rslave, false);
// advance one runner
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
} else if (compare > 0) {
// remove the slave
destination.removeSlave(rslave);
// advance one runner
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
} else if (compare == 0) {
if (destination.isLink()) {
// this is bad, links don't exist on slaves
// name collision
if (source.isFile()) {
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
// set crc now?
} else { // source.isDirectory()
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
}
} else if (source.isFile() && destination.isFile()) {
// both files
FileHandle destinationFile = (FileHandle) destination;
/* long sourceCRC = rslave.getCheckSumForPath(getPath()
+ VirtualFileSystem.separator + source.getName());
long destinationCRC;
try {
destinationCRC = destinationFile.getCheckSum();
} catch (NoAvailableSlaveException e) {
destinationCRC = 0L;
}
*/
if (source.length() != destinationFile.getSize()) {
// || (sourceCRC != destinationCRC && destinationCRC != 0L)) {
// handle collision
Set<RemoteSlave> rslaves = destinationFile.getSlaves();
if (rslaves.contains(rslave) && rslaves.size() == 1) {
// size of the file has changed, but since this is the only slave with the file, just change the size
destinationFile.setSize(source.length());
} else {
if (rslaves.contains(rslave)) {
// the master thought the slave had the file, it's not the same size anymore, remove it
destinationFile.removeSlave(rslave);
}
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
}
} else {
destinationFile.addSlave(rslave);
}
} else if (source.isDirectory() && destination.isDirectory()) {
// this is good, do nothing other than take up this case
} else {
// we have a directory/name collision, let's find which one
// :)
if (source.isDirectory()) { // & destination.isFile()
// we don't care about directories on the slaves, let's
// just skip it
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
} else {
// source.isFile() && destination.isDirectory()
// handle collision
createRemergedFile(source, rslave, true);
// set crc now?
}
}
// advance both runners, they were equal
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
}
}
/**
* Shortcut to create "owner-less" directories.
* @param name
* @return the created directory
* @throws FileExistsException
* @throws FileNotFoundException
*/
public DirectoryHandle createDirectorySystem(String name) throws FileExistsException, FileNotFoundException {
return createDirectorySystem(name, false);
}
/**
* Shortcut to create "owner-less" directories.
* @param name
* @param transientLastModified
* @return the created directory
* @throws FileExistsException
* @throws FileNotFoundException
*/
protected DirectoryHandle createDirectorySystem(String name, boolean transientLastModified)
throws FileExistsException, FileNotFoundException {
return createDirectoryUnchecked(name, "drftpd", "drftpd", transientLastModified);
}
/**
* Given a DirectoryHandle, it makes sure that this directory and all of its parent(s) exist
* @param name
* @throws FileExistsException
* @throws FileNotFoundException
*/
public void createDirectoryRecursive(String name)
throws FileExistsException, FileNotFoundException {
createDirectoryRecursive(name, false);
}
/**
* Given a DirectoryHandle, it makes sure that this directory and all of its parent(s) exist
* @param name
* @param transientLastModified
* @throws FileExistsException
* @throws FileNotFoundException
*/
public void createDirectoryRecursive(String name, boolean transientLastModified)
throws FileExistsException, FileNotFoundException {
DirectoryHandle dir = null;
try {
dir = createDirectorySystem(name, transientLastModified);
} catch (FileNotFoundException e) {
getParent().createDirectoryRecursive(getName(), transientLastModified);
} catch (FileExistsException e) {
throw new FileExistsException("Object already exists -- "
+ getPath() + VirtualFileSystem.separator + name);
}
if (dir == null) {
dir = createDirectorySystem(name, transientLastModified);
}
logger.debug("Created directory " + dir);
}
/**
* Creates a Directory object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For a checked way of creating dirs {@link #createFile(User, String, RemoteSlave)};
* @param name
* @param user
* @param group
* @return the created directory.
* @throws FileNotFoundException
* @throws FileExistsException
*/
public DirectoryHandle createDirectoryUnchecked(String name, String user,
String group) throws FileExistsException, FileNotFoundException {
return createDirectoryUnchecked(name, user, group, false);
}
/**
* Creates a Directory object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For a checked way of creating dirs {@link #createFile(User, String, RemoteSlave)};
* @param name
* @param user
* @param group
* @param transientLastModified
* @return the created directory.
* @throws FileNotFoundException
* @throws FileExistsException
*/
protected DirectoryHandle createDirectoryUnchecked(String name, String user,
String group, boolean transientLastModified) throws FileExistsException, FileNotFoundException {
getInode().createDirectory(name, user, group, transientLastModified);
try {
return getDirectoryUnchecked(name);
} catch (FileNotFoundException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
} catch (ObjectNotValidException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
}
}
/**
* Attempts to create a Directory in the FileSystem with this directory as parent.
* @see For an unchecked way of creating dirs: {@link #createDirectoryUnchecked(String, String, String)}
* @param user
* @param name
* @return the created directory.
* @throws PermissionDeniedException if the given user is not allowed to create dirs.
* @throws FileExistsException
* @throws FileNotFoundException
*/
public DirectoryHandle createDirectory(User user, String name)
throws PermissionDeniedException, FileExistsException, FileNotFoundException {
if (user == null) {
throw new PermissionDeniedException("User cannot be null");
}
DirectoryHandle newDir = getNonExistentDirectoryHandle(name);
checkHiddenPath(newDir, user);
if (!getVFSPermissions().checkPathPermission("makedir", user, newDir)) {
throw new PermissionDeniedException("You are not allowed to create a directory at "+ newDir.getParent());
}
return createDirectoryUnchecked(name, user.getName(), user.getGroup());
}
/**
* Creates a File object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For unchecked creating of files {@link #createFileUnchecked(String, String, String, RemoteSlave)}
* @param name
* @param user
* @param group
* @param initialSlave
* @return the created file.
* @throws FileExistsException
* @throws FileNotFoundException
*/
public FileHandle createFileUnchecked(String name, String user, String group,
RemoteSlave initialSlave) throws FileExistsException,
FileNotFoundException {
return createFileUnchecked(name, user, group, initialSlave, 0L, false);
}
/**
* Creates a File object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For unchecked creating of files {@link #createFileUnchecked(String, String, String, RemoteSlave)}
* @param name
* @param user
* @param group
* @param initialSlave
* @param lastModified
* @param setLastModified
* @return the created file.
* @throws FileExistsException
* @throws FileNotFoundException
*/
protected FileHandle createFileUnchecked(String name, String user, String group,
RemoteSlave initialSlave, long lastModified, boolean setLastModified) throws FileExistsException,
FileNotFoundException {
getInode().createFile(name, user, group, initialSlave.getName(), lastModified, setLastModified);
try {
return getFileUnchecked(name);
} catch (FileNotFoundException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
} catch (ObjectNotValidException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
}
}
/**
* Attempts to create a File in the FileSystem having this directory as parent.
* @param user
* @param name
* @param initialSlave
* @return
* @throws PermissionDeniedException if the user is not allowed to create a file in this dir.
* @throws FileExistsException
* @throws FileNotFoundException
*/
public FileHandle createFile(User user, String name, RemoteSlave initialSlave)
throws PermissionDeniedException, FileExistsException, FileNotFoundException {
if (user == null) {
throw new PermissionDeniedException("User cannot be null");
}
checkHiddenPath(this, user);
if (!getVFSPermissions().checkPathPermission("upload", user, getNonExistentFileHandle(name))) {
throw new PermissionDeniedException("You are not allowed to upload to "+ getParent());
}
return createFileUnchecked(name, user.getName(), user.getGroup(), initialSlave);
}
/**
* Creates a Link object in the FileSystem with this directory as its parent
*/
public LinkHandle createLinkUnchecked(String name, String target, String user,
String group) throws FileExistsException, FileNotFoundException {
getInode().createLink(name, target, user, group);
try {
return getLinkUnchecked(name);
} catch (FileNotFoundException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
} catch (ObjectNotValidException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
}
}
public LinkHandle createLink(User user, String name, String target)
throws FileExistsException, FileNotFoundException, PermissionDeniedException {
if (user == null) {
throw new PermissionDeniedException("User cannot be null");
}
// check if this dir is hidden.
checkHiddenPath(this, user);
InodeHandle inode = getInodeHandle(target, user);
// check if the target is hidden
checkHiddenPath(inode, user);
if (inode.isLink()) {
throw new PermissionDeniedException("Impossible to point a link to a link");
}
return createLinkUnchecked(name, target, user.getName(), user.getGroup());
}
public boolean isRoot() {
return equals(GlobalContext.getGlobalContext().getRoot());
}
/**
* For use during PRET
* Returns a FileHandle for a possibly non-existant directory in this path
* No verification to its existence is made
* @param name
* @return
*/
public FileHandle getNonExistentFileHandle(String argument) {
if (argument.startsWith(VirtualFileSystem.separator)) {
// absolute path, easy to handle
return new FileHandle(argument);
}
// path must be relative
return new FileHandle(getPath() + VirtualFileSystem.separator
+ argument);
}
public void removeSlave(RemoteSlave rslave) throws FileNotFoundException {
boolean empty = isEmptyUnchecked();
for (InodeHandle inode : getInodeHandlesUnchecked()) {
inode.removeSlave(rslave);
}
if (!empty && isEmptyUnchecked()) { // if it wasn't empty before, but is now, delete it
deleteUnchecked();
}
}
public boolean isEmptyUnchecked() throws FileNotFoundException {
return getInodeHandlesUnchecked().size() == 0;
}
public boolean isEmpty(User user) throws FileNotFoundException, PermissionDeniedException {
// let's fetch the list of existent files inside this dir
// if the dir does not exist, FileNotFoundException is thrown
// if the dir exists the operation continues smoothly.
getInode();
try {
checkHiddenPath(this, user);
} catch (FileNotFoundException e) {
// either a race condition happened or the dir is hidden
// cuz we just checked and the dir was here.
throw new PermissionDeniedException("Unable to check if the directory is empty.");
}
return isEmptyUnchecked();
}
@Override
public boolean isDirectory() {
return true;
}
@Override
public boolean isFile() {
return false;
}
@Override
public boolean isLink() {
return false;
}
@Override
public void deleteUnchecked() throws FileNotFoundException {
abortAllTransfers("Directory " + getPath() + " is being deleted");
GlobalContext.getGlobalContext().getSlaveManager().deleteOnAllSlaves(this);
super.deleteUnchecked();
}
public long validateSizeRecursive() throws FileNotFoundException {
Set<InodeHandle> inodes = getInodeHandlesUnchecked();
long newSize = 0;
long oldSize = getSize();
for (InodeHandle inode : inodes) {
if (inode.isDirectory()) {
((DirectoryHandle) inode).validateSizeRecursive();
}
newSize += inode.getSize();
}
getInode().setSize(newSize);
return oldSize - newSize;
}
protected void compareAndUpdateLastModified(long lastModified) throws FileNotFoundException {
getInode().compareAndUpdateLastModified(lastModified);
}
}
| true | true | public void remerge(List<LightRemoteInode> files, RemoteSlave rslave, long lastModified)
throws IOException {
Iterator<LightRemoteInode> sourceIter = files.iterator();
// source comes pre-sorted from the slave
List<InodeHandle> destinationList = null;
try {
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
} catch (FileNotFoundException e) {
// create directory for merging
getParent().createDirectoryRecursive(getName(), true);
// lets try this again, this time, if it doesn't work, we throw an
// IOException up the chain
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
}
try {
// Update the last modified on the dir, this allows us to get a correct
// timestamp on higher level dirs created recursively when remerging a
// lower level. Additionally if the same dir exists on multiple slaves it
// ensures we use the latest timestamp for the dir from all slaves in the
// VFS
compareAndUpdateLastModified(lastModified);
} catch (FileNotFoundException e) {
// Not sure this should be able to happen, for now log an error
logger.error("Directory not found but was there a second ago!",e);
}
Collections.sort(destinationList,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
Iterator<InodeHandle> destinationIter = destinationList.iterator();
LightRemoteInode source = null;
InodeHandle destination = null;
if (sourceIter.hasNext()) {
source = sourceIter.next();
}
if (destinationIter.hasNext()) {
destination = destinationIter.next();
}
while (true) {
/*logger.debug("loop, [destination="
+ (destination == null ? "null" : destination.getName())
+ "][source="
+ (source == null ? "null" : source.getName()) + "]");
*/
// source & destination are set at the "next to process" one OR are
// null and at the end of that list
// case1 : source list is out, remove slave from all remaining
// files/directories
if (source == null) {
while (destination != null) {
// can removeSlave()'s from all types of Inodes, no type
// checking needed
destination.removeSlave(rslave);
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
}
// all done, both lists are empty
return;
}
// case2: destination list is out, add files
if (destination == null) {
while (source != null) {
if (source.isFile()) {
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
source
+ ".isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
// all done, both lists are empty
return;
}
// both source and destination are non-null
// we don't know which one is first alphabetically
int compare = source.getName().compareToIgnoreCase(
destination.getName());
// compare is < 0, source comes before destination
// compare is > 0, source comes after destination
// compare is == 0, they have the same name
if (compare < 0) {
// add the file
createRemergedFile(source, rslave, false);
// advance one runner
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
} else if (compare > 0) {
// remove the slave
destination.removeSlave(rslave);
// advance one runner
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
} else if (compare == 0) {
if (destination.isLink()) {
// this is bad, links don't exist on slaves
// name collision
if (source.isFile()) {
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
// set crc now?
} else { // source.isDirectory()
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
}
} else if (source.isFile() && destination.isFile()) {
// both files
FileHandle destinationFile = (FileHandle) destination;
/* long sourceCRC = rslave.getCheckSumForPath(getPath()
+ VirtualFileSystem.separator + source.getName());
long destinationCRC;
try {
destinationCRC = destinationFile.getCheckSum();
} catch (NoAvailableSlaveException e) {
destinationCRC = 0L;
}
*/
if (source.length() != destinationFile.getSize()) {
// || (sourceCRC != destinationCRC && destinationCRC != 0L)) {
// handle collision
Set<RemoteSlave> rslaves = destinationFile.getSlaves();
if (rslaves.contains(rslave) && rslaves.size() == 1) {
// size of the file has changed, but since this is the only slave with the file, just change the size
destinationFile.setSize(source.length());
} else {
if (rslaves.contains(rslave)) {
// the master thought the slave had the file, it's not the same size anymore, remove it
destinationFile.removeSlave(rslave);
}
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
}
} else {
destinationFile.addSlave(rslave);
}
} else if (source.isDirectory() && destination.isDirectory()) {
// this is good, do nothing other than take up this case
} else {
// we have a directory/name collision, let's find which one
// :)
if (source.isDirectory()) { // & destination.isFile()
// we don't care about directories on the slaves, let's
// just skip it
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
} else {
// source.isFile() && destination.isDirectory()
// handle collision
createRemergedFile(source, rslave, true);
// set crc now?
}
}
// advance both runners, they were equal
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
}
}
| public void remerge(List<LightRemoteInode> files, RemoteSlave rslave, long lastModified)
throws IOException {
Iterator<LightRemoteInode> sourceIter = files.iterator();
// source comes pre-sorted from the slave
List<InodeHandle> destinationList = null;
try {
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
} catch (FileNotFoundException e) {
// create directory for merging
getParent().createDirectoryRecursive(getName(), true);
// lets try this again, this time, if it doesn't work, we throw an
// IOException up the chain
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
}
try {
// Update the last modified on the dir, this allows us to get a correct
// timestamp on higher level dirs created recursively when remerging a
// lower level. Additionally if the same dir exists on multiple slaves it
// ensures we use the latest timestamp for the dir from all slaves in the
// VFS
compareAndUpdateLastModified(lastModified);
} catch (FileNotFoundException e) {
// Not sure this should be able to happen, for now log an error
logger.error("Directory not found but was there a second ago!",e);
}
Collections.sort(destinationList,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
Iterator<InodeHandle> destinationIter = destinationList.iterator();
LightRemoteInode source = null;
InodeHandle destination = null;
if (sourceIter.hasNext()) {
source = sourceIter.next();
}
if (destinationIter.hasNext()) {
destination = destinationIter.next();
}
while (true) {
/*logger.debug("loop, [destination="
+ (destination == null ? "null" : destination.getName())
+ "][source="
+ (source == null ? "null" : source.getName()) + "]");
*/
// source & destination are set at the "next to process" one OR are
// null and at the end of that list
// case1 : source list is out, remove slave from all remaining
// files/directories
if (source == null) {
while (destination != null) {
// can removeSlave()'s from all types of Inodes, no type
// checking needed
destination.removeSlave(rslave);
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
}
// all done, both lists are empty
return;
}
// case2: destination list is out, add files
if (destination == null) {
while (source != null) {
if (source.isFile()) {
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
source.getName()
+ " from slave " + rslave.getName() +
" isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
// all done, both lists are empty
return;
}
// both source and destination are non-null
// we don't know which one is first alphabetically
int compare = source.getName().compareToIgnoreCase(
destination.getName());
// compare is < 0, source comes before destination
// compare is > 0, source comes after destination
// compare is == 0, they have the same name
if (compare < 0) {
// add the file
createRemergedFile(source, rslave, false);
// advance one runner
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
} else if (compare > 0) {
// remove the slave
destination.removeSlave(rslave);
// advance one runner
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
} else if (compare == 0) {
if (destination.isLink()) {
// this is bad, links don't exist on slaves
// name collision
if (source.isFile()) {
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
// set crc now?
} else { // source.isDirectory()
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
}
} else if (source.isFile() && destination.isFile()) {
// both files
FileHandle destinationFile = (FileHandle) destination;
/* long sourceCRC = rslave.getCheckSumForPath(getPath()
+ VirtualFileSystem.separator + source.getName());
long destinationCRC;
try {
destinationCRC = destinationFile.getCheckSum();
} catch (NoAvailableSlaveException e) {
destinationCRC = 0L;
}
*/
if (source.length() != destinationFile.getSize()) {
// || (sourceCRC != destinationCRC && destinationCRC != 0L)) {
// handle collision
Set<RemoteSlave> rslaves = destinationFile.getSlaves();
if (rslaves.contains(rslave) && rslaves.size() == 1) {
// size of the file has changed, but since this is the only slave with the file, just change the size
destinationFile.setSize(source.length());
} else {
if (rslaves.contains(rslave)) {
// the master thought the slave had the file, it's not the same size anymore, remove it
destinationFile.removeSlave(rslave);
}
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
}
} else {
destinationFile.addSlave(rslave);
}
} else if (source.isDirectory() && destination.isDirectory()) {
// this is good, do nothing other than take up this case
} else {
// we have a directory/name collision, let's find which one
// :)
if (source.isDirectory()) { // & destination.isFile()
// we don't care about directories on the slaves, let's
// just skip it
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
} else {
// source.isFile() && destination.isDirectory()
// handle collision
createRemergedFile(source, rslave, true);
// set crc now?
}
}
// advance both runners, they were equal
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
}
}
|
diff --git a/cq-component-maven-plugin/src/main/java/com/citytechinc/cq/component/dialog/maker/impl/SelectionWidgetMaker.java b/cq-component-maven-plugin/src/main/java/com/citytechinc/cq/component/dialog/maker/impl/SelectionWidgetMaker.java
index b29542a..8a09ef0 100644
--- a/cq-component-maven-plugin/src/main/java/com/citytechinc/cq/component/dialog/maker/impl/SelectionWidgetMaker.java
+++ b/cq-component-maven-plugin/src/main/java/com/citytechinc/cq/component/dialog/maker/impl/SelectionWidgetMaker.java
@@ -1,133 +1,133 @@
package com.citytechinc.cq.component.dialog.maker.impl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.codehaus.plexus.util.StringUtils;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.NotFoundException;
import com.citytechinc.cq.component.annotations.DialogField;
import com.citytechinc.cq.component.annotations.widgets.Selection;
import com.citytechinc.cq.component.dialog.DialogElement;
import com.citytechinc.cq.component.dialog.exception.InvalidComponentFieldException;
import com.citytechinc.cq.component.dialog.impl.Option;
import com.citytechinc.cq.component.dialog.impl.SelectionWidget;
import com.citytechinc.cq.component.dialog.maker.AbstractWidgetMaker;
public class SelectionWidgetMaker extends AbstractWidgetMaker{
@Override
public DialogElement make(String xtype, Field widgetField, CtField ctWidgetField,
Class<?> containingClass, CtClass ctContainingClass, Map<Class<?>, String> xtypeMap)
throws ClassNotFoundException, InvalidComponentFieldException, CannotCompileException, NotFoundException {
ClassPool classPool = ctContainingClass.getClassPool();
ClassLoader classLoader = containingClass.getClassLoader();
DialogField dialogFieldAnnotation = (DialogField) ctWidgetField.getAnnotation(DialogField.class);
Selection selectionAnnotation = (Selection) ctWidgetField.getAnnotation(Selection.class);
String name = getNameForField(dialogFieldAnnotation, widgetField);
String fieldName = getFieldNameForField(dialogFieldAnnotation, widgetField);
String fieldLabel = getFieldLabelForField(dialogFieldAnnotation, widgetField);
String fieldDescription = getFieldDescriptionForField(dialogFieldAnnotation);
Boolean isRequired = getIsRequiredForField(dialogFieldAnnotation);
Map<String, String> additionalProperties = getAdditionalPropertiesForField(dialogFieldAnnotation);
String defaultValue = getDefaultValueForField(dialogFieldAnnotation);
List<DialogElement> options = buildSelectionOptionsForField(ctWidgetField, selectionAnnotation, classLoader, classPool);
String selectionType = getSelectionTypeForField(ctWidgetField, selectionAnnotation);
return new SelectionWidget(
selectionType,
name,
fieldLabel,
fieldName,
fieldDescription,
isRequired,
defaultValue,
additionalProperties,
options);
}
private static final String getSelectionTypeForField(CtField widgetField, Selection fieldAnnotation) {
if(fieldAnnotation!=null && (
fieldAnnotation.type().equals(Selection.CHECKBOX) ||
fieldAnnotation.type().equals(Selection.COMBOBOX) ||
fieldAnnotation.type().equals(Selection.RADIO) ||
fieldAnnotation.type().equals(Selection.SELECT))){
return fieldAnnotation.type();
}else{
return Selection.SELECT;
}
}
private static final List<DialogElement> buildSelectionOptionsForField(CtField widgetField, Selection fieldAnnotation, ClassLoader classLoader, ClassPool classPool) throws InvalidComponentFieldException, CannotCompileException, NotFoundException, ClassNotFoundException {
List<DialogElement> options = new ArrayList<DialogElement>();
/*
* Options specified in the annotation take precedence
*/
if (fieldAnnotation!=null && fieldAnnotation.options().length > 0) {
for(com.citytechinc.cq.component.annotations.Option curOptionAnnotation : fieldAnnotation.options()) {
- if (StringUtils.isEmpty(curOptionAnnotation.text()) || StringUtils.isEmpty(curOptionAnnotation.value())) {
+ if (StringUtils.isEmpty(curOptionAnnotation.value())) {
throw new InvalidComponentFieldException("Selection Options specified in the selectionOptions Annotation property must include a non-empty text and value attribute");
}
options.add(new Option(curOptionAnnotation.text(), curOptionAnnotation.value()));
}
}
/*
* If options were not specified by the annotation then we check
* to see if the field is an Enum and if so, the options are pulled
* from the Enum definition
*/
else if (widgetField.getType().isEnum()) {
for(Object curEnumObject : classLoader.loadClass(widgetField.getType().getName()).getEnumConstants()) {
Enum<?> curEnum = (Enum<?>) curEnumObject;
try {
options.add(buildSelectionOptionForEnum(curEnum, classPool));
} catch (SecurityException e) {
throw new InvalidComponentFieldException("Invalid Enum Field", e);
} catch (NoSuchFieldException e) {
throw new InvalidComponentFieldException("Invalid Enum Field", e);
}
}
}
return options;
}
private static final Option buildSelectionOptionForEnum(Enum<?> optionEnum, ClassPool classPool)
throws SecurityException, NoSuchFieldException, NotFoundException, ClassNotFoundException {
String text = optionEnum.name();
String value = optionEnum.name();
CtClass annotatedEnumClass = classPool.getCtClass(optionEnum.getDeclaringClass().getName());
CtField annotatedEnumField = annotatedEnumClass.getField(optionEnum.name());
com.citytechinc.cq.component.annotations.Option optionAnnotation = (com.citytechinc.cq.component.annotations.Option) annotatedEnumField.getAnnotation(com.citytechinc.cq.component.annotations.Option.class);
if (optionAnnotation != null) {
if (StringUtils.isNotEmpty(optionAnnotation.text())) {
text = optionAnnotation.text();
}
if (StringUtils.isNotEmpty(optionAnnotation.value())) {
value = optionAnnotation.value();
}
}
return new Option(text, value);
}
}
| true | true | private static final List<DialogElement> buildSelectionOptionsForField(CtField widgetField, Selection fieldAnnotation, ClassLoader classLoader, ClassPool classPool) throws InvalidComponentFieldException, CannotCompileException, NotFoundException, ClassNotFoundException {
List<DialogElement> options = new ArrayList<DialogElement>();
/*
* Options specified in the annotation take precedence
*/
if (fieldAnnotation!=null && fieldAnnotation.options().length > 0) {
for(com.citytechinc.cq.component.annotations.Option curOptionAnnotation : fieldAnnotation.options()) {
if (StringUtils.isEmpty(curOptionAnnotation.text()) || StringUtils.isEmpty(curOptionAnnotation.value())) {
throw new InvalidComponentFieldException("Selection Options specified in the selectionOptions Annotation property must include a non-empty text and value attribute");
}
options.add(new Option(curOptionAnnotation.text(), curOptionAnnotation.value()));
}
}
/*
* If options were not specified by the annotation then we check
* to see if the field is an Enum and if so, the options are pulled
* from the Enum definition
*/
else if (widgetField.getType().isEnum()) {
for(Object curEnumObject : classLoader.loadClass(widgetField.getType().getName()).getEnumConstants()) {
Enum<?> curEnum = (Enum<?>) curEnumObject;
try {
options.add(buildSelectionOptionForEnum(curEnum, classPool));
} catch (SecurityException e) {
throw new InvalidComponentFieldException("Invalid Enum Field", e);
} catch (NoSuchFieldException e) {
throw new InvalidComponentFieldException("Invalid Enum Field", e);
}
}
}
return options;
}
| private static final List<DialogElement> buildSelectionOptionsForField(CtField widgetField, Selection fieldAnnotation, ClassLoader classLoader, ClassPool classPool) throws InvalidComponentFieldException, CannotCompileException, NotFoundException, ClassNotFoundException {
List<DialogElement> options = new ArrayList<DialogElement>();
/*
* Options specified in the annotation take precedence
*/
if (fieldAnnotation!=null && fieldAnnotation.options().length > 0) {
for(com.citytechinc.cq.component.annotations.Option curOptionAnnotation : fieldAnnotation.options()) {
if (StringUtils.isEmpty(curOptionAnnotation.value())) {
throw new InvalidComponentFieldException("Selection Options specified in the selectionOptions Annotation property must include a non-empty text and value attribute");
}
options.add(new Option(curOptionAnnotation.text(), curOptionAnnotation.value()));
}
}
/*
* If options were not specified by the annotation then we check
* to see if the field is an Enum and if so, the options are pulled
* from the Enum definition
*/
else if (widgetField.getType().isEnum()) {
for(Object curEnumObject : classLoader.loadClass(widgetField.getType().getName()).getEnumConstants()) {
Enum<?> curEnum = (Enum<?>) curEnumObject;
try {
options.add(buildSelectionOptionForEnum(curEnum, classPool));
} catch (SecurityException e) {
throw new InvalidComponentFieldException("Invalid Enum Field", e);
} catch (NoSuchFieldException e) {
throw new InvalidComponentFieldException("Invalid Enum Field", e);
}
}
}
return options;
}
|
diff --git a/ui/web/src/main/java/org/openengsb/ui/web/config/AuditingConfig.java b/ui/web/src/main/java/org/openengsb/ui/web/config/AuditingConfig.java
index 1d948462c..80dedb28e 100644
--- a/ui/web/src/main/java/org/openengsb/ui/web/config/AuditingConfig.java
+++ b/ui/web/src/main/java/org/openengsb/ui/web/config/AuditingConfig.java
@@ -1,78 +1,82 @@
/**
* Copyright 2010 OpenEngSB Division, Vienna University of Technology
*
* 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 org.openengsb.ui.web.config;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.openengsb.core.common.ServiceManager;
import org.openengsb.core.common.service.DomainService;
import org.openengsb.core.common.workflow.RuleBaseException;
import org.openengsb.core.common.workflow.RuleManager;
import org.openengsb.core.common.workflow.model.RuleBaseElementId;
import org.openengsb.core.common.workflow.model.RuleBaseElementType;
import org.openengsb.domain.auditing.AuditingDomain;
public class AuditingConfig {
@SpringBean
private RuleManager ruleManager;
@SpringBean
private DomainService domainService;
public final void setRuleManager(RuleManager ruleManager) {
this.ruleManager = ruleManager;
}
public final void setDomainService(DomainService domainService) {
this.domainService = domainService;
}
public void init() {
try {
ruleManager.addImport(AuditingDomain.class.getCanonicalName());
- ruleManager.addGlobal(AuditingDomain.class.getCanonicalName(), "auditing");
+ try {
+ ruleManager.addGlobal(AuditingDomain.class.getCanonicalName(), "auditing");
+ } catch (RuntimeException e) {
+ // thrown if there is already one global auditing... fine then, go on
+ }
addRule("auditEvent");
List<ServiceManager> serviceManagersForDomain =
domainService.serviceManagersForDomain(AuditingDomain.class);
if (serviceManagersForDomain.size() > 0) {
String defaultConnectorID = "auditing";
serviceManagersForDomain.get(0).update(defaultConnectorID, new HashMap<String, String>());
}
} catch (RuleBaseException e) {
throw new RuntimeException(e);
}
}
private void addRule(String rule) {
InputStream is = null;
try {
is = getClass().getClassLoader().getResourceAsStream(rule + ".rule");
String ruleText = IOUtils.toString(is);
RuleBaseElementId id = new RuleBaseElementId(RuleBaseElementType.Rule, rule);
ruleManager.add(id, ruleText);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
}
}
| true | true | public void init() {
try {
ruleManager.addImport(AuditingDomain.class.getCanonicalName());
ruleManager.addGlobal(AuditingDomain.class.getCanonicalName(), "auditing");
addRule("auditEvent");
List<ServiceManager> serviceManagersForDomain =
domainService.serviceManagersForDomain(AuditingDomain.class);
if (serviceManagersForDomain.size() > 0) {
String defaultConnectorID = "auditing";
serviceManagersForDomain.get(0).update(defaultConnectorID, new HashMap<String, String>());
}
} catch (RuleBaseException e) {
throw new RuntimeException(e);
}
}
| public void init() {
try {
ruleManager.addImport(AuditingDomain.class.getCanonicalName());
try {
ruleManager.addGlobal(AuditingDomain.class.getCanonicalName(), "auditing");
} catch (RuntimeException e) {
// thrown if there is already one global auditing... fine then, go on
}
addRule("auditEvent");
List<ServiceManager> serviceManagersForDomain =
domainService.serviceManagersForDomain(AuditingDomain.class);
if (serviceManagersForDomain.size() > 0) {
String defaultConnectorID = "auditing";
serviceManagersForDomain.get(0).update(defaultConnectorID, new HashMap<String, String>());
}
} catch (RuleBaseException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/plugin/src/main/java/hudson/plugins/findbugs/FindBugsPublisher.java b/plugin/src/main/java/hudson/plugins/findbugs/FindBugsPublisher.java
index b03400d..40020cf 100644
--- a/plugin/src/main/java/hudson/plugins/findbugs/FindBugsPublisher.java
+++ b/plugin/src/main/java/hudson/plugins/findbugs/FindBugsPublisher.java
@@ -1,163 +1,163 @@
package hudson.plugins.findbugs;
import hudson.Launcher;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixBuild;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.plugins.analysis.core.BuildResult;
import hudson.plugins.analysis.core.FilesParser;
import hudson.plugins.analysis.core.HealthAwarePublisher;
import hudson.plugins.analysis.core.ParserResult;
import hudson.plugins.analysis.util.PluginLogger;
import hudson.plugins.findbugs.parser.FindBugsParser;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* Publishes the results of the FindBugs analysis (freestyle project type).
*
* @author Ulli Hafner
*/
public class FindBugsPublisher extends HealthAwarePublisher {
private static final long serialVersionUID = -5748362182226609649L;
private static final String ANT_DEFAULT_PATTERN = "**/findbugs.xml";
private static final String MAVEN_DEFAULT_PATTERN = "**/findbugsXml.xml";
/** Ant file-set pattern of files to work with. */
private final String pattern;
/**
* Creates a new instance of {@link FindBugsPublisher}.
*
* @param healthy
* Report health as 100% when the number of warnings is less than
* this value
* @param unHealthy
* Report health as 0% when the number of warnings is greater
* than this value
* @param thresholdLimit
* determines which warning priorities should be considered when
* evaluating the build stability and health
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param useDeltaValues
* determines whether the absolute annotations delta or the
* actual annotations set difference should be used to evaluate
* the build stability
* @param unstableTotalAll
* annotation threshold
* @param unstableTotalHigh
* annotation threshold
* @param unstableTotalNormal
* annotation threshold
* @param unstableTotalLow
* annotation threshold
* @param unstableNewAll
* annotation threshold
* @param unstableNewHigh
* annotation threshold
* @param unstableNewNormal
* annotation threshold
* @param unstableNewLow
* annotation threshold
* @param failedTotalAll
* annotation threshold
* @param failedTotalHigh
* annotation threshold
* @param failedTotalNormal
* annotation threshold
* @param failedTotalLow
* annotation threshold
* @param failedNewAll
* annotation threshold
* @param failedNewHigh
* annotation threshold
* @param failedNewNormal
* annotation threshold
* @param failedNewLow
* annotation threshold
* @param canRunOnFailed
* determines whether the plug-in can run for failed builds, too
* @param shouldDetectModules
* determines whether module names should be derived from Maven POM or Ant build files
* @param pattern
* Ant file-set pattern to scan for FindBugs files
*/
// CHECKSTYLE:OFF
@SuppressWarnings("PMD.ExcessiveParameterList")
@DataBoundConstructor
public FindBugsPublisher(final String healthy, final String unHealthy, final String thresholdLimit,
final String defaultEncoding, final boolean useDeltaValues,
final String unstableTotalAll, final String unstableTotalHigh, final String unstableTotalNormal, final String unstableTotalLow,
final String unstableNewAll, final String unstableNewHigh, final String unstableNewNormal, final String unstableNewLow,
final String failedTotalAll, final String failedTotalHigh, final String failedTotalNormal, final String failedTotalLow,
final String failedNewAll, final String failedNewHigh, final String failedNewNormal, final String failedNewLow,
final boolean canRunOnFailed, final boolean shouldDetectModules,
final String pattern) {
super(healthy, unHealthy, thresholdLimit, defaultEncoding, useDeltaValues,
unstableTotalAll, unstableTotalHigh, unstableTotalNormal, unstableTotalLow,
unstableNewAll, unstableNewHigh, unstableNewNormal, unstableNewLow,
failedTotalAll, failedTotalHigh, failedTotalNormal, failedTotalLow,
failedNewAll, failedNewHigh, failedNewNormal, failedNewLow,
canRunOnFailed, shouldDetectModules, "FINDBUGS");
this.pattern = pattern;
}
// CHECKSTYLE:ON
/**
* Returns the Ant file-set pattern of files to work with.
*
* @return Ant file-set pattern of files to work with
*/
public String getPattern() {
return pattern;
}
/** {@inheritDoc} */
@Override
public Action getProjectAction(final AbstractProject<?, ?> project) {
return new FindBugsProjectAction(project);
}
/** {@inheritDoc} */
@Override
public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger) throws InterruptedException, IOException {
logger.log("Collecting findbugs analysis files...");
String defaultPattern = isMavenBuild(build) ? MAVEN_DEFAULT_PATTERN : ANT_DEFAULT_PATTERN;
FilesParser collector;
if (shouldDetectModules()) {
collector = new FilesParser(logger, StringUtils.defaultIfEmpty(getPattern(),
- defaultPattern), new FindBugsParser(), isMavenBuild(build), isAntBuild(build));
+ defaultPattern), new FindBugsParser(), isMavenBuild(build));
}
else {
collector = new FilesParser(logger, StringUtils.defaultIfEmpty(getPattern(),
defaultPattern), new FindBugsParser());
}
ParserResult project = build.getWorkspace().act(collector);
FindBugsResult result = new FindBugsResult(build, getDefaultEncoding(), project);
build.getActions().add(new FindBugsResultAction(build, this, result));
return result;
}
/** {@inheritDoc} */
@Override
public FindBugsDescriptor getDescriptor() {
return (FindBugsDescriptor)super.getDescriptor();
}
/** {@inheritDoc} */
public MatrixAggregator createAggregator(final MatrixBuild build, final Launcher launcher,
final BuildListener listener) {
return new FindBugsAnnotationsAggregator(build, launcher, listener, this, getDefaultEncoding());
}
}
| true | true | public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger) throws InterruptedException, IOException {
logger.log("Collecting findbugs analysis files...");
String defaultPattern = isMavenBuild(build) ? MAVEN_DEFAULT_PATTERN : ANT_DEFAULT_PATTERN;
FilesParser collector;
if (shouldDetectModules()) {
collector = new FilesParser(logger, StringUtils.defaultIfEmpty(getPattern(),
defaultPattern), new FindBugsParser(), isMavenBuild(build), isAntBuild(build));
}
else {
collector = new FilesParser(logger, StringUtils.defaultIfEmpty(getPattern(),
defaultPattern), new FindBugsParser());
}
ParserResult project = build.getWorkspace().act(collector);
FindBugsResult result = new FindBugsResult(build, getDefaultEncoding(), project);
build.getActions().add(new FindBugsResultAction(build, this, result));
return result;
}
| public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger) throws InterruptedException, IOException {
logger.log("Collecting findbugs analysis files...");
String defaultPattern = isMavenBuild(build) ? MAVEN_DEFAULT_PATTERN : ANT_DEFAULT_PATTERN;
FilesParser collector;
if (shouldDetectModules()) {
collector = new FilesParser(logger, StringUtils.defaultIfEmpty(getPattern(),
defaultPattern), new FindBugsParser(), isMavenBuild(build));
}
else {
collector = new FilesParser(logger, StringUtils.defaultIfEmpty(getPattern(),
defaultPattern), new FindBugsParser());
}
ParserResult project = build.getWorkspace().act(collector);
FindBugsResult result = new FindBugsResult(build, getDefaultEncoding(), project);
build.getActions().add(new FindBugsResultAction(build, this, result));
return result;
}
|
diff --git a/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISBookCommands.java b/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISBookCommands.java
index 7b3fca565..a7ff6a5bf 100644
--- a/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISBookCommands.java
+++ b/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISBookCommands.java
@@ -1,139 +1,142 @@
/*
* Copyright (C) 2013 eccentric_nz
*
* 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 me.eccentric_nz.TARDIS.commands;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import me.eccentric_nz.TARDIS.TARDIS;
import me.eccentric_nz.TARDIS.achievement.TARDISBook;
import me.eccentric_nz.TARDIS.database.QueryFactory;
import me.eccentric_nz.TARDIS.database.ResultSetAchievements;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* Command /tardisbook [book].
*
* On Alfava Metraxis in the 51st century, River had obtained a book about the
* Weeping Angels. She gave it to the Doctor, who quickly skimmed through it.
* The Doctor commented that it was slow in the middle and asked River if she
* also hated the writer's girlfriend. He asked why there were no images, to
* which River replied that the "image of an Angel is itself an Angel".
*
* @author eccentric_nz
*/
public class TARDISBookCommands implements CommandExecutor {
private TARDIS plugin;
LinkedHashMap<String, String> books;
public TARDISBookCommands(TARDIS plugin) {
this.plugin = plugin;
this.books = getAchievements();
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
// If the player typed /tardisbook then do the following...
if (cmd.getName().equalsIgnoreCase("tardisbook")) {
+ if (args.length < 1) {
+ return false;
+ }
if (sender.hasPermission("tardis.book")) {
String first = args[0].toLowerCase(Locale.ENGLISH);
if (first.equals("list")) {
int b = 1;
sender.sendMessage(TARDIS.plugin.pluginName + "The books of Rassilon");
for (Map.Entry<String, String> entry : books.entrySet()) {
sender.sendMessage(b + ". [" + entry.getKey() + "] - " + entry.getValue());
b++;
}
return true;
}
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if (player == null) {
sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player");
return true;
}
if (args.length < 2) {
sender.sendMessage(plugin.pluginName + "You need to specify a book name!");
return false;
}
String bookname = args[1].toLowerCase(Locale.ENGLISH);
if (!books.containsKey(bookname)) {
sender.sendMessage(plugin.pluginName + "Could not find that book!");
return true;
}
if (first.equals("get")) {
// need to check whether they already have been given the book
TARDISBook book = new TARDISBook(plugin);
// title, author, filename, player
book.writeBook(books.get(bookname), "Rassilon", bookname, player);
return true;
}
if (first.equals("start")) {
if (plugin.ayml.getBoolean(bookname + ".auto")) {
sender.sendMessage(plugin.pluginName + "This achievement is awarded automatically!");
return true;
}
// check they have not already started the achievement
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("player", player.getName());
where.put("name", bookname);
ResultSetAchievements rsa = new ResultSetAchievements(plugin, where, false);
if (rsa.resultSet()) {
if (rsa.isCompleted()) {
if (!plugin.ayml.getBoolean(bookname + ".repeatable")) {
sender.sendMessage(plugin.pluginName + "This achievement can only be gained once!");
return true;
}
} else {
sender.sendMessage(plugin.pluginName + "You have already started this achievement!");
return true;
}
}
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("player", player.getName());
set.put("name", bookname);
QueryFactory qf = new QueryFactory(plugin);
qf.doInsert("achievements", set);
sender.sendMessage(plugin.pluginName + "Achievement '" + bookname + "' started!");
return true;
}
}
}
return false;
}
private LinkedHashMap<String, String> getAchievements() {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
Set<String> aset = plugin.ayml.getRoot().getKeys(false);
for (String a : aset) {
if (plugin.ayml.getBoolean(a + ".enabled")) {
String title_reward = plugin.ayml.getString(a + ".name") + " - " + plugin.ayml.getString(a + ".reward_type") + ":" + plugin.ayml.getString(a + ".reward_amount");
map.put(a, title_reward);
}
}
return map;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
// If the player typed /tardisbook then do the following...
if (cmd.getName().equalsIgnoreCase("tardisbook")) {
if (sender.hasPermission("tardis.book")) {
String first = args[0].toLowerCase(Locale.ENGLISH);
if (first.equals("list")) {
int b = 1;
sender.sendMessage(TARDIS.plugin.pluginName + "The books of Rassilon");
for (Map.Entry<String, String> entry : books.entrySet()) {
sender.sendMessage(b + ". [" + entry.getKey() + "] - " + entry.getValue());
b++;
}
return true;
}
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if (player == null) {
sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player");
return true;
}
if (args.length < 2) {
sender.sendMessage(plugin.pluginName + "You need to specify a book name!");
return false;
}
String bookname = args[1].toLowerCase(Locale.ENGLISH);
if (!books.containsKey(bookname)) {
sender.sendMessage(plugin.pluginName + "Could not find that book!");
return true;
}
if (first.equals("get")) {
// need to check whether they already have been given the book
TARDISBook book = new TARDISBook(plugin);
// title, author, filename, player
book.writeBook(books.get(bookname), "Rassilon", bookname, player);
return true;
}
if (first.equals("start")) {
if (plugin.ayml.getBoolean(bookname + ".auto")) {
sender.sendMessage(plugin.pluginName + "This achievement is awarded automatically!");
return true;
}
// check they have not already started the achievement
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("player", player.getName());
where.put("name", bookname);
ResultSetAchievements rsa = new ResultSetAchievements(plugin, where, false);
if (rsa.resultSet()) {
if (rsa.isCompleted()) {
if (!plugin.ayml.getBoolean(bookname + ".repeatable")) {
sender.sendMessage(plugin.pluginName + "This achievement can only be gained once!");
return true;
}
} else {
sender.sendMessage(plugin.pluginName + "You have already started this achievement!");
return true;
}
}
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("player", player.getName());
set.put("name", bookname);
QueryFactory qf = new QueryFactory(plugin);
qf.doInsert("achievements", set);
sender.sendMessage(plugin.pluginName + "Achievement '" + bookname + "' started!");
return true;
}
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
// If the player typed /tardisbook then do the following...
if (cmd.getName().equalsIgnoreCase("tardisbook")) {
if (args.length < 1) {
return false;
}
if (sender.hasPermission("tardis.book")) {
String first = args[0].toLowerCase(Locale.ENGLISH);
if (first.equals("list")) {
int b = 1;
sender.sendMessage(TARDIS.plugin.pluginName + "The books of Rassilon");
for (Map.Entry<String, String> entry : books.entrySet()) {
sender.sendMessage(b + ". [" + entry.getKey() + "] - " + entry.getValue());
b++;
}
return true;
}
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if (player == null) {
sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player");
return true;
}
if (args.length < 2) {
sender.sendMessage(plugin.pluginName + "You need to specify a book name!");
return false;
}
String bookname = args[1].toLowerCase(Locale.ENGLISH);
if (!books.containsKey(bookname)) {
sender.sendMessage(plugin.pluginName + "Could not find that book!");
return true;
}
if (first.equals("get")) {
// need to check whether they already have been given the book
TARDISBook book = new TARDISBook(plugin);
// title, author, filename, player
book.writeBook(books.get(bookname), "Rassilon", bookname, player);
return true;
}
if (first.equals("start")) {
if (plugin.ayml.getBoolean(bookname + ".auto")) {
sender.sendMessage(plugin.pluginName + "This achievement is awarded automatically!");
return true;
}
// check they have not already started the achievement
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("player", player.getName());
where.put("name", bookname);
ResultSetAchievements rsa = new ResultSetAchievements(plugin, where, false);
if (rsa.resultSet()) {
if (rsa.isCompleted()) {
if (!plugin.ayml.getBoolean(bookname + ".repeatable")) {
sender.sendMessage(plugin.pluginName + "This achievement can only be gained once!");
return true;
}
} else {
sender.sendMessage(plugin.pluginName + "You have already started this achievement!");
return true;
}
}
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("player", player.getName());
set.put("name", bookname);
QueryFactory qf = new QueryFactory(plugin);
qf.doInsert("achievements", set);
sender.sendMessage(plugin.pluginName + "Achievement '" + bookname + "' started!");
return true;
}
}
}
return false;
}
|
diff --git a/HashDatabase/src/org/sleuthkit/autopsy/hashdatabase/HashDbSearchPanel.java b/HashDatabase/src/org/sleuthkit/autopsy/hashdatabase/HashDbSearchPanel.java
index f4c7db191..6ee4d79bf 100644
--- a/HashDatabase/src/org/sleuthkit/autopsy/hashdatabase/HashDbSearchPanel.java
+++ b/HashDatabase/src/org/sleuthkit/autopsy/hashdatabase/HashDbSearchPanel.java
@@ -1,309 +1,309 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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 org.sleuthkit.autopsy.hashdatabase;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import org.sleuthkit.datamodel.FsContent;
/**
* Searches for files by md5 hash, based off the hash given in this panel.
*/
public class HashDbSearchPanel extends javax.swing.JPanel implements ActionListener {
private static final Logger logger = Logger.getLogger(HashDbSearchPanel.class.getName());
private static HashDbSearchPanel instance;
private static boolean ingestRunning = false;
/**
* @return the default instance of this panel
*/
public static HashDbSearchPanel getDefault() {
if (instance == null) {
instance = new HashDbSearchPanel();
}
return instance;
}
/**
* Creates new form HashDbSearchPanel
*/
public HashDbSearchPanel() {
setName(HashDbSearchAction.ACTION_NAME);
initComponents();
customInit();
}
final void customInit() {
searchButton.addActionListener(this);
addButton.addActionListener(this);
removeButton.addActionListener(this);
errorField.setVisible(false);
hashField.requestFocus();
// Pressing enter adds the hash
hashField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER) {
addButton.doClick();
}
}
});
// Pressing delete removes the selected rows
hashTable.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_DELETE) {
removeButton.doClick();
}
}
});
}
/**
* Don't allow any changes if ingest is running
*/
void setIngestRunning(boolean running) {
ingestRunning = running;
if(running) {
titleLabel.setForeground(Color.red);
titleLabel.setText("Ingest is ongoing; this service will be unavailable until it finishes.");
} else {
titleLabel.setForeground(Color.black);
titleLabel.setText("Search for files with the following MD5 hash(es):");
}
hashField.setEditable(!ingestRunning);
searchButton.setEnabled(!ingestRunning);
addButton.setEnabled(!ingestRunning);
removeButton.setEnabled(!ingestRunning);
hashTable.setEnabled(!ingestRunning);
hashLabel.setEnabled(!ingestRunning);
}
void cancelButtonListener(ActionListener l) {
cancelButton.addActionListener(l);
}
/**
* 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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
hashTable = new javax.swing.JTable();
hashField = new javax.swing.JTextField();
addButton = new javax.swing.JButton();
hashLabel = new javax.swing.JLabel();
cancelButton = new javax.swing.JButton();
searchButton = new javax.swing.JButton();
removeButton = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
titleLabel = new javax.swing.JLabel();
errorField = new javax.swing.JLabel();
hashTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"MD5 Hashes"
}
) {
Class[] types = new Class [] {
java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(hashTable);
hashTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.hashTable.columnModel.title0")); // NOI18N
hashField.setText(org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.hashField.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(addButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.addButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(hashLabel, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.hashLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.cancelButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.searchButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(removeButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.removeButton.text")); // NOI18N
titleLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(titleLabel, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.titleLabel.text")); // NOI18N
errorField.setForeground(new java.awt.Color(255, 0, 0));
org.openide.awt.Mnemonics.setLocalizedText(errorField, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.errorField.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(errorField)
.addGap(18, 18, 18)
.addComponent(searchButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cancelButton))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
- .addComponent(titleLabel)
- .addGap(0, 0, Short.MAX_VALUE))
- .addGroup(layout.createSequentialGroup()
.addComponent(hashLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(hashField))
+ .addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(titleLabel)
.addGroup(layout.createSequentialGroup()
+ .addGap(61, 61, 61)
.addComponent(addButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addComponent(removeButton)
- .addGap(0, 0, Short.MAX_VALUE))
- .addComponent(hashField))))))
+ .addComponent(removeButton)))
+ .addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(hashLabel)
+ .addComponent(hashLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hashField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addButton)
.addComponent(removeButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(searchButton)
.addComponent(errorField))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addButton;
private javax.swing.JButton cancelButton;
private javax.swing.JLabel errorField;
private javax.swing.JTextField hashField;
private javax.swing.JLabel hashLabel;
private javax.swing.JTable hashTable;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JButton removeButton;
private javax.swing.JButton searchButton;
private javax.swing.JLabel titleLabel;
// End of variables declaration//GEN-END:variables
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(searchButton)) {
doSearch();
} else if(e.getSource().equals(addButton)) {
add();
} else if(e.getSource().equals(removeButton)) {
remove();
}
}
/**
* Search through all tsk_files to find ones with the same hashes as the
* hashes given.
*/
void doSearch() {
// Make sure all files have an md5 hash
if(HashDbSearcher.isReady()) {
errorField.setEnabled(false);
cancelButton.setText("Done"); // no changes so done
// Get all the rows in the table
int numRows = hashTable.getRowCount();
ArrayList<String> hashes = new ArrayList<String>();
for(int i=0; i<numRows; i++) {
hashes.add((String) hashTable.getValueAt(i, 0));
}
// Get the map of hashes to FsContent and send it to the manager
Map<String, List<FsContent>> map = HashDbSearcher.findFilesBymd5(hashes);
HashDbSearchManager man = new HashDbSearchManager(map);
man.execute();
} else {
errorField.setVisible(true);
}
}
/**
* Add the given text into the table of hashes.
*/
void add() {
cancelButton.setText("Cancel"); // changes means cancel
DefaultTableModel model = (DefaultTableModel) hashTable.getModel();
if(!hashField.getText().equals("")) {
model.addRow(new String[] {hashField.getText()});
hashField.setText(""); // wipe the field
}
hashField.requestFocus(); // select the field to type in
}
/**
* Remove all of the highlighted/selected rows from the table of hashes.
*/
void remove() {
cancelButton.setText("Cancel"); // changes means cancel
DefaultTableModel model = (DefaultTableModel) hashTable.getModel();
int rows[] = hashTable.getSelectedRows();
// Loop backwards to delete highest row index first, otherwise
// index numbers change and the wrong rows are deleted
for(int i=rows.length-1; i>=0; i--) {
model.removeRow(rows[i]);
}
}
}
| false | true | private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
hashTable = new javax.swing.JTable();
hashField = new javax.swing.JTextField();
addButton = new javax.swing.JButton();
hashLabel = new javax.swing.JLabel();
cancelButton = new javax.swing.JButton();
searchButton = new javax.swing.JButton();
removeButton = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
titleLabel = new javax.swing.JLabel();
errorField = new javax.swing.JLabel();
hashTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"MD5 Hashes"
}
) {
Class[] types = new Class [] {
java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(hashTable);
hashTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.hashTable.columnModel.title0")); // NOI18N
hashField.setText(org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.hashField.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(addButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.addButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(hashLabel, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.hashLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.cancelButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.searchButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(removeButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.removeButton.text")); // NOI18N
titleLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(titleLabel, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.titleLabel.text")); // NOI18N
errorField.setForeground(new java.awt.Color(255, 0, 0));
org.openide.awt.Mnemonics.setLocalizedText(errorField, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.errorField.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(errorField)
.addGap(18, 18, 18)
.addComponent(searchButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cancelButton))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
.addComponent(titleLabel)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(hashLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(addButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(removeButton)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(hashField))))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(hashLabel)
.addComponent(hashField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addButton)
.addComponent(removeButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(searchButton)
.addComponent(errorField))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
hashTable = new javax.swing.JTable();
hashField = new javax.swing.JTextField();
addButton = new javax.swing.JButton();
hashLabel = new javax.swing.JLabel();
cancelButton = new javax.swing.JButton();
searchButton = new javax.swing.JButton();
removeButton = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
titleLabel = new javax.swing.JLabel();
errorField = new javax.swing.JLabel();
hashTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"MD5 Hashes"
}
) {
Class[] types = new Class [] {
java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(hashTable);
hashTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.hashTable.columnModel.title0")); // NOI18N
hashField.setText(org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.hashField.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(addButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.addButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(hashLabel, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.hashLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.cancelButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.searchButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(removeButton, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.removeButton.text")); // NOI18N
titleLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(titleLabel, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.titleLabel.text")); // NOI18N
errorField.setForeground(new java.awt.Color(255, 0, 0));
org.openide.awt.Mnemonics.setLocalizedText(errorField, org.openide.util.NbBundle.getMessage(HashDbSearchPanel.class, "HashDbSearchPanel.errorField.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(errorField)
.addGap(18, 18, 18)
.addComponent(searchButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cancelButton))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
.addComponent(hashLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(hashField))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(titleLabel)
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(addButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(removeButton)))
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(hashLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hashField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addButton)
.addComponent(removeButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(searchButton)
.addComponent(errorField))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/LNReader/src/com/erakk/lnreader/helper/BakaTsukiWebChromeClient.java b/LNReader/src/com/erakk/lnreader/helper/BakaTsukiWebChromeClient.java
index 9b407cd..8673a1d 100644
--- a/LNReader/src/com/erakk/lnreader/helper/BakaTsukiWebChromeClient.java
+++ b/LNReader/src/com/erakk/lnreader/helper/BakaTsukiWebChromeClient.java
@@ -1,57 +1,62 @@
package com.erakk.lnreader.helper;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import com.erakk.lnreader.activity.DisplayLightNovelContentActivity;
import com.erakk.lnreader.dao.NovelsDao;
import com.erakk.lnreader.model.BookmarkModel;
public class BakaTsukiWebChromeClient extends WebChromeClient {
private static final String TAG = BakaTsukiWebChromeClient.class.toString();
private static final String HIGHLIGHT_EVENT = "HIGHLIGHT_EVENT";
private static final String ADD = "highlighted";
private static final String REMOVE = "clear";
private static final String SCROLL_EVENT = "SCROLL_EVENT";
private DisplayLightNovelContentActivity caller;
public BakaTsukiWebChromeClient(DisplayLightNovelContentActivity caller) {
super();
this.caller = caller;
}
@Override
public boolean onConsoleMessage (ConsoleMessage consoleMessage) {
if(consoleMessage.message().startsWith(HIGHLIGHT_EVENT)) {
String data[] = consoleMessage.message().split(":");
- BookmarkModel bookmark = new BookmarkModel();
- bookmark.setPage(caller.content.getPage());
- bookmark.setpIndex(Integer.parseInt(data[1]));
- if(data[2].equalsIgnoreCase(ADD)) {
- bookmark.setExcerpt(data[3]);
- NovelsDao.getInstance(caller).addBookmark(bookmark);
+ try{
+ int pIndex = Integer.parseInt(data[1]);
+ BookmarkModel bookmark = new BookmarkModel();
+ bookmark.setPage(caller.content.getPage());
+ bookmark.setpIndex(pIndex);
+ if(data[2].equalsIgnoreCase(ADD)) {
+ bookmark.setExcerpt(data[3]);
+ NovelsDao.getInstance(caller).addBookmark(bookmark);
+ }
+ else if(data[2].equalsIgnoreCase(REMOVE)) {
+ NovelsDao.getInstance(caller).deleteBookmark(bookmark);
+ }
+ caller.refreshBookmarkData();
+ }catch(NumberFormatException ex) {
+ Log.e(TAG, "Error when parsing pIndex: " + ex.getMessage(), ex);
}
- else if(data[2].equalsIgnoreCase(REMOVE)) {
- NovelsDao.getInstance(caller).deleteBookmark(bookmark);
- }
- caller.refreshBookmarkData();
}
else if (consoleMessage.message().startsWith(SCROLL_EVENT)) {
String data[] = consoleMessage.message().split(":");
caller.updateLastLine(Integer.parseInt(data[1]));
}
else {
Log.d(TAG, "Console: " + consoleMessage.lineNumber() + ":" + consoleMessage.message());
}
return true;
}
@Override
public boolean onJsAlert (WebView view, String url, String message, JsResult result) {
Log.d(TAG, "JSAlert: " + message);
return true;
}
}
| false | true | public boolean onConsoleMessage (ConsoleMessage consoleMessage) {
if(consoleMessage.message().startsWith(HIGHLIGHT_EVENT)) {
String data[] = consoleMessage.message().split(":");
BookmarkModel bookmark = new BookmarkModel();
bookmark.setPage(caller.content.getPage());
bookmark.setpIndex(Integer.parseInt(data[1]));
if(data[2].equalsIgnoreCase(ADD)) {
bookmark.setExcerpt(data[3]);
NovelsDao.getInstance(caller).addBookmark(bookmark);
}
else if(data[2].equalsIgnoreCase(REMOVE)) {
NovelsDao.getInstance(caller).deleteBookmark(bookmark);
}
caller.refreshBookmarkData();
}
else if (consoleMessage.message().startsWith(SCROLL_EVENT)) {
String data[] = consoleMessage.message().split(":");
caller.updateLastLine(Integer.parseInt(data[1]));
}
else {
Log.d(TAG, "Console: " + consoleMessage.lineNumber() + ":" + consoleMessage.message());
}
return true;
}
| public boolean onConsoleMessage (ConsoleMessage consoleMessage) {
if(consoleMessage.message().startsWith(HIGHLIGHT_EVENT)) {
String data[] = consoleMessage.message().split(":");
try{
int pIndex = Integer.parseInt(data[1]);
BookmarkModel bookmark = new BookmarkModel();
bookmark.setPage(caller.content.getPage());
bookmark.setpIndex(pIndex);
if(data[2].equalsIgnoreCase(ADD)) {
bookmark.setExcerpt(data[3]);
NovelsDao.getInstance(caller).addBookmark(bookmark);
}
else if(data[2].equalsIgnoreCase(REMOVE)) {
NovelsDao.getInstance(caller).deleteBookmark(bookmark);
}
caller.refreshBookmarkData();
}catch(NumberFormatException ex) {
Log.e(TAG, "Error when parsing pIndex: " + ex.getMessage(), ex);
}
}
else if (consoleMessage.message().startsWith(SCROLL_EVENT)) {
String data[] = consoleMessage.message().split(":");
caller.updateLastLine(Integer.parseInt(data[1]));
}
else {
Log.d(TAG, "Console: " + consoleMessage.lineNumber() + ":" + consoleMessage.message());
}
return true;
}
|
diff --git a/src/edu/ntnu/idi/goldfish/Main.java b/src/edu/ntnu/idi/goldfish/Main.java
index bf090eb..59e7ced 100644
--- a/src/edu/ntnu/idi/goldfish/Main.java
+++ b/src/edu/ntnu/idi/goldfish/Main.java
@@ -1,76 +1,76 @@
package edu.ntnu.idi.goldfish;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.example.grouplens.GroupLensDataModel;
import org.apache.mahout.cf.taste.model.DataModel;
import edu.ntnu.idi.goldfish.MemoryBased.Similarity;
public class Main {
// disable Mahout logging output
static { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog"); }
/**
* @param args
* @throws IOException
* @throws TasteException
*/
public static void main(String[] args) throws IOException, TasteException {
//DataModel model = new GroupLensDataModel(new File("data/movielens-1m/ratings.dat.gz"));
- DataModel dataModel = new GroupLensDataModel(new File("data/sample100/ratings.dat"));
+ DataModel dataModel = new GroupLensDataModel(new File("datasets/sample100/ratings.dat.gz"));
Evaluator evaluator = new Evaluator(dataModel);
/*
* MEMORY-based evaluation
*
* Evaluate KNN and Threshold based neighborhood models.
* Try all different similarity metrics found in ModelBased.Similarity.
*/
for(Similarity similarity : Similarity.values()) {
// KNN: try different neighborhood sizes
for(int K = 7; K >= 1; K -= 1) {
evaluator.add(new KNN(similarity, K));
}
// THRESHOLD: try different thresholds
for(double T = 0.70; T <= 1.00; T += 0.05) {
evaluator.add(new Threshold(similarity, T));
}
}
ArrayList<EvaluationResult> results = evaluator.evaluateAll();
// sort on RMSE (lower is better)
Collections.sort(results, new Comparator<EvaluationResult>() {
public int compare(EvaluationResult a, EvaluationResult b) {
return (a.RMSE > b.RMSE) ? -1 : (a.RMSE < b.RMSE) ? 1 : 0;
}
});
for(EvaluationResult res : results) {
System.out.println(res);
}
/**
* MODEL-based evaluation
*/
// clustering models (KMeans ... EM?)
// latent semantic models (Matrix Factorizations, etc..)
}
}
| true | true | public static void main(String[] args) throws IOException, TasteException {
//DataModel model = new GroupLensDataModel(new File("data/movielens-1m/ratings.dat.gz"));
DataModel dataModel = new GroupLensDataModel(new File("data/sample100/ratings.dat"));
Evaluator evaluator = new Evaluator(dataModel);
/*
* MEMORY-based evaluation
*
* Evaluate KNN and Threshold based neighborhood models.
* Try all different similarity metrics found in ModelBased.Similarity.
*/
for(Similarity similarity : Similarity.values()) {
// KNN: try different neighborhood sizes
for(int K = 7; K >= 1; K -= 1) {
evaluator.add(new KNN(similarity, K));
}
// THRESHOLD: try different thresholds
for(double T = 0.70; T <= 1.00; T += 0.05) {
evaluator.add(new Threshold(similarity, T));
}
}
ArrayList<EvaluationResult> results = evaluator.evaluateAll();
// sort on RMSE (lower is better)
Collections.sort(results, new Comparator<EvaluationResult>() {
public int compare(EvaluationResult a, EvaluationResult b) {
return (a.RMSE > b.RMSE) ? -1 : (a.RMSE < b.RMSE) ? 1 : 0;
}
});
for(EvaluationResult res : results) {
System.out.println(res);
}
/**
* MODEL-based evaluation
*/
// clustering models (KMeans ... EM?)
// latent semantic models (Matrix Factorizations, etc..)
}
| public static void main(String[] args) throws IOException, TasteException {
//DataModel model = new GroupLensDataModel(new File("data/movielens-1m/ratings.dat.gz"));
DataModel dataModel = new GroupLensDataModel(new File("datasets/sample100/ratings.dat.gz"));
Evaluator evaluator = new Evaluator(dataModel);
/*
* MEMORY-based evaluation
*
* Evaluate KNN and Threshold based neighborhood models.
* Try all different similarity metrics found in ModelBased.Similarity.
*/
for(Similarity similarity : Similarity.values()) {
// KNN: try different neighborhood sizes
for(int K = 7; K >= 1; K -= 1) {
evaluator.add(new KNN(similarity, K));
}
// THRESHOLD: try different thresholds
for(double T = 0.70; T <= 1.00; T += 0.05) {
evaluator.add(new Threshold(similarity, T));
}
}
ArrayList<EvaluationResult> results = evaluator.evaluateAll();
// sort on RMSE (lower is better)
Collections.sort(results, new Comparator<EvaluationResult>() {
public int compare(EvaluationResult a, EvaluationResult b) {
return (a.RMSE > b.RMSE) ? -1 : (a.RMSE < b.RMSE) ? 1 : 0;
}
});
for(EvaluationResult res : results) {
System.out.println(res);
}
/**
* MODEL-based evaluation
*/
// clustering models (KMeans ... EM?)
// latent semantic models (Matrix Factorizations, etc..)
}
|
diff --git a/src/org/sablecc/sablecc/core/Context.java b/src/org/sablecc/sablecc/core/Context.java
index f1428af..184753c 100644
--- a/src/org/sablecc/sablecc/core/Context.java
+++ b/src/org/sablecc/sablecc/core/Context.java
@@ -1,384 +1,388 @@
/* This file is part of SableCC ( http://sablecc.org ).
*
* See the NOTICE file distributed with this work for copyright information.
*
* 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 org.sablecc.sablecc.core;
import java.util.*;
import org.sablecc.exception.*;
import org.sablecc.sablecc.automaton.*;
import org.sablecc.sablecc.core.analysis.*;
import org.sablecc.sablecc.core.interfaces.*;
import org.sablecc.sablecc.syntax3.analysis.*;
import org.sablecc.sablecc.syntax3.node.*;
public abstract class Context
implements IVisitableGrammarPart {
final Grammar grammar;
private ATokens tokensDeclaration;
private AIgnored ignoredDeclaration;
private Set<IToken> tokenSet = new LinkedHashSet<IToken>();
private Set<IToken> ignoredSet = new LinkedHashSet<IToken>();
private Context(
Grammar grammar) {
if (grammar == null) {
throw new InternalException("grammar may not be null");
}
this.grammar = grammar;
}
private void addTokensDeclaration(
ATokens tokensDeclaration) {
this.tokensDeclaration = tokensDeclaration;
}
private void addIgnoredDeclaration(
AIgnored ignoredDeclaration) {
this.ignoredDeclaration = ignoredDeclaration;
}
private void resolveUnitsAndAddToSet(
List<PUnit> units,
Set<IToken> set) {
for (PUnit pUnit : units) {
if (pUnit instanceof ANameUnit) {
ANameUnit unit = (ANameUnit) pUnit;
INameDeclaration nameDeclaration = this.grammar
.getGlobalReference(unit.getIdentifier().getText());
if (nameDeclaration instanceof IToken) {
set.add((IToken) nameDeclaration);
}
+ else if (nameDeclaration == null) {
+ throw SemanticException.undefinedReference(
+ unit.getIdentifier());
+ }
else {
throw SemanticException.badReference(
nameDeclaration.getNameIdentifier(),
nameDeclaration.getNameType(),
new String[] { "token" });
}
}
else if (pUnit instanceof AStringUnit) {
AStringUnit unit = (AStringUnit) pUnit;
set.add(this.grammar.getStringExpression(unit.getString()
.getText()));
}
else if (pUnit instanceof ACharacterUnit) {
ACharacterUnit unit = (ACharacterUnit) pUnit;
PCharacter pCharacter = unit.getCharacter();
if (pCharacter instanceof ACharCharacter) {
ACharCharacter character = (ACharCharacter) pCharacter;
set.add(this.grammar.getCharExpression(character.getChar()
.getText()));
}
else if (pCharacter instanceof ADecCharacter) {
ADecCharacter character = (ADecCharacter) pCharacter;
set.add(this.grammar.getDecExpression(character
.getDecChar().getText()));
}
else if (pCharacter instanceof AHexCharacter) {
AHexCharacter character = (AHexCharacter) pCharacter;
set.add(this.grammar.getHexExpression(character
.getHexChar().getText()));
}
else {
throw new InternalException("unhandled character type");
}
}
else if (pUnit instanceof AStartUnit) {
set.add(this.grammar.getStartExpression());
}
else if (pUnit instanceof AEndUnit) {
set.add(this.grammar.getEndExpression());
}
else {
throw new InternalException("unhandled unit type");
}
}
}
public void resolveTokensAndIgnored() {
if (this.tokensDeclaration != null) {
resolveUnitsAndAddToSet(this.tokensDeclaration.getUnits(),
this.tokenSet);
}
if (this.ignoredDeclaration != null) {
resolveUnitsAndAddToSet(this.ignoredDeclaration.getUnits(),
this.ignoredSet);
}
Set<IToken> intersection = new HashSet<IToken>();
intersection.addAll(this.tokenSet);
intersection.retainAll(this.ignoredSet);
if (intersection.size() > 0) {
throw new InternalException("TODO: raise semantic exception");
}
}
Automaton computeAutomaton() {
Automaton automaton = Automaton.getEmptyAutomaton();
if (GrammarCompiler.RESTRICTED_SYNTAX) {
for (IToken iToken : this.tokenSet) {
if (iToken instanceof LexerExpression) {
LexerExpression token = (LexerExpression) iToken;
automaton = automaton.or(token.getAutomaton().accept(
token.getAcceptation()));
}
}
for (IToken iToken : this.ignoredSet) {
if (iToken instanceof LexerExpression) {
LexerExpression token = (LexerExpression) iToken;
automaton = automaton.or(token.getAutomaton().accept(
token.getAcceptation()));
}
}
return automaton;
}
else {
throw new InternalException("not implemented");
}
}
private static void findTokensAndIgnored(
final Context context,
Node contextDeclaration) {
contextDeclaration.apply(new DepthFirstAdapter() {
@Override
public void inATokens(
ATokens node) {
context.addTokensDeclaration(node);
}
@Override
public void inAIgnored(
AIgnored node) {
context.addIgnoredDeclaration(node);
}
});
}
public Set<LexerExpression> getLexerExpressionTokens() {
Set<LexerExpression> set = new LinkedHashSet<LexerExpression>();
for (IToken iToken : this.tokenSet) {
if (iToken instanceof LexerExpression) {
LexerExpression token = (LexerExpression) iToken;
set.add(token);
}
}
return set;
}
public static class NamedContext
extends Context
implements INameDeclaration {
private ALexerContext lexerDeclaration;
private AParserContext parserDeclaration;
NamedContext(
ALexerContext declaration,
Grammar grammar) {
super(grammar);
if (declaration == null) {
throw new InternalException("declaration may not be null");
}
if (declaration.getName() == null) {
throw new InternalException(
"anonymous contexts are not allowed");
}
this.lexerDeclaration = declaration;
findTokensAndIgnored(this, this.lexerDeclaration);
}
NamedContext(
AParserContext declaration,
Grammar grammar) {
super(grammar);
if (declaration == null) {
throw new InternalException("declaration may not be null");
}
if (declaration.getName() == null) {
throw new InternalException(
"anonymous contexts are not allowed");
}
this.parserDeclaration = declaration;
}
void addDeclaration(
AParserContext declaration) {
if (this.parserDeclaration != null) {
throw SemanticException.spuriousParserNamedContextDeclaration(
declaration, this);
}
if (declaration.getName() == null
|| !declaration.getName().getText().equals(getName())) {
throw new InternalException("invalid context declaration");
}
this.parserDeclaration = declaration;
}
@Override
public TIdentifier getNameIdentifier() {
if (this.lexerDeclaration != null) {
return this.lexerDeclaration.getName();
}
return this.parserDeclaration.getName();
}
@Override
public String getName() {
return getNameIdentifier().getText();
}
@Override
public String getNameType() {
return "context";
}
@Override
public void apply(
IGrammarVisitor visitor) {
visitor.visitNamedContext(this);
}
public AParserContext getParserDeclaration() {
return this.parserDeclaration;
}
}
public static class AnonymousContext
extends Context {
private ALexerContext lexerDeclaration;
private AParserContext parserDeclaration;
AnonymousContext(
ALexerContext declaration,
Grammar grammar) {
super(grammar);
if (declaration == null) {
throw new InternalException("declaration may not be null");
}
if (declaration.getName() != null) {
throw new InternalException("named contexts are not allowed");
}
this.lexerDeclaration = declaration;
findTokensAndIgnored(this, this.lexerDeclaration);
}
AnonymousContext(
AParserContext declaration,
Grammar grammar) {
super(grammar);
if (declaration == null) {
throw new InternalException("declaration may not be null");
}
if (declaration.getName() != null) {
throw new InternalException("named contexts are not allowed");
}
this.parserDeclaration = declaration;
}
void addDeclaration(
AParserContext declaration) {
if (this.parserDeclaration != null) {
throw new InternalException(
"the anonymous context may not have two parser declarations");
}
if (declaration.getName() != null) {
throw new InternalException("invalid context declaration");
}
this.parserDeclaration = declaration;
}
@Override
public void apply(
IGrammarVisitor visitor) {
visitor.visitAnonymousContext(this);
}
}
public boolean isIgnored(
LexerExpression lexerExpression) {
return this.ignoredSet.contains(lexerExpression);
}
}
| true | true | private void resolveUnitsAndAddToSet(
List<PUnit> units,
Set<IToken> set) {
for (PUnit pUnit : units) {
if (pUnit instanceof ANameUnit) {
ANameUnit unit = (ANameUnit) pUnit;
INameDeclaration nameDeclaration = this.grammar
.getGlobalReference(unit.getIdentifier().getText());
if (nameDeclaration instanceof IToken) {
set.add((IToken) nameDeclaration);
}
else {
throw SemanticException.badReference(
nameDeclaration.getNameIdentifier(),
nameDeclaration.getNameType(),
new String[] { "token" });
}
}
else if (pUnit instanceof AStringUnit) {
AStringUnit unit = (AStringUnit) pUnit;
set.add(this.grammar.getStringExpression(unit.getString()
.getText()));
}
else if (pUnit instanceof ACharacterUnit) {
ACharacterUnit unit = (ACharacterUnit) pUnit;
PCharacter pCharacter = unit.getCharacter();
if (pCharacter instanceof ACharCharacter) {
ACharCharacter character = (ACharCharacter) pCharacter;
set.add(this.grammar.getCharExpression(character.getChar()
.getText()));
}
else if (pCharacter instanceof ADecCharacter) {
ADecCharacter character = (ADecCharacter) pCharacter;
set.add(this.grammar.getDecExpression(character
.getDecChar().getText()));
}
else if (pCharacter instanceof AHexCharacter) {
AHexCharacter character = (AHexCharacter) pCharacter;
set.add(this.grammar.getHexExpression(character
.getHexChar().getText()));
}
else {
throw new InternalException("unhandled character type");
}
}
else if (pUnit instanceof AStartUnit) {
set.add(this.grammar.getStartExpression());
}
else if (pUnit instanceof AEndUnit) {
set.add(this.grammar.getEndExpression());
}
else {
throw new InternalException("unhandled unit type");
}
}
}
| private void resolveUnitsAndAddToSet(
List<PUnit> units,
Set<IToken> set) {
for (PUnit pUnit : units) {
if (pUnit instanceof ANameUnit) {
ANameUnit unit = (ANameUnit) pUnit;
INameDeclaration nameDeclaration = this.grammar
.getGlobalReference(unit.getIdentifier().getText());
if (nameDeclaration instanceof IToken) {
set.add((IToken) nameDeclaration);
}
else if (nameDeclaration == null) {
throw SemanticException.undefinedReference(
unit.getIdentifier());
}
else {
throw SemanticException.badReference(
nameDeclaration.getNameIdentifier(),
nameDeclaration.getNameType(),
new String[] { "token" });
}
}
else if (pUnit instanceof AStringUnit) {
AStringUnit unit = (AStringUnit) pUnit;
set.add(this.grammar.getStringExpression(unit.getString()
.getText()));
}
else if (pUnit instanceof ACharacterUnit) {
ACharacterUnit unit = (ACharacterUnit) pUnit;
PCharacter pCharacter = unit.getCharacter();
if (pCharacter instanceof ACharCharacter) {
ACharCharacter character = (ACharCharacter) pCharacter;
set.add(this.grammar.getCharExpression(character.getChar()
.getText()));
}
else if (pCharacter instanceof ADecCharacter) {
ADecCharacter character = (ADecCharacter) pCharacter;
set.add(this.grammar.getDecExpression(character
.getDecChar().getText()));
}
else if (pCharacter instanceof AHexCharacter) {
AHexCharacter character = (AHexCharacter) pCharacter;
set.add(this.grammar.getHexExpression(character
.getHexChar().getText()));
}
else {
throw new InternalException("unhandled character type");
}
}
else if (pUnit instanceof AStartUnit) {
set.add(this.grammar.getStartExpression());
}
else if (pUnit instanceof AEndUnit) {
set.add(this.grammar.getEndExpression());
}
else {
throw new InternalException("unhandled unit type");
}
}
}
|
diff --git a/src/eu/cassandra/sim/entities/people/Activity.java b/src/eu/cassandra/sim/entities/people/Activity.java
index 0a14b6b..5d3188a 100644
--- a/src/eu/cassandra/sim/entities/people/Activity.java
+++ b/src/eu/cassandra/sim/entities/people/Activity.java
@@ -1,350 +1,350 @@
/*
Copyright 2011-2013 The Cassandra Consortium (cassandra-fp7.eu)
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 eu.cassandra.sim.entities.people;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.PriorityBlockingQueue;
import org.apache.log4j.Logger;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import eu.cassandra.server.mongo.MongoActivities;
import eu.cassandra.sim.Event;
import eu.cassandra.sim.SimulationParams;
import eu.cassandra.sim.entities.Entity;
import eu.cassandra.sim.entities.appliances.Appliance;
import eu.cassandra.sim.math.ProbabilityDistribution;
import eu.cassandra.sim.utilities.RNG;
import eu.cassandra.sim.utilities.Utils;
public class Activity extends Entity {
static Logger logger = Logger.getLogger(Activity.class);
private final static String WEEKDAYS = "weekdays";
private final static String WEEKENDS = "weekends";
private final static String NONWORKING = "nonworking";
private final static String WORKING = "working";
private final static String ANY = "any";
private final HashMap<String, ProbabilityDistribution> nTimesGivenDay;
private final HashMap<String, ProbabilityDistribution> probStartTime;
private final HashMap<String, ProbabilityDistribution> probDuration;
private HashMap<String, Vector<Appliance>> appliances;
private HashMap<String, Vector<Double>> probApplianceUsed;
private SimulationParams simulationWorld;
private Vector<DBObject> activityModels;
private Vector<DBObject> starts;
private Vector<DBObject> durations;
private Vector<DBObject> times;
public static class Builder {
// Required parameters
private final String name;
private final String description;
private final String type;
private final HashMap<String, ProbabilityDistribution> nTimesGivenDay;
private final HashMap<String, ProbabilityDistribution> probStartTime;
private final HashMap<String, ProbabilityDistribution> probDuration;
// Optional parameters: not available
private HashMap<String, Vector<Appliance>> appliances;
private HashMap<String, Vector<Double>> probApplianceUsed;
private Vector<DBObject> activityModels;
private Vector<DBObject> starts;
private Vector<DBObject> durations;
private Vector<DBObject> times;
private SimulationParams simulationWorld;
public Builder (String aname, String adesc, String atype, SimulationParams world) {
name = aname;
description = adesc;
type = atype;
appliances = new HashMap<String, Vector<Appliance>>();
probApplianceUsed = new HashMap<String, Vector<Double>>();
nTimesGivenDay = new HashMap<String, ProbabilityDistribution>();
probStartTime = new HashMap<String, ProbabilityDistribution>();
probDuration = new HashMap<String, ProbabilityDistribution>();
activityModels = new Vector<DBObject>();
starts = new Vector<DBObject>();
durations = new Vector<DBObject>();
times = new Vector<DBObject>();
simulationWorld = world;
}
public Builder startTime(String day, ProbabilityDistribution probDist) {
probStartTime.put(day, probDist);
return this;
}
public Builder duration(String day, ProbabilityDistribution probDist) {
probDuration.put(day, probDist);
return this;
}
public Builder times(String day, ProbabilityDistribution probDist) {
nTimesGivenDay.put(day, probDist);
return this;
}
public Activity build () {
return new Activity(this);
}
}
private Activity (Builder builder) {
name = builder.name;
description = builder.description;
type = builder.type;
appliances = builder.appliances;
nTimesGivenDay = builder.nTimesGivenDay;
probStartTime = builder.probStartTime;
probDuration = builder.probDuration;
probApplianceUsed = builder.probApplianceUsed;
simulationWorld = builder.simulationWorld;
starts = builder.starts;
times = builder.times;
durations = builder.durations;
activityModels = builder.activityModels;
}
public void addAppliance (String day, Appliance a, Double prob) {
if(appliances.get(day) == null) {
appliances.put(day, new Vector<Appliance>());
}
Vector<Appliance> vector = appliances.get(day);
vector.add(a);
if(probApplianceUsed.get(day) == null) {
probApplianceUsed.put(day, new Vector<Double>());
}
Vector<Double> probVector = probApplianceUsed.get(day);
probVector.add(prob);
}
public void addStartTime(String day, ProbabilityDistribution probDist) {
probStartTime.put(day, probDist);
}
public void addStarts(DBObject o) {
starts.add(o);
}
public void addDurations(DBObject o) {
durations.add(o);
}
public void addTimes(DBObject o) {
times.add(o);
}
public void addModels(DBObject o) {
activityModels.add(o);
}
public Vector<DBObject> getModels() {
return activityModels;
}
public Vector<DBObject> getStarts() {
return starts;
}
public Vector<DBObject> getTimes() {
return times;
}
public Vector<DBObject> getDurations() {
return durations;
}
public void addDuration(String day, ProbabilityDistribution probDist) {
probDuration.put(day, probDist);
}
public void addTimes(String day, ProbabilityDistribution probDist) {
nTimesGivenDay.put(day, probDist);
}
public String getName () {
return name;
}
public String getDescription () {
return description;
}
public String getType () {
return type;
}
public SimulationParams getSimulationWorld () {
return simulationWorld;
}
private String getKey(String keyword) {
Set<String> set = nTimesGivenDay.keySet();
Iterator<String> iter = set.iterator();
while(iter.hasNext()) {
String key = iter.next();
if(key.contains(keyword)) {
return key;
}
}
return new String();
}
public void
updateDailySchedule(int tick, PriorityBlockingQueue<Event> queue) {
/*
* Decide on the number of times the activity is going to be activated
* during a day
*/
ProbabilityDistribution numOfTimesProb;
ProbabilityDistribution startProb;
ProbabilityDistribution durationProb;
Vector<Double> probVector;
Vector<Appliance> vector;
// First search for specific days
String date = simulationWorld.getSimCalendar().getCurrentDate(tick);
String dayOfWeek = simulationWorld.getSimCalendar().getDayOfWeek(tick);
String dateKey = getKey(date);
String dayOfWeekKey = getKey(dayOfWeek);
boolean weekend = simulationWorld.getSimCalendar().isWeekend(tick);
numOfTimesProb = nTimesGivenDay.get(dateKey);
startProb = probStartTime.get(dateKey);
durationProb = probDuration.get(dateKey);
probVector = probApplianceUsed.get(dateKey);
vector = appliances.get(dateKey);
// Then search for specific days
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
numOfTimesProb = nTimesGivenDay.get(dayOfWeekKey);
startProb = probStartTime.get(dayOfWeekKey);
durationProb = probDuration.get(dayOfWeekKey);
probVector = probApplianceUsed.get(dayOfWeekKey);
vector = appliances.get(dayOfWeekKey);
// Then for weekdays and weekends
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
if (weekend) {
numOfTimesProb = nTimesGivenDay.get(WEEKENDS);
startProb = probStartTime.get(WEEKENDS);
durationProb = probDuration.get(WEEKENDS);
probVector = probApplianceUsed.get(WEEKENDS);
vector = appliances.get(WEEKENDS);
} else {
numOfTimesProb = nTimesGivenDay.get(WEEKDAYS);
startProb = probStartTime.get(WEEKDAYS);
durationProb = probDuration.get(WEEKDAYS);
probVector = probApplianceUsed.get(WEEKDAYS);
vector = appliances.get(WEEKDAYS);
}
// Backwards compatibility
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
if (weekend) {
numOfTimesProb = nTimesGivenDay.get(NONWORKING);
startProb = probStartTime.get(NONWORKING);
durationProb = probDuration.get(NONWORKING);
probVector = probApplianceUsed.get(NONWORKING);
vector = appliances.get(NONWORKING);
} else {
numOfTimesProb = nTimesGivenDay.get(WORKING);
startProb = probStartTime.get(WORKING);
durationProb = probDuration.get(WORKING);
probVector = probApplianceUsed.get(WORKING);
vector = appliances.get(WORKING);
}
// Then for any
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
numOfTimesProb = nTimesGivenDay.get(ANY);
startProb = probStartTime.get(ANY);
durationProb = probDuration.get(ANY);
probVector = probApplianceUsed.get(ANY);
vector = appliances.get(ANY);
}
}
}
}
if(notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
int numOfTimes = 0;
try {
numOfTimes = numOfTimesProb.getPrecomputedBin();
} catch (Exception e) {
logger.error(Utils.stackTraceToString(e.getStackTrace()));
e.printStackTrace();
}
/*
* Decide the duration and start time for each activity activation
*/
while (numOfTimes > 0) {
int duration = Math.max(durationProb.getPrecomputedBin(), 1);
- int startTime = startProb.getPrecomputedBin();
+ int startTime = Math.min(Math.max(startProb.getPrecomputedBin(), 0), 1439);
// Select appliances to be switched on
for (int j = 0; j < vector.size(); j++) {
//if (RNG.nextDouble() < probVector.get(j).doubleValue()) {
if (RNG.nextDouble() < 1.0) {
Appliance a = vector.get(j);
int appDuration = duration;
int appStartTime = startTime;
String hash = Utils.hashcode((new Long(RNG.nextLong()).toString()));
Event eOn = new Event(tick + appStartTime, Event.SWITCH_ON, a, hash);
// System.out.println((tick + appStartTime) + " " + Event.SWITCH_ON + " " + a.getName());
queue.offer(eOn);
Event eOff =
new Event(tick + appStartTime + appDuration, Event.SWITCH_OFF, a, hash);
queue.offer(eOff);
// System.out.println((tick + appStartTime + appDuration) + " " + Event.SWITCH_ON + " " + a.getName());
}
}
numOfTimes--;
}
}
}
public boolean notNull(Object a,
Object b,
Object c,
Object d,
Object e) {
return a != null &&
b != null &&
c != null &&
d != null &&
e != null;
}
@Override
public BasicDBObject toDBObject() {
BasicDBObject obj = new BasicDBObject();
obj.put("name", name);
obj.put("description", description);
obj.put("type", type);
obj.put("pers_id", parentId);
return obj;
}
@Override
public String getCollection() {
return MongoActivities.COL_ACTIVITIES;
}
}
| true | true | public void
updateDailySchedule(int tick, PriorityBlockingQueue<Event> queue) {
/*
* Decide on the number of times the activity is going to be activated
* during a day
*/
ProbabilityDistribution numOfTimesProb;
ProbabilityDistribution startProb;
ProbabilityDistribution durationProb;
Vector<Double> probVector;
Vector<Appliance> vector;
// First search for specific days
String date = simulationWorld.getSimCalendar().getCurrentDate(tick);
String dayOfWeek = simulationWorld.getSimCalendar().getDayOfWeek(tick);
String dateKey = getKey(date);
String dayOfWeekKey = getKey(dayOfWeek);
boolean weekend = simulationWorld.getSimCalendar().isWeekend(tick);
numOfTimesProb = nTimesGivenDay.get(dateKey);
startProb = probStartTime.get(dateKey);
durationProb = probDuration.get(dateKey);
probVector = probApplianceUsed.get(dateKey);
vector = appliances.get(dateKey);
// Then search for specific days
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
numOfTimesProb = nTimesGivenDay.get(dayOfWeekKey);
startProb = probStartTime.get(dayOfWeekKey);
durationProb = probDuration.get(dayOfWeekKey);
probVector = probApplianceUsed.get(dayOfWeekKey);
vector = appliances.get(dayOfWeekKey);
// Then for weekdays and weekends
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
if (weekend) {
numOfTimesProb = nTimesGivenDay.get(WEEKENDS);
startProb = probStartTime.get(WEEKENDS);
durationProb = probDuration.get(WEEKENDS);
probVector = probApplianceUsed.get(WEEKENDS);
vector = appliances.get(WEEKENDS);
} else {
numOfTimesProb = nTimesGivenDay.get(WEEKDAYS);
startProb = probStartTime.get(WEEKDAYS);
durationProb = probDuration.get(WEEKDAYS);
probVector = probApplianceUsed.get(WEEKDAYS);
vector = appliances.get(WEEKDAYS);
}
// Backwards compatibility
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
if (weekend) {
numOfTimesProb = nTimesGivenDay.get(NONWORKING);
startProb = probStartTime.get(NONWORKING);
durationProb = probDuration.get(NONWORKING);
probVector = probApplianceUsed.get(NONWORKING);
vector = appliances.get(NONWORKING);
} else {
numOfTimesProb = nTimesGivenDay.get(WORKING);
startProb = probStartTime.get(WORKING);
durationProb = probDuration.get(WORKING);
probVector = probApplianceUsed.get(WORKING);
vector = appliances.get(WORKING);
}
// Then for any
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
numOfTimesProb = nTimesGivenDay.get(ANY);
startProb = probStartTime.get(ANY);
durationProb = probDuration.get(ANY);
probVector = probApplianceUsed.get(ANY);
vector = appliances.get(ANY);
}
}
}
}
if(notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
int numOfTimes = 0;
try {
numOfTimes = numOfTimesProb.getPrecomputedBin();
} catch (Exception e) {
logger.error(Utils.stackTraceToString(e.getStackTrace()));
e.printStackTrace();
}
/*
* Decide the duration and start time for each activity activation
*/
while (numOfTimes > 0) {
int duration = Math.max(durationProb.getPrecomputedBin(), 1);
int startTime = startProb.getPrecomputedBin();
// Select appliances to be switched on
for (int j = 0; j < vector.size(); j++) {
//if (RNG.nextDouble() < probVector.get(j).doubleValue()) {
if (RNG.nextDouble() < 1.0) {
Appliance a = vector.get(j);
int appDuration = duration;
int appStartTime = startTime;
String hash = Utils.hashcode((new Long(RNG.nextLong()).toString()));
Event eOn = new Event(tick + appStartTime, Event.SWITCH_ON, a, hash);
// System.out.println((tick + appStartTime) + " " + Event.SWITCH_ON + " " + a.getName());
queue.offer(eOn);
Event eOff =
new Event(tick + appStartTime + appDuration, Event.SWITCH_OFF, a, hash);
queue.offer(eOff);
// System.out.println((tick + appStartTime + appDuration) + " " + Event.SWITCH_ON + " " + a.getName());
}
}
numOfTimes--;
}
}
}
| public void
updateDailySchedule(int tick, PriorityBlockingQueue<Event> queue) {
/*
* Decide on the number of times the activity is going to be activated
* during a day
*/
ProbabilityDistribution numOfTimesProb;
ProbabilityDistribution startProb;
ProbabilityDistribution durationProb;
Vector<Double> probVector;
Vector<Appliance> vector;
// First search for specific days
String date = simulationWorld.getSimCalendar().getCurrentDate(tick);
String dayOfWeek = simulationWorld.getSimCalendar().getDayOfWeek(tick);
String dateKey = getKey(date);
String dayOfWeekKey = getKey(dayOfWeek);
boolean weekend = simulationWorld.getSimCalendar().isWeekend(tick);
numOfTimesProb = nTimesGivenDay.get(dateKey);
startProb = probStartTime.get(dateKey);
durationProb = probDuration.get(dateKey);
probVector = probApplianceUsed.get(dateKey);
vector = appliances.get(dateKey);
// Then search for specific days
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
numOfTimesProb = nTimesGivenDay.get(dayOfWeekKey);
startProb = probStartTime.get(dayOfWeekKey);
durationProb = probDuration.get(dayOfWeekKey);
probVector = probApplianceUsed.get(dayOfWeekKey);
vector = appliances.get(dayOfWeekKey);
// Then for weekdays and weekends
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
if (weekend) {
numOfTimesProb = nTimesGivenDay.get(WEEKENDS);
startProb = probStartTime.get(WEEKENDS);
durationProb = probDuration.get(WEEKENDS);
probVector = probApplianceUsed.get(WEEKENDS);
vector = appliances.get(WEEKENDS);
} else {
numOfTimesProb = nTimesGivenDay.get(WEEKDAYS);
startProb = probStartTime.get(WEEKDAYS);
durationProb = probDuration.get(WEEKDAYS);
probVector = probApplianceUsed.get(WEEKDAYS);
vector = appliances.get(WEEKDAYS);
}
// Backwards compatibility
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
if (weekend) {
numOfTimesProb = nTimesGivenDay.get(NONWORKING);
startProb = probStartTime.get(NONWORKING);
durationProb = probDuration.get(NONWORKING);
probVector = probApplianceUsed.get(NONWORKING);
vector = appliances.get(NONWORKING);
} else {
numOfTimesProb = nTimesGivenDay.get(WORKING);
startProb = probStartTime.get(WORKING);
durationProb = probDuration.get(WORKING);
probVector = probApplianceUsed.get(WORKING);
vector = appliances.get(WORKING);
}
// Then for any
if(!notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
numOfTimesProb = nTimesGivenDay.get(ANY);
startProb = probStartTime.get(ANY);
durationProb = probDuration.get(ANY);
probVector = probApplianceUsed.get(ANY);
vector = appliances.get(ANY);
}
}
}
}
if(notNull(numOfTimesProb, startProb, durationProb, probVector, vector)) {
int numOfTimes = 0;
try {
numOfTimes = numOfTimesProb.getPrecomputedBin();
} catch (Exception e) {
logger.error(Utils.stackTraceToString(e.getStackTrace()));
e.printStackTrace();
}
/*
* Decide the duration and start time for each activity activation
*/
while (numOfTimes > 0) {
int duration = Math.max(durationProb.getPrecomputedBin(), 1);
int startTime = Math.min(Math.max(startProb.getPrecomputedBin(), 0), 1439);
// Select appliances to be switched on
for (int j = 0; j < vector.size(); j++) {
//if (RNG.nextDouble() < probVector.get(j).doubleValue()) {
if (RNG.nextDouble() < 1.0) {
Appliance a = vector.get(j);
int appDuration = duration;
int appStartTime = startTime;
String hash = Utils.hashcode((new Long(RNG.nextLong()).toString()));
Event eOn = new Event(tick + appStartTime, Event.SWITCH_ON, a, hash);
// System.out.println((tick + appStartTime) + " " + Event.SWITCH_ON + " " + a.getName());
queue.offer(eOn);
Event eOff =
new Event(tick + appStartTime + appDuration, Event.SWITCH_OFF, a, hash);
queue.offer(eOff);
// System.out.println((tick + appStartTime + appDuration) + " " + Event.SWITCH_ON + " " + a.getName());
}
}
numOfTimes--;
}
}
}
|
diff --git a/srcj/com/sun/electric/tool/drc/Schematic.java b/srcj/com/sun/electric/tool/drc/Schematic.java
index 339ff98fb..e1d9d01f1 100644
--- a/srcj/com/sun/electric/tool/drc/Schematic.java
+++ b/srcj/com/sun/electric/tool/drc/Schematic.java
@@ -1,659 +1,659 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Schematic.java
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.drc;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.GenMath;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.network.NetworkTool;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.Name;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.Connection;
import com.sun.electric.database.topology.Geometric;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.topology.RTBounds;
import com.sun.electric.database.topology.RTNode;
import com.sun.electric.database.topology.RTNode.Search;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.technologies.Artwork;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.technologies.Schematics;
import com.sun.electric.tool.user.ErrorLogger;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Class to do schematic design-rule checking.
* Examines artwork of a schematic for sensibility.
*/
public class Schematic
{
// Cells, nodes and arcs
private Set<ElectricObject> nodesChecked = new HashSet<ElectricObject>();
private ErrorLogger errorLogger;
private Map<Geometric,List<Variable>> newVariables = new HashMap<Geometric,List<Variable>>();
public static void doCheck(ErrorLogger errorLog, Cell cell, Geometric[] geomsToCheck, DRC.DRCPreferences dp)
{
Schematic s = new Schematic();
s.errorLogger = errorLog;
s.checkSchematicCellRecursively(cell, geomsToCheck);
DRC.addDRCUpdate(0, null, null, null, null, s.newVariables, dp);
}
private Cell isACellToCheck(Geometric geo)
{
if (geo instanceof NodeInst)
{
NodeInst ni = (NodeInst)geo;
// ignore documentation icon
if (ni.isIconOfParent()) return null;
if (!ni.isCellInstance()) return null;
Cell subCell = (Cell)ni.getProto();
Cell contentsCell = subCell.contentsView();
if (contentsCell == null) contentsCell = subCell;
if (nodesChecked.contains(contentsCell)) return null;
return contentsCell;
}
return null;
}
private void checkSchematicCellRecursively(Cell cell, Geometric[] geomsToCheck)
{
nodesChecked.add(cell);
// ignore if not a schematic
if (!cell.isSchematic() && cell.getTechnology() != Schematics.tech())
return;
// recursively check contents in case of hierchically checking
if (geomsToCheck == null)
{
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
Cell contentsCell = isACellToCheck(ni);
if (contentsCell != null)
checkSchematicCellRecursively(contentsCell, geomsToCheck);
}
}
else
{
for (Geometric geo : geomsToCheck)
{
Cell contentsCell = isACellToCheck(geo);
if (contentsCell != null)
checkSchematicCellRecursively(contentsCell, geomsToCheck);
}
}
// now check this cell
System.out.println("Checking schematic " + cell);
ErrorGrouper eg = new ErrorGrouper(cell);
checkSchematicCell(cell, false, geomsToCheck, eg);
}
private int cellIndexCounter;
private class ErrorGrouper
{
private boolean inited;
private int cellIndex;
private Cell cell;
ErrorGrouper(Cell cell)
{
inited = false;
cellIndex = cellIndexCounter++;
this.cell = cell;
}
public int getSortKey()
{
if (!inited)
{
inited = true;
errorLogger.setGroupName(cellIndex, cell.getName());
}
return cellIndex;
}
}
private void checkSchematicCell(Cell cell, boolean justThis, Geometric[] geomsToCheck, ErrorGrouper eg)
{
int initialErrorCount = errorLogger.getNumErrors();
Netlist netlist = cell.getNetlist();
// Normal hierarchically geometry
if (geomsToCheck == null)
{
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (!ni.isCellInstance() &&
ni.getProto().getTechnology() == Generic.tech()) continue;
schematicDoCheck(netlist, ni, eg);
}
for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
schematicDoCheck(netlist, ai, eg);
}
} else
{
for (Geometric geo : geomsToCheck)
schematicDoCheck(netlist, geo, eg);
}
checkCaseInsensitiveNetworks(netlist, eg);
checkArrayedIconsConflicts(cell, eg);
int errorCount = errorLogger.getNumErrors();
int thisErrors = errorCount - initialErrorCount;
String indent = " ";
if (justThis) indent = "";
if (thisErrors == 0) System.out.println(indent + "No errors found"); else
System.out.println(indent + thisErrors + " errors found");
if (justThis) errorLogger.termLogging(true);
}
/**
* Method to add all variables of a given NodeInst that must be added after Schematics DRC job is done.
*/
private void addVariable(NodeInst ni, Variable var)
{
List<Variable> list = newVariables.get(ni);
if (list == null) // first time
{
list = new ArrayList<Variable>();
newVariables.put(ni, list);
}
list.add(var);
}
/**
* Method to check schematic object "geom".
*/
private void schematicDoCheck(Netlist netlist, Geometric geom, ErrorGrouper eg)
{
// Checked already
if (nodesChecked.contains(geom))
return;
nodesChecked.add(geom);
Cell cell = geom.getParent();
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
NodeProto np = ni.getProto();
// check for bus pins that don't connect to any bus arcs
if (np == Schematics.tech().busPinNode)
{
// proceed only if it has no exports on it
if (!ni.hasExports())
{
// must not connect to any bus arcs
boolean found = false;
for(Iterator<Connection> it = ni.getConnections(); it.hasNext(); )
{
Connection con = it.next();
if (con.getArc().getProto() == Schematics.tech().bus_arc) { found = true; break; }
}
if (!found)
{
errorLogger.logError("Bus pin does not connect to any bus arcs", geom, cell, null, eg.getSortKey());
return;
}
}
// make a list of all bus networks at the pin
Set<Network> onPin = new HashSet<Network>();
boolean hadBusses = false;
for(Iterator<Connection> it = ni.getConnections(); it.hasNext(); )
{
Connection con = it.next();
ArcInst ai = con.getArc();
if (ai.getProto() != Schematics.tech().bus_arc) continue;
hadBusses = true;
- int wid = ai.getNameKey().busWidth();
+ int wid = netlist.getBusWidth(ai);
for(int i=0; i<wid; i++)
{
Network net = netlist.getNetwork(ai, i);
onPin.add(net);
}
}
// flag any wire arcs not connected to each other through the bus pin
List<Geometric> geomList = null;
for(Iterator<Connection> it = ni.getConnections(); it.hasNext(); )
{
Connection con = it.next();
ArcInst ai = con.getArc();
if (ai.getProto() != Schematics.tech().wire_arc) continue;
Network net = netlist.getNetwork(ai, 0);
if (onPin.contains(net)) continue;
if (geomList == null) geomList = new ArrayList<Geometric>();
geomList.add(ai);
}
if (geomList != null)
{
geomList.add(ni);
String msg;
if (hadBusses) msg = "Wire arcs do not connect to bus through a bus pin"; else
msg = "Wire arcs do not connect to each other through a bus pin";
errorLogger.logMessage(msg, geomList, cell, eg.getSortKey(), true);
return;
}
}
// check all pins
if (np.getFunction().isPin())
{
// may be stranded if there are no exports or arcs
if (!ni.hasExports() && !ni.hasConnections())
{
// see if the pin has displayable variables on it
boolean found = false;
for(Iterator<Variable> it = ni.getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (var.isDisplay()) { found = true; break; }
}
if (!found)
{
errorLogger.logError("Stranded pin (not connected or exported)", geom, cell, null, eg.getSortKey());
return;
}
}
if (ni.isInlinePin())
{
errorLogger.logError("Unnecessary pin (between 2 arcs)", geom, cell, null, eg.getSortKey());
return;
}
Point2D pinLoc = ni.invisiblePinWithOffsetText(false);
if (pinLoc != null)
{
List<Geometric> geomList = new ArrayList<Geometric>();
List<EPoint> ptList = new ArrayList<EPoint>();
geomList.add(geom);
ptList.add(new EPoint(ni.getAnchorCenterX(), ni.getAnchorCenterY()));
ptList.add(new EPoint(pinLoc.getX(), pinLoc.getY()));
errorLogger.logMessageWithLines("Invisible pin has text in different location",
geomList, ptList, cell, eg.getSortKey(), true);
return;
}
}
// check parameters
if (np instanceof Cell)
{
Cell instCell = (Cell)np;
Cell contentsCell = instCell.contentsView();
if (contentsCell == null) contentsCell = instCell;
// ensure that this node matches the parameter list
for(Iterator<Variable> it = ni.getDefinedParameters(); it.hasNext(); )
{
Variable var = it.next();
assert ni.isParam(var.getKey());
Variable foundVar = contentsCell.getParameter(var.getKey());
if (foundVar == null)
{
// this node's parameter is no longer on the cell: delete from instance
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" is invalid", geom, cell, null, eg.getSortKey());
} else
{
// this node's parameter is still on the cell: make sure units are OK
if (var.getUnit() != foundVar.getUnit())
{
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" had incorrect units (now fixed)", geom, cell, null, eg.getSortKey());
addVariable(ni, var.withUnit(foundVar.getUnit()));
}
// make sure visibility is OK
if (foundVar.isInterior())
{
if (var.isDisplay())
{
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" should not be visible (now fixed)", geom, cell, null, eg.getSortKey());
addVariable(ni, var.withDisplay(false));
}
} else
{
if (!var.isDisplay())
{
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" should be visible (now fixed)", geom, cell, null, eg.getSortKey());
addVariable(ni, var.withDisplay(true));
}
}
}
}
// make sure instance name isn't the same as a network in the cell
String nodeName = ni.getName();
for(Iterator<Network> it = netlist.getNetworks(); it.hasNext(); )
{
Network net = it.next();
if (net.hasName(nodeName))
{
errorLogger.logError("Node " + ni + " is named '" + nodeName +
"' which conflicts with a network name in this cell", geom, cell, null, eg.getSortKey());
break;
}
}
}
// check all exports for proper icon/schematics characteristics match
Cell parentCell = ni.getParent();
for(Iterator<Cell> cIt = parentCell.getCellGroup().getCells(); cIt.hasNext(); )
{
Cell iconCell = cIt.next();
if (iconCell.getView() != View.ICON) continue;
for(Iterator<Export> it = ni.getExports(); it.hasNext(); )
{
Export e = it.next();
List<Export> allExports = e.findAllEquivalents(iconCell, false);
for(Export iconExport : allExports)
{
if (e.getCharacteristic() != iconExport.getCharacteristic())
{
errorLogger.logError("Export '" + e.getName() + "' on " + ni +
" is " + e.getCharacteristic().getFullName() +
" but export in icon cell " + iconCell.describe(false) + " is " +
iconExport.getCharacteristic().getFullName(), geom, cell, null, eg.getSortKey());
}
}
}
}
// check for port overlap
checkPortOverlap(netlist, ni, eg);
} else
{
ArcInst ai = (ArcInst)geom;
// check for being floating if it does not have a visible name on it
boolean checkDangle = false;
if (Artwork.isArtworkArc(ai.getProto()))
return; // ignore artwork arcs
Name arcName = ai.getNameKey();
if (arcName == null || arcName.isTempname()) checkDangle = true;
if (checkDangle)
{
// do not check for dangle when busses are on named networks
if (ai.getProto() == Schematics.tech().bus_arc)
{
Name name = netlist.getBusName(ai);
if (name != null && !name.isTempname()) checkDangle = false;
}
}
if (checkDangle)
{
// check to see if this arc is floating
for(int i=0; i<2; i++)
{
NodeInst ni = ai.getPortInst(i).getNodeInst();
// OK if not a pin
if (!ni.getProto().getFunction().isPin()) continue;
// OK if it has exports on it
if (ni.hasExports()) continue;
// OK if it connects to more than 1 arc
if (ni.getNumConnections() != 1) continue;
// the arc dangles
errorLogger.logError("Arc dangles", geom, cell, null, eg.getSortKey());
return;
}
}
// check to see if its width is sensible
int signals = netlist.getBusWidth(ai);
if (signals < 1) signals = 1;
for(int i=0; i<2; i++)
{
PortInst pi = ai.getPortInst(i);
NodeInst ni = pi.getNodeInst();
if (!ni.isCellInstance()) continue;
Cell subNp = (Cell)ni.getProto();
PortProto pp = pi.getPortProto();
Cell np = subNp.contentsView();
if (np != null)
{
pp = ((Export)pi.getPortProto()).findEquivalent(np);
if (pp == null || pp == pi.getPortProto())
{
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(geom);
geomList.add(ni);
errorLogger.logMessage("Arc " + ai.describe(true) + " connects to " +
pi.getPortProto() + " of " + ni + ", but there is no equivalent port in " + np,
geomList, cell, eg.getSortKey(), true);
continue;
}
}
int portWidth = netlist.getBusWidth((Export)pp);
if (portWidth < 1) portWidth = 1;
int nodeSize = ni.getNameKey().busWidth();
if (nodeSize <= 0) nodeSize = 1;
if (signals != portWidth && signals != portWidth*nodeSize)
{
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(geom);
geomList.add(ni);
errorLogger.logMessage("Arc " + ai.describe(true) + " (" + signals + " wide) connects to " +
pp + " of " + ni + " (" + portWidth + " wide)", geomList, cell, eg.getSortKey(), true);
}
}
// check to see if it covers a pin
Rectangle2D rect = ai.getBounds();
Network net = netlist.getNetwork(ai, 0);
for(RTNode.Search sea = new RTNode.Search(rect, cell.getTopology().getRTree(), true); sea.hasNext(); )
{
Geometric oGeom = (Geometric)sea.next();
if (oGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)oGeom;
// must be a pin on an unconnected network
if (ni.getFunction() != PrimitiveNode.Function.PIN) continue;
if (ni.getProto().getTechnology() == Generic.tech()) continue;
Network oNet = netlist.getNetwork(ni.getOnlyPortInst());
if (net == oNet) continue;
// error if it is on the line of this arc
Rectangle2D bound = ni.getBounds();
if (bound.getWidth() > 0 || bound.getHeight() > 0) continue;
Point2D ctr = new Point2D.Double(bound.getCenterX(), bound.getCenterY());
if (GenMath.isOnLine(ai.getHeadLocation(), ai.getTailLocation(), ctr))
{
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(ai);
geomList.add(ni);
errorLogger.logMessage("Pin " + ni.describe(false) + " touches arc " + ai.describe(true) + " but does not connect to it ",
geomList, cell, eg.getSortKey(), true);
}
}
}
}
}
/**
* Method to check whether any port on a node overlaps others without connecting.
*/
private void checkPortOverlap(Netlist netlist, NodeInst ni, ErrorGrouper eg)
{
if (ni.getProto().getTechnology() == Generic.tech() ||
ni.getProto().getTechnology() == Artwork.tech()) return;
Cell cell = ni.getParent();
for(Iterator<PortInst> it = ni.getPortInsts(); it.hasNext(); )
{
PortInst pi = it.next();
Network net = netlist.getNetwork(pi);
Rectangle2D bounds = pi.getPoly().getBounds2D();
for(Iterator<RTBounds> sIt = cell.searchIterator(bounds); sIt.hasNext(); )
{
Geometric oGeom = (Geometric)sIt.next();
if (!(oGeom instanceof NodeInst)) continue;
NodeInst oNi = (NodeInst)oGeom;
if (ni == oNi) continue;
if (ni.getNodeIndex() > oNi.getNodeIndex()) continue;
if (oNi.getProto().getTechnology() == Generic.tech() ||
oNi.getProto().getTechnology() == Artwork.tech()) continue;
// see if ports touch
for(Iterator<PortInst> pIt = oNi.getPortInsts(); pIt.hasNext(); )
{
PortInst oPi = pIt.next();
Rectangle2D oBounds = oPi.getPoly().getBounds2D();
if (bounds.getMaxX() < oBounds.getMinX()) continue;
if (bounds.getMinX() > oBounds.getMaxX()) continue;
if (bounds.getMaxY() < oBounds.getMinY()) continue;
if (bounds.getMinY() > oBounds.getMaxY()) continue;
// see if they are connected
if (net == netlist.getNetwork(oPi)) continue;
// report the error
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(ni);
geomList.add(oNi);
errorLogger.logMessage("Nodes '" + ni + "' '" + oNi + "' have touching ports that are not connected",
geomList, cell, eg.getSortKey(), true);
return;
}
}
}
}
private void checkCaseInsensitiveNetworks(Netlist netlist, ErrorGrouper eg) {
Cell cell = netlist.getCell();
HashMap<String, Network> canonicToNetwork = new HashMap<String, Network>();
for (Iterator<Network> it = netlist.getNetworks(); it.hasNext(); ) {
Network net = it.next();
for (Iterator<String> sit = net.getNames(); sit.hasNext(); ) {
String s = sit.next();
String cs = TextUtils.canonicString(s);
Network net1 = canonicToNetwork.get(cs);
if (net1 == null ) {
canonicToNetwork.put(cs, net);
} else if (net1 != net) {
String message = "Network: Schematic " + cell.libDescribe() + " doesn't connect " + net + " and " + net1;
boolean sameName = net1.hasName(s);
if (sameName)
message += " Like-named Global and Export may be connected in future releases";
System.out.println(message);
List<Geometric> geomList = new ArrayList<Geometric>();
push(geomList, net);
push(geomList, net1);
errorLogger.logMessage(message, geomList, cell, eg.getSortKey(), sameName);
}
}
}
}
private void checkArrayedIconsConflicts(Cell cell, ErrorGrouper eg) {
IdentityHashMap<Name,NodeInst> name2node = new IdentityHashMap<Name,NodeInst>();
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
Name n = ni.getNameKey();
if (n.isTempname()) {
continue;
}
for (int arrayIndex = 0; arrayIndex < n.busWidth(); arrayIndex++) {
Name subName = n.subname(arrayIndex);
NodeInst oni = name2node.get(subName);
if (oni != null) {
String msg = "Network: " + cell + " has instances " + ni + " and "
+ oni + " with same name <" + subName + ">";
System.out.println(msg);
List<Geometric> geomList = Arrays.<Geometric>asList(ni, oni);
errorLogger.logMessage(msg, geomList, cell, eg.getSortKey(), true);
}
}
}
}
private void push(List<Geometric> geomList, Network net) {
Iterator<Export> eit = net.getExports();
if (eit.hasNext()) {
geomList.add(eit.next().getOriginalPort().getNodeInst());
return;
}
Iterator<ArcInst> ait = net.getArcs();
if (ait.hasNext()) {
geomList.add(ait.next());
return;
}
Iterator<PortInst> pit = net.getPorts();
if (pit.hasNext()) {
geomList.add(pit.next().getNodeInst());
return;
}
}
}
| true | true | private void schematicDoCheck(Netlist netlist, Geometric geom, ErrorGrouper eg)
{
// Checked already
if (nodesChecked.contains(geom))
return;
nodesChecked.add(geom);
Cell cell = geom.getParent();
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
NodeProto np = ni.getProto();
// check for bus pins that don't connect to any bus arcs
if (np == Schematics.tech().busPinNode)
{
// proceed only if it has no exports on it
if (!ni.hasExports())
{
// must not connect to any bus arcs
boolean found = false;
for(Iterator<Connection> it = ni.getConnections(); it.hasNext(); )
{
Connection con = it.next();
if (con.getArc().getProto() == Schematics.tech().bus_arc) { found = true; break; }
}
if (!found)
{
errorLogger.logError("Bus pin does not connect to any bus arcs", geom, cell, null, eg.getSortKey());
return;
}
}
// make a list of all bus networks at the pin
Set<Network> onPin = new HashSet<Network>();
boolean hadBusses = false;
for(Iterator<Connection> it = ni.getConnections(); it.hasNext(); )
{
Connection con = it.next();
ArcInst ai = con.getArc();
if (ai.getProto() != Schematics.tech().bus_arc) continue;
hadBusses = true;
int wid = ai.getNameKey().busWidth();
for(int i=0; i<wid; i++)
{
Network net = netlist.getNetwork(ai, i);
onPin.add(net);
}
}
// flag any wire arcs not connected to each other through the bus pin
List<Geometric> geomList = null;
for(Iterator<Connection> it = ni.getConnections(); it.hasNext(); )
{
Connection con = it.next();
ArcInst ai = con.getArc();
if (ai.getProto() != Schematics.tech().wire_arc) continue;
Network net = netlist.getNetwork(ai, 0);
if (onPin.contains(net)) continue;
if (geomList == null) geomList = new ArrayList<Geometric>();
geomList.add(ai);
}
if (geomList != null)
{
geomList.add(ni);
String msg;
if (hadBusses) msg = "Wire arcs do not connect to bus through a bus pin"; else
msg = "Wire arcs do not connect to each other through a bus pin";
errorLogger.logMessage(msg, geomList, cell, eg.getSortKey(), true);
return;
}
}
// check all pins
if (np.getFunction().isPin())
{
// may be stranded if there are no exports or arcs
if (!ni.hasExports() && !ni.hasConnections())
{
// see if the pin has displayable variables on it
boolean found = false;
for(Iterator<Variable> it = ni.getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (var.isDisplay()) { found = true; break; }
}
if (!found)
{
errorLogger.logError("Stranded pin (not connected or exported)", geom, cell, null, eg.getSortKey());
return;
}
}
if (ni.isInlinePin())
{
errorLogger.logError("Unnecessary pin (between 2 arcs)", geom, cell, null, eg.getSortKey());
return;
}
Point2D pinLoc = ni.invisiblePinWithOffsetText(false);
if (pinLoc != null)
{
List<Geometric> geomList = new ArrayList<Geometric>();
List<EPoint> ptList = new ArrayList<EPoint>();
geomList.add(geom);
ptList.add(new EPoint(ni.getAnchorCenterX(), ni.getAnchorCenterY()));
ptList.add(new EPoint(pinLoc.getX(), pinLoc.getY()));
errorLogger.logMessageWithLines("Invisible pin has text in different location",
geomList, ptList, cell, eg.getSortKey(), true);
return;
}
}
// check parameters
if (np instanceof Cell)
{
Cell instCell = (Cell)np;
Cell contentsCell = instCell.contentsView();
if (contentsCell == null) contentsCell = instCell;
// ensure that this node matches the parameter list
for(Iterator<Variable> it = ni.getDefinedParameters(); it.hasNext(); )
{
Variable var = it.next();
assert ni.isParam(var.getKey());
Variable foundVar = contentsCell.getParameter(var.getKey());
if (foundVar == null)
{
// this node's parameter is no longer on the cell: delete from instance
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" is invalid", geom, cell, null, eg.getSortKey());
} else
{
// this node's parameter is still on the cell: make sure units are OK
if (var.getUnit() != foundVar.getUnit())
{
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" had incorrect units (now fixed)", geom, cell, null, eg.getSortKey());
addVariable(ni, var.withUnit(foundVar.getUnit()));
}
// make sure visibility is OK
if (foundVar.isInterior())
{
if (var.isDisplay())
{
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" should not be visible (now fixed)", geom, cell, null, eg.getSortKey());
addVariable(ni, var.withDisplay(false));
}
} else
{
if (!var.isDisplay())
{
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" should be visible (now fixed)", geom, cell, null, eg.getSortKey());
addVariable(ni, var.withDisplay(true));
}
}
}
}
// make sure instance name isn't the same as a network in the cell
String nodeName = ni.getName();
for(Iterator<Network> it = netlist.getNetworks(); it.hasNext(); )
{
Network net = it.next();
if (net.hasName(nodeName))
{
errorLogger.logError("Node " + ni + " is named '" + nodeName +
"' which conflicts with a network name in this cell", geom, cell, null, eg.getSortKey());
break;
}
}
}
// check all exports for proper icon/schematics characteristics match
Cell parentCell = ni.getParent();
for(Iterator<Cell> cIt = parentCell.getCellGroup().getCells(); cIt.hasNext(); )
{
Cell iconCell = cIt.next();
if (iconCell.getView() != View.ICON) continue;
for(Iterator<Export> it = ni.getExports(); it.hasNext(); )
{
Export e = it.next();
List<Export> allExports = e.findAllEquivalents(iconCell, false);
for(Export iconExport : allExports)
{
if (e.getCharacteristic() != iconExport.getCharacteristic())
{
errorLogger.logError("Export '" + e.getName() + "' on " + ni +
" is " + e.getCharacteristic().getFullName() +
" but export in icon cell " + iconCell.describe(false) + " is " +
iconExport.getCharacteristic().getFullName(), geom, cell, null, eg.getSortKey());
}
}
}
}
// check for port overlap
checkPortOverlap(netlist, ni, eg);
} else
{
ArcInst ai = (ArcInst)geom;
// check for being floating if it does not have a visible name on it
boolean checkDangle = false;
if (Artwork.isArtworkArc(ai.getProto()))
return; // ignore artwork arcs
Name arcName = ai.getNameKey();
if (arcName == null || arcName.isTempname()) checkDangle = true;
if (checkDangle)
{
// do not check for dangle when busses are on named networks
if (ai.getProto() == Schematics.tech().bus_arc)
{
Name name = netlist.getBusName(ai);
if (name != null && !name.isTempname()) checkDangle = false;
}
}
if (checkDangle)
{
// check to see if this arc is floating
for(int i=0; i<2; i++)
{
NodeInst ni = ai.getPortInst(i).getNodeInst();
// OK if not a pin
if (!ni.getProto().getFunction().isPin()) continue;
// OK if it has exports on it
if (ni.hasExports()) continue;
// OK if it connects to more than 1 arc
if (ni.getNumConnections() != 1) continue;
// the arc dangles
errorLogger.logError("Arc dangles", geom, cell, null, eg.getSortKey());
return;
}
}
// check to see if its width is sensible
int signals = netlist.getBusWidth(ai);
if (signals < 1) signals = 1;
for(int i=0; i<2; i++)
{
PortInst pi = ai.getPortInst(i);
NodeInst ni = pi.getNodeInst();
if (!ni.isCellInstance()) continue;
Cell subNp = (Cell)ni.getProto();
PortProto pp = pi.getPortProto();
Cell np = subNp.contentsView();
if (np != null)
{
pp = ((Export)pi.getPortProto()).findEquivalent(np);
if (pp == null || pp == pi.getPortProto())
{
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(geom);
geomList.add(ni);
errorLogger.logMessage("Arc " + ai.describe(true) + " connects to " +
pi.getPortProto() + " of " + ni + ", but there is no equivalent port in " + np,
geomList, cell, eg.getSortKey(), true);
continue;
}
}
int portWidth = netlist.getBusWidth((Export)pp);
if (portWidth < 1) portWidth = 1;
int nodeSize = ni.getNameKey().busWidth();
if (nodeSize <= 0) nodeSize = 1;
if (signals != portWidth && signals != portWidth*nodeSize)
{
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(geom);
geomList.add(ni);
errorLogger.logMessage("Arc " + ai.describe(true) + " (" + signals + " wide) connects to " +
pp + " of " + ni + " (" + portWidth + " wide)", geomList, cell, eg.getSortKey(), true);
}
}
// check to see if it covers a pin
Rectangle2D rect = ai.getBounds();
Network net = netlist.getNetwork(ai, 0);
for(RTNode.Search sea = new RTNode.Search(rect, cell.getTopology().getRTree(), true); sea.hasNext(); )
{
Geometric oGeom = (Geometric)sea.next();
if (oGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)oGeom;
// must be a pin on an unconnected network
if (ni.getFunction() != PrimitiveNode.Function.PIN) continue;
if (ni.getProto().getTechnology() == Generic.tech()) continue;
Network oNet = netlist.getNetwork(ni.getOnlyPortInst());
if (net == oNet) continue;
// error if it is on the line of this arc
Rectangle2D bound = ni.getBounds();
if (bound.getWidth() > 0 || bound.getHeight() > 0) continue;
Point2D ctr = new Point2D.Double(bound.getCenterX(), bound.getCenterY());
if (GenMath.isOnLine(ai.getHeadLocation(), ai.getTailLocation(), ctr))
{
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(ai);
geomList.add(ni);
errorLogger.logMessage("Pin " + ni.describe(false) + " touches arc " + ai.describe(true) + " but does not connect to it ",
geomList, cell, eg.getSortKey(), true);
}
}
}
}
}
| private void schematicDoCheck(Netlist netlist, Geometric geom, ErrorGrouper eg)
{
// Checked already
if (nodesChecked.contains(geom))
return;
nodesChecked.add(geom);
Cell cell = geom.getParent();
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
NodeProto np = ni.getProto();
// check for bus pins that don't connect to any bus arcs
if (np == Schematics.tech().busPinNode)
{
// proceed only if it has no exports on it
if (!ni.hasExports())
{
// must not connect to any bus arcs
boolean found = false;
for(Iterator<Connection> it = ni.getConnections(); it.hasNext(); )
{
Connection con = it.next();
if (con.getArc().getProto() == Schematics.tech().bus_arc) { found = true; break; }
}
if (!found)
{
errorLogger.logError("Bus pin does not connect to any bus arcs", geom, cell, null, eg.getSortKey());
return;
}
}
// make a list of all bus networks at the pin
Set<Network> onPin = new HashSet<Network>();
boolean hadBusses = false;
for(Iterator<Connection> it = ni.getConnections(); it.hasNext(); )
{
Connection con = it.next();
ArcInst ai = con.getArc();
if (ai.getProto() != Schematics.tech().bus_arc) continue;
hadBusses = true;
int wid = netlist.getBusWidth(ai);
for(int i=0; i<wid; i++)
{
Network net = netlist.getNetwork(ai, i);
onPin.add(net);
}
}
// flag any wire arcs not connected to each other through the bus pin
List<Geometric> geomList = null;
for(Iterator<Connection> it = ni.getConnections(); it.hasNext(); )
{
Connection con = it.next();
ArcInst ai = con.getArc();
if (ai.getProto() != Schematics.tech().wire_arc) continue;
Network net = netlist.getNetwork(ai, 0);
if (onPin.contains(net)) continue;
if (geomList == null) geomList = new ArrayList<Geometric>();
geomList.add(ai);
}
if (geomList != null)
{
geomList.add(ni);
String msg;
if (hadBusses) msg = "Wire arcs do not connect to bus through a bus pin"; else
msg = "Wire arcs do not connect to each other through a bus pin";
errorLogger.logMessage(msg, geomList, cell, eg.getSortKey(), true);
return;
}
}
// check all pins
if (np.getFunction().isPin())
{
// may be stranded if there are no exports or arcs
if (!ni.hasExports() && !ni.hasConnections())
{
// see if the pin has displayable variables on it
boolean found = false;
for(Iterator<Variable> it = ni.getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (var.isDisplay()) { found = true; break; }
}
if (!found)
{
errorLogger.logError("Stranded pin (not connected or exported)", geom, cell, null, eg.getSortKey());
return;
}
}
if (ni.isInlinePin())
{
errorLogger.logError("Unnecessary pin (between 2 arcs)", geom, cell, null, eg.getSortKey());
return;
}
Point2D pinLoc = ni.invisiblePinWithOffsetText(false);
if (pinLoc != null)
{
List<Geometric> geomList = new ArrayList<Geometric>();
List<EPoint> ptList = new ArrayList<EPoint>();
geomList.add(geom);
ptList.add(new EPoint(ni.getAnchorCenterX(), ni.getAnchorCenterY()));
ptList.add(new EPoint(pinLoc.getX(), pinLoc.getY()));
errorLogger.logMessageWithLines("Invisible pin has text in different location",
geomList, ptList, cell, eg.getSortKey(), true);
return;
}
}
// check parameters
if (np instanceof Cell)
{
Cell instCell = (Cell)np;
Cell contentsCell = instCell.contentsView();
if (contentsCell == null) contentsCell = instCell;
// ensure that this node matches the parameter list
for(Iterator<Variable> it = ni.getDefinedParameters(); it.hasNext(); )
{
Variable var = it.next();
assert ni.isParam(var.getKey());
Variable foundVar = contentsCell.getParameter(var.getKey());
if (foundVar == null)
{
// this node's parameter is no longer on the cell: delete from instance
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" is invalid", geom, cell, null, eg.getSortKey());
} else
{
// this node's parameter is still on the cell: make sure units are OK
if (var.getUnit() != foundVar.getUnit())
{
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" had incorrect units (now fixed)", geom, cell, null, eg.getSortKey());
addVariable(ni, var.withUnit(foundVar.getUnit()));
}
// make sure visibility is OK
if (foundVar.isInterior())
{
if (var.isDisplay())
{
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" should not be visible (now fixed)", geom, cell, null, eg.getSortKey());
addVariable(ni, var.withDisplay(false));
}
} else
{
if (!var.isDisplay())
{
String trueVarName = var.getTrueName();
errorLogger.logError("Parameter '" + trueVarName + "' on " + ni +
" should be visible (now fixed)", geom, cell, null, eg.getSortKey());
addVariable(ni, var.withDisplay(true));
}
}
}
}
// make sure instance name isn't the same as a network in the cell
String nodeName = ni.getName();
for(Iterator<Network> it = netlist.getNetworks(); it.hasNext(); )
{
Network net = it.next();
if (net.hasName(nodeName))
{
errorLogger.logError("Node " + ni + " is named '" + nodeName +
"' which conflicts with a network name in this cell", geom, cell, null, eg.getSortKey());
break;
}
}
}
// check all exports for proper icon/schematics characteristics match
Cell parentCell = ni.getParent();
for(Iterator<Cell> cIt = parentCell.getCellGroup().getCells(); cIt.hasNext(); )
{
Cell iconCell = cIt.next();
if (iconCell.getView() != View.ICON) continue;
for(Iterator<Export> it = ni.getExports(); it.hasNext(); )
{
Export e = it.next();
List<Export> allExports = e.findAllEquivalents(iconCell, false);
for(Export iconExport : allExports)
{
if (e.getCharacteristic() != iconExport.getCharacteristic())
{
errorLogger.logError("Export '" + e.getName() + "' on " + ni +
" is " + e.getCharacteristic().getFullName() +
" but export in icon cell " + iconCell.describe(false) + " is " +
iconExport.getCharacteristic().getFullName(), geom, cell, null, eg.getSortKey());
}
}
}
}
// check for port overlap
checkPortOverlap(netlist, ni, eg);
} else
{
ArcInst ai = (ArcInst)geom;
// check for being floating if it does not have a visible name on it
boolean checkDangle = false;
if (Artwork.isArtworkArc(ai.getProto()))
return; // ignore artwork arcs
Name arcName = ai.getNameKey();
if (arcName == null || arcName.isTempname()) checkDangle = true;
if (checkDangle)
{
// do not check for dangle when busses are on named networks
if (ai.getProto() == Schematics.tech().bus_arc)
{
Name name = netlist.getBusName(ai);
if (name != null && !name.isTempname()) checkDangle = false;
}
}
if (checkDangle)
{
// check to see if this arc is floating
for(int i=0; i<2; i++)
{
NodeInst ni = ai.getPortInst(i).getNodeInst();
// OK if not a pin
if (!ni.getProto().getFunction().isPin()) continue;
// OK if it has exports on it
if (ni.hasExports()) continue;
// OK if it connects to more than 1 arc
if (ni.getNumConnections() != 1) continue;
// the arc dangles
errorLogger.logError("Arc dangles", geom, cell, null, eg.getSortKey());
return;
}
}
// check to see if its width is sensible
int signals = netlist.getBusWidth(ai);
if (signals < 1) signals = 1;
for(int i=0; i<2; i++)
{
PortInst pi = ai.getPortInst(i);
NodeInst ni = pi.getNodeInst();
if (!ni.isCellInstance()) continue;
Cell subNp = (Cell)ni.getProto();
PortProto pp = pi.getPortProto();
Cell np = subNp.contentsView();
if (np != null)
{
pp = ((Export)pi.getPortProto()).findEquivalent(np);
if (pp == null || pp == pi.getPortProto())
{
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(geom);
geomList.add(ni);
errorLogger.logMessage("Arc " + ai.describe(true) + " connects to " +
pi.getPortProto() + " of " + ni + ", but there is no equivalent port in " + np,
geomList, cell, eg.getSortKey(), true);
continue;
}
}
int portWidth = netlist.getBusWidth((Export)pp);
if (portWidth < 1) portWidth = 1;
int nodeSize = ni.getNameKey().busWidth();
if (nodeSize <= 0) nodeSize = 1;
if (signals != portWidth && signals != portWidth*nodeSize)
{
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(geom);
geomList.add(ni);
errorLogger.logMessage("Arc " + ai.describe(true) + " (" + signals + " wide) connects to " +
pp + " of " + ni + " (" + portWidth + " wide)", geomList, cell, eg.getSortKey(), true);
}
}
// check to see if it covers a pin
Rectangle2D rect = ai.getBounds();
Network net = netlist.getNetwork(ai, 0);
for(RTNode.Search sea = new RTNode.Search(rect, cell.getTopology().getRTree(), true); sea.hasNext(); )
{
Geometric oGeom = (Geometric)sea.next();
if (oGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)oGeom;
// must be a pin on an unconnected network
if (ni.getFunction() != PrimitiveNode.Function.PIN) continue;
if (ni.getProto().getTechnology() == Generic.tech()) continue;
Network oNet = netlist.getNetwork(ni.getOnlyPortInst());
if (net == oNet) continue;
// error if it is on the line of this arc
Rectangle2D bound = ni.getBounds();
if (bound.getWidth() > 0 || bound.getHeight() > 0) continue;
Point2D ctr = new Point2D.Double(bound.getCenterX(), bound.getCenterY());
if (GenMath.isOnLine(ai.getHeadLocation(), ai.getTailLocation(), ctr))
{
List<Geometric> geomList = new ArrayList<Geometric>();
geomList.add(ai);
geomList.add(ni);
errorLogger.logMessage("Pin " + ni.describe(false) + " touches arc " + ai.describe(true) + " but does not connect to it ",
geomList, cell, eg.getSortKey(), true);
}
}
}
}
}
|
diff --git a/src/shoddybattleclient/ChallengeWindow.java b/src/shoddybattleclient/ChallengeWindow.java
index 4e9c9f3..ac47280 100644
--- a/src/shoddybattleclient/ChallengeWindow.java
+++ b/src/shoddybattleclient/ChallengeWindow.java
@@ -1,149 +1,150 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* ChallengeWindow.java
*
* Created on Apr 23, 2009, 10:33:15 PM
*/
package shoddybattleclient;
import java.awt.FileDialog;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import shoddybattleclient.network.ServerLink;
import shoddybattleclient.network.ServerLink.ChallengeMediator;
import shoddybattleclient.shoddybattle.*;
import shoddybattleclient.utils.TeamFileParser;
/**
*
* @author ben
*/
public class ChallengeWindow extends javax.swing.JFrame {
private Pokemon[] m_team = null;
private ServerLink m_link;
private String m_opponent;
/** Creates new form ChallengeWindow */
public ChallengeWindow(ServerLink link, String opponent) {
initComponents();
m_link = link;
m_opponent = opponent;
btnChallenge.setEnabled(false);
}
/** 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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
lstTeam = new javax.swing.JList();
btnLoad = new javax.swing.JButton();
btnChallenge = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setLocationByPlatform(true);
jScrollPane1.setViewportView(lstTeam);
btnLoad.setText("Load Team");
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
btnChallenge.setText("Challenge");
btnChallenge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChallengeActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, btnChallenge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, btnLoad, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(btnLoad)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(btnChallenge)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
FileDialog fd = new FileDialog(this, "Choose a team to load", FileDialog.LOAD);
fd.setVisible(true);
if (fd.getFile() == null) return;
String file = fd.getDirectory() + fd.getFile();
//String file = "/home/Catherine/team1.sbt";
TeamFileParser tfp = new TeamFileParser();
m_team = tfp.parseTeam(file);
if (m_team != null) {
lstTeam.setModel(new DefaultComboBoxModel(m_team));
btnChallenge.setEnabled(true);
}
}//GEN-LAST:event_btnLoadActionPerformed
private void btnChallengeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChallengeActionPerformed
m_link.postChallenge(new ChallengeMediator() {
public Pokemon[] getTeam() {
return m_team;
}
public void informResolved(boolean accepted) {
if (accepted) {
m_link.postChallengeTeam(m_opponent, m_team);
} else {
// todo: internationalisation
JOptionPane.showMessageDialog(ChallengeWindow.this,
m_opponent + " rejected the challenge.");
}
dispose();
}
public String getOpponent() {
return m_opponent;
}
public int getGeneration() {
return 1; // platinum
}
public int getActivePartySize() {
return 2; // doubles
}
});
btnChallenge.setEnabled(false);
}//GEN-LAST:event_btnChallengeActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnChallenge;
private javax.swing.JButton btnLoad;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList lstTeam;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
lstTeam = new javax.swing.JList();
btnLoad = new javax.swing.JButton();
btnChallenge = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jScrollPane1.setViewportView(lstTeam);
btnLoad.setText("Load Team");
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
btnChallenge.setText("Challenge");
btnChallenge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChallengeActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, btnChallenge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, btnLoad, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(btnLoad)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(btnChallenge)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
lstTeam = new javax.swing.JList();
btnLoad = new javax.swing.JButton();
btnChallenge = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
jScrollPane1.setViewportView(lstTeam);
btnLoad.setText("Load Team");
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
btnChallenge.setText("Challenge");
btnChallenge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChallengeActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, btnChallenge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, btnLoad, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(btnLoad)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(btnChallenge)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/mod/jodd-wot/src/jodd/lagarto/adapter/htmlstapler/HtmlStaplerTagAdapter.java b/mod/jodd-wot/src/jodd/lagarto/adapter/htmlstapler/HtmlStaplerTagAdapter.java
index 664b90370..0c68500c2 100644
--- a/mod/jodd-wot/src/jodd/lagarto/adapter/htmlstapler/HtmlStaplerTagAdapter.java
+++ b/mod/jodd-wot/src/jodd/lagarto/adapter/htmlstapler/HtmlStaplerTagAdapter.java
@@ -1,102 +1,102 @@
// Copyright (c) 2003-2011, Jodd Team (jodd.org). All Rights Reserved.
package jodd.lagarto.adapter.htmlstapler;
import jodd.lagarto.Tag;
import jodd.lagarto.TagAdapter;
import jodd.lagarto.TagVisitor;
import javax.servlet.http.HttpServletRequest;
/**
* HTML Stapler tag adapter parses HTML page and collects all information
* about linking resource files.
*/
public class HtmlStaplerTagAdapter extends TagAdapter {
protected final HtmlStaplerBundlesManager bundlesManager;
protected final BundleAction jsBundleAction;
protected final BundleAction cssBundleAction;
protected boolean insideConditionalComment;
public HtmlStaplerTagAdapter(TagVisitor target, HttpServletRequest request) {
super(target);
bundlesManager = HtmlStaplerBundlesManager.getBundlesManager(request);
jsBundleAction = bundlesManager.start(request, "js");
cssBundleAction = bundlesManager.start(request, "css");
insideConditionalComment = false;
}
// ---------------------------------------------------------------- javascripts
@Override
public void script(Tag tag, CharSequence body) {
if (insideConditionalComment == false) {
String src = tag.getAttributeValue("src", false);
if (src != null) {
String link = jsBundleAction.processLink(src);
if (link != null) {
tag.setAttributeValue("src", false, link);
super.script(tag, body);
}
return;
}
}
super.script(tag, body);
}
// ---------------------------------------------------------------- css
@Override
public void tag(Tag tag) {
if (insideConditionalComment == false) {
if (tag.getName().equalsIgnoreCase("link")) {
String type = tag.getAttributeValue("type", false);
- if (type == null || type.equalsIgnoreCase("text/css") == true) {
+ if (type != null && type.equalsIgnoreCase("text/css") == true) {
String media = tag.getAttributeValue("media", false);
if (media == null || media.contains("screen")) {
String href = tag.getAttributeValue("href", false);
String link = cssBundleAction.processLink(href);
if (link != null) {
tag.setAttribute("href", false, link);
super.tag(tag);
}
return;
}
}
}
}
super.tag(tag);
}
// ---------------------------------------------------------------- conditional comments
@Override
public void condCommentStart(CharSequence conditionalComment, boolean isDownlevelHidden) {
insideConditionalComment = true;
super.condCommentStart(conditionalComment, isDownlevelHidden);
}
@Override
public void condCommentEnd(CharSequence conditionalComment, boolean isDownlevelHidden) {
insideConditionalComment = false;
super.condCommentEnd(conditionalComment, isDownlevelHidden);
}
// ---------------------------------------------------------------- end
@Override
public void end() {
jsBundleAction.end();
cssBundleAction.end();
super.end();
}
}
| true | true | public void tag(Tag tag) {
if (insideConditionalComment == false) {
if (tag.getName().equalsIgnoreCase("link")) {
String type = tag.getAttributeValue("type", false);
if (type == null || type.equalsIgnoreCase("text/css") == true) {
String media = tag.getAttributeValue("media", false);
if (media == null || media.contains("screen")) {
String href = tag.getAttributeValue("href", false);
String link = cssBundleAction.processLink(href);
if (link != null) {
tag.setAttribute("href", false, link);
super.tag(tag);
}
return;
}
}
}
}
super.tag(tag);
}
| public void tag(Tag tag) {
if (insideConditionalComment == false) {
if (tag.getName().equalsIgnoreCase("link")) {
String type = tag.getAttributeValue("type", false);
if (type != null && type.equalsIgnoreCase("text/css") == true) {
String media = tag.getAttributeValue("media", false);
if (media == null || media.contains("screen")) {
String href = tag.getAttributeValue("href", false);
String link = cssBundleAction.processLink(href);
if (link != null) {
tag.setAttribute("href", false, link);
super.tag(tag);
}
return;
}
}
}
}
super.tag(tag);
}
|
diff --git a/src/com/hackrgt/katanalocate/MainActivity.java b/src/com/hackrgt/katanalocate/MainActivity.java
index 2a9dae4..e6557e1 100644
--- a/src/com/hackrgt/katanalocate/MainActivity.java
+++ b/src/com/hackrgt/katanalocate/MainActivity.java
@@ -1,133 +1,133 @@
package com.hackrgt.katanalocate;
import java.io.File;
import com.facebook.FacebookActivity;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.hackrgt.katanalocate.R;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends FacebookActivity {
private MainFragment mainFragment;
private boolean isResumed = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//open a facebook session
this.openSession();
if (savedInstanceState == null) {
// Add the fragment
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Restore the fragment
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
/*
* Testing Inbox View
*/
Log.d("Main Activity", "Tried to create DBHelper");
//DataBaseHelper dbhelper = new DataBaseHelper(this);
//dbhelper.addUser("Chandim", "Chandim", "Success");
//dbhelper.addUser("Diya", "Diya", "Dummy");
MessageTable message = new MessageTable(1, "10:30", 36, 54, "Troll", "Troll", "Diya", 2);
MessageTable message2 = new MessageTable(2, "9:00", 36, 54, "Troll2", "Troll2", "Diya", 2);
UserTable Receiver = new UserTable("Chandim", "Chandim", "Success");
UserTable Sender = new UserTable("Diya", "Diya", "Dummy");
//dbhelper.addMessage(message, Sender, Receiver);
//dbhelper.addMessage(message2, Receiver, Sender);
//dbhelper.checkMessage();
//dbhelper.checkUser();
//dbhelper.checkSendReceive();
}
@Override
protected void onSessionStateChange(SessionState state, Exception exception) {
super.onSessionStateChange(state, exception);
if (isResumed) {
mainFragment.onSessionStateChange(state, exception);
if (state.isClosed()) {
//Default to SSO login and show dialog if Facebook App isnt installed
this.openSession();
}
}
if (state.isOpened()) {
//Get database and check if it has been created
File database = getApplicationContext().getDatabasePath("DatabaseLocation");
if (!database.exists()) {
//Get users Facebook Id
Log.d("Chandim - Main Activity", "Database doesn't exist");
final Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
Request request = Request.newMeRequest(
session,
new Request.GraphUserCallback() {
// callback after Graph API response with user object
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
final String userId = user.getId();
final String userName = user.getName();
//Add the user to the sqlite database
Log.d("Chandim - Main Activity", "Database created");
DataBaseHelper helper = new DataBaseHelper(MainActivity.this);
helper.addUser(userId, userName, "");
helper.addUser("Chandim", "Chandim", "Success");
helper.addUser("Diya", "Diya", "Dummy");
helper.addUser("Nathan", "Nathan", "Hurley");
- MessageTable message = new MessageTable(1, "10:00", 36, 54, "Hi", "It's been a while, how are you?", "Diya", 2);
+ MessageTable message = new MessageTable(1, "1234567", 36, 54, "Hi", "It's been a while, how are you?", "Diya", 2);
helper.sendMessage(message, "Nathan", user.getId());
}
}
}
);
Request.executeBatchAsync(request);
}
}
}
}
@Override
public void onResume() {
super.onResume();
isResumed = true;
}
@Override
public void onPause() {
super.onPause();
isResumed = false;
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session.getState(), null);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
| true | true | protected void onSessionStateChange(SessionState state, Exception exception) {
super.onSessionStateChange(state, exception);
if (isResumed) {
mainFragment.onSessionStateChange(state, exception);
if (state.isClosed()) {
//Default to SSO login and show dialog if Facebook App isnt installed
this.openSession();
}
}
if (state.isOpened()) {
//Get database and check if it has been created
File database = getApplicationContext().getDatabasePath("DatabaseLocation");
if (!database.exists()) {
//Get users Facebook Id
Log.d("Chandim - Main Activity", "Database doesn't exist");
final Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
Request request = Request.newMeRequest(
session,
new Request.GraphUserCallback() {
// callback after Graph API response with user object
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
final String userId = user.getId();
final String userName = user.getName();
//Add the user to the sqlite database
Log.d("Chandim - Main Activity", "Database created");
DataBaseHelper helper = new DataBaseHelper(MainActivity.this);
helper.addUser(userId, userName, "");
helper.addUser("Chandim", "Chandim", "Success");
helper.addUser("Diya", "Diya", "Dummy");
helper.addUser("Nathan", "Nathan", "Hurley");
MessageTable message = new MessageTable(1, "10:00", 36, 54, "Hi", "It's been a while, how are you?", "Diya", 2);
helper.sendMessage(message, "Nathan", user.getId());
}
}
}
);
Request.executeBatchAsync(request);
}
}
}
}
| protected void onSessionStateChange(SessionState state, Exception exception) {
super.onSessionStateChange(state, exception);
if (isResumed) {
mainFragment.onSessionStateChange(state, exception);
if (state.isClosed()) {
//Default to SSO login and show dialog if Facebook App isnt installed
this.openSession();
}
}
if (state.isOpened()) {
//Get database and check if it has been created
File database = getApplicationContext().getDatabasePath("DatabaseLocation");
if (!database.exists()) {
//Get users Facebook Id
Log.d("Chandim - Main Activity", "Database doesn't exist");
final Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
Request request = Request.newMeRequest(
session,
new Request.GraphUserCallback() {
// callback after Graph API response with user object
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
final String userId = user.getId();
final String userName = user.getName();
//Add the user to the sqlite database
Log.d("Chandim - Main Activity", "Database created");
DataBaseHelper helper = new DataBaseHelper(MainActivity.this);
helper.addUser(userId, userName, "");
helper.addUser("Chandim", "Chandim", "Success");
helper.addUser("Diya", "Diya", "Dummy");
helper.addUser("Nathan", "Nathan", "Hurley");
MessageTable message = new MessageTable(1, "1234567", 36, 54, "Hi", "It's been a while, how are you?", "Diya", 2);
helper.sendMessage(message, "Nathan", user.getId());
}
}
}
);
Request.executeBatchAsync(request);
}
}
}
}
|
diff --git a/src/org/geometerplus/zlibrary/ui/android/view/AnimationProvider.java b/src/org/geometerplus/zlibrary/ui/android/view/AnimationProvider.java
index ddaf7698..c6f0dc83 100644
--- a/src/org/geometerplus/zlibrary/ui/android/view/AnimationProvider.java
+++ b/src/org/geometerplus/zlibrary/ui/android/view/AnimationProvider.java
@@ -1,45 +1,45 @@
/*
* Copyright (C) 2007-2011 Geometer Plus <[email protected]>
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.ui.android.view;
import android.graphics.*;
abstract class AnimationProvider {
protected final Paint myPaint;
protected int myStartX;
protected int myStartY;
protected int myEndX;
protected int myEndY;
protected boolean myHorizontal;
protected AnimationProvider(Paint paint) {
myPaint = paint;
}
public void setup(int startX, int startY, int endX, int endY, boolean horizontal) {
myStartX = startX;
- myStartX = startY;
+ myStartY = startY;
myEndX = endX;
myEndY = endY;
myHorizontal = horizontal;
}
public abstract void draw(Canvas canvas, Bitmap bgBitmap, Bitmap fgBitmap);
}
| true | true | public void setup(int startX, int startY, int endX, int endY, boolean horizontal) {
myStartX = startX;
myStartX = startY;
myEndX = endX;
myEndY = endY;
myHorizontal = horizontal;
}
| public void setup(int startX, int startY, int endX, int endY, boolean horizontal) {
myStartX = startX;
myStartY = startY;
myEndX = endX;
myEndY = endY;
myHorizontal = horizontal;
}
|
diff --git a/src/testrunner-lib/src/com/robomorphine/test/filtering/FilterPredicate.java b/src/testrunner-lib/src/com/robomorphine/test/filtering/FilterPredicate.java
index 503a30e..fa6f90e 100644
--- a/src/testrunner-lib/src/com/robomorphine/test/filtering/FilterPredicate.java
+++ b/src/testrunner-lib/src/com/robomorphine/test/filtering/FilterPredicate.java
@@ -1,337 +1,337 @@
package com.robomorphine.test.filtering;
import com.robomorphine.test.annotation.LongTest;
import com.robomorphine.test.annotation.ManualTest;
import com.robomorphine.test.annotation.NonUiTest;
import com.robomorphine.test.annotation.PerformanceTest;
import com.robomorphine.test.annotation.ShortTest;
import com.robomorphine.test.annotation.StabilityTest;
import com.robomorphine.test.annotation.UiTest;
import com.robomorphine.test.filtering.FilterParser.FilterEntry;
import com.robomorphine.test.predicate.HasAnnotation;
import com.robomorphine.test.predicate.IsEnabled;
import com.robomorphine.test.predicate.IsUiTest;
import com.robomorphine.test.predicate.Predicate;
import com.robomorphine.test.predicate.Predicates;
import com.robomorphine.test.predicate.TestTypeEqualsTo;
import android.test.suitebuilder.TestMethod;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* This predicate has special logic for filtering test cases.
* As input it receives a filter of type: "[{+,-}<annotationClass>]*",
* where "+" symbol means "include" and "-" means "exclude".
*
* For example: "+andoird.test.ann1+andoird.test.ann2-andoird.test.ann3".
* "-andoird.test.ann1"
* "-andoird.test.ann1-andoird.test.ann2"
*
* For any TestMethod to be included it should have ANY of "+" annotations and NONE
* of the "-" annotations.
* ( Exclusion "-" takes precedences over Inclusion "+" ). The order is not relevant.
*
* Note: TestMethod annotations are "inherited" from enclosing TestCase class.
*
* For example:
* @a
* class T1 extends TestCase
* {
* void tm1() {}
* @b void tm2() {}
* @b @c void tm3() {}
* @b @c @d void tm4() {}
* }
*
* "+a" -> tm1, tm2, tm3, tm4
* "-a" -> none
* "+b" -> tm2, tm3, tm4
* "-b" -> tm1
* "+a-b" -> tm1
* "+c-d" -> tm3
* "-d+a" -> tm1, tm2, tm3
*
*
* As a special case, if first +/- symbol is omitted then predicate assumes "+".
*
* For example: "android.test.ann1+android.test.ann2" == "+android.test.ann1+android.test.ann2".
*
* Some specific annotations have built-in aliases. This aliases are case insensitive
* (but note that annotation class names _are_ case sensitive). List of aliases:
*
* s, small - com.robomorphine.test.annotation.SmallTest
* short - com.robomorphine.test.annotation.ShortTest (same as SmallTest)
* m, medium - com.robomorphine.test.annotation.MediumTest
* l, large - com.robomorphine.test.annotation.LargeTest
* long - com.robomorphine.test.annotation.LongTest (same as LargeTest) *
* p, perf, performance - com.robomorphine.test.annotation.PerformanceTest
* st, stability - com.robomorphine.test.annotation.StabilityTest
* mn, manual - com.robomorphine.test.annotation.ManualTest
* ui - com.robomorphine.test.annotation.UiTest
*
* For example:
*
* "+s-medium" == "+com.robomorphine.test.annotation.SmallTest-com.robomorphine.test.annotation.MediumTest"
* "s+M+l" == "s+m+l" == "S+M+L"
*
* But some annotations have special meaning and a handled in a different way then all other annotations are.
*
* First special annotation is "com.robomorphine.test.annotation.DisabledTest". When test
* is marked with such annotation it will not run.
*
* Second group of special annotation are:
*
* UiTest - com.robomorphine.test.annotation.UiTest
* NonUiTest - com.robomorphine.test.annotation.NonUiTest
*
* Note that when "+ui" or "-ui" is specified on filter, FilterPredicate uses special logic for
* filtering. It does not use usual "annotation present" logic. If "+ui" or "-ui" is met in filter,
* than "IsUiTest" predicate is used on all test methods. It has next logic (in order of precedence):
*
* 1) If test method has NonUiTest annotation, its considered non-ui test.
* 2) If test method has UiTest annotation, its considered ui test.
* 3) If test method's class has NonUiTest annotation, its considered non-ui test.
* 4) If test method's class has UiTest annotation, its considered ui test.
* 5) If test method's class extends ActivityInstrumentationTestCase/mIsActivityInstrumentationTestCase2
* class its considered ui test.
* 6) Otherwise test method is considered non-ui test.
*
* At any given time each test method is either ui test or non-ui test. If "+ui" test is specified,
* then only ui tests are filtered in. If "-ui" is specified, then only non-ui tests are filtered in.
* If "+ui"/"-ui" is omitted from filter then both ui and non-ui tests are filtered in.
*
* Third (and last) group of special annotations represent test types:
*
* small/short - com.robomorphine.test.annotation.SmallTest/.ShortTest
* medium - android.test.suitebuilder.annotation.MediumTest
* large/long - android.test.suitebuilder.annotation.LargeTest/.LongTest
* performance - android.test.suitebuilder.annotation.PerformanceTest
* stability - android.test.suitebuilder.annotation.StabilityTest
* manual - android.test.suitebuilder.annotation.ManualTest
*
* At any given time any TestMethod may have only one effective test type associated with it.
* Even if several annotations are applied to this TestMethod, only one will take effect during filtering.
* Here is how effective test type is calculated:
*
* 1) If TestMethod has only one TestType annotation -> this annotation takes effect.
* For example:
* @SmallTest void testM1() {} -> small test
* @ManualTest void testM2() {} -> manual test
*
* 2) If TestMethod has several TestType annotations, only one annotations takes effect.
* The winner is determined by annotation precedence order which is next:
* manual > stability > performance > large/long > medium > small/short.
*
* For example:
* @SmallTest @LargeTest void testM1() -> large test
* @LargeTest @SmallTest void testM1() -> large test
* @LargeTest @SmallTest @ManualTest void testM1() -> manual test
*
* 3) If TestMethod has no test type annotations, then test type annotations are taken
* from enclosing TestCase class. If TestCase class has only one test type annotation
* then it takes effects.
*
* For example:
* @SmallTest class T1 extends TestCase
* {
* void testM1() {} -> small test
* }
*
* @LargeTest class T1 extends TestCase
* {
* void testM1() {} -> large test
* }
*
* 4) If TestMethod has no test type annotations, but enclosing TestCase class has
* several test type annotations, then only one test type annotation takes effect.
* This annotation is determined as in step #2 for test methods: according to test type precedence.
*
* For example:
*
* @SmallTest @LargeTest class T1 extends TestCase
* {
* void testM1() {} -> large test
* }
*
* @LargeTest @SmallTest class T1 extends TestCase
* {
* void testM1() {} -> large test
* }
*
* @LargeTest @SmallTest @ManualTest class T1 extends TestCase
* {
* void testM1() {} -> manual test
* }
*
* 5) If nor TestMethod, neither enclosing TestCase class has any of the test type annotations,
* then test is considered to be SmallTest.
*
* For example:
*
* class T1 extends TestCase
* {
* void testM1() {} -> small test
* }
*
*/
public class FilterPredicate implements Predicate<TestMethod> {
private static final String TAG = FilterPredicate.class.getSimpleName();
private final static Map<String, String> KNOWN_ALIASES;
static {
Map<String, String> map = new HashMap<String, String>();
map.put("s".toLowerCase(), SmallTest.class.getName());
map.put("small".toLowerCase(), SmallTest.class.getName());
map.put("short".toLowerCase(), ShortTest.class.getName());
map.put("m".toLowerCase(), MediumTest.class.getName());
map.put("medium".toLowerCase(), MediumTest.class.getName());
map.put("l".toLowerCase(), LargeTest.class.getName());
map.put("large".toLowerCase(), LargeTest.class.getName());
map.put("long".toLowerCase(), LongTest.class.getName());
map.put("p".toLowerCase(), PerformanceTest.class.getName());
map.put("perf".toLowerCase(), PerformanceTest.class.getName());
map.put("performance".toLowerCase(), PerformanceTest.class.getName());
map.put("st".toLowerCase(), StabilityTest.class.getName());
map.put("stable".toLowerCase(), StabilityTest.class.getName());
map.put("stability".toLowerCase(), StabilityTest.class.getName());
map.put("ui".toLowerCase(), UiTest.class.getName());
map.put("mn".toLowerCase(), ManualTest.class.getName());
map.put("manual".toLowerCase(), ManualTest.class.getName());
KNOWN_ALIASES = Collections.unmodifiableMap(map);
}
public String getByAlias(String val) {
val = val.toLowerCase();
if (KNOWN_ALIASES.containsKey(val)) {
return KNOWN_ALIASES.get(val);
}
return val;
}
private final static Predicate<TestMethod> TRUE_PREDICATE = Predicates.<TestMethod>alwaysTrue();
private final Predicate<TestMethod> m_predicate;
public FilterPredicate(String filter) {
Log.w(TAG, "Filtering tests with: \"" + filter + "\"");
m_predicate = createPredicate(FilterParser.parse(filter));
}
@SuppressWarnings("unchecked")
private Class<? extends Annotation> getAnnotationClass(String annotationClassName) {
if (annotationClassName == null) {
return null;
}
annotationClassName = getByAlias(annotationClassName);
try {
Class<?> annotationClass = Class.forName(annotationClassName);
if (annotationClass.isAnnotation()) {
return (Class<? extends Annotation>) annotationClass;
} else {
String msg = String.format("Provided annotation value \"%s\" is not an Annotation",
annotationClassName);
Log.e(TAG, msg);
}
} catch (ClassNotFoundException e) {
String msg = String.format("Could not find class for specified annotation \"%s\"",
annotationClassName);
Log.e(TAG, msg);
}
return null;
}
@SuppressWarnings("all")
private Predicate<TestMethod> createPredicate(List<FilterEntry> filterEntries) {
if (filterEntries == null) {
filterEntries = new LinkedList<FilterEntry>();
}
List<Predicate<TestMethod>> orPredicates = new ArrayList<Predicate<TestMethod>>(
filterEntries.size());
List<Predicate<TestMethod>> andPredicates = new ArrayList<Predicate<TestMethod>>(
filterEntries.size());
for (FilterEntry filterEntry : filterEntries) {
Class<? extends Annotation> annotation = getAnnotationClass(filterEntry.value);
if (annotation != null) {
addPredicate(filterEntry.action, annotation, orPredicates, andPredicates);
}
}
/* skip disabled tests */
andPredicates.add(new IsEnabled());
if (orPredicates.isEmpty())
orPredicates.add(TRUE_PREDICATE);
if (andPredicates.isEmpty())
andPredicates.add(TRUE_PREDICATE);
return Predicates.and(Predicates.or(orPredicates), Predicates.and(andPredicates));
}
private void addPredicate(int action, Class<? extends Annotation> annotation,
List<Predicate<TestMethod>> orPredicates, List<Predicate<TestMethod>> andPredicates) {
/* Special handling for annotations that indicate test type */
if (TestTypeEqualsTo.isTestTypeAnnotation(annotation)) {
switch (action) {
case FilterParser.INCLUDE_ACTION:
orPredicates.add(new TestTypeEqualsTo(annotation));
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates
.add(Predicates.<TestMethod> not(new TestTypeEqualsTo(annotation)));
break;
}
} else if(annotation == UiTest.class) {
switch(action) {
case FilterParser.INCLUDE_ACTION:
andPredicates.add(new IsUiTest());
break;
case FilterParser.EXCLUDE_ACTION:
- andPredicates.add(Predicates.not(new IsUiTest()));
+ andPredicates.add(Predicates.<TestMethod>not(new IsUiTest()));
break;
}
} else if(annotation == NonUiTest.class) {
switch(action) {
case FilterParser.INCLUDE_ACTION:
- andPredicates.add(Predicates.not(new IsUiTest()));
+ andPredicates.add(Predicates.<TestMethod>not(new IsUiTest()));
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates.add(new IsUiTest());
break;
}
} else {
/* All other annotation are handled using standard rules */
switch (action) {
case FilterParser.INCLUDE_ACTION:
orPredicates.add(new HasAnnotation(annotation));
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates.add(Predicates.<TestMethod> not(new HasAnnotation(annotation)));
break;
}
}
}
@Override
public boolean apply(TestMethod t) {
return m_predicate.apply(t);
}
@Override
public String toString() {
return "[filter " + m_predicate.toString() + "]";
}
}
| false | true | private void addPredicate(int action, Class<? extends Annotation> annotation,
List<Predicate<TestMethod>> orPredicates, List<Predicate<TestMethod>> andPredicates) {
/* Special handling for annotations that indicate test type */
if (TestTypeEqualsTo.isTestTypeAnnotation(annotation)) {
switch (action) {
case FilterParser.INCLUDE_ACTION:
orPredicates.add(new TestTypeEqualsTo(annotation));
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates
.add(Predicates.<TestMethod> not(new TestTypeEqualsTo(annotation)));
break;
}
} else if(annotation == UiTest.class) {
switch(action) {
case FilterParser.INCLUDE_ACTION:
andPredicates.add(new IsUiTest());
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates.add(Predicates.not(new IsUiTest()));
break;
}
} else if(annotation == NonUiTest.class) {
switch(action) {
case FilterParser.INCLUDE_ACTION:
andPredicates.add(Predicates.not(new IsUiTest()));
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates.add(new IsUiTest());
break;
}
} else {
/* All other annotation are handled using standard rules */
switch (action) {
case FilterParser.INCLUDE_ACTION:
orPredicates.add(new HasAnnotation(annotation));
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates.add(Predicates.<TestMethod> not(new HasAnnotation(annotation)));
break;
}
}
}
| private void addPredicate(int action, Class<? extends Annotation> annotation,
List<Predicate<TestMethod>> orPredicates, List<Predicate<TestMethod>> andPredicates) {
/* Special handling for annotations that indicate test type */
if (TestTypeEqualsTo.isTestTypeAnnotation(annotation)) {
switch (action) {
case FilterParser.INCLUDE_ACTION:
orPredicates.add(new TestTypeEqualsTo(annotation));
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates
.add(Predicates.<TestMethod> not(new TestTypeEqualsTo(annotation)));
break;
}
} else if(annotation == UiTest.class) {
switch(action) {
case FilterParser.INCLUDE_ACTION:
andPredicates.add(new IsUiTest());
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates.add(Predicates.<TestMethod>not(new IsUiTest()));
break;
}
} else if(annotation == NonUiTest.class) {
switch(action) {
case FilterParser.INCLUDE_ACTION:
andPredicates.add(Predicates.<TestMethod>not(new IsUiTest()));
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates.add(new IsUiTest());
break;
}
} else {
/* All other annotation are handled using standard rules */
switch (action) {
case FilterParser.INCLUDE_ACTION:
orPredicates.add(new HasAnnotation(annotation));
break;
case FilterParser.EXCLUDE_ACTION:
andPredicates.add(Predicates.<TestMethod> not(new HasAnnotation(annotation)));
break;
}
}
}
|
diff --git a/src/com/mitsugaru/Karmiconomy/DatabaseHandler.java b/src/com/mitsugaru/Karmiconomy/DatabaseHandler.java
index e99708a..fcb25db 100644
--- a/src/com/mitsugaru/Karmiconomy/DatabaseHandler.java
+++ b/src/com/mitsugaru/Karmiconomy/DatabaseHandler.java
@@ -1,937 +1,939 @@
package com.mitsugaru.Karmiconomy;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import lib.Mitsugaru.SQLibrary.MySQL;
import lib.Mitsugaru.SQLibrary.SQLite;
import lib.Mitsugaru.SQLibrary.Database.Query;
public class DatabaseHandler
{
private Karmiconomy plugin;
private static Config config;
private SQLite sqlite;
private MySQL mysql;
private boolean useMySQL;
private final DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
public DatabaseHandler(Karmiconomy plugin, Config conf)
{
this.plugin = plugin;
config = conf;
useMySQL = config.useMySQL;
checkTables();
if (config.importSQL)
{
if (useMySQL)
{
importSQL();
}
config.set("mysql.import", false);
}
}
private void checkTables()
{
if (useMySQL)
{
// Connect to mysql database
mysql = new MySQL(plugin.getLogger(), Karmiconomy.TAG, config.host,
config.port, config.database, config.user, config.password);
// Check if table exists
if (!mysql.checkTable(Table.MASTER.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created master table");
// Create table
mysql.createTable("CREATE TABLE "
+ Table.MASTER.getName()
+ " (id INT UNSIGNED NOT NULL AUTO_INCREMENT, playername varchar(32) NOT NULL, laston TEXT NOT NULL, UNIQUE (playername), PRIMARY KEY (id));");
}
if (!mysql.checkTable(Table.ITEMS.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created items table");
mysql.createTable("CREATE TABLE "
+ Table.ITEMS.getName()
+ " (row INT UNSIGNED NOT NULL AUTO_INCREMENT, id INT UNSIGNED NOT NULL, itemid SMALLINT UNSIGNED NOT NULL, data TINYTEXT, durability TINYTEXT, place INT NOT NULL, destroy INT NOT NULL, craft INT NOT NULL, enchant INT NOT NULL, playerDrop INT NOT NULL, pickup INT NOT NULL, PRIMARY KEY(row))");
}
if (!mysql.checkTable(Table.COMMAND.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created command table");
mysql.createTable("CREATE TABLE "
+ Table.COMMAND.getName()
+ " (row INT UNSIGNED NOT NULL AUTO_INCREMENT, id INT UNSIGNED NOT NULL, command TEXT NOT NULL, count INT NOT NULL, PRIMARY KEY(row));");
}
if (!mysql.checkTable(Table.DATA.getName()))
{
plugin.getLogger()
.info(Karmiconomy.TAG + " Created data table");
mysql.createTable("CREATE TABLE "
+ Table.DATA.getName()
+ " (id INT UNSIGNED NOT NULL, bedenter INT NOT NULL, bedleave INT NOT NULL, bowshoot INT NOT NULL, chat INT NOT NULL, death INT NOT NULL, creative INT NOT NULL, survival INT NOT NULL, playerJoin INT NOT NULL, kick INT NOT NULL, quit INT NOT NULL, respawn INT NOT NULL, worldchange INT NOT NULL, tameocelot INT NOT NULL, tamewolf INT NOT NULL, paintingplace INT NOT NULL, eggThrow INT NOT NULL, sneak INT NOT NULL, sprint INT NOT NULL, PRIMARY KEY (id));");
}
if (!mysql.checkTable(Table.PORTAL.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created portal table");
mysql.createTable("CREATE TABLE "
+ Table.PORTAL.getName()
+ " (id INT UNSIGNED NOT NULL, pcreatenether INT NOT NULL, pcreateend INT NOT NULL, pcreatecustom INT NOT NULL, portalenter INT NOT NULL, PRIMARY KEY(id));");
}
if (!mysql.checkTable(Table.BUCKET.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created bucket table");
mysql.createTable("CREATE TABLE "
+ Table.BUCKET.getName()
+ " (id INT UNSIGNED NOT NULL, bemptylava INT NOT NULL, bemptywater INT NOT NULL, bfilllava INT NOT NULL, bfillwater INT NOT NULL, PRIMARY KEY(id));");
}
}
else
{
// Connect to sql database
sqlite = new SQLite(plugin.getLogger(), Karmiconomy.TAG, "data",
plugin.getDataFolder().getAbsolutePath());
// Check if table exists
if (!sqlite.checkTable(Table.MASTER.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created master table");
// Create table
sqlite.createTable("CREATE TABLE "
+ Table.MASTER.getName()
+ " (id INTEGER PRIMARY KEY, playername varchar(32) NOT NULL, laston TEXT NOT NULL, UNIQUE (playername));");
}
if (!sqlite.checkTable(Table.ITEMS.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created items table");
sqlite.createTable("CREATE TABLE "
+ Table.ITEMS.getName()
+ " (row INTEGER PRIMARY KEY, id INTEGER NOT NULL, itemid INTEGER NOT NULL, data TEXT NOT NULL, durability TEXT NOT NULL, place INTEGER NOT NULL, destroy INTEGER NOT NULL, craft INTEGER NOT NULL, enchant INTEGER NOT NULL, playerDrop INTEGER NOT NULL, pickup INT NOT NULL)");
}
if (!sqlite.checkTable(Table.COMMAND.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created command table");
sqlite.createTable("CREATE TABLE "
+ Table.COMMAND.getName()
+ " (row INTEGER PRIMARY KEY, id INTEGER NOT NULL, command TEXT NOT NULL, count INTEGER NOT NULL);");
}
if (!sqlite.checkTable(Table.DATA.getName()))
{
plugin.getLogger()
.info(Karmiconomy.TAG + " Created data table");
sqlite.createTable("CREATE TABLE "
+ Table.DATA.getName()
+ " (id INTEGER PRIMARY KEY, bedenter INTEGER NOT NULL, bedleave INTEGER NOT NULL, bowshoot INTEGER NOT NULL, chat INTEGER NOT NULL, death INTEGER NOT NULL, creative INTEGER NOT NULL, survival INTEGER NOT NULL, playerJoin INTEGER NOT NULL, kick INTEGER NOT NULL, quit INTEGER NOT NULL, respawn INTEGER NOT NULL, worldchange INTEGER NOT NULL, tameocelot INTEGER NOT NULL, tamewolf INTEGER NOT NULL, paintingplace INTEGER NOT NULL, eggThrow INTEGER NOT NULL, sneak INTEGER NOT NULL, sprint INTEGER NOT NULL);");
}
if (!sqlite.checkTable(Table.PORTAL.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created portal table");
sqlite.createTable("CREATE TABLE "
+ Table.PORTAL.getName()
+ " (id INTEGER PRIMARY KEY, pcreatenether INTEGER NOT NULL, pcreateend INTEGER NOT NULL, pcreatecustom INTEGER NOT NULL, portalenter INTEGER NOT NULL);");
}
if (!sqlite.checkTable(Table.BUCKET.getName()))
{
plugin.getLogger().info(
Karmiconomy.TAG + " Created bucket table");
sqlite.createTable("CREATE TABLE "
+ Table.BUCKET.getName()
+ " (id INTEGER PRIMARY KEY, bemptylava INTEGER NOT NULL, bemptywater INTEGER NOT NULL, bfilllava INTEGER NOT NULL, bfillwater INTEGER NOT NULL);");
}
}
}
private void importSQL()
{
// Connect to sql database
try
{
// Grab local SQLite database
sqlite = new SQLite(plugin.getLogger(), Karmiconomy.TAG, "data",
plugin.getDataFolder().getAbsolutePath());
// Copy tables
Query rs = sqlite.select("SELECT * FROM " + Table.MASTER.getName()
+ ";");
if (rs.getResult().next())
{
plugin.getLogger().info(
Karmiconomy.TAG + " Importing master table...");
do
{
// import master
PreparedStatement statement = mysql.prepare("INSERT INTO "
+ Table.MASTER.getName()
+ " (id, playername, laston) VALUES(?,?,?);");
statement.setInt(1, rs.getResult().getInt("id"));
statement.setString(2,
rs.getResult().getString("playername"));
statement.setString(3, rs.getResult().getString("laston"));
statement.executeUpdate();
statement.close();
} while (rs.getResult().next());
}
rs.closeQuery();
rs = sqlite.select("SELECT * FROM " + Table.DATA.getName() + ";");
if (rs.getResult().next())
{
plugin.getLogger().info(
Karmiconomy.TAG + " Importing data table...");
do
{
PreparedStatement statement = mysql
.prepare("INSERT INTO "
+ Table.DATA.getName()
+ " (id, bedenter, bedleave, bowshoot, chat, death, creative, survival, playerJoin, kick, quit, respawn, worldchange, tameocelot, tamewolf, paintingplace, eggThrow, sneak, sprint) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
statement.setInt(1, rs.getResult().getInt("id"));
statement.setInt(2, rs.getResult().getInt("bedenter"));
statement.setInt(3, rs.getResult().getInt("bedleave"));
statement.setInt(4, rs.getResult().getInt("bowshoot"));
statement.setInt(5, rs.getResult().getInt("chat"));
statement.setInt(6, rs.getResult().getInt("death"));
statement.setInt(7, rs.getResult().getInt("creative"));
statement.setInt(8, rs.getResult().getInt("survival"));
statement.setInt(9, rs.getResult().getInt("playerJoin"));
statement.setInt(10, rs.getResult().getInt("kick"));
statement.setInt(11, rs.getResult().getInt("quit"));
statement.setInt(12, rs.getResult().getInt("respawn"));
statement.setInt(13, rs.getResult().getInt("worldchange"));
statement.setInt(14, rs.getResult().getInt("tameocelot"));
statement.setInt(15, rs.getResult().getInt("tamewolf"));
statement.setInt(16, rs.getResult().getInt("paintingplace"));
statement.setInt(17, rs.getResult().getInt("eggThrow"));
statement.setInt(18, rs.getResult().getInt("sneak"));
statement.setInt(19, rs.getResult().getInt("sprint"));
statement.execute();
statement.close();
} while (rs.getResult().next());
}
//Import items
rs = sqlite.select("SELECT * FROM " + Table.ITEMS.getName() + ";");
if(rs.getResult().next())
{
plugin.getLogger().info(
Karmiconomy.TAG + " Importing portal table...");
PreparedStatement statement = mysql.prepare("INSERT INTO " + Table.ITEMS.getName() + "(id, itemid, data, durability, place, destroy, craft, enchant, playerDrop, pickup) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
statement.setInt(1, rs.getResult().getInt("id"));
statement.setInt(2, rs.getResult().getInt("itemid"));
statement.setString(3, rs.getResult().getString("data"));
statement.setString(4, rs.getResult().getString("durability"));
statement.setInt(5, rs.getResult().getInt("place"));
statement.setInt(6, rs.getResult().getInt("destroy"));
statement.setInt(7, rs.getResult().getInt("craft"));
statement.setInt(8, rs.getResult().getInt("enchant"));
statement.setInt(9, rs.getResult().getInt("playerDrop"));
statement.setInt(10, rs.getResult().getInt("pickup"));
statement.execute();
statement.close();
}
rs.closeQuery();
// TODO import command
rs.closeQuery();
rs = sqlite.select("SELECT * FROM " + Table.PORTAL.getName() + ";");
if (rs.getResult().next())
{
plugin.getLogger().info(
Karmiconomy.TAG + " Importing portal table...");
do
{
PreparedStatement statement = mysql
.prepare("INSERT INTO "
+ Table.PORTAL.getName()
+ " (id,pcreatenether, pcreateend, pcreatecustom, portalenter) VALUES (?,?,?,?,?);");
statement.setInt(1, rs.getResult().getInt("id"));
statement.setInt(2, rs.getResult().getInt("pcreatenether"));
statement.setInt(3, rs.getResult().getInt("pcreateend"));
statement.setInt(4, rs.getResult().getInt("pcreatecustom"));
statement.setInt(5, rs.getResult().getInt("portalenter"));
statement.executeUpdate();
statement.close();
} while (rs.getResult().next());
}
rs.closeQuery();
rs = sqlite.select("SELECT * FROM " + Table.BUCKET.getName() + ";");
if (rs.getResult().next())
{
plugin.getLogger().info(
Karmiconomy.TAG + " Importing bucket table...");
do
{
PreparedStatement statement = mysql
.prepare("INSERT INTO "
+ Table.BUCKET.getName()
+ " (id,bemptylava, bemptywater, bfilllava, bfillwater) VALUES (?,?,?,?,?);");
statement.setInt(1, rs.getResult().getInt("id"));
statement.setInt(2, rs.getResult().getInt("bemptylava"));
statement.setInt(3, rs.getResult().getInt("bemptywater"));
statement.setInt(4, rs.getResult().getInt("bfilllava"));
statement.setInt(5, rs.getResult().getInt("bfillwater"));
statement.executeUpdate();
statement.close();
} while (rs.getResult().next());
}
rs.closeQuery();
plugin.getLogger().info(
Karmiconomy.TAG + " Done importing SQLite into MySQL");
}
catch (SQLException e)
{
plugin.getLogger().warning(
Karmiconomy.TAG + " SQL Exception on Import");
e.printStackTrace();
}
}
public boolean checkConnection()
{
boolean connected = false;
if (useMySQL)
{
connected = mysql.checkConnection();
}
else
{
connected = sqlite.checkConnection();
}
return connected;
}
public void close()
{
if (useMySQL)
{
mysql.close();
}
else
{
sqlite.close();
}
}
public Query select(String query)
{
if (useMySQL)
{
return mysql.select(query);
}
else
{
return sqlite.select(query);
}
}
public void standardQuery(String query)
{
if (useMySQL)
{
mysql.standardQuery(query);
}
else
{
sqlite.standardQuery(query);
}
}
private int getPlayerId(String name)
{
int id = -1;
try
{
final Query query = select("SELECT * FROM "
+ Table.MASTER.getName() + " WHERE playername='" + name
+ "';");
if (query.getResult().next())
{
id = query.getResult().getInt("id");
}
query.closeQuery();
}
catch (SQLException e)
{
plugin.getLogger().warning("SQL Exception on grabbing player ID");
e.printStackTrace();
}
return id;
}
public boolean addPlayer(String name)
{
if (!name.contains("'"))
{
int id = getPlayerId(name);
if (id == -1)
{
// Generate last on
final String laston = dateFormat.format(new Date());
// Insert player to master database
final String query = "INSERT INTO " + Table.MASTER.getName()
+ " (playername,laston) VALUES('" + name + "','"
+ laston + "');";
standardQuery(query);
// Grab generated id
id = getPlayerId(name);
if (id != -1)
{
// Add player data table
standardQuery("INSERT INTO "
+ Table.DATA.getName()
+ " (id, bedenter, bedleave, bowshoot, chat, death, creative, survival, playerJoin, kick, quit, respawn, worldchange, tameocelot, tamewolf, paintingplace, eggThrow, sneak, sprint) VALUES('"
+ id
+ "','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0');");
// Add player portal table
standardQuery("INSERT INTO "
+ Table.PORTAL.getName()
+ " (id, pcreatenether, pcreateend, pcreatecustom, portalenter) VALUES('"
+ id + "','0','0','0','0');");
// Add player bucket table
standardQuery("INSERT INTO "
+ Table.BUCKET.getName()
+ " (id, bemptylava, bemptywater, bfilllava, bfillwater) VALUES('"
+ id + "','0','0','0','0');");
return true;
}
else
{
plugin.getLogger().warning(
"Player '" + name
+ "' NOT successfully added to database!");
}
}
}
else
{
plugin.getLogger().warning(
"Illegal character for player: " + name
+ " ... Not added to database.");
}
return false;
}
public boolean checkDateReset(String name)
{
boolean valid = false;
boolean same = false;
int id = getPlayerId(name);
if (id != -1)
{
valid = true;
}
else
{
// Reset was called, but somehow player did not exist. Add them to
// the database
addPlayer(name);
}
if (valid)
{
try
{
// Grab date
String date = "";
final Query query = select("SELECT * FROM "
+ Table.MASTER.getName() + " WHERE id='" + id + "'");
if (query.getResult().next())
{
date = query.getResult().getString("laston");
}
query.closeQuery();
final String current = dateFormat.format(new Date());
// Compare
final String[] dArray = date.split("-");
final String[] cArray = current.split("-");
if (cArray[0].equals(dArray[0]) && cArray[1].equals(dArray[1])
&& cArray[2].equals(dArray[2]))
{
same = true;
}
else
{
//Update date
standardQuery("UPDATE " + Table.MASTER.getName() + " SET laston='" + current + "' WHERE id='" + id + "';");
}
}
catch (SQLException e)
{
plugin.getLogger().warning(
"SQL Exception on grabbing player date");
e.printStackTrace();
}
catch (NullPointerException n)
{
plugin.getLogger().warning("NPE on grabbing player date");
n.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException a)
{
plugin.getLogger()
.warning(
"ArrayIndexOutOfBoundsExceptoin on grabbing player date");
a.printStackTrace();
}
}
return same;
}
public boolean resetAllValues(String name)
{
boolean drop = false;
int id = getPlayerId(name);
if (id != -1)
{
drop = true;
}
else
{
// Reset was called, but somehow player did not exist. Add them to
// the
// database
return addPlayer(name);
}
if (drop)
{
// Reset player values in data table
standardQuery("UPDATE "
+ Table.DATA.getName()
+ " SET bedenter='0', bedleave='0', bowshoot='0', chat='0', death='0', creative='0', survival='0', playerJoin='0', kick='0', quit='0', respawn='0', worldchange='0', tameocelot='0', tamewolf='0', paintingplace='0', eggThrow='0', sneak='0', sprint='0' WHERE id='"
+ id + "';");
// Reset player values in portal table
standardQuery("UPDATE "
+ Table.PORTAL.getName()
+ " SET pcreatenether='0', pcreateend='0', pcreatecustom='0', portalenter='0' WHERE id='"
+ id + "';");
// Reset player values in bucket table
standardQuery("UPDATE "
+ Table.BUCKET.getName()
+ " SET bemptylava='0', bemptywater='0', bfilllava='0', bfillwater='0' WHERE id='"
+ id + "';");
// Drop everything in items for player id
standardQuery("DELETE FROM " + Table.ITEMS.getName()
+ " WHERE id='" + id + "';");
// Drop everything in commands for player id
standardQuery("DELETE FROM " + Table.COMMAND.getName()
+ " WHERE id='" + id + "';");
}
else
{
plugin.getLogger().warning("Could not reset values for: " + name);
}
return drop;
}
public void resetValue(Field field, String name, Item item, String command)
{
// TODO reset specfied field
}
public void incrementData(Field field, String name, Item item,
String command)
{
boolean inc = false;
int id = getPlayerId(name);
if (id != -1)
{
inc = true;
}
else
{
// Increment was called, but somehow player did not exist. Add them
// to
// database
addPlayer(name);
id = getPlayerId(name);
if (id != -1)
{
inc = true;
}
}
if (inc)
{
// Grab previous value
int value = getData(field, name, item, command);
// Increment count of specified field for given player name and
// optional item / command
value++;
switch (field.getTable())
{
case DATA:
{
// Update
standardQuery("UPDATE " + field.getTable().getName()
+ " SET " + field.getColumnName() + "='" + value
+ "' WHERE id='" + id + "';");
break;
}
case ITEMS:
{
// Handle items
if (item != null)
{
if (item.isTool())
{
standardQuery("UPDATE "
+ field.getTable().getName() + " SET "
+ field.getColumnName() + "='" + value
+ "' WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "';");
}
else if (item.isPotion())
{
// See if entry exists
standardQuery("UPDATE "
+ field.getTable().getName() + " SET "
+ field.getColumnName() + "='" + value
+ "' WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "' AND durability='"
+ item.itemDurability() + "';");
}
else
{
// See if entry exists
standardQuery("UPDATE "
+ field.getTable().getName() + " SET "
+ field.getColumnName() + "='" + value
+ "' WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "' AND data='"
+ item.itemData() + "' AND durability='"
+ item.itemDurability() + "';");
}
}
else
{
plugin.getLogger().warning(
"Item cannot be null for field: " + field);
}
break;
}
case COMMAND:
{
// TODO check if insert or update
break;
}
case PORTAL:
{
// Update
standardQuery("UPDATE " + field.getTable().getName()
+ " SET " + field.getColumnName() + "='" + value
+ "' WHERE id='" + id + "';");
break;
}
case BUCKET:
{
// Update
standardQuery("UPDATE " + field.getTable().getName()
+ " SET " + field.getColumnName() + "='" + value
+ "' WHERE id='" + id + "';");
break;
}
default:
{
if (config.debugUnhandled)
{
plugin.getLogger().warning(
"Unhandled table " + field.getTable().getName()
+ " for field " + field);
}
break;
}
}
}
else
{
plugin.getLogger().warning(
"Could not increment value '" + field + "' for: " + name);
}
}
public int getData(Field field, String name, Item item, String command)
{
boolean validId = false;
int data = -1;
int id = getPlayerId(name);
if (id == -1)
{
plugin.getLogger().warning(
"Player '" + name + "' not found in master database!");
addPlayer(name);
id = getPlayerId(name);
if (id != -1)
{
validId = true;
}
}
else
{
validId = true;
}
if (validId)
{
try
{
Query query = null;
switch (field.getTable())
{
case DATA:
{
// Handle data specific stuff
query = select("SELECT * FROM "
+ field.getTable().getName() + " WHERE id='"
+ id + "';");
if (query.getResult().next())
{
data = query.getResult().getInt(
field.getColumnName());
}
break;
}
case ITEMS:
{
boolean found = false;
if (item != null)
{
// Handle items
if (item.isTool())
{
// See if entry exists
query = select("SELECT * FROM "
+ field.getTable().getName()
+ " WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "';");
if (query.getResult().next())
{
found = true;
data = query.getResult().getInt(
field.getColumnName());
}
else
{
// No entry, create one
data = 0;
}
query.closeQuery();
if (!found)
{
// Add entry for tool item
standardQuery("INSERT INTO "
+ field.getTable().getName()
+ " (id,itemid,data,durability,place,destroy,craft,enchant,playerDrop) VALUES('"
+ id + "','" + item.itemId()
+ "','0','0','0','0','0','0','0');");
}
}
else if (item.isPotion())
{
// See if entry exists
query = select("SELECT * FROM "
+ field.getTable().getName()
+ " WHERE id='" + id + "' AND itemid='"
- + item.itemId() + "' AND durability='"
+ + item.itemId() + "' AND data='"
+ + item.itemDurability()
+ + "' AND durability='"
+ item.itemDurability() + "';");
if (query.getResult().next())
{
found = true;
data = query.getResult().getInt(
field.getColumnName());
}
else
{
// No entry, create one
data = 0;
}
query.closeQuery();
// Only record durability
if (!found)
{
// Add entry for tool item
standardQuery("INSERT INTO "
+ field.getTable().getName()
+ " (id,itemid,data,durability,place,destroy,craft,enchant,playerDrop) VALUES('"
+ id + "','" + item.itemId()
- + "','0','" + item.itemDurability()
+ + "','" +item.itemDurability() +"','" + item.itemDurability()
+ "','0','0','0','0','0');");
}
}
else
{
// See if entry exists
query = select("SELECT * FROM "
+ field.getTable().getName()
+ " WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "' AND data='"
+ item.itemData()
+ "' AND durability='"
+ item.itemDurability() + "';");
if (query.getResult().next())
{
found = true;
data = query.getResult().getInt(
field.getColumnName());
}
else
{
// No entry, create one
data = 0;
}
query.closeQuery();
// Normal, so set everything
if (!found)
{
// Add entry for tool item
standardQuery("INSERT INTO "
+ field.getTable().getName()
+ " (id,itemid,data,durability,place,destroy,craft,enchant,playerDrop,pickup) VALUES('"
+ id + "','" + item.itemId()
+ "','" + item.itemData() + "','"
+ item.itemDurability()
+ "','0','0','0','0','0','0');");
}
}
}
else
{
plugin.getLogger().warning(
"Item cannot be null for field: " + field);
}
break;
}
case COMMAND:
{
if (command != null)
{
// TODO handle command specific stuff
}
else
{
plugin.getLogger().warning(
"Command cannot be null for field: "
+ field);
}
break;
}
case PORTAL:
{
query = select("SELECT * FROM "
+ field.getTable().getName() + " WHERE id='"
+ id + "';");
if (query.getResult().next())
{
data = query.getResult().getInt(
field.getColumnName());
}
break;
}
case BUCKET:
{
query = select("SELECT * FROM "
+ field.getTable().getName() + " WHERE id='"
+ id + "';");
if (query.getResult().next())
{
data = query.getResult().getInt(
field.getColumnName());
}
break;
}
default:
{
if (config.debugUnhandled)
{
plugin.getLogger().warning(
"Unhandled table '"
+ field.getTable().getName()
+ "' for field '" + field + "'");
}
break;
}
}
if (query != null)
{
query.closeQuery();
}
}
catch (SQLException e)
{
plugin.getLogger().warning("SQL Exception on Import");
e.printStackTrace();
}
}
return data;
}
public enum Field
{
// TODO eggs, painting break?, vehicle
BOW_SHOOT(Table.DATA, "bowshoot"), BED_ENTER(Table.DATA, "bedenter"), BED_LEAVE(
Table.DATA, "bedleave"), BLOCK_PLACE(Table.ITEMS, "place"), BLOCK_DESTROY(
Table.ITEMS, "destroy"), ITEM_CRAFT(Table.ITEMS, "craft"), ITEM_ENCHANT(
Table.ITEMS, "enchant"), ITEM_DROP(Table.ITEMS, "playerDrop"), ITEM_PICKUP(
Table.ITEMS, "pickup"), EGG_THROW(Table.DATA, "eggThrow"), CHAT(
Table.DATA, "chat"), COMMAND(Table.COMMAND, "command"), DEATH(
Table.DATA, "death"), CREATIVE(Table.DATA, "creative"), SURVIVAL(
Table.DATA, "survival"), JOIN(Table.DATA, "playerJoin"), KICK(
Table.DATA, "kick"), QUIT(Table.DATA, "quit"), RESPAWN(
Table.DATA, "respawn"), SNEAK(Table.DATA, "sneak"), SPRINT(
Table.DATA, "sprint"), PAINTING_PLACE(Table.DATA,
"paintingplace"), PORTAL_CREATE_NETHER(Table.PORTAL,
"pcreatenether"), PORTAL_CREATE_END(Table.PORTAL, "pcreateend"), PORTAL_CREATE_CUSTOM(
Table.PORTAL, "pcreatecustom"), PORTAL_ENTER(Table.PORTAL,
"portalenter"), TAME_OCELOT(Table.DATA, "tameocelot"), TAME_WOLF(
Table.DATA, "tamewolf"), WORLD_CHANGE(Table.DATA, "worldchange"), BUCKET_EMPTY_LAVA(
Table.BUCKET, "bemptylava"), BUCKET_EMPTY_WATER(Table.BUCKET,
"bemptywater"), BUCKET_FILL_LAVA(Table.BUCKET, "bfilllava"), BUCKET_FILL_WATER(
Table.BUCKET, "bfillwater");
private final Table table;
private final String columnname;
private Field(Table table, String columnname)
{
this.table = table;
this.columnname = columnname;
}
public Table getTable()
{
return table;
}
public String getColumnName()
{
return columnname;
}
}
public enum Table
{
MASTER(config.tablePrefix + "master"), ITEMS(config.tablePrefix
+ "items"), DATA(config.tablePrefix + "data"), COMMAND(
config.tablePrefix + "command"), PORTAL(config.tablePrefix
+ "portal"), BUCKET(config.tablePrefix + "bucket");
private final String table;
private Table(String table)
{
this.table = table;
}
public String getName()
{
return table;
}
@Override
public String toString()
{
return table;
}
}
}
| false | true | public int getData(Field field, String name, Item item, String command)
{
boolean validId = false;
int data = -1;
int id = getPlayerId(name);
if (id == -1)
{
plugin.getLogger().warning(
"Player '" + name + "' not found in master database!");
addPlayer(name);
id = getPlayerId(name);
if (id != -1)
{
validId = true;
}
}
else
{
validId = true;
}
if (validId)
{
try
{
Query query = null;
switch (field.getTable())
{
case DATA:
{
// Handle data specific stuff
query = select("SELECT * FROM "
+ field.getTable().getName() + " WHERE id='"
+ id + "';");
if (query.getResult().next())
{
data = query.getResult().getInt(
field.getColumnName());
}
break;
}
case ITEMS:
{
boolean found = false;
if (item != null)
{
// Handle items
if (item.isTool())
{
// See if entry exists
query = select("SELECT * FROM "
+ field.getTable().getName()
+ " WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "';");
if (query.getResult().next())
{
found = true;
data = query.getResult().getInt(
field.getColumnName());
}
else
{
// No entry, create one
data = 0;
}
query.closeQuery();
if (!found)
{
// Add entry for tool item
standardQuery("INSERT INTO "
+ field.getTable().getName()
+ " (id,itemid,data,durability,place,destroy,craft,enchant,playerDrop) VALUES('"
+ id + "','" + item.itemId()
+ "','0','0','0','0','0','0','0');");
}
}
else if (item.isPotion())
{
// See if entry exists
query = select("SELECT * FROM "
+ field.getTable().getName()
+ " WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "' AND durability='"
+ item.itemDurability() + "';");
if (query.getResult().next())
{
found = true;
data = query.getResult().getInt(
field.getColumnName());
}
else
{
// No entry, create one
data = 0;
}
query.closeQuery();
// Only record durability
if (!found)
{
// Add entry for tool item
standardQuery("INSERT INTO "
+ field.getTable().getName()
+ " (id,itemid,data,durability,place,destroy,craft,enchant,playerDrop) VALUES('"
+ id + "','" + item.itemId()
+ "','0','" + item.itemDurability()
+ "','0','0','0','0','0');");
}
}
else
{
// See if entry exists
query = select("SELECT * FROM "
+ field.getTable().getName()
+ " WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "' AND data='"
+ item.itemData()
+ "' AND durability='"
+ item.itemDurability() + "';");
if (query.getResult().next())
{
found = true;
data = query.getResult().getInt(
field.getColumnName());
}
else
{
// No entry, create one
data = 0;
}
query.closeQuery();
// Normal, so set everything
if (!found)
{
// Add entry for tool item
standardQuery("INSERT INTO "
+ field.getTable().getName()
+ " (id,itemid,data,durability,place,destroy,craft,enchant,playerDrop,pickup) VALUES('"
+ id + "','" + item.itemId()
+ "','" + item.itemData() + "','"
+ item.itemDurability()
+ "','0','0','0','0','0','0');");
}
}
}
else
{
plugin.getLogger().warning(
"Item cannot be null for field: " + field);
}
break;
}
case COMMAND:
{
if (command != null)
{
// TODO handle command specific stuff
}
else
{
plugin.getLogger().warning(
"Command cannot be null for field: "
+ field);
}
break;
}
case PORTAL:
{
query = select("SELECT * FROM "
+ field.getTable().getName() + " WHERE id='"
+ id + "';");
if (query.getResult().next())
{
data = query.getResult().getInt(
field.getColumnName());
}
break;
}
case BUCKET:
{
query = select("SELECT * FROM "
+ field.getTable().getName() + " WHERE id='"
+ id + "';");
if (query.getResult().next())
{
data = query.getResult().getInt(
field.getColumnName());
}
break;
}
default:
{
if (config.debugUnhandled)
{
plugin.getLogger().warning(
"Unhandled table '"
+ field.getTable().getName()
+ "' for field '" + field + "'");
}
break;
}
}
if (query != null)
{
query.closeQuery();
}
}
catch (SQLException e)
{
plugin.getLogger().warning("SQL Exception on Import");
e.printStackTrace();
}
}
return data;
}
| public int getData(Field field, String name, Item item, String command)
{
boolean validId = false;
int data = -1;
int id = getPlayerId(name);
if (id == -1)
{
plugin.getLogger().warning(
"Player '" + name + "' not found in master database!");
addPlayer(name);
id = getPlayerId(name);
if (id != -1)
{
validId = true;
}
}
else
{
validId = true;
}
if (validId)
{
try
{
Query query = null;
switch (field.getTable())
{
case DATA:
{
// Handle data specific stuff
query = select("SELECT * FROM "
+ field.getTable().getName() + " WHERE id='"
+ id + "';");
if (query.getResult().next())
{
data = query.getResult().getInt(
field.getColumnName());
}
break;
}
case ITEMS:
{
boolean found = false;
if (item != null)
{
// Handle items
if (item.isTool())
{
// See if entry exists
query = select("SELECT * FROM "
+ field.getTable().getName()
+ " WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "';");
if (query.getResult().next())
{
found = true;
data = query.getResult().getInt(
field.getColumnName());
}
else
{
// No entry, create one
data = 0;
}
query.closeQuery();
if (!found)
{
// Add entry for tool item
standardQuery("INSERT INTO "
+ field.getTable().getName()
+ " (id,itemid,data,durability,place,destroy,craft,enchant,playerDrop) VALUES('"
+ id + "','" + item.itemId()
+ "','0','0','0','0','0','0','0');");
}
}
else if (item.isPotion())
{
// See if entry exists
query = select("SELECT * FROM "
+ field.getTable().getName()
+ " WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "' AND data='"
+ item.itemDurability()
+ "' AND durability='"
+ item.itemDurability() + "';");
if (query.getResult().next())
{
found = true;
data = query.getResult().getInt(
field.getColumnName());
}
else
{
// No entry, create one
data = 0;
}
query.closeQuery();
// Only record durability
if (!found)
{
// Add entry for tool item
standardQuery("INSERT INTO "
+ field.getTable().getName()
+ " (id,itemid,data,durability,place,destroy,craft,enchant,playerDrop) VALUES('"
+ id + "','" + item.itemId()
+ "','" +item.itemDurability() +"','" + item.itemDurability()
+ "','0','0','0','0','0');");
}
}
else
{
// See if entry exists
query = select("SELECT * FROM "
+ field.getTable().getName()
+ " WHERE id='" + id + "' AND itemid='"
+ item.itemId() + "' AND data='"
+ item.itemData()
+ "' AND durability='"
+ item.itemDurability() + "';");
if (query.getResult().next())
{
found = true;
data = query.getResult().getInt(
field.getColumnName());
}
else
{
// No entry, create one
data = 0;
}
query.closeQuery();
// Normal, so set everything
if (!found)
{
// Add entry for tool item
standardQuery("INSERT INTO "
+ field.getTable().getName()
+ " (id,itemid,data,durability,place,destroy,craft,enchant,playerDrop,pickup) VALUES('"
+ id + "','" + item.itemId()
+ "','" + item.itemData() + "','"
+ item.itemDurability()
+ "','0','0','0','0','0','0');");
}
}
}
else
{
plugin.getLogger().warning(
"Item cannot be null for field: " + field);
}
break;
}
case COMMAND:
{
if (command != null)
{
// TODO handle command specific stuff
}
else
{
plugin.getLogger().warning(
"Command cannot be null for field: "
+ field);
}
break;
}
case PORTAL:
{
query = select("SELECT * FROM "
+ field.getTable().getName() + " WHERE id='"
+ id + "';");
if (query.getResult().next())
{
data = query.getResult().getInt(
field.getColumnName());
}
break;
}
case BUCKET:
{
query = select("SELECT * FROM "
+ field.getTable().getName() + " WHERE id='"
+ id + "';");
if (query.getResult().next())
{
data = query.getResult().getInt(
field.getColumnName());
}
break;
}
default:
{
if (config.debugUnhandled)
{
plugin.getLogger().warning(
"Unhandled table '"
+ field.getTable().getName()
+ "' for field '" + field + "'");
}
break;
}
}
if (query != null)
{
query.closeQuery();
}
}
catch (SQLException e)
{
plugin.getLogger().warning("SQL Exception on Import");
e.printStackTrace();
}
}
return data;
}
|
diff --git a/src/main/java/net/alpha01/jwtest/pages/session/SessionsPage.java b/src/main/java/net/alpha01/jwtest/pages/session/SessionsPage.java
index 989c0cb..b700238 100644
--- a/src/main/java/net/alpha01/jwtest/pages/session/SessionsPage.java
+++ b/src/main/java/net/alpha01/jwtest/pages/session/SessionsPage.java
@@ -1,237 +1,238 @@
package net.alpha01.jwtest.pages.session;
import java.io.File;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.List;
import net.alpha01.jwtest.beans.Plan;
import net.alpha01.jwtest.beans.Profile;
import net.alpha01.jwtest.beans.Session;
import net.alpha01.jwtest.beans.TestCase;
import net.alpha01.jwtest.component.AjaxLinkSecure;
import net.alpha01.jwtest.component.BookmarkablePageLinkSecure;
import net.alpha01.jwtest.component.HtmlLabel;
import net.alpha01.jwtest.component.TmpFileDownloadModel;
import net.alpha01.jwtest.dao.PlanMapper;
import net.alpha01.jwtest.dao.ProfileMapper;
import net.alpha01.jwtest.dao.SessionMapper;
import net.alpha01.jwtest.dao.SqlConnection;
import net.alpha01.jwtest.dao.SqlSessionMapper;
import net.alpha01.jwtest.dao.TestCaseMapper;
import net.alpha01.jwtest.pages.HomePage;
import net.alpha01.jwtest.pages.LayoutPage;
import net.alpha01.jwtest.pages.plan.PlanPage;
import net.alpha01.jwtest.panels.result.ResultsTablePanel;
import net.alpha01.jwtest.panels.testcase.TestCasesTablePanel;
import net.alpha01.jwtest.reports.SessionReport;
import net.alpha01.jwtest.util.JWTestUtil;
import org.apache.log4j.Logger;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.image.ContextImage;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import com.itextpdf.text.DocumentException;
public class SessionsPage extends LayoutPage {
private static final long serialVersionUID = 1L;
private Model<Session> sesModel = new Model<Session>(getSession().getCurrentSession());
private Session currSession;
public SessionsPage(PageParameters params) {
super();
if (getSession().getCurrentProject() == null) {
error("Nessun progetto selezionato");
setResponsePage(HomePage.class);
return;
}
SqlSessionMapper<SessionMapper> sesMapper = SqlConnection.getSessionMapper(SessionMapper.class);
if (!params.get("idSession").isNull()){
//load session based on idSession parameter
currSession=sesMapper.getMapper().get(BigInteger.valueOf(params.get("idSession").toLong()));
+ getSession().setCurrentSession(currSession);
}
if (currSession==null){
//load session from WebSession
currSession = getSession().getCurrentSession();
}
//PROFILE
if (currSession!=null && currSession.getId_profile()!=null){
Profile profile = sesMapper.getSqlSession().getMapper(ProfileMapper.class).get(currSession.getId_profile());
add(new HtmlLabel("profileDescription",profile.getDescription()));
}else{
add(new Label("profileDescription"));
}
if (currSession!=null && currSession.getId_plan()!=null){
//PLAN LNK
BookmarkablePageLink<String> planLnk=new BookmarkablePageLink<String>("planLnk", PlanPage.class,new PageParameters().add("idPlan",currSession.getId_plan()));
Plan plan = sesMapper.getSqlSession().getMapper(PlanMapper.class).get(currSession.getId_plan());
planLnk.add(new Label("planName",plan.getName()));
add(planLnk);
}else{
Link<Void> planLnk=new Link<Void>("planLnk"){
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
}
};
planLnk.add(new Label("planName"));
add(planLnk);
}
List<TestCase> testcases = null;
if (currSession == null) {
add(new EmptyPanel("testcasesTable"));
add(new EmptyPanel("resultsTable"));
} else {
TestCaseMapper testMapper = sesMapper.getSqlSession().getMapper(TestCaseMapper.class);
testcases = testMapper.getAllUncheckedBySession(currSession.getId());
add(new TestCasesTablePanel("testcasesTable", testcases, 20, currSession.isOpened()));
add(new ResultsTablePanel("resultsTable",JWTestUtil.translate("results", this), currSession.getId().intValue(), 10, currSession.isOpened() && JWTestUtil.isAuthorized(Roles.ADMIN, "PROJECT_ADMIN", "MANAGER").getObject()));
}
// Menu
AjaxLinkSecure<String> closeLnk = new AjaxLinkSecure<String>("closeLnk", Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER") {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
SqlSessionMapper<SessionMapper> sesMapper = SqlConnection.getSessionMapper(SessionMapper.class);
currSession.setEnd_date(GregorianCalendar.getInstance().getTime());
if (sesMapper.getMapper().update(currSession).equals(1)) {
sesMapper.commit();
info("Session closed");
} else {
sesMapper.rollback();
error("SQL Error");
}
sesMapper.close();
setResponsePage(SessionsPage.class);
}
};
closeLnk.add(new ContextImage("closeSessionImg", "images/close_session.png"));
AjaxLinkSecure<String> reopenLnk = new AjaxLinkSecure<String>("reopenLnk", Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER") {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
SqlSessionMapper<SessionMapper> sesMapper = SqlConnection.getSessionMapper(SessionMapper.class);
currSession.setEnd_date(null);
if (sesMapper.getMapper().update(currSession).equals(1)) {
sesMapper.commit();
info("Session closed");
} else {
sesMapper.rollback();
error("SQL Error");
}
sesMapper.close();
setResponsePage(SessionsPage.class);
}
};
reopenLnk.add(new ContextImage("reopenSessionImg", "images/reopen_session.png"));
if (currSession == null) {
reopenLnk.forceVisible(false);
closeLnk.forceVisible(false);
} else {
if (testcases != null && testcases.size() != 0) {
closeLnk.forceVisible(false);
reopenLnk.forceVisible(false);
}
if (!currSession.isOpened()) {
closeLnk.forceVisible(false);
reopenLnk.forceVisible(true);
} else {
reopenLnk.forceVisible(false);
}
}
add(reopenLnk);
add(closeLnk);
// Start Session Link
if (currSession != null) {
add(new BookmarkablePageLinkSecure<String>("startSessionLnk", StartSessionPage.class, Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER").add(new ContextImage("addSessionImg", "images/add_session.png")));
} else {
add((new BookmarkablePageLinkSecure<String>("startSessionLnk", StartSessionPage.class, Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER").add(new ContextImage("addSessionImg", "images/add_session.png"))).setVisible(false));
}
// Delete Session Link
if (currSession != null) {
PageParameters delParams = new PageParameters();
delParams.add("idSession", currSession.getId());
add(new BookmarkablePageLinkSecure<String>("delLnk", DeleteSessionPage.class, delParams, Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER").add(new ContextImage("delSessionImg", "images/delete_session.png")));
} else {
add((new BookmarkablePageLink<String>("delLnk", DeleteSessionPage.class).add(new ContextImage("delSessionImg", "images/delete_session.png"))).setVisible(false));
}
IModel<File> reportFileModel = new TmpFileDownloadModel() {
private static final long serialVersionUID = 1L;
@Override
protected File getFile() {
try {
return SessionReport.generateReport(getSession().getCurrentSession());
} catch (DocumentException e) {
return null;
}
}
};
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
String reportFileName="";
if (currSession!=null){
String strEndDate="";
if (currSession.getEnd_date()!=null){
strEndDate = sdf.format(currSession.getEnd_date());
}
reportFileName=getSession().getCurrentProject().getName()+"-testResult-"+currSession.getVersion().replace('.', '_')+"-"+strEndDate+".pdf";
}
DownloadLink reportLnk = new DownloadLink("reportLnk", reportFileModel,reportFileName);
if (currSession == null || (currSession != null && currSession.isOpened())) {
reportLnk.setVisible(false);
reportLnk.setEnabled(false);
}
reportLnk.add(new ContextImage("reportImg", "images/report.png"));
add(reportLnk);
// FORM
Form<Session> selectSessionForm = new Form<Session>("selectSessionForm");
List<Session> sessions = sesMapper.getMapper().getAllByProject(getSession().getCurrentProject().getId());
DropDownChoice<Session> sessionFld = new DropDownChoice<Session>("sessionFld", sesModel, sessions) {
private static final long serialVersionUID = 1L;
@Override
protected boolean wantOnSelectionChangedNotifications() {
return true;
}
@Override
protected void onSelectionChanged(Session newSelection) {
Logger.getLogger(getClass()).debug("Session changed:" + newSelection);
SessionsPage.this.getSession().setCurrentSession(newSelection);
currSession = newSelection;
setResponsePage(SessionsPage.class);
};
};
selectSessionForm.add(sessionFld);
add(selectSessionForm);
sesMapper.close();
}
}
| true | true | public SessionsPage(PageParameters params) {
super();
if (getSession().getCurrentProject() == null) {
error("Nessun progetto selezionato");
setResponsePage(HomePage.class);
return;
}
SqlSessionMapper<SessionMapper> sesMapper = SqlConnection.getSessionMapper(SessionMapper.class);
if (!params.get("idSession").isNull()){
//load session based on idSession parameter
currSession=sesMapper.getMapper().get(BigInteger.valueOf(params.get("idSession").toLong()));
}
if (currSession==null){
//load session from WebSession
currSession = getSession().getCurrentSession();
}
//PROFILE
if (currSession!=null && currSession.getId_profile()!=null){
Profile profile = sesMapper.getSqlSession().getMapper(ProfileMapper.class).get(currSession.getId_profile());
add(new HtmlLabel("profileDescription",profile.getDescription()));
}else{
add(new Label("profileDescription"));
}
if (currSession!=null && currSession.getId_plan()!=null){
//PLAN LNK
BookmarkablePageLink<String> planLnk=new BookmarkablePageLink<String>("planLnk", PlanPage.class,new PageParameters().add("idPlan",currSession.getId_plan()));
Plan plan = sesMapper.getSqlSession().getMapper(PlanMapper.class).get(currSession.getId_plan());
planLnk.add(new Label("planName",plan.getName()));
add(planLnk);
}else{
Link<Void> planLnk=new Link<Void>("planLnk"){
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
}
};
planLnk.add(new Label("planName"));
add(planLnk);
}
List<TestCase> testcases = null;
if (currSession == null) {
add(new EmptyPanel("testcasesTable"));
add(new EmptyPanel("resultsTable"));
} else {
TestCaseMapper testMapper = sesMapper.getSqlSession().getMapper(TestCaseMapper.class);
testcases = testMapper.getAllUncheckedBySession(currSession.getId());
add(new TestCasesTablePanel("testcasesTable", testcases, 20, currSession.isOpened()));
add(new ResultsTablePanel("resultsTable",JWTestUtil.translate("results", this), currSession.getId().intValue(), 10, currSession.isOpened() && JWTestUtil.isAuthorized(Roles.ADMIN, "PROJECT_ADMIN", "MANAGER").getObject()));
}
// Menu
AjaxLinkSecure<String> closeLnk = new AjaxLinkSecure<String>("closeLnk", Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER") {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
SqlSessionMapper<SessionMapper> sesMapper = SqlConnection.getSessionMapper(SessionMapper.class);
currSession.setEnd_date(GregorianCalendar.getInstance().getTime());
if (sesMapper.getMapper().update(currSession).equals(1)) {
sesMapper.commit();
info("Session closed");
} else {
sesMapper.rollback();
error("SQL Error");
}
sesMapper.close();
setResponsePage(SessionsPage.class);
}
};
closeLnk.add(new ContextImage("closeSessionImg", "images/close_session.png"));
AjaxLinkSecure<String> reopenLnk = new AjaxLinkSecure<String>("reopenLnk", Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER") {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
SqlSessionMapper<SessionMapper> sesMapper = SqlConnection.getSessionMapper(SessionMapper.class);
currSession.setEnd_date(null);
if (sesMapper.getMapper().update(currSession).equals(1)) {
sesMapper.commit();
info("Session closed");
} else {
sesMapper.rollback();
error("SQL Error");
}
sesMapper.close();
setResponsePage(SessionsPage.class);
}
};
reopenLnk.add(new ContextImage("reopenSessionImg", "images/reopen_session.png"));
if (currSession == null) {
reopenLnk.forceVisible(false);
closeLnk.forceVisible(false);
} else {
if (testcases != null && testcases.size() != 0) {
closeLnk.forceVisible(false);
reopenLnk.forceVisible(false);
}
if (!currSession.isOpened()) {
closeLnk.forceVisible(false);
reopenLnk.forceVisible(true);
} else {
reopenLnk.forceVisible(false);
}
}
add(reopenLnk);
add(closeLnk);
// Start Session Link
if (currSession != null) {
add(new BookmarkablePageLinkSecure<String>("startSessionLnk", StartSessionPage.class, Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER").add(new ContextImage("addSessionImg", "images/add_session.png")));
} else {
add((new BookmarkablePageLinkSecure<String>("startSessionLnk", StartSessionPage.class, Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER").add(new ContextImage("addSessionImg", "images/add_session.png"))).setVisible(false));
}
// Delete Session Link
if (currSession != null) {
PageParameters delParams = new PageParameters();
delParams.add("idSession", currSession.getId());
add(new BookmarkablePageLinkSecure<String>("delLnk", DeleteSessionPage.class, delParams, Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER").add(new ContextImage("delSessionImg", "images/delete_session.png")));
} else {
add((new BookmarkablePageLink<String>("delLnk", DeleteSessionPage.class).add(new ContextImage("delSessionImg", "images/delete_session.png"))).setVisible(false));
}
IModel<File> reportFileModel = new TmpFileDownloadModel() {
private static final long serialVersionUID = 1L;
@Override
protected File getFile() {
try {
return SessionReport.generateReport(getSession().getCurrentSession());
} catch (DocumentException e) {
return null;
}
}
};
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
String reportFileName="";
if (currSession!=null){
String strEndDate="";
if (currSession.getEnd_date()!=null){
strEndDate = sdf.format(currSession.getEnd_date());
}
reportFileName=getSession().getCurrentProject().getName()+"-testResult-"+currSession.getVersion().replace('.', '_')+"-"+strEndDate+".pdf";
}
DownloadLink reportLnk = new DownloadLink("reportLnk", reportFileModel,reportFileName);
if (currSession == null || (currSession != null && currSession.isOpened())) {
reportLnk.setVisible(false);
reportLnk.setEnabled(false);
}
reportLnk.add(new ContextImage("reportImg", "images/report.png"));
add(reportLnk);
// FORM
Form<Session> selectSessionForm = new Form<Session>("selectSessionForm");
List<Session> sessions = sesMapper.getMapper().getAllByProject(getSession().getCurrentProject().getId());
DropDownChoice<Session> sessionFld = new DropDownChoice<Session>("sessionFld", sesModel, sessions) {
private static final long serialVersionUID = 1L;
@Override
protected boolean wantOnSelectionChangedNotifications() {
return true;
}
@Override
protected void onSelectionChanged(Session newSelection) {
Logger.getLogger(getClass()).debug("Session changed:" + newSelection);
SessionsPage.this.getSession().setCurrentSession(newSelection);
currSession = newSelection;
setResponsePage(SessionsPage.class);
};
};
selectSessionForm.add(sessionFld);
add(selectSessionForm);
sesMapper.close();
}
| public SessionsPage(PageParameters params) {
super();
if (getSession().getCurrentProject() == null) {
error("Nessun progetto selezionato");
setResponsePage(HomePage.class);
return;
}
SqlSessionMapper<SessionMapper> sesMapper = SqlConnection.getSessionMapper(SessionMapper.class);
if (!params.get("idSession").isNull()){
//load session based on idSession parameter
currSession=sesMapper.getMapper().get(BigInteger.valueOf(params.get("idSession").toLong()));
getSession().setCurrentSession(currSession);
}
if (currSession==null){
//load session from WebSession
currSession = getSession().getCurrentSession();
}
//PROFILE
if (currSession!=null && currSession.getId_profile()!=null){
Profile profile = sesMapper.getSqlSession().getMapper(ProfileMapper.class).get(currSession.getId_profile());
add(new HtmlLabel("profileDescription",profile.getDescription()));
}else{
add(new Label("profileDescription"));
}
if (currSession!=null && currSession.getId_plan()!=null){
//PLAN LNK
BookmarkablePageLink<String> planLnk=new BookmarkablePageLink<String>("planLnk", PlanPage.class,new PageParameters().add("idPlan",currSession.getId_plan()));
Plan plan = sesMapper.getSqlSession().getMapper(PlanMapper.class).get(currSession.getId_plan());
planLnk.add(new Label("planName",plan.getName()));
add(planLnk);
}else{
Link<Void> planLnk=new Link<Void>("planLnk"){
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
}
};
planLnk.add(new Label("planName"));
add(planLnk);
}
List<TestCase> testcases = null;
if (currSession == null) {
add(new EmptyPanel("testcasesTable"));
add(new EmptyPanel("resultsTable"));
} else {
TestCaseMapper testMapper = sesMapper.getSqlSession().getMapper(TestCaseMapper.class);
testcases = testMapper.getAllUncheckedBySession(currSession.getId());
add(new TestCasesTablePanel("testcasesTable", testcases, 20, currSession.isOpened()));
add(new ResultsTablePanel("resultsTable",JWTestUtil.translate("results", this), currSession.getId().intValue(), 10, currSession.isOpened() && JWTestUtil.isAuthorized(Roles.ADMIN, "PROJECT_ADMIN", "MANAGER").getObject()));
}
// Menu
AjaxLinkSecure<String> closeLnk = new AjaxLinkSecure<String>("closeLnk", Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER") {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
SqlSessionMapper<SessionMapper> sesMapper = SqlConnection.getSessionMapper(SessionMapper.class);
currSession.setEnd_date(GregorianCalendar.getInstance().getTime());
if (sesMapper.getMapper().update(currSession).equals(1)) {
sesMapper.commit();
info("Session closed");
} else {
sesMapper.rollback();
error("SQL Error");
}
sesMapper.close();
setResponsePage(SessionsPage.class);
}
};
closeLnk.add(new ContextImage("closeSessionImg", "images/close_session.png"));
AjaxLinkSecure<String> reopenLnk = new AjaxLinkSecure<String>("reopenLnk", Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER") {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
SqlSessionMapper<SessionMapper> sesMapper = SqlConnection.getSessionMapper(SessionMapper.class);
currSession.setEnd_date(null);
if (sesMapper.getMapper().update(currSession).equals(1)) {
sesMapper.commit();
info("Session closed");
} else {
sesMapper.rollback();
error("SQL Error");
}
sesMapper.close();
setResponsePage(SessionsPage.class);
}
};
reopenLnk.add(new ContextImage("reopenSessionImg", "images/reopen_session.png"));
if (currSession == null) {
reopenLnk.forceVisible(false);
closeLnk.forceVisible(false);
} else {
if (testcases != null && testcases.size() != 0) {
closeLnk.forceVisible(false);
reopenLnk.forceVisible(false);
}
if (!currSession.isOpened()) {
closeLnk.forceVisible(false);
reopenLnk.forceVisible(true);
} else {
reopenLnk.forceVisible(false);
}
}
add(reopenLnk);
add(closeLnk);
// Start Session Link
if (currSession != null) {
add(new BookmarkablePageLinkSecure<String>("startSessionLnk", StartSessionPage.class, Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER").add(new ContextImage("addSessionImg", "images/add_session.png")));
} else {
add((new BookmarkablePageLinkSecure<String>("startSessionLnk", StartSessionPage.class, Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER").add(new ContextImage("addSessionImg", "images/add_session.png"))).setVisible(false));
}
// Delete Session Link
if (currSession != null) {
PageParameters delParams = new PageParameters();
delParams.add("idSession", currSession.getId());
add(new BookmarkablePageLinkSecure<String>("delLnk", DeleteSessionPage.class, delParams, Roles.ADMIN, "PROJECT_ADMIN", "MANAGER", "TESTER").add(new ContextImage("delSessionImg", "images/delete_session.png")));
} else {
add((new BookmarkablePageLink<String>("delLnk", DeleteSessionPage.class).add(new ContextImage("delSessionImg", "images/delete_session.png"))).setVisible(false));
}
IModel<File> reportFileModel = new TmpFileDownloadModel() {
private static final long serialVersionUID = 1L;
@Override
protected File getFile() {
try {
return SessionReport.generateReport(getSession().getCurrentSession());
} catch (DocumentException e) {
return null;
}
}
};
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
String reportFileName="";
if (currSession!=null){
String strEndDate="";
if (currSession.getEnd_date()!=null){
strEndDate = sdf.format(currSession.getEnd_date());
}
reportFileName=getSession().getCurrentProject().getName()+"-testResult-"+currSession.getVersion().replace('.', '_')+"-"+strEndDate+".pdf";
}
DownloadLink reportLnk = new DownloadLink("reportLnk", reportFileModel,reportFileName);
if (currSession == null || (currSession != null && currSession.isOpened())) {
reportLnk.setVisible(false);
reportLnk.setEnabled(false);
}
reportLnk.add(new ContextImage("reportImg", "images/report.png"));
add(reportLnk);
// FORM
Form<Session> selectSessionForm = new Form<Session>("selectSessionForm");
List<Session> sessions = sesMapper.getMapper().getAllByProject(getSession().getCurrentProject().getId());
DropDownChoice<Session> sessionFld = new DropDownChoice<Session>("sessionFld", sesModel, sessions) {
private static final long serialVersionUID = 1L;
@Override
protected boolean wantOnSelectionChangedNotifications() {
return true;
}
@Override
protected void onSelectionChanged(Session newSelection) {
Logger.getLogger(getClass()).debug("Session changed:" + newSelection);
SessionsPage.this.getSession().setCurrentSession(newSelection);
currSession = newSelection;
setResponsePage(SessionsPage.class);
};
};
selectSessionForm.add(sessionFld);
add(selectSessionForm);
sesMapper.close();
}
|
diff --git a/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingDiagramEditorUtil.java b/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingDiagramEditorUtil.java
index 43a2931f5..e744de3d2 100644
--- a/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingDiagramEditorUtil.java
+++ b/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingDiagramEditorUtil.java
@@ -1,647 +1,647 @@
/*
* (c) Fachhochschule Potsdam
*/
package org.fritzing.fritzing.diagram.part;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.OperationHistoryFactory;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.common.util.WrappedException;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.diagram.core.services.ViewService;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IPrimaryEditPart;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
import org.eclipse.gmf.runtime.emf.core.GMFEditingDomainFactory;
import org.eclipse.gmf.runtime.emf.core.util.EMFCoreUtil;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.fritzing.fritzing.DocumentRoot;
import org.fritzing.fritzing.FritzingFactory;
import org.fritzing.fritzing.Sketch;
import org.fritzing.fritzing.diagram.edit.parts.SketchEditPart;
import com.ice.jni.registry.Registry;
import com.ice.jni.registry.RegistryKey;
/**
* @generated
*/
/**
* @author andre
*
*/
public class FritzingDiagramEditorUtil {
/**
* @generated
*/
public static Map getSaveOptions() {
Map saveOptions = new HashMap();
saveOptions.put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED,
Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
return saveOptions;
}
/**
* @generated
*/
public static boolean openDiagram(Resource diagram)
throws PartInitException {
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
page.openEditor(new URIEditorInput(diagram.getURI()),
FritzingDiagramEditor.ID);
return true;
}
/**
* @generated
*/
public static String getUniqueFileName(IPath containerFullPath,
String fileName, String extension) {
if (containerFullPath == null) {
containerFullPath = new Path(""); //$NON-NLS-1$
}
if (fileName == null || fileName.trim().length() == 0) {
fileName = "default"; //$NON-NLS-1$
}
IPath filePath = containerFullPath.append(fileName);
if (extension != null && !extension.equals(filePath.getFileExtension())) {
filePath = filePath.addFileExtension(extension);
}
extension = filePath.getFileExtension();
fileName = filePath.removeFileExtension().lastSegment();
int i = 1;
while (filePath.toFile().exists()) {
i++;
filePath = containerFullPath.append(fileName + i);
if (extension != null) {
filePath = filePath.addFileExtension(extension);
}
}
return filePath.lastSegment();
}
/**
* Allows user to select file and loads it as a model.
*
* @generated
*/
public static Resource openModel(Shell shell, String description,
TransactionalEditingDomain editingDomain) {
FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);
if (description != null) {
fileDialog.setText(description);
}
fileDialog.open();
String fileName = fileDialog.getFileName();
if (fileName == null || fileName.length() == 0) {
return null;
}
if (fileDialog.getFilterPath() != null) {
fileName = fileDialog.getFilterPath() + File.separator + fileName;
}
URI uri = URI.createFileURI(fileName);
Resource resource = null;
try {
resource = editingDomain.getResourceSet().getResource(uri, true);
} catch (WrappedException we) {
FritzingDiagramEditorPlugin.getInstance().logError(
"Unable to load resource: " + uri, we); //$NON-NLS-1$
MessageDialog
.openError(
shell,
Messages.FritzingDiagramEditorUtil_OpenModelResourceErrorDialogTitle,
NLS
.bind(
Messages.FritzingDiagramEditorUtil_OpenModelResourceErrorDialogMessage,
fileName));
}
return resource;
}
/**
* Runs the wizard in a dialog.
*
* @generated
*/
public static void runWizard(Shell shell, Wizard wizard, String settingsKey) {
IDialogSettings pluginDialogSettings = FritzingDiagramEditorPlugin
.getInstance().getDialogSettings();
IDialogSettings wizardDialogSettings = pluginDialogSettings
.getSection(settingsKey);
if (wizardDialogSettings == null) {
wizardDialogSettings = pluginDialogSettings
.addNewSection(settingsKey);
}
wizard.setDialogSettings(wizardDialogSettings);
WizardDialog dialog = new WizardDialog(shell, wizard);
dialog.create();
dialog.getShell().setSize(Math.max(500, dialog.getShell().getSize().x),
500);
dialog.open();
}
/**
* @generated
*/
public static Resource createDiagram(URI diagramURI, URI modelURI,
IProgressMonitor progressMonitor) {
TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE
.createEditingDomain();
progressMonitor
.beginTask(
Messages.FritzingDiagramEditorUtil_CreateDiagramProgressTask,
3);
final Resource diagramResource = editingDomain.getResourceSet()
.createResource(diagramURI);
final Resource modelResource = editingDomain.getResourceSet()
.createResource(modelURI);
final String diagramName = diagramURI.lastSegment();
AbstractTransactionalCommand command = new AbstractTransactionalCommand(
editingDomain,
Messages.FritzingDiagramEditorUtil_CreateDiagramCommandLabel,
Collections.EMPTY_LIST) {
protected CommandResult doExecuteWithResult(
IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
Sketch model = createInitialModel();
attachModelToResource(model, modelResource);
Diagram diagram = ViewService.createDiagram(model,
SketchEditPart.MODEL_ID,
FritzingDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);
if (diagram != null) {
diagramResource.getContents().add(diagram);
diagram.setName(diagramName);
diagram.setElement(model);
}
try {
modelResource
.save(org.fritzing.fritzing.diagram.part.FritzingDiagramEditorUtil
.getSaveOptions());
diagramResource
.save(org.fritzing.fritzing.diagram.part.FritzingDiagramEditorUtil
.getSaveOptions());
} catch (IOException e) {
FritzingDiagramEditorPlugin.getInstance().logError(
"Unable to store model and diagram resources", e); //$NON-NLS-1$
}
return CommandResult.newOKCommandResult();
}
};
try {
OperationHistoryFactory.getOperationHistory().execute(command,
new SubProgressMonitor(progressMonitor, 1), null);
} catch (ExecutionException e) {
FritzingDiagramEditorPlugin.getInstance().logError(
"Unable to create model and diagram", e); //$NON-NLS-1$
}
return diagramResource;
}
/**
* Create a new instance of domain element associated with canvas.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static Sketch createInitialModel() {
return FritzingFactory.eINSTANCE.createSketch();
}
/**
* Store model element in the resource.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static void attachModelToResource(Sketch model, Resource resource) {
resource.getContents().add(createDocumentRoot(model));
}
/**
* @generated
*/
private static DocumentRoot createDocumentRoot(Sketch model) {
DocumentRoot docRoot = FritzingFactory.eINSTANCE.createDocumentRoot();
docRoot.setSketch(model);
return docRoot;
}
/**
* @generated
*/
public static void selectElementsInDiagram(
IDiagramWorkbenchPart diagramPart, List/*EditPart*/editParts) {
diagramPart.getDiagramGraphicalViewer().deselectAll();
EditPart firstPrimary = null;
for (Iterator it = editParts.iterator(); it.hasNext();) {
EditPart nextPart = (EditPart) it.next();
diagramPart.getDiagramGraphicalViewer().appendSelection(nextPart);
if (firstPrimary == null && nextPart instanceof IPrimaryEditPart) {
firstPrimary = nextPart;
}
}
if (!editParts.isEmpty()) {
diagramPart.getDiagramGraphicalViewer().reveal(
firstPrimary != null ? firstPrimary : (EditPart) editParts
.get(0));
}
}
/**
* @generated
*/
private static int findElementsInDiagramByID(DiagramEditPart diagramPart,
EObject element, List editPartCollector) {
IDiagramGraphicalViewer viewer = (IDiagramGraphicalViewer) diagramPart
.getViewer();
final int intialNumOfEditParts = editPartCollector.size();
if (element instanceof View) { // support notation element lookup
EditPart editPart = (EditPart) viewer.getEditPartRegistry().get(
element);
if (editPart != null) {
editPartCollector.add(editPart);
return 1;
}
}
String elementID = EMFCoreUtil.getProxyID(element);
List associatedParts = viewer.findEditPartsForElement(elementID,
IGraphicalEditPart.class);
// perform the possible hierarchy disjoint -> take the top-most parts only
for (Iterator editPartIt = associatedParts.iterator(); editPartIt
.hasNext();) {
EditPart nextPart = (EditPart) editPartIt.next();
EditPart parentPart = nextPart.getParent();
while (parentPart != null && !associatedParts.contains(parentPart)) {
parentPart = parentPart.getParent();
}
if (parentPart == null) {
editPartCollector.add(nextPart);
}
}
if (intialNumOfEditParts == editPartCollector.size()) {
if (!associatedParts.isEmpty()) {
editPartCollector.add(associatedParts.iterator().next());
} else {
if (element.eContainer() != null) {
return findElementsInDiagramByID(diagramPart, element
.eContainer(), editPartCollector);
}
}
}
return editPartCollector.size() - intialNumOfEditParts;
}
/**
* @generated
*/
public static View findView(DiagramEditPart diagramEditPart,
EObject targetElement, LazyElement2ViewMap lazyElement2ViewMap) {
boolean hasStructuralURI = false;
if (targetElement.eResource() instanceof XMLResource) {
hasStructuralURI = ((XMLResource) targetElement.eResource())
.getID(targetElement) == null;
}
View view = null;
if (hasStructuralURI
&& !lazyElement2ViewMap.getElement2ViewMap().isEmpty()) {
view = (View) lazyElement2ViewMap.getElement2ViewMap().get(
targetElement);
} else if (findElementsInDiagramByID(diagramEditPart, targetElement,
lazyElement2ViewMap.editPartTmpHolder) > 0) {
EditPart editPart = (EditPart) lazyElement2ViewMap.editPartTmpHolder
.get(0);
lazyElement2ViewMap.editPartTmpHolder.clear();
view = editPart.getModel() instanceof View ? (View) editPart
.getModel() : null;
}
return (view == null) ? diagramEditPart.getDiagramView() : view;
}
/**
* @generated
*/
public static class LazyElement2ViewMap {
/**
* @generated
*/
private Map element2ViewMap;
/**
* @generated
*/
private View scope;
/**
* @generated
*/
private Set elementSet;
/**
* @generated
*/
public final List editPartTmpHolder = new ArrayList();
/**
* @generated
*/
public LazyElement2ViewMap(View scope, Set elements) {
this.scope = scope;
this.elementSet = elements;
}
/**
* @generated
*/
public final Map getElement2ViewMap() {
if (element2ViewMap == null) {
element2ViewMap = new HashMap();
// map possible notation elements to itself as these can't be found by view.getElement()
for (Iterator it = elementSet.iterator(); it.hasNext();) {
EObject element = (EObject) it.next();
if (element instanceof View) {
View view = (View) element;
if (view.getDiagram() == scope.getDiagram()) {
element2ViewMap.put(element, element); // take only those that part of our diagram
}
}
}
buildElement2ViewMap(scope, element2ViewMap, elementSet);
}
return element2ViewMap;
}
/**
* @generated
*/
static Map buildElement2ViewMap(View parentView, Map element2ViewMap,
Set elements) {
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
if (parentView.isSetElement()
&& !element2ViewMap.containsKey(parentView.getElement())
&& elements.contains(parentView.getElement())) {
element2ViewMap.put(parentView.getElement(), parentView);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
for (Iterator it = parentView.getChildren().iterator(); it
.hasNext();) {
buildElement2ViewMap((View) it.next(), element2ViewMap,
elements);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
for (Iterator it = parentView.getSourceEdges().iterator(); it
.hasNext();) {
buildElement2ViewMap((View) it.next(), element2ViewMap,
elements);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
for (Iterator it = parentView.getSourceEdges().iterator(); it
.hasNext();) {
buildElement2ViewMap((View) it.next(), element2ViewMap,
elements);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
return element2ViewMap;
}
} //LazyElement2ViewMap
/**
* @generated NOT
*/
public static URI getActiveDiagramURI() throws NullPointerException {
IEditorInput input = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage().getActiveEditor()
.getEditorInput();
return ((URIEditorInput) input).getURI();
}
/**
* @generated NOT
*/
public static FritzingDiagramEditor getActiveDiagramPart()
throws NullPointerException {
IEditorPart editor = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
return ((FritzingDiagramEditor) editor);
}
/**
* @generated NOT
*/
public static Boolean openFritzingFile(URI fileURI) {
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage page = workbenchWindow.getActivePage();
IEditorDescriptor editorDescriptor = workbench.getEditorRegistry()
.getDefaultEditor(fileURI.toFileString());
if (editorDescriptor == null) {
MessageDialog
.openError(
workbenchWindow.getShell(),
Messages.DiagramEditorActionBarAdvisor_DefaultFileEditorTitle,
NLS
.bind(
Messages.DiagramEditorActionBarAdvisor_DefaultFileEditorMessage,
fileURI.toFileString()));
return false;
} else {
try {
page.openEditor(new URIEditorInput(fileURI), editorDescriptor
.getId());
} catch (PartInitException exception) {
MessageDialog
.openError(
workbenchWindow.getShell(),
Messages.DiagramEditorActionBarAdvisor_DefaultEditorOpenErrorTitle,
exception.getMessage());
return false;
}
}
return true;
}
/**
* @return the install location of Fritzing on the hard drive
*/
public static String getFritzingLocation() {
String fritzingLocation = Platform.getInstallLocation().getURL()
.getPath();
if (Platform.getOS().equals(Platform.OS_WIN32)) {
fritzingLocation = fritzingLocation.startsWith("/") ? fritzingLocation
.substring(1)
: fritzingLocation;
}
return fritzingLocation;
}
public static File getFritzingUserFolder() {
File location = new File(System.getProperty("user.home") + "/Fritzing"); // fallback location
// taken from Arduinos Base.getDefaultSketchbookFolder():
if (Platform.getOS().equals(Platform.OS_MACOSX)) {
try {
Class clazz = Class.forName("com.apple.eio.FileManager");
java.lang.reflect.Method m = clazz.getMethod("findFolder",
new Class[] { int.class });
String docPath = (String) m.invoke(null,
- new Object[] { new Integer(kUserDomain) });
+ new Object[] { new Short(kUserDomain), new Integer(kDocumentsFolderType) });
location = new File(docPath + "/Fritzing");
} catch (Exception ex) {
ex.printStackTrace();
}
// carbon folder constants
// http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/folder_manager_ref/constant_6.html#//apple_ref/doc/uid/TP30000238/C006889
// additional information found in the local file:
// /System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/CarbonCore.framework/Headers/
/*
try {
MRJOSType domainDocuments = new MRJOSType("docs");
//File libraryFolder = MRJFileUtils.findFolder(domainDocuments);
// for 77, try switching this to the user domain, just to be sure
Method findFolderMethod =
MRJFileUtils.class.getMethod("findFolder",
new Class[] { Short.TYPE,
MRJOSType.class });
File documentsFolder = (File)
findFolderMethod.invoke(null, new Object[] { new Short(kUserDomain),
domainDocuments });
location = new File(documentsFolder, "Fritzing");
} catch (Exception e) {
//showError("Could not find folder",
// "Could not locate the Documents folder.", e);
// sketchbookFolder = promptSketchbookLocation();
}
*/
} else if (Platform.getOS().equals(Platform.OS_WIN32)) {
// looking for Documents and Settings/blah/My Documents/Fritzing
// or on Vista Users/blah/Documents/Fritzing
// (though using a reg key since it's different on other platforms)
// http://support.microsoft.com/?kbid=221837&sd=RMVP
// The path to the My Documents folder is stored in the
// following registry key, where path is the complete path
// to your storage location:
// HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
// Value Name: Personal
// Value Type: REG_SZ
// Value Data: path
try {
RegistryKey topKey = Registry.HKEY_CURRENT_USER;
String localKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion"
+ "\\Explorer\\Shell Folders";
RegistryKey localKey = topKey.openSubKey(localKeyPath);
String personalPath = cleanKey(localKey
.getStringValue("Personal"));
//topKey.closeKey(); // necessary?
//localKey.closeKey();
location = new File(personalPath, "Fritzing");
} catch (Exception e) {
//showError("Problem getting folder",
// "Could not locate the Documents folder.", e);
// sketchbookFolder = promptSketchbookLocation();
}
}
return location;
}
// taken from Arduinos Base.cleanKey():
static public String cleanKey(String what) {
// jnireg seems to be reading the chars as bytes
// so maybe be as simple as & 0xff and then running through decoder
char c[] = what.toCharArray();
// if chars are in the tooHigh range, it's prolly because
// a byte from the jni registry was turned into a char
// and there was a sign extension.
// e.g. 0xFC (252, umlaut u) became 0xFFFC (65532).
// but on a japanese system, maybe this is two-byte and ok?
int tooHigh = 65536 - 128;
for (int i = 0; i < c.length; i++) {
if (c[i] >= tooHigh)
c[i] &= 0xff;
}
return new String(c);
}
static final int kDocumentsFolderType = ('d' << 24) | ('o' << 16)
| ('c' << 8) | 's';
static final int kPreferencesFolderType = ('p' << 24) | ('r' << 16)
| ('e' << 8) | 'f';
static final int kDomainLibraryFolderType = ('d' << 24) | ('l' << 16)
| ('i' << 8) | 'b';
static final short kUserDomain = -32763;
}
| true | true | public static File getFritzingUserFolder() {
File location = new File(System.getProperty("user.home") + "/Fritzing"); // fallback location
// taken from Arduinos Base.getDefaultSketchbookFolder():
if (Platform.getOS().equals(Platform.OS_MACOSX)) {
try {
Class clazz = Class.forName("com.apple.eio.FileManager");
java.lang.reflect.Method m = clazz.getMethod("findFolder",
new Class[] { int.class });
String docPath = (String) m.invoke(null,
new Object[] { new Integer(kUserDomain) });
location = new File(docPath + "/Fritzing");
} catch (Exception ex) {
ex.printStackTrace();
}
// carbon folder constants
// http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/folder_manager_ref/constant_6.html#//apple_ref/doc/uid/TP30000238/C006889
// additional information found in the local file:
// /System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/CarbonCore.framework/Headers/
/*
try {
MRJOSType domainDocuments = new MRJOSType("docs");
//File libraryFolder = MRJFileUtils.findFolder(domainDocuments);
// for 77, try switching this to the user domain, just to be sure
Method findFolderMethod =
MRJFileUtils.class.getMethod("findFolder",
new Class[] { Short.TYPE,
MRJOSType.class });
File documentsFolder = (File)
findFolderMethod.invoke(null, new Object[] { new Short(kUserDomain),
domainDocuments });
location = new File(documentsFolder, "Fritzing");
} catch (Exception e) {
//showError("Could not find folder",
// "Could not locate the Documents folder.", e);
// sketchbookFolder = promptSketchbookLocation();
}
*/
} else if (Platform.getOS().equals(Platform.OS_WIN32)) {
// looking for Documents and Settings/blah/My Documents/Fritzing
// or on Vista Users/blah/Documents/Fritzing
// (though using a reg key since it's different on other platforms)
// http://support.microsoft.com/?kbid=221837&sd=RMVP
// The path to the My Documents folder is stored in the
// following registry key, where path is the complete path
// to your storage location:
// HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
// Value Name: Personal
// Value Type: REG_SZ
// Value Data: path
try {
RegistryKey topKey = Registry.HKEY_CURRENT_USER;
String localKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion"
+ "\\Explorer\\Shell Folders";
RegistryKey localKey = topKey.openSubKey(localKeyPath);
String personalPath = cleanKey(localKey
.getStringValue("Personal"));
//topKey.closeKey(); // necessary?
//localKey.closeKey();
location = new File(personalPath, "Fritzing");
} catch (Exception e) {
//showError("Problem getting folder",
// "Could not locate the Documents folder.", e);
// sketchbookFolder = promptSketchbookLocation();
}
}
return location;
}
| public static File getFritzingUserFolder() {
File location = new File(System.getProperty("user.home") + "/Fritzing"); // fallback location
// taken from Arduinos Base.getDefaultSketchbookFolder():
if (Platform.getOS().equals(Platform.OS_MACOSX)) {
try {
Class clazz = Class.forName("com.apple.eio.FileManager");
java.lang.reflect.Method m = clazz.getMethod("findFolder",
new Class[] { int.class });
String docPath = (String) m.invoke(null,
new Object[] { new Short(kUserDomain), new Integer(kDocumentsFolderType) });
location = new File(docPath + "/Fritzing");
} catch (Exception ex) {
ex.printStackTrace();
}
// carbon folder constants
// http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/folder_manager_ref/constant_6.html#//apple_ref/doc/uid/TP30000238/C006889
// additional information found in the local file:
// /System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/CarbonCore.framework/Headers/
/*
try {
MRJOSType domainDocuments = new MRJOSType("docs");
//File libraryFolder = MRJFileUtils.findFolder(domainDocuments);
// for 77, try switching this to the user domain, just to be sure
Method findFolderMethod =
MRJFileUtils.class.getMethod("findFolder",
new Class[] { Short.TYPE,
MRJOSType.class });
File documentsFolder = (File)
findFolderMethod.invoke(null, new Object[] { new Short(kUserDomain),
domainDocuments });
location = new File(documentsFolder, "Fritzing");
} catch (Exception e) {
//showError("Could not find folder",
// "Could not locate the Documents folder.", e);
// sketchbookFolder = promptSketchbookLocation();
}
*/
} else if (Platform.getOS().equals(Platform.OS_WIN32)) {
// looking for Documents and Settings/blah/My Documents/Fritzing
// or on Vista Users/blah/Documents/Fritzing
// (though using a reg key since it's different on other platforms)
// http://support.microsoft.com/?kbid=221837&sd=RMVP
// The path to the My Documents folder is stored in the
// following registry key, where path is the complete path
// to your storage location:
// HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
// Value Name: Personal
// Value Type: REG_SZ
// Value Data: path
try {
RegistryKey topKey = Registry.HKEY_CURRENT_USER;
String localKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion"
+ "\\Explorer\\Shell Folders";
RegistryKey localKey = topKey.openSubKey(localKeyPath);
String personalPath = cleanKey(localKey
.getStringValue("Personal"));
//topKey.closeKey(); // necessary?
//localKey.closeKey();
location = new File(personalPath, "Fritzing");
} catch (Exception e) {
//showError("Problem getting folder",
// "Could not locate the Documents folder.", e);
// sketchbookFolder = promptSketchbookLocation();
}
}
return location;
}
|
diff --git a/Kandidat33MobileGame/src/gamestate/PlatformSceneObjectDataSource.java b/Kandidat33MobileGame/src/gamestate/PlatformSceneObjectDataSource.java
index a60fa9d..70db673 100644
--- a/Kandidat33MobileGame/src/gamestate/PlatformSceneObjectDataSource.java
+++ b/Kandidat33MobileGame/src/gamestate/PlatformSceneObjectDataSource.java
@@ -1,48 +1,48 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gamestate;
import com.jme3.asset.AssetManager;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import variables.P;
/**
*
* @author dagen
*/
public class PlatformSceneObjectDataSource implements SceneObjectDataSource{
AssetManager assetManager;
private static int counter = 0;
private static Geometry geometery;
public PlatformSceneObjectDataSource(AssetManager assetManager){
this.assetManager = assetManager;
}
public Spatial getSceneObject(){
Geometry geometry;
if(this.geometery == null){
Box model = new Box(Vector3f.ZERO,P.platformLength,P.platformHeight,P.platformWidth);
geometry = new Geometry("Platform" , model);
Material material = new Material(this.assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
ColorRGBA color = ColorRGBA.Blue;
material.setColor("Color", color);
geometry.setMaterial(material);
- return (this.geometery = geometery);
+ return (this.geometery = geometry);
}
return (geometry = this.geometery.clone(true));
}
}
| true | true | public Spatial getSceneObject(){
Geometry geometry;
if(this.geometery == null){
Box model = new Box(Vector3f.ZERO,P.platformLength,P.platformHeight,P.platformWidth);
geometry = new Geometry("Platform" , model);
Material material = new Material(this.assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
ColorRGBA color = ColorRGBA.Blue;
material.setColor("Color", color);
geometry.setMaterial(material);
return (this.geometery = geometery);
}
return (geometry = this.geometery.clone(true));
}
| public Spatial getSceneObject(){
Geometry geometry;
if(this.geometery == null){
Box model = new Box(Vector3f.ZERO,P.platformLength,P.platformHeight,P.platformWidth);
geometry = new Geometry("Platform" , model);
Material material = new Material(this.assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
ColorRGBA color = ColorRGBA.Blue;
material.setColor("Color", color);
geometry.setMaterial(material);
return (this.geometery = geometry);
}
return (geometry = this.geometery.clone(true));
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/commands/entity/ShootCommand.java b/src/main/java/net/aufdemrand/denizen/scripts/commands/entity/ShootCommand.java
index cd487ac57..76257f8f3 100644
--- a/src/main/java/net/aufdemrand/denizen/scripts/commands/entity/ShootCommand.java
+++ b/src/main/java/net/aufdemrand/denizen/scripts/commands/entity/ShootCommand.java
@@ -1,276 +1,278 @@
package net.aufdemrand.denizen.scripts.commands.entity;
import java.util.List;
import net.aufdemrand.denizen.exceptions.CommandExecutionException;
import net.aufdemrand.denizen.exceptions.InvalidArgumentsException;
import net.aufdemrand.denizen.objects.Element;
import net.aufdemrand.denizen.objects.aH;
import net.aufdemrand.denizen.objects.dEntity;
import net.aufdemrand.denizen.objects.dList;
import net.aufdemrand.denizen.objects.dLocation;
import net.aufdemrand.denizen.objects.dScript;
import net.aufdemrand.denizen.scripts.ScriptEntry;
import net.aufdemrand.denizen.scripts.commands.AbstractCommand;
import net.aufdemrand.denizen.scripts.queues.ScriptQueue;
import net.aufdemrand.denizen.scripts.queues.core.InstantQueue;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizen.utilities.Conversion;
import net.aufdemrand.denizen.utilities.Velocity;
import net.aufdemrand.denizen.utilities.entity.Gravity;
import net.aufdemrand.denizen.utilities.entity.Position;
import net.aufdemrand.denizen.utilities.entity.Rotation;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
/**
* Shoots an entity through the air up to a certain height, optionally using a custom gravity value and triggering a script on impact with a surface.
*
* @author David Cernat
*/
public class ShootCommand extends AbstractCommand {
@Override
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {
for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) {
if (!scriptEntry.hasObject("origin")
&& arg.matchesPrefix("origin, o, source, shooter, s")) {
if (arg.matchesArgumentType(dEntity.class))
scriptEntry.addObject("originEntity", arg.asType(dEntity.class));
else if (arg.matchesArgumentType(dLocation.class))
scriptEntry.addObject("originLocation", arg.asType(dLocation.class));
else
dB.echoError("Ignoring unrecognized argument: " + arg.raw_value);
}
else if (!scriptEntry.hasObject("destination")
&& arg.matchesArgumentType(dLocation.class)
&& arg.matchesPrefix("destination, d")) {
scriptEntry.addObject("destination", arg.asType(dLocation.class));
}
else if (!scriptEntry.hasObject("height")
&& arg.matchesPrimitive(aH.PrimitiveType.Double)
&& arg.matchesPrefix("height, h")) {
scriptEntry.addObject("height", arg.asElement());
}
else if (!scriptEntry.hasObject("speed")
&& arg.matchesPrimitive(aH.PrimitiveType.Double)
&& arg.matchesPrefix("speed")) {
scriptEntry.addObject("speed", arg.asElement());
}
else if (!scriptEntry.hasObject("script")
&& arg.matchesArgumentType(dScript.class)) {
scriptEntry.addObject("script", arg.asType(dScript.class));
}
else if (!scriptEntry.hasObject("shooter")
&& arg.matchesArgumentType(dEntity.class)
&& arg.matchesPrefix("shooter")) {
scriptEntry.addObject("shooter", arg.asType(dEntity.class));
}
else if (!scriptEntry.hasObject("entities")
&& arg.matchesArgumentList(dEntity.class)) {
scriptEntry.addObject("entities", arg.asType(dList.class).filter(dEntity.class));
}
// Don't document this argument; it is for debug purposes only
else if (!scriptEntry.hasObject("gravity")
&& arg.matchesPrimitive(aH.PrimitiveType.Double)
&& arg.matchesPrefix("gravity, g")) {
scriptEntry.addObject("gravity", arg.asElement());
}
else arg.reportUnhandled();
}
// Use the NPC or player's locations as the origin if one is not specified
if (!scriptEntry.hasObject("originLocation")) {
scriptEntry.defaultObject("originEntity",
scriptEntry.hasNPC() ? scriptEntry.getNPC().getDenizenEntity() : null,
scriptEntry.hasPlayer() ? scriptEntry.getPlayer().getDenizenEntity() : null);
}
scriptEntry.defaultObject("height", new Element(3));
// Check to make sure required arguments have been filled
if (!scriptEntry.hasObject("entities"))
throw new InvalidArgumentsException("Must specify entity/entities!");
if (!scriptEntry.hasObject("originEntity") && !scriptEntry.hasObject("originLocation"))
throw new InvalidArgumentsException("Must specify an origin location!");
}
@SuppressWarnings("unchecked")
@Override
public void execute(final ScriptEntry scriptEntry) throws CommandExecutionException {
dEntity originEntity = (dEntity) scriptEntry.getObject("originEntity");
dLocation originLocation = scriptEntry.hasObject("originLocation") ?
(dLocation) scriptEntry.getObject("originLocation") :
new dLocation(originEntity.getEyeLocation()
.add(originEntity.getEyeLocation().getDirection())
.subtract(0, 0.4, 0));
// If there is no destination set, but there is a shooter, get a point
// in front of the shooter and set it as the destination
final dLocation destination = scriptEntry.hasObject("destination") ?
(dLocation) scriptEntry.getObject("destination") :
(originEntity != null ? new dLocation(originEntity.getEyeLocation()
.add(originEntity.getEyeLocation().getDirection()
.multiply(30)))
: null);
// TODO: Same as PUSH -- is this the place to do this?
if (destination == null) {
dB.report(scriptEntry, getName(), "No destination specified!");
return;
}
List<dEntity> entities = (List<dEntity>) scriptEntry.getObject("entities");
final dScript script = (dScript) scriptEntry.getObject("script");
dEntity shooter = (dEntity) scriptEntry.getObject("shooter");
Element height = scriptEntry.getElement("height");
Element gravity = scriptEntry.getElement("gravity");
Element speed = scriptEntry.getElement("speed");
// Report to dB
dB.report(scriptEntry, getName(), aH.debugObj("origin", originEntity != null ? originEntity : originLocation) +
aH.debugObj("entities", entities.toString()) +
destination.debug() +
height.debug() +
(gravity != null ? gravity.debug(): "") +
(speed != null ? speed.debug(): "") +
(script != null ? script.debug() : "") +
(shooter != null ? shooter.debug() : ""));
// Keep a dList of entities that can be called using <entry[name].shot_entities>
// later in the script queue
final dList entityList = new dList();
// Go through all the entities, spawning/teleporting and rotating them
for (dEntity entity : entities) {
entity.spawnAt(originLocation);
// Only add to entityList after the entities have been
// spawned, otherwise you'll get something like "e@skeleton"
// instead of "e@57" on it
entityList.add(entity.toString());
Rotation.faceLocation(entity.getBukkitEntity(), destination);
// If the current entity is a projectile, set its shooter
// when applicable
if (entity.isProjectile() && (shooter != null || originEntity != null)) {
entity.setShooter(shooter != null ? shooter : originEntity);
}
}
// Add entities to context so that the specific entities created/spawned
// can be fetched.
scriptEntry.addObject("shot_entities", entityList);
Position.mount(Conversion.convertEntities(entities));
// Get the entity at the bottom of the entity list, because
// only its gravity should be affected and tracked considering
// that the other entities will be mounted on it
final dEntity lastEntity = entities.get(entities.size() - 1);
if (gravity == null) {
String entityType = lastEntity.getEntityType().name();
for (Gravity defaultGravity : Gravity.values()) {
if (defaultGravity.name().equals(entityType)) {
gravity = new Element(defaultGravity.getGravity());
}
}
// If the gravity is still null, use a default value
if (gravity == null) {
gravity = new Element(0.115);
}
}
if (speed == null) {
Vector v1 = lastEntity.getLocation().toVector();
Vector v2 = destination.toVector();
Vector v3 = Velocity.calculate(v1, v2, gravity.asDouble(), height.asDouble());
lastEntity.setVelocity(v3);
}
else {
lastEntity.setVelocity(destination.subtract(originLocation).toVector()
.normalize().multiply(speed.asDouble()));
}
// A task used to trigger a script if the entity is no longer
// being shot, when the script argument is used
BukkitRunnable task = new BukkitRunnable() {
boolean flying = true;
+ dLocation lastLocation = null;
Vector lastVelocity = null;
public void run() {
// If the entity is no longer spawned, stop the task
if (!lastEntity.isSpawned()) {
flying = false;
}
// Else, if the entity is no longer traveling through
// the air, stop the task
else if (lastVelocity != null) {
if (lastVelocity.distance
(lastEntity.getBukkitEntity().getVelocity()) < 0.05) {
flying = false;
}
}
// Stop the task and run the script if conditions
// are met
if (!flying) {
this.cancel();
List<ScriptEntry> entries = script.getContainer().getBaseEntries
(scriptEntry.getPlayer(),
scriptEntry.getNPC());
ScriptQueue queue = InstantQueue.getQueue(ScriptQueue._getNextId()).addEntries(entries);
- queue.addDefinition("location", lastEntity.getLocation().identify());
+ queue.addDefinition("location", lastLocation.identify());
queue.addDefinition("shot_entities", entityList.toString());
queue.addDefinition("last_entity", lastEntity.identify());
queue.start();
}
else {
+ lastLocation = lastEntity.getLocation();
lastVelocity = lastEntity.getVelocity();
}
}
};
// Run the task above if a script argument was specified
if (script != null) {
task.runTaskTimer(denizen, 0, 2);
}
}
}
| false | true | public void execute(final ScriptEntry scriptEntry) throws CommandExecutionException {
dEntity originEntity = (dEntity) scriptEntry.getObject("originEntity");
dLocation originLocation = scriptEntry.hasObject("originLocation") ?
(dLocation) scriptEntry.getObject("originLocation") :
new dLocation(originEntity.getEyeLocation()
.add(originEntity.getEyeLocation().getDirection())
.subtract(0, 0.4, 0));
// If there is no destination set, but there is a shooter, get a point
// in front of the shooter and set it as the destination
final dLocation destination = scriptEntry.hasObject("destination") ?
(dLocation) scriptEntry.getObject("destination") :
(originEntity != null ? new dLocation(originEntity.getEyeLocation()
.add(originEntity.getEyeLocation().getDirection()
.multiply(30)))
: null);
// TODO: Same as PUSH -- is this the place to do this?
if (destination == null) {
dB.report(scriptEntry, getName(), "No destination specified!");
return;
}
List<dEntity> entities = (List<dEntity>) scriptEntry.getObject("entities");
final dScript script = (dScript) scriptEntry.getObject("script");
dEntity shooter = (dEntity) scriptEntry.getObject("shooter");
Element height = scriptEntry.getElement("height");
Element gravity = scriptEntry.getElement("gravity");
Element speed = scriptEntry.getElement("speed");
// Report to dB
dB.report(scriptEntry, getName(), aH.debugObj("origin", originEntity != null ? originEntity : originLocation) +
aH.debugObj("entities", entities.toString()) +
destination.debug() +
height.debug() +
(gravity != null ? gravity.debug(): "") +
(speed != null ? speed.debug(): "") +
(script != null ? script.debug() : "") +
(shooter != null ? shooter.debug() : ""));
// Keep a dList of entities that can be called using <entry[name].shot_entities>
// later in the script queue
final dList entityList = new dList();
// Go through all the entities, spawning/teleporting and rotating them
for (dEntity entity : entities) {
entity.spawnAt(originLocation);
// Only add to entityList after the entities have been
// spawned, otherwise you'll get something like "e@skeleton"
// instead of "e@57" on it
entityList.add(entity.toString());
Rotation.faceLocation(entity.getBukkitEntity(), destination);
// If the current entity is a projectile, set its shooter
// when applicable
if (entity.isProjectile() && (shooter != null || originEntity != null)) {
entity.setShooter(shooter != null ? shooter : originEntity);
}
}
// Add entities to context so that the specific entities created/spawned
// can be fetched.
scriptEntry.addObject("shot_entities", entityList);
Position.mount(Conversion.convertEntities(entities));
// Get the entity at the bottom of the entity list, because
// only its gravity should be affected and tracked considering
// that the other entities will be mounted on it
final dEntity lastEntity = entities.get(entities.size() - 1);
if (gravity == null) {
String entityType = lastEntity.getEntityType().name();
for (Gravity defaultGravity : Gravity.values()) {
if (defaultGravity.name().equals(entityType)) {
gravity = new Element(defaultGravity.getGravity());
}
}
// If the gravity is still null, use a default value
if (gravity == null) {
gravity = new Element(0.115);
}
}
if (speed == null) {
Vector v1 = lastEntity.getLocation().toVector();
Vector v2 = destination.toVector();
Vector v3 = Velocity.calculate(v1, v2, gravity.asDouble(), height.asDouble());
lastEntity.setVelocity(v3);
}
else {
lastEntity.setVelocity(destination.subtract(originLocation).toVector()
.normalize().multiply(speed.asDouble()));
}
// A task used to trigger a script if the entity is no longer
// being shot, when the script argument is used
BukkitRunnable task = new BukkitRunnable() {
boolean flying = true;
Vector lastVelocity = null;
public void run() {
// If the entity is no longer spawned, stop the task
if (!lastEntity.isSpawned()) {
flying = false;
}
// Else, if the entity is no longer traveling through
// the air, stop the task
else if (lastVelocity != null) {
if (lastVelocity.distance
(lastEntity.getBukkitEntity().getVelocity()) < 0.05) {
flying = false;
}
}
// Stop the task and run the script if conditions
// are met
if (!flying) {
this.cancel();
List<ScriptEntry> entries = script.getContainer().getBaseEntries
(scriptEntry.getPlayer(),
scriptEntry.getNPC());
ScriptQueue queue = InstantQueue.getQueue(ScriptQueue._getNextId()).addEntries(entries);
queue.addDefinition("location", lastEntity.getLocation().identify());
queue.addDefinition("shot_entities", entityList.toString());
queue.addDefinition("last_entity", lastEntity.identify());
queue.start();
}
else {
lastVelocity = lastEntity.getVelocity();
}
}
};
// Run the task above if a script argument was specified
if (script != null) {
task.runTaskTimer(denizen, 0, 2);
}
}
| public void execute(final ScriptEntry scriptEntry) throws CommandExecutionException {
dEntity originEntity = (dEntity) scriptEntry.getObject("originEntity");
dLocation originLocation = scriptEntry.hasObject("originLocation") ?
(dLocation) scriptEntry.getObject("originLocation") :
new dLocation(originEntity.getEyeLocation()
.add(originEntity.getEyeLocation().getDirection())
.subtract(0, 0.4, 0));
// If there is no destination set, but there is a shooter, get a point
// in front of the shooter and set it as the destination
final dLocation destination = scriptEntry.hasObject("destination") ?
(dLocation) scriptEntry.getObject("destination") :
(originEntity != null ? new dLocation(originEntity.getEyeLocation()
.add(originEntity.getEyeLocation().getDirection()
.multiply(30)))
: null);
// TODO: Same as PUSH -- is this the place to do this?
if (destination == null) {
dB.report(scriptEntry, getName(), "No destination specified!");
return;
}
List<dEntity> entities = (List<dEntity>) scriptEntry.getObject("entities");
final dScript script = (dScript) scriptEntry.getObject("script");
dEntity shooter = (dEntity) scriptEntry.getObject("shooter");
Element height = scriptEntry.getElement("height");
Element gravity = scriptEntry.getElement("gravity");
Element speed = scriptEntry.getElement("speed");
// Report to dB
dB.report(scriptEntry, getName(), aH.debugObj("origin", originEntity != null ? originEntity : originLocation) +
aH.debugObj("entities", entities.toString()) +
destination.debug() +
height.debug() +
(gravity != null ? gravity.debug(): "") +
(speed != null ? speed.debug(): "") +
(script != null ? script.debug() : "") +
(shooter != null ? shooter.debug() : ""));
// Keep a dList of entities that can be called using <entry[name].shot_entities>
// later in the script queue
final dList entityList = new dList();
// Go through all the entities, spawning/teleporting and rotating them
for (dEntity entity : entities) {
entity.spawnAt(originLocation);
// Only add to entityList after the entities have been
// spawned, otherwise you'll get something like "e@skeleton"
// instead of "e@57" on it
entityList.add(entity.toString());
Rotation.faceLocation(entity.getBukkitEntity(), destination);
// If the current entity is a projectile, set its shooter
// when applicable
if (entity.isProjectile() && (shooter != null || originEntity != null)) {
entity.setShooter(shooter != null ? shooter : originEntity);
}
}
// Add entities to context so that the specific entities created/spawned
// can be fetched.
scriptEntry.addObject("shot_entities", entityList);
Position.mount(Conversion.convertEntities(entities));
// Get the entity at the bottom of the entity list, because
// only its gravity should be affected and tracked considering
// that the other entities will be mounted on it
final dEntity lastEntity = entities.get(entities.size() - 1);
if (gravity == null) {
String entityType = lastEntity.getEntityType().name();
for (Gravity defaultGravity : Gravity.values()) {
if (defaultGravity.name().equals(entityType)) {
gravity = new Element(defaultGravity.getGravity());
}
}
// If the gravity is still null, use a default value
if (gravity == null) {
gravity = new Element(0.115);
}
}
if (speed == null) {
Vector v1 = lastEntity.getLocation().toVector();
Vector v2 = destination.toVector();
Vector v3 = Velocity.calculate(v1, v2, gravity.asDouble(), height.asDouble());
lastEntity.setVelocity(v3);
}
else {
lastEntity.setVelocity(destination.subtract(originLocation).toVector()
.normalize().multiply(speed.asDouble()));
}
// A task used to trigger a script if the entity is no longer
// being shot, when the script argument is used
BukkitRunnable task = new BukkitRunnable() {
boolean flying = true;
dLocation lastLocation = null;
Vector lastVelocity = null;
public void run() {
// If the entity is no longer spawned, stop the task
if (!lastEntity.isSpawned()) {
flying = false;
}
// Else, if the entity is no longer traveling through
// the air, stop the task
else if (lastVelocity != null) {
if (lastVelocity.distance
(lastEntity.getBukkitEntity().getVelocity()) < 0.05) {
flying = false;
}
}
// Stop the task and run the script if conditions
// are met
if (!flying) {
this.cancel();
List<ScriptEntry> entries = script.getContainer().getBaseEntries
(scriptEntry.getPlayer(),
scriptEntry.getNPC());
ScriptQueue queue = InstantQueue.getQueue(ScriptQueue._getNextId()).addEntries(entries);
queue.addDefinition("location", lastLocation.identify());
queue.addDefinition("shot_entities", entityList.toString());
queue.addDefinition("last_entity", lastEntity.identify());
queue.start();
}
else {
lastLocation = lastEntity.getLocation();
lastVelocity = lastEntity.getVelocity();
}
}
};
// Run the task above if a script argument was specified
if (script != null) {
task.runTaskTimer(denizen, 0, 2);
}
}
|
diff --git a/src/main/java/org/primefaces/extensions/component/tooltip/TooltipRenderer.java b/src/main/java/org/primefaces/extensions/component/tooltip/TooltipRenderer.java
index dbd2b6a9..ed0cd62d 100644
--- a/src/main/java/org/primefaces/extensions/component/tooltip/TooltipRenderer.java
+++ b/src/main/java/org/primefaces/extensions/component/tooltip/TooltipRenderer.java
@@ -1,139 +1,139 @@
/*
* Copyright 2011 PrimeFaces Extensions.
*
* 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.
*
* $Id$
*/
package org.primefaces.extensions.component.tooltip;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.primefaces.extensions.util.ComponentUtils;
import org.primefaces.extensions.util.FastStringWriter;
import org.primefaces.renderkit.CoreRenderer;
/**
* Renderer for the {@link Tooltip} component.
*
* @author Oleg Varaksin / last modified by $Author$
* @version $Revision$
* @since 0.2
*/
public class TooltipRenderer extends CoreRenderer {
@Override
public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
Tooltip tooltip = (Tooltip) component;
String clientId = tooltip.getClientId(context);
boolean global = tooltip.isGlobal();
boolean shared = tooltip.isShared();
boolean autoShow = tooltip.isAutoShow();
boolean mouseTracking = tooltip.isMouseTracking();
String target = null;
if (!global || (tooltip.getFor() != null || tooltip.getForSelector() != null)) {
target = ComponentUtils.findTarget(context, tooltip);
}
startScript(writer, clientId);
writer.write("$(function() {");
writer.write("PrimeFacesExt.cw('Tooltip', '" + tooltip.resolveWidgetVar() + "',{");
writer.write("id:'" + clientId + "'");
writer.write(",global:" + global);
writer.write(",shared:" + shared);
writer.write(",autoShow:" + autoShow);
if (target == null) {
writer.write(",forTarget:null");
} else {
writer.write(",forTarget:'" + target + "'");
}
if (!global) {
writer.write(",content:\"");
if (tooltip.getChildCount() > 0) {
FastStringWriter fsw = new FastStringWriter();
ResponseWriter clonedWriter = writer.cloneWithWriter(fsw);
context.setResponseWriter(clonedWriter);
renderChildren(context, tooltip);
context.setResponseWriter(writer);
writer.write(escapeText(fsw.toString()));
} else {
String valueToRender = ComponentUtils.getValueToRender(context, tooltip);
if (valueToRender != null) {
writer.write(escapeText(valueToRender));
}
}
writer.write("\"");
}
// events
if (mouseTracking) {
writer.write(",hide:{fixed:true}");
} else if (shared && !global) {
writer.write(",show:{target:$('" + target + "')" + ",delay:" + tooltip.getShowDelay()
+ ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength()
+ ");}}");
writer.write(",hide:{target:$('" + target + "')" + ",delay:" + tooltip.getHideDelay()
+ ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength()
+ ");}}");
} else if (autoShow) {
writer.write(",show:{when:false,ready:true}");
writer.write(",hide:false");
} else {
writer.write(",show:{event:'" + tooltip.getShowEvent() + "',delay:" + tooltip.getShowDelay()
+ ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength()
+ ");}}");
writer.write(",hide:{event:'" + tooltip.getHideEvent() + "',delay:" + tooltip.getHideDelay()
+ ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength()
+ ");}}");
}
// position
writer.write(",position: {");
writer.write("at:'" + tooltip.getAtPosition() + "'");
writer.write(",my:'" + tooltip.getMyPosition() + "'");
writer.write(",adjust:{x:" + tooltip.getAdjustX() + ",y:" + tooltip.getAdjustY() + "}");
+ writer.write(",viewport:$(window)");
if (mouseTracking) {
writer.write(",target:'mouse'");
- writer.write(",viewport:$(window)");
} else if (shared && !global) {
writer.write(",target:'event'");
writer.write(",effect:false");
}
writer.write("}},true);});");
endScript(writer);
}
@Override
public void encodeChildren(final FacesContext context, final UIComponent component) throws IOException {
//do nothing
}
@Override
public boolean getRendersChildren() {
return true;
}
}
| false | true | public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
Tooltip tooltip = (Tooltip) component;
String clientId = tooltip.getClientId(context);
boolean global = tooltip.isGlobal();
boolean shared = tooltip.isShared();
boolean autoShow = tooltip.isAutoShow();
boolean mouseTracking = tooltip.isMouseTracking();
String target = null;
if (!global || (tooltip.getFor() != null || tooltip.getForSelector() != null)) {
target = ComponentUtils.findTarget(context, tooltip);
}
startScript(writer, clientId);
writer.write("$(function() {");
writer.write("PrimeFacesExt.cw('Tooltip', '" + tooltip.resolveWidgetVar() + "',{");
writer.write("id:'" + clientId + "'");
writer.write(",global:" + global);
writer.write(",shared:" + shared);
writer.write(",autoShow:" + autoShow);
if (target == null) {
writer.write(",forTarget:null");
} else {
writer.write(",forTarget:'" + target + "'");
}
if (!global) {
writer.write(",content:\"");
if (tooltip.getChildCount() > 0) {
FastStringWriter fsw = new FastStringWriter();
ResponseWriter clonedWriter = writer.cloneWithWriter(fsw);
context.setResponseWriter(clonedWriter);
renderChildren(context, tooltip);
context.setResponseWriter(writer);
writer.write(escapeText(fsw.toString()));
} else {
String valueToRender = ComponentUtils.getValueToRender(context, tooltip);
if (valueToRender != null) {
writer.write(escapeText(valueToRender));
}
}
writer.write("\"");
}
// events
if (mouseTracking) {
writer.write(",hide:{fixed:true}");
} else if (shared && !global) {
writer.write(",show:{target:$('" + target + "')" + ",delay:" + tooltip.getShowDelay()
+ ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength()
+ ");}}");
writer.write(",hide:{target:$('" + target + "')" + ",delay:" + tooltip.getHideDelay()
+ ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength()
+ ");}}");
} else if (autoShow) {
writer.write(",show:{when:false,ready:true}");
writer.write(",hide:false");
} else {
writer.write(",show:{event:'" + tooltip.getShowEvent() + "',delay:" + tooltip.getShowDelay()
+ ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength()
+ ");}}");
writer.write(",hide:{event:'" + tooltip.getHideEvent() + "',delay:" + tooltip.getHideDelay()
+ ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength()
+ ");}}");
}
// position
writer.write(",position: {");
writer.write("at:'" + tooltip.getAtPosition() + "'");
writer.write(",my:'" + tooltip.getMyPosition() + "'");
writer.write(",adjust:{x:" + tooltip.getAdjustX() + ",y:" + tooltip.getAdjustY() + "}");
if (mouseTracking) {
writer.write(",target:'mouse'");
writer.write(",viewport:$(window)");
} else if (shared && !global) {
writer.write(",target:'event'");
writer.write(",effect:false");
}
writer.write("}},true);});");
endScript(writer);
}
| public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
Tooltip tooltip = (Tooltip) component;
String clientId = tooltip.getClientId(context);
boolean global = tooltip.isGlobal();
boolean shared = tooltip.isShared();
boolean autoShow = tooltip.isAutoShow();
boolean mouseTracking = tooltip.isMouseTracking();
String target = null;
if (!global || (tooltip.getFor() != null || tooltip.getForSelector() != null)) {
target = ComponentUtils.findTarget(context, tooltip);
}
startScript(writer, clientId);
writer.write("$(function() {");
writer.write("PrimeFacesExt.cw('Tooltip', '" + tooltip.resolveWidgetVar() + "',{");
writer.write("id:'" + clientId + "'");
writer.write(",global:" + global);
writer.write(",shared:" + shared);
writer.write(",autoShow:" + autoShow);
if (target == null) {
writer.write(",forTarget:null");
} else {
writer.write(",forTarget:'" + target + "'");
}
if (!global) {
writer.write(",content:\"");
if (tooltip.getChildCount() > 0) {
FastStringWriter fsw = new FastStringWriter();
ResponseWriter clonedWriter = writer.cloneWithWriter(fsw);
context.setResponseWriter(clonedWriter);
renderChildren(context, tooltip);
context.setResponseWriter(writer);
writer.write(escapeText(fsw.toString()));
} else {
String valueToRender = ComponentUtils.getValueToRender(context, tooltip);
if (valueToRender != null) {
writer.write(escapeText(valueToRender));
}
}
writer.write("\"");
}
// events
if (mouseTracking) {
writer.write(",hide:{fixed:true}");
} else if (shared && !global) {
writer.write(",show:{target:$('" + target + "')" + ",delay:" + tooltip.getShowDelay()
+ ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength()
+ ");}}");
writer.write(",hide:{target:$('" + target + "')" + ",delay:" + tooltip.getHideDelay()
+ ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength()
+ ");}}");
} else if (autoShow) {
writer.write(",show:{when:false,ready:true}");
writer.write(",hide:false");
} else {
writer.write(",show:{event:'" + tooltip.getShowEvent() + "',delay:" + tooltip.getShowDelay()
+ ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength()
+ ");}}");
writer.write(",hide:{event:'" + tooltip.getHideEvent() + "',delay:" + tooltip.getHideDelay()
+ ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength()
+ ");}}");
}
// position
writer.write(",position: {");
writer.write("at:'" + tooltip.getAtPosition() + "'");
writer.write(",my:'" + tooltip.getMyPosition() + "'");
writer.write(",adjust:{x:" + tooltip.getAdjustX() + ",y:" + tooltip.getAdjustY() + "}");
writer.write(",viewport:$(window)");
if (mouseTracking) {
writer.write(",target:'mouse'");
} else if (shared && !global) {
writer.write(",target:'event'");
writer.write(",effect:false");
}
writer.write("}},true);});");
endScript(writer);
}
|
diff --git a/src/com/android/browser/TitleBarBase.java b/src/com/android/browser/TitleBarBase.java
index ee4a2a68..7e8ea1ac 100644
--- a/src/com/android/browser/TitleBarBase.java
+++ b/src/com/android/browser/TitleBarBase.java
@@ -1,430 +1,432 @@
/*
* 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 com.android.browser.UI.DropdownChangeListener;
import com.android.browser.UrlInputView.UrlInputListener;
import com.android.browser.autocomplete.SuggestedTextController.TextChangeWatcher;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.speech.RecognizerResultsIntent;
import android.text.TextUtils;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.AbsoluteLayout;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.List;
/**
* Base class for a title bar used by the browser.
*/
public class TitleBarBase extends RelativeLayout
implements OnClickListener, OnFocusChangeListener, UrlInputListener,
TextChangeWatcher, DeviceAccountLogin.AutoLoginCallback {
protected static final int PROGRESS_MAX = 100;
// These need to be set by the subclass.
protected ImageView mFavicon;
protected ImageView mLockIcon;
protected Drawable mGenericFavicon;
protected UiController mUiController;
protected BaseUi mBaseUi;
protected UrlInputView mUrlInput;
protected boolean mInVoiceMode;
// Auto-login UI
protected View mAutoLogin;
protected Spinner mAutoLoginAccount;
protected Button mAutoLoginLogin;
protected ProgressBar mAutoLoginProgress;
protected TextView mAutoLoginError;
protected ImageButton mAutoLoginCancel;
protected DeviceAccountLogin mAutoLoginHandler;
protected ArrayAdapter<String> mAccountsAdapter;
public TitleBarBase(Context context, UiController controller, BaseUi ui) {
super(context, null);
mUiController = controller;
mBaseUi = ui;
mGenericFavicon = context.getResources().getDrawable(
R.drawable.app_web_browser_sm);
}
protected void initLayout(Context context, int layoutId) {
LayoutInflater factory = LayoutInflater.from(context);
factory.inflate(layoutId, this);
mUrlInput = (UrlInputView) findViewById(R.id.url);
mLockIcon = (ImageView) findViewById(R.id.lock);
mUrlInput.setUrlInputListener(this);
mUrlInput.setController(mUiController);
mUrlInput.setOnFocusChangeListener(this);
mUrlInput.setSelectAllOnFocus(true);
mUrlInput.addQueryTextWatcher(this);
mAutoLogin = findViewById(R.id.autologin);
mAutoLoginAccount = (Spinner) findViewById(R.id.autologin_account);
mAutoLoginLogin = (Button) findViewById(R.id.autologin_login);
mAutoLoginLogin.setOnClickListener(this);
mAutoLoginProgress = (ProgressBar) findViewById(R.id.autologin_progress);
mAutoLoginError = (TextView) findViewById(R.id.autologin_error);
mAutoLoginCancel = (ImageButton) mAutoLogin.findViewById(R.id.autologin_close);
mAutoLoginCancel.setOnClickListener(this);
}
protected void setupUrlInput() {
}
/* package */ void setProgress(int newProgress) {}
/* package */ void setLock(Drawable d) {
assert mLockIcon != null;
if (null == d) {
mLockIcon.setVisibility(View.GONE);
} else {
mLockIcon.setImageDrawable(d);
mLockIcon.setVisibility(View.VISIBLE);
}
}
/* package */ void setFavicon(Bitmap icon) {
assert mFavicon != null;
Drawable[] array = new Drawable[3];
array[0] = new PaintDrawable(Color.BLACK);
PaintDrawable p = new PaintDrawable(Color.WHITE);
array[1] = p;
if (icon == null) {
array[2] = mGenericFavicon;
} else {
array[2] = new BitmapDrawable(icon);
}
LayerDrawable d = new LayerDrawable(array);
d.setLayerInset(1, 1, 1, 1, 1);
d.setLayerInset(2, 2, 2, 2, 2);
mFavicon.setImageDrawable(d);
}
void setTitleGravity(int gravity) {
int newTop = 0;
if (gravity != Gravity.NO_GRAVITY) {
View parent = (View) getParent();
if (parent != null) {
if (gravity == Gravity.TOP) {
newTop = parent.getScrollY();
} else if (gravity == Gravity.BOTTOM) {
newTop = parent.getScrollY() + parent.getHeight() - getHeight();
}
}
}
AbsoluteLayout.LayoutParams lp = (AbsoluteLayout.LayoutParams) getLayoutParams();
if (lp != null) {
lp.y = newTop;
setLayoutParams(lp);
}
}
public int getEmbeddedHeight() {
return getHeight();
}
protected void updateAutoLogin(Tab tab, boolean animate) {
DeviceAccountLogin login = tab.getDeviceAccountLogin();
if (login != null) {
mAutoLoginHandler = login;
ContextThemeWrapper wrapper = new ContextThemeWrapper(mContext,
android.R.style.Theme_Holo_Light);
mAccountsAdapter = new ArrayAdapter<String>(wrapper,
android.R.layout.simple_spinner_item, login.getAccountNames());
mAccountsAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
mAutoLoginAccount.setAdapter(mAccountsAdapter);
mAutoLoginAccount.setSelection(0);
mAutoLoginAccount.setEnabled(true);
mAutoLoginLogin.setEnabled(true);
mAutoLoginProgress.setVisibility(View.GONE);
mAutoLoginError.setVisibility(View.GONE);
switch (login.getState()) {
case DeviceAccountLogin.PROCESSING:
mAutoLoginAccount.setEnabled(false);
mAutoLoginLogin.setEnabled(false);
mAutoLoginProgress.setVisibility(View.VISIBLE);
break;
case DeviceAccountLogin.FAILED:
mAutoLoginProgress.setVisibility(View.GONE);
mAutoLoginError.setVisibility(View.VISIBLE);
break;
case DeviceAccountLogin.INITIAL:
break;
default:
throw new IllegalStateException();
}
showAutoLogin(animate);
+ } else {
+ hideAutoLogin(animate);
}
}
protected void showAutoLogin(boolean animate) {
mAutoLogin.setVisibility(View.VISIBLE);
if (animate) {
mAutoLogin.startAnimation(AnimationUtils.loadAnimation(
getContext(), R.anim.autologin_enter));
}
}
protected void hideAutoLogin(boolean animate) {
mAutoLoginHandler = null;
if (animate) {
Animation anim = AnimationUtils.loadAnimation(
getContext(), R.anim.autologin_exit);
anim.setAnimationListener(new AnimationListener() {
@Override public void onAnimationEnd(Animation a) {
mAutoLogin.setVisibility(View.GONE);
mBaseUi.refreshWebView();
}
@Override public void onAnimationStart(Animation a) {}
@Override public void onAnimationRepeat(Animation a) {}
});
mAutoLogin.startAnimation(anim);
} else if (mAutoLogin.getAnimation() == null) {
mAutoLogin.setVisibility(View.GONE);
mBaseUi.refreshWebView();
}
}
@Override
public void loginFailed() {
mAutoLoginAccount.setEnabled(true);
mAutoLoginLogin.setEnabled(true);
mAutoLoginProgress.setVisibility(View.GONE);
mAutoLoginError.setVisibility(View.VISIBLE);
}
protected boolean inAutoLogin() {
return mAutoLoginHandler != null;
}
@Override
public void onClick(View v) {
if (mAutoLoginCancel == v) {
if (mAutoLoginHandler != null) {
mAutoLoginHandler.cancel();
mAutoLoginHandler = null;
}
hideAutoLogin(true);
} else if (mAutoLoginLogin == v) {
if (mAutoLoginHandler != null) {
mAutoLoginAccount.setEnabled(false);
mAutoLoginLogin.setEnabled(false);
mAutoLoginProgress.setVisibility(View.VISIBLE);
mAutoLoginError.setVisibility(View.GONE);
mAutoLoginHandler.login(
mAutoLoginAccount.getSelectedItemPosition(), this);
}
}
}
@Override
public void onFocusChange(View view, boolean hasFocus) {
// if losing focus and not in touch mode, leave as is
if (hasFocus || view.isInTouchMode() || mUrlInput.needsUpdate()) {
setFocusState(hasFocus);
}
if (hasFocus) {
mUrlInput.forceIme();
if (mInVoiceMode) {
mUrlInput.forceFilter();
}
} else if (!mUrlInput.needsUpdate()) {
mUrlInput.dismissDropDown();
mUrlInput.hideIME();
if (mUrlInput.getText().length() == 0) {
Tab currentTab = mUiController.getTabControl().getCurrentTab();
if (currentTab != null) {
mUrlInput.setText(currentTab.getUrl(), false);
}
}
}
mUrlInput.clearNeedsUpdate();
}
protected void setFocusState(boolean focus) {
if (focus) {
updateSearchMode(false);
}
}
protected void updateSearchMode(boolean userEdited) {
setSearchMode(!userEdited || TextUtils.isEmpty(mUrlInput.getUserText()));
}
protected void setSearchMode(boolean voiceSearchEnabled) {}
boolean isEditingUrl() {
return mUrlInput.hasFocus();
}
void stopEditingUrl() {
mUrlInput.clearFocus();
}
void setDisplayTitle(String title) {
if (!isEditingUrl()) {
mUrlInput.setText(title, false);
}
}
// UrlInput text watcher
@Override
public void onTextChanged(String newText) {
if (mUrlInput.hasFocus()) {
// check if input field is empty and adjust voice search state
updateSearchMode(true);
// clear voice mode when user types
setInVoiceMode(false, null);
}
}
// voicesearch
public void setInVoiceMode(boolean voicemode, List<String> voiceResults) {
mInVoiceMode = voicemode;
mUrlInput.setVoiceResults(voiceResults);
}
void setIncognitoMode(boolean incognito) {
mUrlInput.setIncognitoMode(incognito);
}
void clearCompletions() {
mUrlInput.setSuggestedText(null);
}
// UrlInputListener implementation
/**
* callback from suggestion dropdown
* user selected a suggestion
*/
@Override
public void onAction(String text, String extra, String source) {
mUiController.getCurrentTopWebView().requestFocus();
mBaseUi.hideTitleBar();
Intent i = new Intent();
String action = null;
if (UrlInputView.VOICE.equals(source)) {
action = RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS;
source = null;
} else {
action = Intent.ACTION_SEARCH;
}
i.setAction(action);
i.putExtra(SearchManager.QUERY, text);
if (extra != null) {
i.putExtra(SearchManager.EXTRA_DATA_KEY, extra);
}
if (source != null) {
Bundle appData = new Bundle();
appData.putString(com.android.common.Search.SOURCE, source);
i.putExtra(SearchManager.APP_DATA, appData);
}
mUiController.handleNewIntent(i);
setDisplayTitle(text);
}
@Override
public void onDismiss() {
final Tab currentTab = mBaseUi.getActiveTab();
mBaseUi.hideTitleBar();
post(new Runnable() {
public void run() {
clearFocus();
if ((currentTab != null) && !mInVoiceMode) {
setDisplayTitle(currentTab.getUrl());
}
}
});
}
/**
* callback from the suggestion dropdown
* copy text to input field and stay in edit mode
*/
@Override
public void onCopySuggestion(String text) {
mUrlInput.setText(text, true);
if (text != null) {
mUrlInput.setSelection(text.length());
}
}
public void setCurrentUrlIsBookmark(boolean isBookmark) {
}
@Override
public boolean dispatchKeyEventPreIme(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.KEYCODE_BACK) {
// catch back key in order to do slightly more cleanup than usual
mUrlInput.clearFocus();
return true;
}
return super.dispatchKeyEventPreIme(evt);
}
protected WebView getCurrentWebView() {
Tab t = mBaseUi.getActiveTab();
if (t != null) {
return t.getWebView();
} else {
return null;
}
}
void registerDropdownChangeListener(DropdownChangeListener d) {
mUrlInput.registerDropdownChangeListener(d);
}
}
| true | true | protected void updateAutoLogin(Tab tab, boolean animate) {
DeviceAccountLogin login = tab.getDeviceAccountLogin();
if (login != null) {
mAutoLoginHandler = login;
ContextThemeWrapper wrapper = new ContextThemeWrapper(mContext,
android.R.style.Theme_Holo_Light);
mAccountsAdapter = new ArrayAdapter<String>(wrapper,
android.R.layout.simple_spinner_item, login.getAccountNames());
mAccountsAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
mAutoLoginAccount.setAdapter(mAccountsAdapter);
mAutoLoginAccount.setSelection(0);
mAutoLoginAccount.setEnabled(true);
mAutoLoginLogin.setEnabled(true);
mAutoLoginProgress.setVisibility(View.GONE);
mAutoLoginError.setVisibility(View.GONE);
switch (login.getState()) {
case DeviceAccountLogin.PROCESSING:
mAutoLoginAccount.setEnabled(false);
mAutoLoginLogin.setEnabled(false);
mAutoLoginProgress.setVisibility(View.VISIBLE);
break;
case DeviceAccountLogin.FAILED:
mAutoLoginProgress.setVisibility(View.GONE);
mAutoLoginError.setVisibility(View.VISIBLE);
break;
case DeviceAccountLogin.INITIAL:
break;
default:
throw new IllegalStateException();
}
showAutoLogin(animate);
}
}
| protected void updateAutoLogin(Tab tab, boolean animate) {
DeviceAccountLogin login = tab.getDeviceAccountLogin();
if (login != null) {
mAutoLoginHandler = login;
ContextThemeWrapper wrapper = new ContextThemeWrapper(mContext,
android.R.style.Theme_Holo_Light);
mAccountsAdapter = new ArrayAdapter<String>(wrapper,
android.R.layout.simple_spinner_item, login.getAccountNames());
mAccountsAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
mAutoLoginAccount.setAdapter(mAccountsAdapter);
mAutoLoginAccount.setSelection(0);
mAutoLoginAccount.setEnabled(true);
mAutoLoginLogin.setEnabled(true);
mAutoLoginProgress.setVisibility(View.GONE);
mAutoLoginError.setVisibility(View.GONE);
switch (login.getState()) {
case DeviceAccountLogin.PROCESSING:
mAutoLoginAccount.setEnabled(false);
mAutoLoginLogin.setEnabled(false);
mAutoLoginProgress.setVisibility(View.VISIBLE);
break;
case DeviceAccountLogin.FAILED:
mAutoLoginProgress.setVisibility(View.GONE);
mAutoLoginError.setVisibility(View.VISIBLE);
break;
case DeviceAccountLogin.INITIAL:
break;
default:
throw new IllegalStateException();
}
showAutoLogin(animate);
} else {
hideAutoLogin(animate);
}
}
|
diff --git a/pluginsource/org/enigma/backend/EnigmaSettings.java b/pluginsource/org/enigma/backend/EnigmaSettings.java
index 6acf7a7a..07dd3a9b 100644
--- a/pluginsource/org/enigma/backend/EnigmaSettings.java
+++ b/pluginsource/org/enigma/backend/EnigmaSettings.java
@@ -1,278 +1,278 @@
/*
* Copyright (C) 2010 IsmAvatar <[email protected]>
*
* This file is part of Enigma Plugin.
* Enigma Plugin is free software and comes with ABSOLUTELY NO WARRANTY.
* See LICENSE for details.
*/
package org.enigma.backend;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import org.enigma.EYamlParser;
import org.enigma.EYamlParser.YamlNode;
import org.lateralgm.main.LGM;
public class EnigmaSettings
{
//Compatibility / Progess options
public int cppStrings = 0; // Defines what language strings are inherited from. 0 = GML, 1 = C
public int cppOperators = 0; // Defines what language operators ++ and -- are inherited from. 0 = GML, 1 = C
public int cppEquals = 0; // Defines whether = should be exclusively treated as a setter. 0 = GML (= or ==) 1 = C (= only)
public int literalHandling = 0; // Determines how literals are treated. 0 = enigma::variant, 1 = C-scalar
public int structHandling = 0; // Defines behavior of the closing brace of struct {}. 0 = Implied semicolon, 1 = ISO C
//Advanced options
public int instanceTypes = 0; // Defines how to represent instances. 0 = Integer, 1 = Pointer
public int storageClass = 0; // Determines how instances are stored in memory. 0 = Map, 1 = List, 2 = Array
public String definitions = "", globalLocals = "";
public String initialization = "", cleanup = "";
public TargetSelection targetPlatform, targetGraphics, targetAudio, targetCollision;
static final List<TargetSelection> tPlatforms, tGraphics, tAudios, tCollisions;
static
{
tPlatforms = findTargets("Platforms");
tGraphics = findTargets("Graphics_Systems");
tAudios = findTargets("Audio_Systems");
tCollisions = findTargets("Collision_Systems");
}
public static class TargetSelection
{
public String name, id; //mandatory
public Set<String> depends; //mandatory, non-empty
public String rep, desc, auth, ext; //optional
public String toString()
{
return name;
}
}
//target is one of ""Platforms","Audio_Systems","Graphics_Systems","Collision_Systems"
private static List<TargetSelection> findTargets(String target)
{
ArrayList<TargetSelection> targets = new ArrayList<TargetSelection>();
File f = new File(LGM.workDir.getParentFile(),"ENIGMAsystem");
f = new File(f,"SHELL");
f = new File(f,target);
File files[] = f.listFiles();
for (File dir : files)
{
if (!dir.isDirectory()) continue;
//technically this could stand to be a .properties file, rather than e-yaml
File prop = new File(dir,"About.ey");
try
{
Set<String> depends = new HashSet<String>();
YamlNode node;
if (!target.equals("Platforms"))
{
String[] configs = new File(dir,"Config").list();
if (configs == null) continue;
for (String conf : configs)
if (conf.endsWith(".ey")) depends.add(normalize(conf.substring(0,conf.length() - 3)));
if (depends.isEmpty()) continue;
node = EYamlParser.parse(new Scanner(prop));
}
else
{
node = EYamlParser.parse(new Scanner(prop));
String norm = normalize(node.getMC("Build-Platforms"));
if (norm.isEmpty()) continue;
for (String s : norm.split(","))
if (!s.isEmpty()) depends.add(s);
}
TargetSelection ps = new TargetSelection();
ps.name = node.getMC("Name");
- ps.id = node.getMC("Identifier");
+ ps.id = node.getMC("Identifier").toLowerCase();
ps.depends = depends;
ps.rep = node.getMC("Represents",null);
ps.desc = node.getMC("Description",null);
ps.auth = node.getMC("Author",null);
ps.ext = node.getMC("Build-Extension",null);
targets.add(ps);
}
catch (FileNotFoundException e)
{
//yaml file missing, skip to next file
}
catch (IndexOutOfBoundsException e)
{
//insufficient yaml, skip to next file
}
}
//if not empty, we may safely assume that the first one is the default selection,
//or technically, that any of them is the default. The user can/will change it in UI.
return targets;
}
//get rid of any "[]-_ " (and space), and convert to lowercase.
private static String normalize(String s)
{
return s.toLowerCase().replaceAll("[\\[\\]\\-\\s_]","");
}
public EnigmaSettings()
{
this(true);
}
private EnigmaSettings(boolean load)
{
if (!load) return;
loadDefinitions();
targetPlatform = findFirst(tPlatforms,getOS());
if (targetPlatform != null)
{
targetGraphics = findFirst(tGraphics,targetPlatform.id);
targetAudio = findFirst(tAudios,targetPlatform.id);
targetCollision = findFirst(tCollisions,targetPlatform.id);
}
}
private static String getOS()
{
String os = normalize(System.getProperty("os.name"));
if (os.contains("nux") || os.contains("nix")) return "linux";
if (os.contains("win")) return "windows";
if (os.contains("mac")) return "macosx";
return os;
}
private static TargetSelection findFirst(List<TargetSelection> tsl, String depends)
{
for (TargetSelection ts : tsl)
if (ts.depends.contains(depends)) return ts;
return null;
}
private List<TargetSelection> getTargetArray(List<TargetSelection> itsl)
{
List<TargetSelection> otsl = new ArrayList<TargetSelection>();
String depends;
if (itsl == tPlatforms)
depends = getOS();
else
{
if (targetPlatform == null) return otsl;
depends = targetPlatform.id;
}
for (TargetSelection ts : itsl)
if (ts.depends.contains(depends)) otsl.add(ts);
return otsl;
}
public Object[] getTargetPlatformsArray()
{
return getTargetArray(tPlatforms).toArray();
}
public Object[] getTargetGraphicsArray()
{
return getTargetArray(tGraphics).toArray();
}
public Object[] getTargetAudiosArray()
{
return getTargetArray(tAudios).toArray();
}
public Object[] getTargetCollisionsArray()
{
return getTargetArray(tCollisions).toArray();
}
void loadDefinitions()
{
definitions = fileToString(new File(LGM.workDir.getParentFile(),"definitions.h"));
}
public void saveDefinitions()
{
writeString(new File(LGM.workDir.getParentFile(),"definitions.h"),definitions);
}
String fileToString(File f)
{
StringBuffer sb = new StringBuffer(1024);
try
{
FileReader in = new FileReader(f);
char[] cbuf = new char[1024];
int size = 0;
while ((size = in.read(cbuf)) > -1)
sb.append(cbuf,0,size);
in.close();
}
catch (IOException e)
{
}
return sb.toString();
}
void writeString(File f, String s)
{
try
{
PrintStream ps = new PrintStream(f);
ps.print(s);
ps.close();
}
catch (FileNotFoundException e)
{
}
}
public String toTargetYaml()
{
return "%e-yaml\n---\n"//
+ "target-windowing: " + (targetPlatform == null ? "" : targetPlatform.id) + "\n"//
+ "target-graphics: " + (targetGraphics == null ? "" : targetGraphics.id) + "\n"//
+ "target-audio: " + (targetAudio == null ? "" : targetAudio.id) + "\n"//
+ "target-collision: " + (targetCollision == null ? "" : targetCollision.id) + "\n";//
}
public EnigmaSettings copy()
{
EnigmaSettings es = new EnigmaSettings(false);
es.cppStrings = cppStrings;
es.cppOperators = cppOperators;
es.literalHandling = literalHandling;
es.structHandling = structHandling;
es.instanceTypes = instanceTypes;
es.storageClass = storageClass;
es.definitions = definitions;
es.globalLocals = globalLocals;
es.initialization = initialization;
es.cleanup = cleanup;
es.targetPlatform = targetPlatform;
es.targetGraphics = targetGraphics;
es.targetAudio = targetAudio;
es.targetCollision = targetCollision;
return es;
}
}
| true | true | private static List<TargetSelection> findTargets(String target)
{
ArrayList<TargetSelection> targets = new ArrayList<TargetSelection>();
File f = new File(LGM.workDir.getParentFile(),"ENIGMAsystem");
f = new File(f,"SHELL");
f = new File(f,target);
File files[] = f.listFiles();
for (File dir : files)
{
if (!dir.isDirectory()) continue;
//technically this could stand to be a .properties file, rather than e-yaml
File prop = new File(dir,"About.ey");
try
{
Set<String> depends = new HashSet<String>();
YamlNode node;
if (!target.equals("Platforms"))
{
String[] configs = new File(dir,"Config").list();
if (configs == null) continue;
for (String conf : configs)
if (conf.endsWith(".ey")) depends.add(normalize(conf.substring(0,conf.length() - 3)));
if (depends.isEmpty()) continue;
node = EYamlParser.parse(new Scanner(prop));
}
else
{
node = EYamlParser.parse(new Scanner(prop));
String norm = normalize(node.getMC("Build-Platforms"));
if (norm.isEmpty()) continue;
for (String s : norm.split(","))
if (!s.isEmpty()) depends.add(s);
}
TargetSelection ps = new TargetSelection();
ps.name = node.getMC("Name");
ps.id = node.getMC("Identifier");
ps.depends = depends;
ps.rep = node.getMC("Represents",null);
ps.desc = node.getMC("Description",null);
ps.auth = node.getMC("Author",null);
ps.ext = node.getMC("Build-Extension",null);
targets.add(ps);
}
catch (FileNotFoundException e)
{
//yaml file missing, skip to next file
}
catch (IndexOutOfBoundsException e)
{
//insufficient yaml, skip to next file
}
}
//if not empty, we may safely assume that the first one is the default selection,
//or technically, that any of them is the default. The user can/will change it in UI.
return targets;
}
| private static List<TargetSelection> findTargets(String target)
{
ArrayList<TargetSelection> targets = new ArrayList<TargetSelection>();
File f = new File(LGM.workDir.getParentFile(),"ENIGMAsystem");
f = new File(f,"SHELL");
f = new File(f,target);
File files[] = f.listFiles();
for (File dir : files)
{
if (!dir.isDirectory()) continue;
//technically this could stand to be a .properties file, rather than e-yaml
File prop = new File(dir,"About.ey");
try
{
Set<String> depends = new HashSet<String>();
YamlNode node;
if (!target.equals("Platforms"))
{
String[] configs = new File(dir,"Config").list();
if (configs == null) continue;
for (String conf : configs)
if (conf.endsWith(".ey")) depends.add(normalize(conf.substring(0,conf.length() - 3)));
if (depends.isEmpty()) continue;
node = EYamlParser.parse(new Scanner(prop));
}
else
{
node = EYamlParser.parse(new Scanner(prop));
String norm = normalize(node.getMC("Build-Platforms"));
if (norm.isEmpty()) continue;
for (String s : norm.split(","))
if (!s.isEmpty()) depends.add(s);
}
TargetSelection ps = new TargetSelection();
ps.name = node.getMC("Name");
ps.id = node.getMC("Identifier").toLowerCase();
ps.depends = depends;
ps.rep = node.getMC("Represents",null);
ps.desc = node.getMC("Description",null);
ps.auth = node.getMC("Author",null);
ps.ext = node.getMC("Build-Extension",null);
targets.add(ps);
}
catch (FileNotFoundException e)
{
//yaml file missing, skip to next file
}
catch (IndexOutOfBoundsException e)
{
//insufficient yaml, skip to next file
}
}
//if not empty, we may safely assume that the first one is the default selection,
//or technically, that any of them is the default. The user can/will change it in UI.
return targets;
}
|
diff --git a/src/main/java/com/photon/phresco/util/PhrescoDynamicLoader.java b/src/main/java/com/photon/phresco/util/PhrescoDynamicLoader.java
index 2ca09d6..95be808 100644
--- a/src/main/java/com/photon/phresco/util/PhrescoDynamicLoader.java
+++ b/src/main/java/com/photon/phresco/util/PhrescoDynamicLoader.java
@@ -1,162 +1,165 @@
package com.photon.phresco.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.util.artifact.DefaultArtifact;
import org.xml.sax.SAXException;
import com.photon.phresco.api.ApplicationProcessor;
import com.photon.phresco.api.DynamicPageParameter;
import com.photon.phresco.api.DynamicParameter;
import com.photon.phresco.commons.model.ArtifactGroup;
import com.photon.phresco.commons.model.ArtifactInfo;
import com.photon.phresco.commons.model.RepoInfo;
import com.photon.phresco.exception.ConfigurationException;
import com.photon.phresco.exception.PhrescoException;
public class PhrescoDynamicLoader {
RepoInfo repoInfo;
List<ArtifactGroup> plugins;
public PhrescoDynamicLoader(RepoInfo repoInfo, List<ArtifactGroup> plugins) {
this.repoInfo = repoInfo;
this.plugins = plugins;
}
public DynamicParameter getDynamicParameter(String className) throws PhrescoException {
DynamicParameter dynamicParameter;
try {
Class<DynamicParameter> apiClass = (Class<DynamicParameter>) Class
.forName(className, true, getURLClassLoader());
dynamicParameter = (DynamicParameter) apiClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new PhrescoException(e);
}
return dynamicParameter;
}
public DynamicPageParameter getDynamicPageParameter(String className) throws PhrescoException {
DynamicPageParameter dynamicPageParameter;
try {
Class<DynamicPageParameter> apiClass = (Class<DynamicPageParameter>) Class
.forName(className, true, getURLClassLoader());
dynamicPageParameter = (DynamicPageParameter) apiClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new PhrescoException(e);
}
return dynamicPageParameter;
}
public ApplicationProcessor getApplicationProcessor(String className) throws PhrescoException {
ApplicationProcessor applicationProcessor = null;
try {
Class<ApplicationProcessor> apiClass = (Class<ApplicationProcessor>) Class
.forName(className, true, getURLClassLoader());
ApplicationProcessor newInstance = apiClass.newInstance();
applicationProcessor = (ApplicationProcessor) newInstance;
} catch (Exception e) {
e.printStackTrace();
throw new PhrescoException(e);
}
return applicationProcessor;
}
public InputStream getResourceAsStream(String fileName) throws PhrescoException {
List<Artifact> artifacts = new ArrayList<Artifact>();
+ Artifact foundArtifact = null;
String destFile = "";
JarFile jarfile = null;
for (ArtifactGroup plugin : plugins) {
List<ArtifactInfo> versions = plugin.getVersions();
for (ArtifactInfo artifactInfo : versions) {
- Artifact artifact = new DefaultArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar", artifactInfo.getVersion());
- artifacts.add(artifact);
+ foundArtifact = new DefaultArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar", artifactInfo.getVersion());
+ artifacts.add(foundArtifact);
}
}
try {
URL[] artifactURLs = MavenArtifactResolver.resolve(repoInfo.getGroupRepoURL(), repoInfo.getRepoUserName(),
repoInfo.getRepoPassword(), artifacts);
for (URL url : artifactURLs) {
File jarFile = new File(url.toURI());
- jarfile = new JarFile(jarFile);
- for (Enumeration<JarEntry> em = jarfile.entries(); em
- .hasMoreElements();) {
- JarEntry jarEntry = em.nextElement();
- if (jarEntry.getName().endsWith(fileName)) {
- destFile = jarEntry.getName();
- }
- }
+ if(jarFile.getName().equals(foundArtifact.getArtifactId() + "-" + foundArtifact.getVersion() + "." + foundArtifact.getExtension())) {
+ jarfile = new JarFile(jarFile);
+ for (Enumeration<JarEntry> em = jarfile.entries(); em
+ .hasMoreElements();) {
+ JarEntry jarEntry = em.nextElement();
+ if (jarEntry.getName().endsWith(fileName)) {
+ destFile = jarEntry.getName();
+ }
+ }
+ }
}
if(StringUtils.isNotEmpty(destFile)) {
ZipEntry entry = jarfile.getEntry(destFile);
return jarfile.getInputStream(entry);
}
} catch (Exception e) {
throw new PhrescoException(e);
}
return null;
}
private URLClassLoader getURLClassLoader() throws PhrescoException {
List<Artifact> artifacts = new ArrayList<Artifact>();
for (ArtifactGroup plugin : plugins) {
List<ArtifactInfo> versions = plugin.getVersions();
for (ArtifactInfo artifactInfo : versions) {
Artifact artifact = new DefaultArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar", artifactInfo.getVersion());
artifacts.add(artifact);
}
}
URL[] artifactURLs;
try {
artifactURLs = MavenArtifactResolver.resolve(repoInfo.getGroupRepoURL(), repoInfo.getRepoUserName(),
repoInfo.getRepoPassword(), artifacts);
} catch (Exception e) {
e.printStackTrace();
throw new PhrescoException(e);
}
ClassLoader clsLoader = Thread.currentThread().getContextClassLoader();
if (clsLoader == null) {
clsLoader = this.getClass().getClassLoader();
}
URLClassLoader classLoader = new URLClassLoader(artifactURLs, clsLoader);
return classLoader;
}
public static void main(String[] args) throws PhrescoException, IOException, ParserConfigurationException, SAXException, ConfigurationException {
RepoInfo repoinfo = new RepoInfo();
repoinfo.setRepoName("releases");
repoinfo.setRepoUserName("admin");
// repoinfo.setRepoPassword("ZGV2cmVwbzI=");
repoinfo.setRepoPassword("devrepo2");
repoinfo.setGroupRepoURL("http://172.16.17.226:8080/repository/content/groups/public/");
ArtifactGroup group = new ArtifactGroup();
group.setGroupId("com.photon.sample.appprocessor");
group.setArtifactId("testappprocessor");
group.setPackaging("jar");
ArtifactInfo info = new ArtifactInfo();
info.setVersion("1.0.0");
group.setVersions(Arrays.asList(info));
PhrescoDynamicLoader loader = new PhrescoDynamicLoader(repoinfo, Arrays.asList(group) );
ApplicationProcessor applicationProcessor = loader.getApplicationProcessor("com.photon.sample.appprocessor.testappprocessor.TestApplicationProcessor");
applicationProcessor.preCreate(null);
}
}
| false | true | public InputStream getResourceAsStream(String fileName) throws PhrescoException {
List<Artifact> artifacts = new ArrayList<Artifact>();
String destFile = "";
JarFile jarfile = null;
for (ArtifactGroup plugin : plugins) {
List<ArtifactInfo> versions = plugin.getVersions();
for (ArtifactInfo artifactInfo : versions) {
Artifact artifact = new DefaultArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar", artifactInfo.getVersion());
artifacts.add(artifact);
}
}
try {
URL[] artifactURLs = MavenArtifactResolver.resolve(repoInfo.getGroupRepoURL(), repoInfo.getRepoUserName(),
repoInfo.getRepoPassword(), artifacts);
for (URL url : artifactURLs) {
File jarFile = new File(url.toURI());
jarfile = new JarFile(jarFile);
for (Enumeration<JarEntry> em = jarfile.entries(); em
.hasMoreElements();) {
JarEntry jarEntry = em.nextElement();
if (jarEntry.getName().endsWith(fileName)) {
destFile = jarEntry.getName();
}
}
}
if(StringUtils.isNotEmpty(destFile)) {
ZipEntry entry = jarfile.getEntry(destFile);
return jarfile.getInputStream(entry);
}
} catch (Exception e) {
throw new PhrescoException(e);
}
return null;
}
| public InputStream getResourceAsStream(String fileName) throws PhrescoException {
List<Artifact> artifacts = new ArrayList<Artifact>();
Artifact foundArtifact = null;
String destFile = "";
JarFile jarfile = null;
for (ArtifactGroup plugin : plugins) {
List<ArtifactInfo> versions = plugin.getVersions();
for (ArtifactInfo artifactInfo : versions) {
foundArtifact = new DefaultArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar", artifactInfo.getVersion());
artifacts.add(foundArtifact);
}
}
try {
URL[] artifactURLs = MavenArtifactResolver.resolve(repoInfo.getGroupRepoURL(), repoInfo.getRepoUserName(),
repoInfo.getRepoPassword(), artifacts);
for (URL url : artifactURLs) {
File jarFile = new File(url.toURI());
if(jarFile.getName().equals(foundArtifact.getArtifactId() + "-" + foundArtifact.getVersion() + "." + foundArtifact.getExtension())) {
jarfile = new JarFile(jarFile);
for (Enumeration<JarEntry> em = jarfile.entries(); em
.hasMoreElements();) {
JarEntry jarEntry = em.nextElement();
if (jarEntry.getName().endsWith(fileName)) {
destFile = jarEntry.getName();
}
}
}
}
if(StringUtils.isNotEmpty(destFile)) {
ZipEntry entry = jarfile.getEntry(destFile);
return jarfile.getInputStream(entry);
}
} catch (Exception e) {
throw new PhrescoException(e);
}
return null;
}
|
diff --git a/TaskListRSF/tool/src/java/org/sakaiproject/tool/tasklist/rsf/TaskListProducer.java b/TaskListRSF/tool/src/java/org/sakaiproject/tool/tasklist/rsf/TaskListProducer.java
index 00e526b..35e28e3 100644
--- a/TaskListRSF/tool/src/java/org/sakaiproject/tool/tasklist/rsf/TaskListProducer.java
+++ b/TaskListRSF/tool/src/java/org/sakaiproject/tool/tasklist/rsf/TaskListProducer.java
@@ -1,139 +1,139 @@
/*
* Created on May 29, 2006
*/
package org.sakaiproject.tool.tasklist.rsf;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.tool.tasklist.api.Task;
import org.sakaiproject.tool.tasklist.api.TaskListManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.localeutil.LocaleGetter;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.DefaultView;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.stringutil.StringList;
public class TaskListProducer implements ViewComponentProducer,
NavigationCaseReporter, DefaultView {
public static final String VIEW_ID = "TaskList";
private UserDirectoryService userDirectoryService;
private TaskListManager taskListManager;
private ToolManager toolManager;
private MessageLocator messageLocator;
private LocaleGetter localegetter;
public String getViewID() {
return VIEW_ID;
}
public void setMessageLocator(MessageLocator messageLocator) {
this.messageLocator = messageLocator;
}
public void setUserDirectoryService(UserDirectoryService userDirectoryService) {
this.userDirectoryService = userDirectoryService;
}
public void setTaskListManager(TaskListManager taskListManager) {
this.taskListManager = taskListManager;
}
public void setToolManager(ToolManager toolManager) {
this.toolManager = toolManager;
}
public void setLocaleGetter(LocaleGetter localegetter) {
this.localegetter = localegetter;
}
public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
String username = userDirectoryService.getCurrentUser().getDisplayName();
UIOutput.make(tofill, "current-username", username);
// Illustrates fetching messages from locator - remaining messages are
// written out
// in template - localising HTML template directly is probably easier than
// localising properties files.
UIOutput.make(tofill, "task-list-title", messageLocator
.getMessage("task_list_title"));
User currentuser = userDirectoryService.getCurrentUser();
String currentuserid = currentuser.getEid();
UIForm newtask = UIForm.make(tofill, "new-task-form");
UIInput.make(newtask, "new-task-name", "#{taskListBean.newtask.task}");
UICommand.make(newtask, "submit-new-task",
"#{taskListBean.processActionAdd}");
// pre-bind the task's owner to avoid annoying the handler having to fetch
// it
newtask.parameters.add(new UIELBinding("#{taskListBean.newtask.owner}",
currentuserid));
String siteId = toolManager.getCurrentPlacement().getContext();
newtask.parameters.add(new UIELBinding("#{taskListBean.siteID}", siteId));
UIForm deleteform = UIForm.make(tofill, "delete-task-form");
// Create a multiple selection control for the tasks to be deleted.
// We will fill in the options at the loop end once we have collected them.
UISelect deleteselect = UISelect.makeMultiple(deleteform, "delete-select",
null, "#{taskListBean.deleteids}", new String[] {});
Map tasks = taskListManager.findAllTasks(siteId);
StringList deletable = new StringList();
// JSF DateTimeConverter is a fun piece of kit - now here's a good way to shed
// 600 lines:
// http://fisheye5.cenqua.com/viewrep/javaserverfaces-sources/jsf-api/src/javax/faces/convert/DateTimeConverter.java
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT, localegetter.get());
for (Iterator iter = tasks.values().iterator(); iter.hasNext();) {
Task task = (Task) iter.next();
boolean candelete = task.getOwner().equals(currentuserid);
UIBranchContainer taskrow = UIBranchContainer.make(deleteform,
candelete ? "task-row:deletable"
- : "task-row:nondeletable");
+ : "task-row:nondeletable", task.getId().toString());
if (candelete) {
UISelectChoice.make(taskrow, "task-select", deleteselect.getFullID(),
deletable.size());
deletable.add(task.getId().toString());
}
UIOutput.make(taskrow, "task-name", task.getTask());
UIOutput.make(taskrow, "task-owner", task.getOwner());
UIOutput.make(taskrow, "task-date", df.format(task.getCreationDate()));
}
deleteselect.optionlist.setValue(deletable.toStringArray());
deleteform.parameters.add(new UIELBinding("#{taskListBean.siteID}", siteId));
UICommand.make(deleteform, "delete-tasks",
"#{taskListBean.processActionDelete}");
}
public List reportNavigationCases() {
List togo = new ArrayList(); // Always navigate back to this view.
togo.add(new NavigationCase(null, new SimpleViewParameters(VIEW_ID)));
return togo;
}
}
| true | true | public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
String username = userDirectoryService.getCurrentUser().getDisplayName();
UIOutput.make(tofill, "current-username", username);
// Illustrates fetching messages from locator - remaining messages are
// written out
// in template - localising HTML template directly is probably easier than
// localising properties files.
UIOutput.make(tofill, "task-list-title", messageLocator
.getMessage("task_list_title"));
User currentuser = userDirectoryService.getCurrentUser();
String currentuserid = currentuser.getEid();
UIForm newtask = UIForm.make(tofill, "new-task-form");
UIInput.make(newtask, "new-task-name", "#{taskListBean.newtask.task}");
UICommand.make(newtask, "submit-new-task",
"#{taskListBean.processActionAdd}");
// pre-bind the task's owner to avoid annoying the handler having to fetch
// it
newtask.parameters.add(new UIELBinding("#{taskListBean.newtask.owner}",
currentuserid));
String siteId = toolManager.getCurrentPlacement().getContext();
newtask.parameters.add(new UIELBinding("#{taskListBean.siteID}", siteId));
UIForm deleteform = UIForm.make(tofill, "delete-task-form");
// Create a multiple selection control for the tasks to be deleted.
// We will fill in the options at the loop end once we have collected them.
UISelect deleteselect = UISelect.makeMultiple(deleteform, "delete-select",
null, "#{taskListBean.deleteids}", new String[] {});
Map tasks = taskListManager.findAllTasks(siteId);
StringList deletable = new StringList();
// JSF DateTimeConverter is a fun piece of kit - now here's a good way to shed
// 600 lines:
// http://fisheye5.cenqua.com/viewrep/javaserverfaces-sources/jsf-api/src/javax/faces/convert/DateTimeConverter.java
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT, localegetter.get());
for (Iterator iter = tasks.values().iterator(); iter.hasNext();) {
Task task = (Task) iter.next();
boolean candelete = task.getOwner().equals(currentuserid);
UIBranchContainer taskrow = UIBranchContainer.make(deleteform,
candelete ? "task-row:deletable"
: "task-row:nondeletable");
if (candelete) {
UISelectChoice.make(taskrow, "task-select", deleteselect.getFullID(),
deletable.size());
deletable.add(task.getId().toString());
}
UIOutput.make(taskrow, "task-name", task.getTask());
UIOutput.make(taskrow, "task-owner", task.getOwner());
UIOutput.make(taskrow, "task-date", df.format(task.getCreationDate()));
}
deleteselect.optionlist.setValue(deletable.toStringArray());
deleteform.parameters.add(new UIELBinding("#{taskListBean.siteID}", siteId));
UICommand.make(deleteform, "delete-tasks",
"#{taskListBean.processActionDelete}");
}
| public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
String username = userDirectoryService.getCurrentUser().getDisplayName();
UIOutput.make(tofill, "current-username", username);
// Illustrates fetching messages from locator - remaining messages are
// written out
// in template - localising HTML template directly is probably easier than
// localising properties files.
UIOutput.make(tofill, "task-list-title", messageLocator
.getMessage("task_list_title"));
User currentuser = userDirectoryService.getCurrentUser();
String currentuserid = currentuser.getEid();
UIForm newtask = UIForm.make(tofill, "new-task-form");
UIInput.make(newtask, "new-task-name", "#{taskListBean.newtask.task}");
UICommand.make(newtask, "submit-new-task",
"#{taskListBean.processActionAdd}");
// pre-bind the task's owner to avoid annoying the handler having to fetch
// it
newtask.parameters.add(new UIELBinding("#{taskListBean.newtask.owner}",
currentuserid));
String siteId = toolManager.getCurrentPlacement().getContext();
newtask.parameters.add(new UIELBinding("#{taskListBean.siteID}", siteId));
UIForm deleteform = UIForm.make(tofill, "delete-task-form");
// Create a multiple selection control for the tasks to be deleted.
// We will fill in the options at the loop end once we have collected them.
UISelect deleteselect = UISelect.makeMultiple(deleteform, "delete-select",
null, "#{taskListBean.deleteids}", new String[] {});
Map tasks = taskListManager.findAllTasks(siteId);
StringList deletable = new StringList();
// JSF DateTimeConverter is a fun piece of kit - now here's a good way to shed
// 600 lines:
// http://fisheye5.cenqua.com/viewrep/javaserverfaces-sources/jsf-api/src/javax/faces/convert/DateTimeConverter.java
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT, localegetter.get());
for (Iterator iter = tasks.values().iterator(); iter.hasNext();) {
Task task = (Task) iter.next();
boolean candelete = task.getOwner().equals(currentuserid);
UIBranchContainer taskrow = UIBranchContainer.make(deleteform,
candelete ? "task-row:deletable"
: "task-row:nondeletable", task.getId().toString());
if (candelete) {
UISelectChoice.make(taskrow, "task-select", deleteselect.getFullID(),
deletable.size());
deletable.add(task.getId().toString());
}
UIOutput.make(taskrow, "task-name", task.getTask());
UIOutput.make(taskrow, "task-owner", task.getOwner());
UIOutput.make(taskrow, "task-date", df.format(task.getCreationDate()));
}
deleteselect.optionlist.setValue(deletable.toStringArray());
deleteform.parameters.add(new UIELBinding("#{taskListBean.siteID}", siteId));
UICommand.make(deleteform, "delete-tasks",
"#{taskListBean.processActionDelete}");
}
|
diff --git a/src/database/SQLHelper.java b/src/database/SQLHelper.java
index b0268d3..2eefd68 100644
--- a/src/database/SQLHelper.java
+++ b/src/database/SQLHelper.java
@@ -1,125 +1,125 @@
package database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import logic.Debt;
/**
* A simple helper class to generate (and execute) SQL queries
*/
public class SQLHelper {
/**
* Generates a SQL query to check if a specified row exists in the given table, using a query on the form:
* SELECT EXISTS(SELECT 1 FROM <tableName> WHERE <fieldNameToCheck>=<fieldValueToCheck>
* @param tableName The table name
* @param fieldNameToCheck The field (or column) to check
* @param fieldValueToCheck The field (or column) value to check for
* @return The generated SQL query
*/
public static String existsQuery(String tableName, String fieldNameToCheck, String fieldValueToCheck) {
// TODO RUNAR fix injection!
return "SELECT * FROM " + tableName + " WHERE " + fieldNameToCheck + "=" + fieldValueToCheck;
// return "SELECT EXISTS(SELECT 1 FROM " + tableName + " WHERE " + fieldNameToCheck + "=" + fieldValueToCheck;
}
/**
* Executes a SQL query to check if a specified row exists in the given table, using a query on the form:
* SELECT EXISTS(SELECT 1 FROM <tableName> WHERE <fieldNameToCheck>=<fieldValueToCheck>
* @param con The connection to the server
* @param tableName The table name
* @param fieldNameToCheck The field (or column) to check
* @param fieldValueToCheck The field (or column) value to check for
* @throws SQLException
* @return True if the row exists, false if not
*/
public static boolean exists(Connection con, String tableName, String fieldNameToCheck, String fieldValueToCheck) throws SQLException {
return con.createStatement().executeQuery(existsQuery(tableName, fieldNameToCheck, fieldValueToCheck)).next();
}
/**
* Executes a SQL update with the given values
* @param con The connection to the database
* @param tableName The table to update
* @param fieldNamesToUpdate The fields (or columns) to update
* @param fieldValuesToUpdate The fields' (or columns') values to update to
* @param rowIdFieldName The field (or column) to use to id the correct row, null for all rows
* @param rowIdFieldValue The field's (or column's) value to check to id the correct row, null for all rows
* @throws SQLException
*/
public static void update(Connection con, String tableName, String[] fieldNamesToUpdate, String[] fieldValuesToUpdate, String rowIdFieldName, String rowIdFieldValue) throws SQLException {
if(fieldNamesToUpdate.length != fieldValuesToUpdate.length)
throw new IndexOutOfBoundsException("The lengths of the fieldNamesToUpdate and fieldValuesToUpdate must be equal.");
StringBuilder sb = new StringBuilder("UPDATE " + tableName + " SET ");
for (int i = 0; i < fieldValuesToUpdate.length; i++) {
sb.append(fieldNamesToUpdate[i] + "=" + '?' + (i < fieldValuesToUpdate.length - 1 ? ", " : ""));
}
// Add WHERE clause if specified
if(rowIdFieldName != null && rowIdFieldValue != null) {
sb.append(" WHERE " + rowIdFieldName + "=" + rowIdFieldValue);
}
System.out.println("Running query: " + sb.toString());
PreparedStatement prep = con.prepareStatement(sb.toString());
for(int i = 0; i < fieldValuesToUpdate.length; i++) {
- prep.setString(i, fieldValuesToUpdate[i]);
+ prep.setString(i + 1, fieldValuesToUpdate[i]);
}
prep.executeUpdate();
//st.executeUpdate(sb.toString());
}
/**
* Executes a SQL insert with the given values
* @param con The connection to the server
* @param tableName The name of the target table
* @param fieldNames The field names that shall be inserted
* @param fieldValues The field values that shall be inserted
* @throws SQLException
*/
public static void insert(Connection con, String tableName, String[] fieldNames, String[] fieldValues) throws SQLException {
if(fieldNames.length != fieldValues.length)
throw new IndexOutOfBoundsException("fieldNames and fieldValues must be of the same length.");
StringBuilder query = new StringBuilder("INSERT INTO " + tableName + " (");
StringBuilder values = new StringBuilder();
for (int i = 0; i < fieldValues.length; i++) {
query.append(fieldNames[i] + (i < fieldValues.length - 1 ? ", " : ") VALUES ("));
//values.append('"' + fieldValues[i] + '"' + (i < fieldValues.length - 1 ? ", " : ")"));
values.append("?"+(i < fieldValues.length - 1 ? ", " : ")"));
}
query.append(values);
System.out.println(query.toString());
PreparedStatement prep = con.prepareStatement(query.toString());
for(int i = 0; i < fieldValues.length; i++) {
prep.setString(i + 1, fieldValues[i]);
}
prep.executeUpdate();
}
/**
* Will check if the debt given as argument exists in the database, and will
* o update the debt if it already exists (as of now the only updateable field is the status)
* o insert the debt if it is not present in the database
* @param con The connection to the server
* @param d The debt to update/insert
* @return True if the debt was updated, false if it was inserted (created)
* @throws SQLException
*/
public static boolean updateDebt(Connection con, Debt d) throws SQLException {
// Check if the debt already exists
if(SQLHelper.exists(con, DatabaseUnit.TABLE_DEBT, DatabaseUnit.FIELD_DEBT_ID, d.getId() + "")) {
// Update the values that can change
// TODO: Anything else that can change than the status??
SQLHelper.update(con, DatabaseUnit.TABLE_DEBT, new String[]{DatabaseUnit.FIELD_DEBT_STATUS, DatabaseUnit.FIELD_DEBT_AMOUNT, DatabaseUnit.FIELD_DEBT_FROM_USER, DatabaseUnit.FIELD_DEBT_TO_USER},
new String[]{d.getStatus() + "", d.getAmount() + "", d.getFrom().getUsername(), d.getTo().getUsername()},
DatabaseUnit.FIELD_DEBT_ID, d.getId() + "");
return true;
} else {
// If not, create it
SQLHelper.insert(con, DatabaseUnit.TABLE_DEBT, new String[]{DatabaseUnit.FIELD_DEBT_ID, DatabaseUnit.FIELD_DEBT_AMOUNT, DatabaseUnit.FIELD_DEBT_WHAT, DatabaseUnit.FIELD_DEBT_TO_USER, DatabaseUnit.FIELD_DEBT_FROM_USER, DatabaseUnit.FIELD_DEBT_REQUESTED_BY_USER, DatabaseUnit.FIELD_DEBT_COMMENT, DatabaseUnit.FIELD_DEBT_STATUS},
new String[]{d.getId()+"", d.getAmount()+"", d.getWhat(), d.getTo().getUsername(), d.getFrom().getUsername(), d.getRequestedBy().getUsername(), d.getComment(), d.getStatus().toString()});
return false;
}
}
}
| true | true | public static void update(Connection con, String tableName, String[] fieldNamesToUpdate, String[] fieldValuesToUpdate, String rowIdFieldName, String rowIdFieldValue) throws SQLException {
if(fieldNamesToUpdate.length != fieldValuesToUpdate.length)
throw new IndexOutOfBoundsException("The lengths of the fieldNamesToUpdate and fieldValuesToUpdate must be equal.");
StringBuilder sb = new StringBuilder("UPDATE " + tableName + " SET ");
for (int i = 0; i < fieldValuesToUpdate.length; i++) {
sb.append(fieldNamesToUpdate[i] + "=" + '?' + (i < fieldValuesToUpdate.length - 1 ? ", " : ""));
}
// Add WHERE clause if specified
if(rowIdFieldName != null && rowIdFieldValue != null) {
sb.append(" WHERE " + rowIdFieldName + "=" + rowIdFieldValue);
}
System.out.println("Running query: " + sb.toString());
PreparedStatement prep = con.prepareStatement(sb.toString());
for(int i = 0; i < fieldValuesToUpdate.length; i++) {
prep.setString(i, fieldValuesToUpdate[i]);
}
prep.executeUpdate();
//st.executeUpdate(sb.toString());
}
| public static void update(Connection con, String tableName, String[] fieldNamesToUpdate, String[] fieldValuesToUpdate, String rowIdFieldName, String rowIdFieldValue) throws SQLException {
if(fieldNamesToUpdate.length != fieldValuesToUpdate.length)
throw new IndexOutOfBoundsException("The lengths of the fieldNamesToUpdate and fieldValuesToUpdate must be equal.");
StringBuilder sb = new StringBuilder("UPDATE " + tableName + " SET ");
for (int i = 0; i < fieldValuesToUpdate.length; i++) {
sb.append(fieldNamesToUpdate[i] + "=" + '?' + (i < fieldValuesToUpdate.length - 1 ? ", " : ""));
}
// Add WHERE clause if specified
if(rowIdFieldName != null && rowIdFieldValue != null) {
sb.append(" WHERE " + rowIdFieldName + "=" + rowIdFieldValue);
}
System.out.println("Running query: " + sb.toString());
PreparedStatement prep = con.prepareStatement(sb.toString());
for(int i = 0; i < fieldValuesToUpdate.length; i++) {
prep.setString(i + 1, fieldValuesToUpdate[i]);
}
prep.executeUpdate();
//st.executeUpdate(sb.toString());
}
|
diff --git a/iphone/test/java/org/openqa/selenium/iphone/IPhoneDriverTestSuite.java b/iphone/test/java/org/openqa/selenium/iphone/IPhoneDriverTestSuite.java
index 2ffb449d7..dc425eee9 100644
--- a/iphone/test/java/org/openqa/selenium/iphone/IPhoneDriverTestSuite.java
+++ b/iphone/test/java/org/openqa/selenium/iphone/IPhoneDriverTestSuite.java
@@ -1,56 +1,55 @@
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google 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 org.openqa.selenium.iphone;
import static org.openqa.selenium.Ignore.Driver.IPHONE;
import static org.openqa.selenium.Ignore.Driver.REMOTE;
import org.openqa.selenium.TestSuiteBuilder;
import org.openqa.selenium.internal.FileHandler;
import junit.framework.Test;
import junit.framework.TestCase;
import java.io.File;
public class IPhoneDriverTestSuite extends TestCase {
public static Test suite() throws Exception {
return new TestSuiteBuilder()
.addSourceDir("iphone")
- .addSourceDir("remote")
.addSourceDir("common")
.usingDriver(TestIPhoneSimulatorDriver.class)
.exclude(IPHONE)
.exclude(REMOTE)
.keepDriverInstance()
.includeJavascriptTests()
.create();
}
public static class TestIPhoneSimulatorDriver extends IPhoneSimulatorDriver {
public TestIPhoneSimulatorDriver() throws Exception {
super(locateSimulatorBinary());
}
private static IPhoneSimulatorBinary locateSimulatorBinary() throws Exception {
File iWebDriverApp = FileHandler.locateInProject(
"iphone/build/Release-iphonesimulator/iWebDriver.app/iWebDriver");
return new IPhoneSimulatorBinary(iWebDriverApp);
}
}
}
| true | true | public static Test suite() throws Exception {
return new TestSuiteBuilder()
.addSourceDir("iphone")
.addSourceDir("remote")
.addSourceDir("common")
.usingDriver(TestIPhoneSimulatorDriver.class)
.exclude(IPHONE)
.exclude(REMOTE)
.keepDriverInstance()
.includeJavascriptTests()
.create();
}
| public static Test suite() throws Exception {
return new TestSuiteBuilder()
.addSourceDir("iphone")
.addSourceDir("common")
.usingDriver(TestIPhoneSimulatorDriver.class)
.exclude(IPHONE)
.exclude(REMOTE)
.keepDriverInstance()
.includeJavascriptTests()
.create();
}
|
diff --git a/src/cc/osint/graphd/server/GraphCommandExecutor.java b/src/cc/osint/graphd/server/GraphCommandExecutor.java
index b140516..b3db9c2 100644
--- a/src/cc/osint/graphd/server/GraphCommandExecutor.java
+++ b/src/cc/osint/graphd/server/GraphCommandExecutor.java
@@ -1,620 +1,625 @@
package cc.osint.graphd.server;
import java.lang.*;
import java.lang.ref.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.*;
import org.jboss.netty.channel.Channel;
import cc.osint.graphd.graph.*;
public class GraphCommandExecutor implements Runnable {
private static final Logger log = Logger.getLogger(
GraphCommandExecutor.class.getName());
private String graphName;
private WeakReference<Graph> graphRef;
LinkedBlockingQueue<GraphCommand> graphCommandQueue;
public GraphCommandExecutor(String graphName,
WeakReference<Graph> graphRef) {
this.graphName = graphName;
this.graphRef = graphRef;
graphCommandQueue = new LinkedBlockingQueue<GraphCommand>();
log.info("start: GraphCommandExecutor(" + this.graphName + ")");
}
public void queue(GraphCommand cmd) throws Exception {
graphCommandQueue.put(cmd);
}
public void run() {
while (true) {
GraphCommand graphCommand = null;
String response;
try {
graphCommand = graphCommandQueue.take();
if (graphCommand.poisonPill) {
log.info(graphName + ": detected poison pill: terminator processor");
return;
}
long requestTimeStart = System.currentTimeMillis();
response =
execute(graphCommand.responseChannel,
graphCommand.clientId,
graphCommand.clientState,
graphCommand.request,
graphCommand.cmd,
graphCommand.args);
long requestTimeElapsed = System.currentTimeMillis() - requestTimeStart;
log.info("[" + requestTimeElapsed + "ms]");
} catch (Exception ex) {
ex.printStackTrace();
response = GraphServerProtocol.R_ERR + GraphServerProtocol.SPACE + ex.getMessage();
}
(graphCommand.responseChannel).write(response.trim() + GraphServerProtocol.NL);
}
}
protected String execute(Channel responseChannel,
String clientId,
ConcurrentHashMap<String, String> clientState,
String request,
String cmd,
String[] args) throws Exception {
StringBuffer rsb = new StringBuffer();
// all operations require a db to be selected (via GraphServerProtocol.CMD_USE)
if (null == clientState.get(GraphServerHandler.ST_DB)) {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" REQUIRE_USE_DB");
return rsb.toString();
}
Graph gr = graphRef.get();
if (null == gr) {
GraphCommand killCmd = new GraphCommand();
killCmd.poisonPill = true;
graphCommandQueue.clear();
graphCommandQueue.put(killCmd);
return GraphServerProtocol.R_ERR + GraphServerProtocol.SPACE + " GRAPH_NO_LONGER_EXISTS :queue cleared & poison pill sent";
}
/*
* handle dynamic <<query>> expansion, replacement & execution, e.g.
*
* [...] <<_type:v _key:m*>> [...]
*
* TODO: take the responseChannel direct-send hack out of this and think about
* how to either queue the commands (& add an "echo-batch-ok" or equiv to the tail to
* signify end of the batched command execution) or move this up to the thread loop?
*
*/
if (request.indexOf("<<") != -1 &&
request.indexOf(">>") != -1) {
String query = request.substring(request.indexOf("<<")+2,
request.indexOf(">>"));
String prefix = request.substring(0, request.indexOf("<<")).trim();
String suffix = request.substring(request.indexOf(">>")+2).trim();
log.info("executing selector: [" + prefix + "] " + query + " [" + suffix + "]:");
List<JSONObject> selectorResults = gr.queryGraphIndex(query);
for(JSONObject selectorResult: selectorResults) {
String batchRequestKey = selectorResult.getString(Graph.KEY_FIELD);
String batchRequest =
prefix + " " +
batchRequestKey + " " +
suffix;
String batchCmd;
String[] batchArgs;
if (batchRequest.indexOf(GraphServerProtocol.SPACE) != -1) {
batchCmd = batchRequest.substring(0,
batchRequest.indexOf(GraphServerProtocol.SPACE)).trim().toLowerCase();
batchArgs = batchRequest.substring(
batchRequest.indexOf(GraphServerProtocol.SPACE)).trim().split(GraphServerProtocol.SPACE);
} else {
batchCmd = batchRequest.trim().toLowerCase();
batchArgs = new String[0];
}
String batchCmdResponse =
execute(responseChannel,
clientId,
clientState,
batchRequest,
batchCmd,
batchArgs);
- responseChannel.write(batchCmdResponse.trim() + GraphServerProtocol.NL);
+ String responseParts[] = batchCmdResponse.split(GraphServerProtocol.NL);
+ for(String responsePart: responseParts) {
+ if (responsePart.charAt(0) != '-') {
+ responseChannel.write(responsePart.trim() + GraphServerProtocol.NL);
+ }
+ }
}
return GraphServerProtocol.R_BATCH_OK;
}
// CREATE VERTEX: cvert <key> <json>
if (cmd.equals(GraphServerProtocol.CMD_CVERT)) {
String key = args[0];
String json = request.substring(request.indexOf(GraphServerProtocol.SPACE + key) +
(key.length()+1)).trim(); // remainder of line
JSONObject jo = null;
try {
jo = new JSONObject(json);
gr.addVertex(key, jo);
rsb.append(GraphServerProtocol.R_OK);
} catch (org.json.JSONException jsonEx) {
jsonEx.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" BAD_JSON ");
rsb.append(jsonEx.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.SPACE);
rsb.append(ex.getMessage());
}
// CREATE EDGE: cedge <key> <vFromKey> <vToKey> <rel> <json>
// OR: cedge <key> <vFromKey> <vToKey> <rel> <weight> <json>
} else if (cmd.equals(GraphServerProtocol.CMD_CEDGE)) {
String key = args[0];
String vFromKey = args[1];
String vToKey = args[2];
String rel = args[3];
double weight = 1.0;
String json;
if (args[4].charAt(0) == '{') {
json = request.substring(request.indexOf(GraphServerProtocol.SPACE + rel) +
(rel.length()+1)).trim(); // remainder of line
} else {
weight = Double.parseDouble(args[4]);
json = request.substring(request.indexOf(GraphServerProtocol.SPACE + args[4]) +
(args[4].length()+1)).trim(); // remainder of line
}
JSONObject jo = null;
try {
jo = new JSONObject(json);
jo.put(Graph.EDGE_SOURCE_FIELD, vFromKey);
jo.put(Graph.EDGE_TARGET_FIELD, vToKey);
jo.put(Graph.WEIGHT_FIELD, weight);
jo.put(Graph.RELATION_FIELD, rel);
gr.addEdge(key, jo, vFromKey, vToKey, rel, weight);
rsb.append(GraphServerProtocol.R_OK);
} catch (org.json.JSONException jsonEx) {
jsonEx.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" BAD_JSON ");
rsb.append(jsonEx.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.SPACE);
rsb.append(ex.getMessage());
}
// DELETE OBJECT: del <key>
} else if (cmd.equals(GraphServerProtocol.CMD_DEL)) {
String key = args[0];
JSONObject obj = gr.get(key);
if (null == obj) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
String _type = obj.getString(Graph.TYPE_FIELD);
if (_type.equals(Graph.VERTEX_TYPE)) {
JSONVertex jv = gr.getVertex(key);
gr.removeVertex(jv);
rsb.append(GraphServerProtocol.R_OK);
} else if (_type.equals(Graph.EDGE_TYPE)) {
JSONEdge je = gr.getEdge(key);
gr.removeEdge(je);
rsb.append(GraphServerProtocol.R_OK);
} else {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.SPACE);
rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE);
}
}
// OBJECT EXISTS: exists <key>
} else if (cmd.equals(GraphServerProtocol.CMD_EXISTS)) {
String key = args[0];
rsb.append(gr.exists(key) + " " + key);
rsb.append(GraphServerProtocol.R_OK);
// GET OBJECT: get <key>
} else if (cmd.equals(GraphServerProtocol.CMD_GET)) {
String key = args[0];
JSONObject jo = gr.get(key);
if (jo == null) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append(prepareResult(jo));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// QUERY GRAPH OBJECTS: q <query>
} else if (cmd.equals(GraphServerProtocol.CMD_Q)) {
String q = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim(); // remainder of line past "q "
List<JSONObject> results = gr.queryGraphIndex(q);
JSONArray ja = new JSONArray();
for(JSONObject jo: results) {
ja.put(jo);
}
JSONObject res = new JSONObject();
res.put("results", ja);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// QUERY PROCESSES: qp <query>
} else if (cmd.equals(GraphServerProtocol.CMD_QP)) {
String q = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim(); // remainder of line past "qp "
List<JSONObject> results = gr.queryProcessIndex(q);
JSONArray ja = new JSONArray();
for(JSONObject jo: results) {
ja.put(jo);
}
JSONObject res = new JSONObject();
res.put("results", ja);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// DIJKSTRA SHORTEST PATH: spath <from> <to> <radius>
} else if (cmd.equals(GraphServerProtocol.CMD_SPATH)) {
String vFromKey = args[0];
String vToKey = args[1];
double radius = Double.POSITIVE_INFINITY;
if (args.length == 3) {
radius = Double.parseDouble(args[2]);
}
JSONObject result = gr.getShortestPath(vFromKey, vToKey, radius);
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(prepareResult(result));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// SET VERTEX/EDGE ATTRIBUTE: set <key> <attr> <value>
} else if (cmd.equals(GraphServerProtocol.CMD_SET)) {
String key = args[0];
String attr = args[1];
String val;
if (args.length == 2) {
// clear value
val = null;
} else {
val = request.substring(request.indexOf(GraphServerProtocol.SPACE + args[1]) +
(args[1].length()+1)).trim(); // remainder of line
}
if (attr.startsWith("_") &&
!attr.equals(Graph.WEIGHT_FIELD)) {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" CANNOT_SET_RESERVED_PROPERTY");
} else {
JSONObject obj = gr.get(key);
if (null == obj) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
String _type = obj.getString(Graph.TYPE_FIELD);
if (_type.equals(Graph.VERTEX_TYPE)) {
JSONVertex jv = gr.getVertex(key);
if (null != val) {
jv.put(attr, val);
} else {
jv.remove(attr);
}
gr.indexObject(key, _type, jv);
rsb.append(GraphServerProtocol.R_OK);
} else if (_type.equals(Graph.EDGE_TYPE)) {
JSONEdge je = gr.getEdge(key);
if (null != val) {
je.put(attr, val);
} else {
je.remove(attr);
}
if (attr.equals(Graph.WEIGHT_FIELD)) {
gr.setEdgeWeight(je, Double.parseDouble(val));
}
gr.indexObject(key, _type, je.asJSONObject().getJSONObject(Graph.DATA_FIELD));
rsb.append(GraphServerProtocol.R_OK);
} else {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE);
}
}
}
// INCREASE EDGE WEIGHT: incw <edge_key> <amount>
} else if (cmd.equals(GraphServerProtocol.CMD_INCW)) {
String key = args[0];
double w_amt = Double.parseDouble(args[1]);
JSONEdge je = gr.getEdge(key);
if (null == je) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
double weight = gr.getEdgeWeight(je);
weight += w_amt;
gr.setEdgeWeight(je, weight);
je.put(Graph.WEIGHT_FIELD, "" + weight);
gr.indexObject(key, Graph.EDGE_TYPE, je.asJSONObject().getJSONObject(Graph.DATA_FIELD));
rsb.append(GraphServerProtocol.R_OK);
}
// DUMP INTERNAL REPRESENTATION OF VERTEX/EDGE: spy <key>
} else if (cmd.equals(GraphServerProtocol.CMD_SPY)) {
String key = args[0];
JSONObject obj = gr.get(key);
if (null == obj) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
String _type = obj.getString(Graph.TYPE_FIELD);
if (_type.equals(Graph.EDGE_TYPE)) {
JSONEdge je = gr.getEdge(key);
if (null == je) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append(je.asClientJSONObject().toString(4) + GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (_type.equals(Graph.VERTEX_TYPE)) {
JSONVertex jv = gr.getVertex(key);
if (null == jv) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append(jv.toString(4) + GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE);
}
}
// K-SHORTEST-PATHS: kspath <from> <to> <k> <optional:maxHops>
} else if (cmd.equals(GraphServerProtocol.CMD_KSPATH)) {
String vFromKey = args[0];
String vToKey = args[1];
int k = Integer.parseInt(args[2]);
int maxHops = 0;
if (args.length > 3) {
maxHops = Integer.parseInt(args[3]);
}
JSONObject result = gr.getKShortestPaths(vFromKey, vToKey, k, maxHops);
rsb.append(prepareResult(result));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// HAMILTONIAN CYCLE: hc
} else if (cmd.equals(GraphServerProtocol.CMD_HC)) {
List<JSONVertex> results = gr.getHamiltonianCycle();
if (null == results) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
JSONObject res = new JSONObject();
JSONArray cycle = new JSONArray();
for(JSONVertex jo: results) {
cycle.put(jo);
}
res.put("cycle", cycle);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// EULERIAN CIRCUIT: ec
} else if (cmd.equals(GraphServerProtocol.CMD_EC)) {
List<JSONVertex> results = gr.getEulerianCircuit();
if (null == results) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
JSONObject res = new JSONObject();
JSONArray circuit = new JSONArray();
for(JSONVertex jo: results) {
circuit.put(jo);
}
res.put("circuit", circuit);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// EDWARDS KARP MAXIMUM FLOW: ekmf <from> <to>
} else if (cmd.equals(GraphServerProtocol.CMD_EKMF)) {
String vSourceKey = args[0];
String vSinkKey = args[1];
JSONObject flowResult = gr.getEKMF(vSourceKey, vSinkKey);
if (null == flowResult) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(flowResult.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// CHROMATIC NUMBER: cn
} else if (cmd.equals(GraphServerProtocol.CMD_CN)) {
JSONObject result = new JSONObject();
result.put("chromatic_number", gr.getChromaticNumber());
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// KRUSKAL'S MINIMUM SPANNING TREE: kmst
} else if (cmd.equals(GraphServerProtocol.CMD_KMST)) {
JSONObject result = gr.getKMST();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// VERTEX COVER: GREEDY: vcg
} else if (cmd.equals(GraphServerProtocol.CMD_VCG)) {
JSONObject result = gr.getGreedyVertexCover();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// VERTEX COVER: 2-APPROXIMATION: vc2a
} else if (cmd.equals(GraphServerProtocol.CMD_VC2A)) {
JSONObject result = gr.get2ApproximationVertexCover();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// MAXIMALLY CONNECTED SET BY VERTEX: csetv <key>
} else if (cmd.equals(GraphServerProtocol.CMD_CSETV)) {
String key = args[0];
JSONVertex v = gr.getVertex(key);
if (null == v) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
JSONObject result = gr.getConnectedSetByVertex(v);
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// ALL MAXIMALLY CONNECTED SETS: csets
} else if (cmd.equals(GraphServerProtocol.CMD_CSETS)) {
JSONObject result = gr.getConnectedSets();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// CONNECTEDNESS TEST: iscon
} else if (cmd.equals(GraphServerProtocol.CMD_ISCON)) {
rsb.append("" + gr.isConnected());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// UNDIRECTED PATH EXISTENCE TEST: upathex <from> <to>
} else if (cmd.equals(GraphServerProtocol.CMD_UPATHEX)) {
JSONVertex vFrom = gr.getVertex(args[0]);
JSONVertex vTo = gr.getVertex(args[1]);
if (null == vFrom ||
null == vTo) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append("" + gr.pathExists(vFrom, vTo));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// FIND ALL MAXIMAL CLIQUES: Bron Kerosch Clique Finder
} else if (cmd.equals(GraphServerProtocol.CMD_FAMC)) {
JSONObject result = gr.getAllMaximalCliques();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// FIND BIGGEST MAXIMAL CLIQUES: Bron Kerosch Clique Finder
} else if (cmd.equals(GraphServerProtocol.CMD_FBMC)) {
JSONObject result = gr.getBiggestMaximalCliques();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (cmd.equals(GraphServerProtocol.CMD_ASPV)) {
JSONObject result = gr.getAllShortestPathsFrom(
gr.getVertex(args[0]));
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (cmd.equals(GraphServerProtocol.CMD_GCYC)) {
JSONObject result = gr.getGraphCycles();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (cmd.equals(GraphServerProtocol.CMD_VCYC)) {
JSONObject result = gr.getGraphCyclesContainingVertex(
gr.getVertex(args[0]));
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
/*
* SIMULATION
*/
// EMIT A MESSAGE TO A RUNNING SIMULATION PROCESS: emit <key> <process_name> <json_msg>
} else if (cmd.equals(GraphServerProtocol.CMD_EMIT)) {
String key = args[0];
String processName = args[1];
String json = request.substring(request.indexOf(GraphServerProtocol.SPACE + processName) +
(processName.length()+1)).trim(); // remainder of line
JSONObject jo = null;
jo = new JSONObject(json);
gr.emit(key, processName, jo);
rsb.append(GraphServerProtocol.R_OK);
}
// EVENT-SUBSCRIPTION MANAGEMENT
// JAVASCRIPT "POINT-OF-VIEW" TRAVERSAL
return rsb.toString();
}
/* utility methods */
private String prepareResult(JSONObject jo) throws Exception {
//String s = jo.toString();
//s = s.replaceAll(GraphServerProtocol.NL, GraphServerProtocol.SPACE);
//return s;
return jo.toString();
}
}
| true | true | protected String execute(Channel responseChannel,
String clientId,
ConcurrentHashMap<String, String> clientState,
String request,
String cmd,
String[] args) throws Exception {
StringBuffer rsb = new StringBuffer();
// all operations require a db to be selected (via GraphServerProtocol.CMD_USE)
if (null == clientState.get(GraphServerHandler.ST_DB)) {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" REQUIRE_USE_DB");
return rsb.toString();
}
Graph gr = graphRef.get();
if (null == gr) {
GraphCommand killCmd = new GraphCommand();
killCmd.poisonPill = true;
graphCommandQueue.clear();
graphCommandQueue.put(killCmd);
return GraphServerProtocol.R_ERR + GraphServerProtocol.SPACE + " GRAPH_NO_LONGER_EXISTS :queue cleared & poison pill sent";
}
/*
* handle dynamic <<query>> expansion, replacement & execution, e.g.
*
* [...] <<_type:v _key:m*>> [...]
*
* TODO: take the responseChannel direct-send hack out of this and think about
* how to either queue the commands (& add an "echo-batch-ok" or equiv to the tail to
* signify end of the batched command execution) or move this up to the thread loop?
*
*/
if (request.indexOf("<<") != -1 &&
request.indexOf(">>") != -1) {
String query = request.substring(request.indexOf("<<")+2,
request.indexOf(">>"));
String prefix = request.substring(0, request.indexOf("<<")).trim();
String suffix = request.substring(request.indexOf(">>")+2).trim();
log.info("executing selector: [" + prefix + "] " + query + " [" + suffix + "]:");
List<JSONObject> selectorResults = gr.queryGraphIndex(query);
for(JSONObject selectorResult: selectorResults) {
String batchRequestKey = selectorResult.getString(Graph.KEY_FIELD);
String batchRequest =
prefix + " " +
batchRequestKey + " " +
suffix;
String batchCmd;
String[] batchArgs;
if (batchRequest.indexOf(GraphServerProtocol.SPACE) != -1) {
batchCmd = batchRequest.substring(0,
batchRequest.indexOf(GraphServerProtocol.SPACE)).trim().toLowerCase();
batchArgs = batchRequest.substring(
batchRequest.indexOf(GraphServerProtocol.SPACE)).trim().split(GraphServerProtocol.SPACE);
} else {
batchCmd = batchRequest.trim().toLowerCase();
batchArgs = new String[0];
}
String batchCmdResponse =
execute(responseChannel,
clientId,
clientState,
batchRequest,
batchCmd,
batchArgs);
responseChannel.write(batchCmdResponse.trim() + GraphServerProtocol.NL);
}
return GraphServerProtocol.R_BATCH_OK;
}
// CREATE VERTEX: cvert <key> <json>
if (cmd.equals(GraphServerProtocol.CMD_CVERT)) {
String key = args[0];
String json = request.substring(request.indexOf(GraphServerProtocol.SPACE + key) +
(key.length()+1)).trim(); // remainder of line
JSONObject jo = null;
try {
jo = new JSONObject(json);
gr.addVertex(key, jo);
rsb.append(GraphServerProtocol.R_OK);
} catch (org.json.JSONException jsonEx) {
jsonEx.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" BAD_JSON ");
rsb.append(jsonEx.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.SPACE);
rsb.append(ex.getMessage());
}
// CREATE EDGE: cedge <key> <vFromKey> <vToKey> <rel> <json>
// OR: cedge <key> <vFromKey> <vToKey> <rel> <weight> <json>
} else if (cmd.equals(GraphServerProtocol.CMD_CEDGE)) {
String key = args[0];
String vFromKey = args[1];
String vToKey = args[2];
String rel = args[3];
double weight = 1.0;
String json;
if (args[4].charAt(0) == '{') {
json = request.substring(request.indexOf(GraphServerProtocol.SPACE + rel) +
(rel.length()+1)).trim(); // remainder of line
} else {
weight = Double.parseDouble(args[4]);
json = request.substring(request.indexOf(GraphServerProtocol.SPACE + args[4]) +
(args[4].length()+1)).trim(); // remainder of line
}
JSONObject jo = null;
try {
jo = new JSONObject(json);
jo.put(Graph.EDGE_SOURCE_FIELD, vFromKey);
jo.put(Graph.EDGE_TARGET_FIELD, vToKey);
jo.put(Graph.WEIGHT_FIELD, weight);
jo.put(Graph.RELATION_FIELD, rel);
gr.addEdge(key, jo, vFromKey, vToKey, rel, weight);
rsb.append(GraphServerProtocol.R_OK);
} catch (org.json.JSONException jsonEx) {
jsonEx.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" BAD_JSON ");
rsb.append(jsonEx.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.SPACE);
rsb.append(ex.getMessage());
}
// DELETE OBJECT: del <key>
} else if (cmd.equals(GraphServerProtocol.CMD_DEL)) {
String key = args[0];
JSONObject obj = gr.get(key);
if (null == obj) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
String _type = obj.getString(Graph.TYPE_FIELD);
if (_type.equals(Graph.VERTEX_TYPE)) {
JSONVertex jv = gr.getVertex(key);
gr.removeVertex(jv);
rsb.append(GraphServerProtocol.R_OK);
} else if (_type.equals(Graph.EDGE_TYPE)) {
JSONEdge je = gr.getEdge(key);
gr.removeEdge(je);
rsb.append(GraphServerProtocol.R_OK);
} else {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.SPACE);
rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE);
}
}
// OBJECT EXISTS: exists <key>
} else if (cmd.equals(GraphServerProtocol.CMD_EXISTS)) {
String key = args[0];
rsb.append(gr.exists(key) + " " + key);
rsb.append(GraphServerProtocol.R_OK);
// GET OBJECT: get <key>
} else if (cmd.equals(GraphServerProtocol.CMD_GET)) {
String key = args[0];
JSONObject jo = gr.get(key);
if (jo == null) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append(prepareResult(jo));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// QUERY GRAPH OBJECTS: q <query>
} else if (cmd.equals(GraphServerProtocol.CMD_Q)) {
String q = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim(); // remainder of line past "q "
List<JSONObject> results = gr.queryGraphIndex(q);
JSONArray ja = new JSONArray();
for(JSONObject jo: results) {
ja.put(jo);
}
JSONObject res = new JSONObject();
res.put("results", ja);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// QUERY PROCESSES: qp <query>
} else if (cmd.equals(GraphServerProtocol.CMD_QP)) {
String q = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim(); // remainder of line past "qp "
List<JSONObject> results = gr.queryProcessIndex(q);
JSONArray ja = new JSONArray();
for(JSONObject jo: results) {
ja.put(jo);
}
JSONObject res = new JSONObject();
res.put("results", ja);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// DIJKSTRA SHORTEST PATH: spath <from> <to> <radius>
} else if (cmd.equals(GraphServerProtocol.CMD_SPATH)) {
String vFromKey = args[0];
String vToKey = args[1];
double radius = Double.POSITIVE_INFINITY;
if (args.length == 3) {
radius = Double.parseDouble(args[2]);
}
JSONObject result = gr.getShortestPath(vFromKey, vToKey, radius);
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(prepareResult(result));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// SET VERTEX/EDGE ATTRIBUTE: set <key> <attr> <value>
} else if (cmd.equals(GraphServerProtocol.CMD_SET)) {
String key = args[0];
String attr = args[1];
String val;
if (args.length == 2) {
// clear value
val = null;
} else {
val = request.substring(request.indexOf(GraphServerProtocol.SPACE + args[1]) +
(args[1].length()+1)).trim(); // remainder of line
}
if (attr.startsWith("_") &&
!attr.equals(Graph.WEIGHT_FIELD)) {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" CANNOT_SET_RESERVED_PROPERTY");
} else {
JSONObject obj = gr.get(key);
if (null == obj) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
String _type = obj.getString(Graph.TYPE_FIELD);
if (_type.equals(Graph.VERTEX_TYPE)) {
JSONVertex jv = gr.getVertex(key);
if (null != val) {
jv.put(attr, val);
} else {
jv.remove(attr);
}
gr.indexObject(key, _type, jv);
rsb.append(GraphServerProtocol.R_OK);
} else if (_type.equals(Graph.EDGE_TYPE)) {
JSONEdge je = gr.getEdge(key);
if (null != val) {
je.put(attr, val);
} else {
je.remove(attr);
}
if (attr.equals(Graph.WEIGHT_FIELD)) {
gr.setEdgeWeight(je, Double.parseDouble(val));
}
gr.indexObject(key, _type, je.asJSONObject().getJSONObject(Graph.DATA_FIELD));
rsb.append(GraphServerProtocol.R_OK);
} else {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE);
}
}
}
// INCREASE EDGE WEIGHT: incw <edge_key> <amount>
} else if (cmd.equals(GraphServerProtocol.CMD_INCW)) {
String key = args[0];
double w_amt = Double.parseDouble(args[1]);
JSONEdge je = gr.getEdge(key);
if (null == je) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
double weight = gr.getEdgeWeight(je);
weight += w_amt;
gr.setEdgeWeight(je, weight);
je.put(Graph.WEIGHT_FIELD, "" + weight);
gr.indexObject(key, Graph.EDGE_TYPE, je.asJSONObject().getJSONObject(Graph.DATA_FIELD));
rsb.append(GraphServerProtocol.R_OK);
}
// DUMP INTERNAL REPRESENTATION OF VERTEX/EDGE: spy <key>
} else if (cmd.equals(GraphServerProtocol.CMD_SPY)) {
String key = args[0];
JSONObject obj = gr.get(key);
if (null == obj) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
String _type = obj.getString(Graph.TYPE_FIELD);
if (_type.equals(Graph.EDGE_TYPE)) {
JSONEdge je = gr.getEdge(key);
if (null == je) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append(je.asClientJSONObject().toString(4) + GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (_type.equals(Graph.VERTEX_TYPE)) {
JSONVertex jv = gr.getVertex(key);
if (null == jv) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append(jv.toString(4) + GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE);
}
}
// K-SHORTEST-PATHS: kspath <from> <to> <k> <optional:maxHops>
} else if (cmd.equals(GraphServerProtocol.CMD_KSPATH)) {
String vFromKey = args[0];
String vToKey = args[1];
int k = Integer.parseInt(args[2]);
int maxHops = 0;
if (args.length > 3) {
maxHops = Integer.parseInt(args[3]);
}
JSONObject result = gr.getKShortestPaths(vFromKey, vToKey, k, maxHops);
rsb.append(prepareResult(result));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// HAMILTONIAN CYCLE: hc
} else if (cmd.equals(GraphServerProtocol.CMD_HC)) {
List<JSONVertex> results = gr.getHamiltonianCycle();
if (null == results) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
JSONObject res = new JSONObject();
JSONArray cycle = new JSONArray();
for(JSONVertex jo: results) {
cycle.put(jo);
}
res.put("cycle", cycle);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// EULERIAN CIRCUIT: ec
} else if (cmd.equals(GraphServerProtocol.CMD_EC)) {
List<JSONVertex> results = gr.getEulerianCircuit();
if (null == results) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
JSONObject res = new JSONObject();
JSONArray circuit = new JSONArray();
for(JSONVertex jo: results) {
circuit.put(jo);
}
res.put("circuit", circuit);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// EDWARDS KARP MAXIMUM FLOW: ekmf <from> <to>
} else if (cmd.equals(GraphServerProtocol.CMD_EKMF)) {
String vSourceKey = args[0];
String vSinkKey = args[1];
JSONObject flowResult = gr.getEKMF(vSourceKey, vSinkKey);
if (null == flowResult) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(flowResult.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// CHROMATIC NUMBER: cn
} else if (cmd.equals(GraphServerProtocol.CMD_CN)) {
JSONObject result = new JSONObject();
result.put("chromatic_number", gr.getChromaticNumber());
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// KRUSKAL'S MINIMUM SPANNING TREE: kmst
} else if (cmd.equals(GraphServerProtocol.CMD_KMST)) {
JSONObject result = gr.getKMST();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// VERTEX COVER: GREEDY: vcg
} else if (cmd.equals(GraphServerProtocol.CMD_VCG)) {
JSONObject result = gr.getGreedyVertexCover();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// VERTEX COVER: 2-APPROXIMATION: vc2a
} else if (cmd.equals(GraphServerProtocol.CMD_VC2A)) {
JSONObject result = gr.get2ApproximationVertexCover();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// MAXIMALLY CONNECTED SET BY VERTEX: csetv <key>
} else if (cmd.equals(GraphServerProtocol.CMD_CSETV)) {
String key = args[0];
JSONVertex v = gr.getVertex(key);
if (null == v) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
JSONObject result = gr.getConnectedSetByVertex(v);
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// ALL MAXIMALLY CONNECTED SETS: csets
} else if (cmd.equals(GraphServerProtocol.CMD_CSETS)) {
JSONObject result = gr.getConnectedSets();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// CONNECTEDNESS TEST: iscon
} else if (cmd.equals(GraphServerProtocol.CMD_ISCON)) {
rsb.append("" + gr.isConnected());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// UNDIRECTED PATH EXISTENCE TEST: upathex <from> <to>
} else if (cmd.equals(GraphServerProtocol.CMD_UPATHEX)) {
JSONVertex vFrom = gr.getVertex(args[0]);
JSONVertex vTo = gr.getVertex(args[1]);
if (null == vFrom ||
null == vTo) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append("" + gr.pathExists(vFrom, vTo));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// FIND ALL MAXIMAL CLIQUES: Bron Kerosch Clique Finder
} else if (cmd.equals(GraphServerProtocol.CMD_FAMC)) {
JSONObject result = gr.getAllMaximalCliques();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// FIND BIGGEST MAXIMAL CLIQUES: Bron Kerosch Clique Finder
} else if (cmd.equals(GraphServerProtocol.CMD_FBMC)) {
JSONObject result = gr.getBiggestMaximalCliques();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (cmd.equals(GraphServerProtocol.CMD_ASPV)) {
JSONObject result = gr.getAllShortestPathsFrom(
gr.getVertex(args[0]));
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (cmd.equals(GraphServerProtocol.CMD_GCYC)) {
JSONObject result = gr.getGraphCycles();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (cmd.equals(GraphServerProtocol.CMD_VCYC)) {
JSONObject result = gr.getGraphCyclesContainingVertex(
gr.getVertex(args[0]));
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
/*
* SIMULATION
*/
// EMIT A MESSAGE TO A RUNNING SIMULATION PROCESS: emit <key> <process_name> <json_msg>
} else if (cmd.equals(GraphServerProtocol.CMD_EMIT)) {
String key = args[0];
String processName = args[1];
String json = request.substring(request.indexOf(GraphServerProtocol.SPACE + processName) +
(processName.length()+1)).trim(); // remainder of line
JSONObject jo = null;
jo = new JSONObject(json);
gr.emit(key, processName, jo);
rsb.append(GraphServerProtocol.R_OK);
}
// EVENT-SUBSCRIPTION MANAGEMENT
// JAVASCRIPT "POINT-OF-VIEW" TRAVERSAL
return rsb.toString();
}
| protected String execute(Channel responseChannel,
String clientId,
ConcurrentHashMap<String, String> clientState,
String request,
String cmd,
String[] args) throws Exception {
StringBuffer rsb = new StringBuffer();
// all operations require a db to be selected (via GraphServerProtocol.CMD_USE)
if (null == clientState.get(GraphServerHandler.ST_DB)) {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" REQUIRE_USE_DB");
return rsb.toString();
}
Graph gr = graphRef.get();
if (null == gr) {
GraphCommand killCmd = new GraphCommand();
killCmd.poisonPill = true;
graphCommandQueue.clear();
graphCommandQueue.put(killCmd);
return GraphServerProtocol.R_ERR + GraphServerProtocol.SPACE + " GRAPH_NO_LONGER_EXISTS :queue cleared & poison pill sent";
}
/*
* handle dynamic <<query>> expansion, replacement & execution, e.g.
*
* [...] <<_type:v _key:m*>> [...]
*
* TODO: take the responseChannel direct-send hack out of this and think about
* how to either queue the commands (& add an "echo-batch-ok" or equiv to the tail to
* signify end of the batched command execution) or move this up to the thread loop?
*
*/
if (request.indexOf("<<") != -1 &&
request.indexOf(">>") != -1) {
String query = request.substring(request.indexOf("<<")+2,
request.indexOf(">>"));
String prefix = request.substring(0, request.indexOf("<<")).trim();
String suffix = request.substring(request.indexOf(">>")+2).trim();
log.info("executing selector: [" + prefix + "] " + query + " [" + suffix + "]:");
List<JSONObject> selectorResults = gr.queryGraphIndex(query);
for(JSONObject selectorResult: selectorResults) {
String batchRequestKey = selectorResult.getString(Graph.KEY_FIELD);
String batchRequest =
prefix + " " +
batchRequestKey + " " +
suffix;
String batchCmd;
String[] batchArgs;
if (batchRequest.indexOf(GraphServerProtocol.SPACE) != -1) {
batchCmd = batchRequest.substring(0,
batchRequest.indexOf(GraphServerProtocol.SPACE)).trim().toLowerCase();
batchArgs = batchRequest.substring(
batchRequest.indexOf(GraphServerProtocol.SPACE)).trim().split(GraphServerProtocol.SPACE);
} else {
batchCmd = batchRequest.trim().toLowerCase();
batchArgs = new String[0];
}
String batchCmdResponse =
execute(responseChannel,
clientId,
clientState,
batchRequest,
batchCmd,
batchArgs);
String responseParts[] = batchCmdResponse.split(GraphServerProtocol.NL);
for(String responsePart: responseParts) {
if (responsePart.charAt(0) != '-') {
responseChannel.write(responsePart.trim() + GraphServerProtocol.NL);
}
}
}
return GraphServerProtocol.R_BATCH_OK;
}
// CREATE VERTEX: cvert <key> <json>
if (cmd.equals(GraphServerProtocol.CMD_CVERT)) {
String key = args[0];
String json = request.substring(request.indexOf(GraphServerProtocol.SPACE + key) +
(key.length()+1)).trim(); // remainder of line
JSONObject jo = null;
try {
jo = new JSONObject(json);
gr.addVertex(key, jo);
rsb.append(GraphServerProtocol.R_OK);
} catch (org.json.JSONException jsonEx) {
jsonEx.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" BAD_JSON ");
rsb.append(jsonEx.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.SPACE);
rsb.append(ex.getMessage());
}
// CREATE EDGE: cedge <key> <vFromKey> <vToKey> <rel> <json>
// OR: cedge <key> <vFromKey> <vToKey> <rel> <weight> <json>
} else if (cmd.equals(GraphServerProtocol.CMD_CEDGE)) {
String key = args[0];
String vFromKey = args[1];
String vToKey = args[2];
String rel = args[3];
double weight = 1.0;
String json;
if (args[4].charAt(0) == '{') {
json = request.substring(request.indexOf(GraphServerProtocol.SPACE + rel) +
(rel.length()+1)).trim(); // remainder of line
} else {
weight = Double.parseDouble(args[4]);
json = request.substring(request.indexOf(GraphServerProtocol.SPACE + args[4]) +
(args[4].length()+1)).trim(); // remainder of line
}
JSONObject jo = null;
try {
jo = new JSONObject(json);
jo.put(Graph.EDGE_SOURCE_FIELD, vFromKey);
jo.put(Graph.EDGE_TARGET_FIELD, vToKey);
jo.put(Graph.WEIGHT_FIELD, weight);
jo.put(Graph.RELATION_FIELD, rel);
gr.addEdge(key, jo, vFromKey, vToKey, rel, weight);
rsb.append(GraphServerProtocol.R_OK);
} catch (org.json.JSONException jsonEx) {
jsonEx.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" BAD_JSON ");
rsb.append(jsonEx.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.SPACE);
rsb.append(ex.getMessage());
}
// DELETE OBJECT: del <key>
} else if (cmd.equals(GraphServerProtocol.CMD_DEL)) {
String key = args[0];
JSONObject obj = gr.get(key);
if (null == obj) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
String _type = obj.getString(Graph.TYPE_FIELD);
if (_type.equals(Graph.VERTEX_TYPE)) {
JSONVertex jv = gr.getVertex(key);
gr.removeVertex(jv);
rsb.append(GraphServerProtocol.R_OK);
} else if (_type.equals(Graph.EDGE_TYPE)) {
JSONEdge je = gr.getEdge(key);
gr.removeEdge(je);
rsb.append(GraphServerProtocol.R_OK);
} else {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.SPACE);
rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE);
}
}
// OBJECT EXISTS: exists <key>
} else if (cmd.equals(GraphServerProtocol.CMD_EXISTS)) {
String key = args[0];
rsb.append(gr.exists(key) + " " + key);
rsb.append(GraphServerProtocol.R_OK);
// GET OBJECT: get <key>
} else if (cmd.equals(GraphServerProtocol.CMD_GET)) {
String key = args[0];
JSONObject jo = gr.get(key);
if (jo == null) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append(prepareResult(jo));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// QUERY GRAPH OBJECTS: q <query>
} else if (cmd.equals(GraphServerProtocol.CMD_Q)) {
String q = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim(); // remainder of line past "q "
List<JSONObject> results = gr.queryGraphIndex(q);
JSONArray ja = new JSONArray();
for(JSONObject jo: results) {
ja.put(jo);
}
JSONObject res = new JSONObject();
res.put("results", ja);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// QUERY PROCESSES: qp <query>
} else if (cmd.equals(GraphServerProtocol.CMD_QP)) {
String q = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim(); // remainder of line past "qp "
List<JSONObject> results = gr.queryProcessIndex(q);
JSONArray ja = new JSONArray();
for(JSONObject jo: results) {
ja.put(jo);
}
JSONObject res = new JSONObject();
res.put("results", ja);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// DIJKSTRA SHORTEST PATH: spath <from> <to> <radius>
} else if (cmd.equals(GraphServerProtocol.CMD_SPATH)) {
String vFromKey = args[0];
String vToKey = args[1];
double radius = Double.POSITIVE_INFINITY;
if (args.length == 3) {
radius = Double.parseDouble(args[2]);
}
JSONObject result = gr.getShortestPath(vFromKey, vToKey, radius);
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(prepareResult(result));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// SET VERTEX/EDGE ATTRIBUTE: set <key> <attr> <value>
} else if (cmd.equals(GraphServerProtocol.CMD_SET)) {
String key = args[0];
String attr = args[1];
String val;
if (args.length == 2) {
// clear value
val = null;
} else {
val = request.substring(request.indexOf(GraphServerProtocol.SPACE + args[1]) +
(args[1].length()+1)).trim(); // remainder of line
}
if (attr.startsWith("_") &&
!attr.equals(Graph.WEIGHT_FIELD)) {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(" CANNOT_SET_RESERVED_PROPERTY");
} else {
JSONObject obj = gr.get(key);
if (null == obj) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
String _type = obj.getString(Graph.TYPE_FIELD);
if (_type.equals(Graph.VERTEX_TYPE)) {
JSONVertex jv = gr.getVertex(key);
if (null != val) {
jv.put(attr, val);
} else {
jv.remove(attr);
}
gr.indexObject(key, _type, jv);
rsb.append(GraphServerProtocol.R_OK);
} else if (_type.equals(Graph.EDGE_TYPE)) {
JSONEdge je = gr.getEdge(key);
if (null != val) {
je.put(attr, val);
} else {
je.remove(attr);
}
if (attr.equals(Graph.WEIGHT_FIELD)) {
gr.setEdgeWeight(je, Double.parseDouble(val));
}
gr.indexObject(key, _type, je.asJSONObject().getJSONObject(Graph.DATA_FIELD));
rsb.append(GraphServerProtocol.R_OK);
} else {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE);
}
}
}
// INCREASE EDGE WEIGHT: incw <edge_key> <amount>
} else if (cmd.equals(GraphServerProtocol.CMD_INCW)) {
String key = args[0];
double w_amt = Double.parseDouble(args[1]);
JSONEdge je = gr.getEdge(key);
if (null == je) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
double weight = gr.getEdgeWeight(je);
weight += w_amt;
gr.setEdgeWeight(je, weight);
je.put(Graph.WEIGHT_FIELD, "" + weight);
gr.indexObject(key, Graph.EDGE_TYPE, je.asJSONObject().getJSONObject(Graph.DATA_FIELD));
rsb.append(GraphServerProtocol.R_OK);
}
// DUMP INTERNAL REPRESENTATION OF VERTEX/EDGE: spy <key>
} else if (cmd.equals(GraphServerProtocol.CMD_SPY)) {
String key = args[0];
JSONObject obj = gr.get(key);
if (null == obj) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
String _type = obj.getString(Graph.TYPE_FIELD);
if (_type.equals(Graph.EDGE_TYPE)) {
JSONEdge je = gr.getEdge(key);
if (null == je) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append(je.asClientJSONObject().toString(4) + GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (_type.equals(Graph.VERTEX_TYPE)) {
JSONVertex jv = gr.getVertex(key);
if (null == jv) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append(jv.toString(4) + GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else {
rsb.append(GraphServerProtocol.R_ERR);
rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE);
}
}
// K-SHORTEST-PATHS: kspath <from> <to> <k> <optional:maxHops>
} else if (cmd.equals(GraphServerProtocol.CMD_KSPATH)) {
String vFromKey = args[0];
String vToKey = args[1];
int k = Integer.parseInt(args[2]);
int maxHops = 0;
if (args.length > 3) {
maxHops = Integer.parseInt(args[3]);
}
JSONObject result = gr.getKShortestPaths(vFromKey, vToKey, k, maxHops);
rsb.append(prepareResult(result));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// HAMILTONIAN CYCLE: hc
} else if (cmd.equals(GraphServerProtocol.CMD_HC)) {
List<JSONVertex> results = gr.getHamiltonianCycle();
if (null == results) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
JSONObject res = new JSONObject();
JSONArray cycle = new JSONArray();
for(JSONVertex jo: results) {
cycle.put(jo);
}
res.put("cycle", cycle);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// EULERIAN CIRCUIT: ec
} else if (cmd.equals(GraphServerProtocol.CMD_EC)) {
List<JSONVertex> results = gr.getEulerianCircuit();
if (null == results) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
JSONObject res = new JSONObject();
JSONArray circuit = new JSONArray();
for(JSONVertex jo: results) {
circuit.put(jo);
}
res.put("circuit", circuit);
rsb.append(prepareResult(res));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// EDWARDS KARP MAXIMUM FLOW: ekmf <from> <to>
} else if (cmd.equals(GraphServerProtocol.CMD_EKMF)) {
String vSourceKey = args[0];
String vSinkKey = args[1];
JSONObject flowResult = gr.getEKMF(vSourceKey, vSinkKey);
if (null == flowResult) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(flowResult.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// CHROMATIC NUMBER: cn
} else if (cmd.equals(GraphServerProtocol.CMD_CN)) {
JSONObject result = new JSONObject();
result.put("chromatic_number", gr.getChromaticNumber());
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// KRUSKAL'S MINIMUM SPANNING TREE: kmst
} else if (cmd.equals(GraphServerProtocol.CMD_KMST)) {
JSONObject result = gr.getKMST();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// VERTEX COVER: GREEDY: vcg
} else if (cmd.equals(GraphServerProtocol.CMD_VCG)) {
JSONObject result = gr.getGreedyVertexCover();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// VERTEX COVER: 2-APPROXIMATION: vc2a
} else if (cmd.equals(GraphServerProtocol.CMD_VC2A)) {
JSONObject result = gr.get2ApproximationVertexCover();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// MAXIMALLY CONNECTED SET BY VERTEX: csetv <key>
} else if (cmd.equals(GraphServerProtocol.CMD_CSETV)) {
String key = args[0];
JSONVertex v = gr.getVertex(key);
if (null == v) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
JSONObject result = gr.getConnectedSetByVertex(v);
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// ALL MAXIMALLY CONNECTED SETS: csets
} else if (cmd.equals(GraphServerProtocol.CMD_CSETS)) {
JSONObject result = gr.getConnectedSets();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// CONNECTEDNESS TEST: iscon
} else if (cmd.equals(GraphServerProtocol.CMD_ISCON)) {
rsb.append("" + gr.isConnected());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
// UNDIRECTED PATH EXISTENCE TEST: upathex <from> <to>
} else if (cmd.equals(GraphServerProtocol.CMD_UPATHEX)) {
JSONVertex vFrom = gr.getVertex(args[0]);
JSONVertex vTo = gr.getVertex(args[1]);
if (null == vFrom ||
null == vTo) {
rsb.append(GraphServerProtocol.R_NOT_FOUND);
} else {
rsb.append("" + gr.pathExists(vFrom, vTo));
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// FIND ALL MAXIMAL CLIQUES: Bron Kerosch Clique Finder
} else if (cmd.equals(GraphServerProtocol.CMD_FAMC)) {
JSONObject result = gr.getAllMaximalCliques();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
// FIND BIGGEST MAXIMAL CLIQUES: Bron Kerosch Clique Finder
} else if (cmd.equals(GraphServerProtocol.CMD_FBMC)) {
JSONObject result = gr.getBiggestMaximalCliques();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (cmd.equals(GraphServerProtocol.CMD_ASPV)) {
JSONObject result = gr.getAllShortestPathsFrom(
gr.getVertex(args[0]));
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (cmd.equals(GraphServerProtocol.CMD_GCYC)) {
JSONObject result = gr.getGraphCycles();
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
} else if (cmd.equals(GraphServerProtocol.CMD_VCYC)) {
JSONObject result = gr.getGraphCyclesContainingVertex(
gr.getVertex(args[0]));
if (null == result) {
rsb.append(GraphServerProtocol.R_NOT_EXIST);
} else {
rsb.append(result.toString());
rsb.append(GraphServerProtocol.NL);
rsb.append(GraphServerProtocol.R_OK);
}
/*
* SIMULATION
*/
// EMIT A MESSAGE TO A RUNNING SIMULATION PROCESS: emit <key> <process_name> <json_msg>
} else if (cmd.equals(GraphServerProtocol.CMD_EMIT)) {
String key = args[0];
String processName = args[1];
String json = request.substring(request.indexOf(GraphServerProtocol.SPACE + processName) +
(processName.length()+1)).trim(); // remainder of line
JSONObject jo = null;
jo = new JSONObject(json);
gr.emit(key, processName, jo);
rsb.append(GraphServerProtocol.R_OK);
}
// EVENT-SUBSCRIPTION MANAGEMENT
// JAVASCRIPT "POINT-OF-VIEW" TRAVERSAL
return rsb.toString();
}
|
diff --git a/obex/javax/obex/ServerOperation.java b/obex/javax/obex/ServerOperation.java
index 12c53b50..1d8a4d66 100644
--- a/obex/javax/obex/ServerOperation.java
+++ b/obex/javax/obex/ServerOperation.java
@@ -1,721 +1,721 @@
/*
* Copyright (c) 2010-2011, Motorola, 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 the Motorola, 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 THE COPYRIGHT HOLDER 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 javax.obex;
import java.io.IOException;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.io.DataOutputStream;
/**
* This class implements the Operation interface for server side connections.
* <P>
* <STRONG>Request Codes</STRONG> There are four different request codes that
* are in this class. 0x02 is a PUT request that signals that the request is not
* complete and requires an additional OBEX packet. 0x82 is a PUT request that
* says that request is complete. In this case, the server can begin sending the
* response. The 0x03 is a GET request that signals that the request is not
* finished. When the server receives a 0x83, the client is signaling the server
* that it is done with its request. TODO: Extend the ClientOperation and reuse
* the methods defined TODO: in that class.
* @hide
*/
public final class ServerOperation implements Operation, BaseStream {
public boolean isAborted;
public HeaderSet requestHeader;
public HeaderSet replyHeader;
public boolean finalBitSet;
private InputStream mInput;
private ServerSession mParent;
private int mMaxPacketLength;
private int mResponseSize;
private boolean mClosed;
private boolean mGetOperation;
private PrivateInputStream mPrivateInput;
private PrivateOutputStream mPrivateOutput;
private boolean mPrivateOutputOpen;
private String mExceptionString;
private ServerRequestHandler mListener;
private boolean mRequestFinished;
private boolean mHasBody;
private ObexByteBuffer mData;
private ObexByteBuffer mBodyBuffer;
private ObexByteBuffer mHeaderBuffer;
private boolean mEndofBody = true;
/**
* Creates new ServerOperation
* @param p the parent that created this object
* @param in the input stream to read from
* @param out the output stream to write to
* @param request the initial request that was received from the client
* @param maxSize the max packet size that the client will accept
* @param listen the listener that is responding to the request
* @throws IOException if an IO error occurs
*/
public ServerOperation(ServerSession p, InputStream in, int request, int maxSize,
ServerRequestHandler listen) throws IOException {
isAborted = false;
mParent = p;
mInput = in;
mMaxPacketLength = maxSize;
mClosed = false;
requestHeader = new HeaderSet();
replyHeader = new HeaderSet();
mPrivateInput = new PrivateInputStream(this);
mResponseSize = 3;
mListener = listen;
mRequestFinished = false;
mPrivateOutputOpen = false;
mHasBody = false;
mData = new ObexByteBuffer(32);
mBodyBuffer = new ObexByteBuffer(32);
mHeaderBuffer = new ObexByteBuffer(32);
/*
* Determine if this is a PUT request
*/
if ((request == 0x02) || (request == 0x82)) {
/*
* It is a PUT request.
*/
mGetOperation = false;
/*
* Determine if the final bit is set
*/
if ((request & 0x80) == 0) {
finalBitSet = false;
} else {
finalBitSet = true;
mRequestFinished = true;
}
} else if ((request == 0x03) || (request == 0x83)) {
/*
* It is a GET request.
*/
mGetOperation = true;
// For Get request, final bit set is decided by server side logic
finalBitSet = false;
if (request == 0x83) {
mRequestFinished = true;
}
} else {
throw new IOException("ServerOperation can not handle such request");
}
int length = in.read();
length = (length << 8) + in.read();
/*
* Determine if the packet length is larger than this device can receive
*/
if (length > ObexHelper.MAX_PACKET_SIZE_INT) {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE, null);
throw new IOException("Packet received was too large");
}
/*
* Determine if any headers were sent in the initial request
*/
if (length > 3) {
mData.reset();
mData.write(in, length - 3);
ObexHelper.updateHeaderSet(requestHeader, mData, mBodyBuffer, mHeaderBuffer);
if (mBodyBuffer.getLength() > 0) {
mHasBody = true;
}
if (mListener.getConnectionId() != -1 && requestHeader.mConnectionID != null) {
mListener.setConnectionId(ObexHelper.convertToLong(requestHeader.mConnectionID));
} else {
mListener.setConnectionId(1);
}
if (requestHeader.mAuthResp != null) {
if (!mParent.handleAuthResp(requestHeader.mAuthResp)) {
mExceptionString = "Authentication Failed";
mParent.sendResponse(ResponseCodes.OBEX_HTTP_UNAUTHORIZED, null);
mClosed = true;
requestHeader.mAuthResp = null;
return;
}
}
if (requestHeader.mAuthChall != null) {
mParent.handleAuthChall(requestHeader);
// send the authResp to the client
replyHeader.mAuthResp = new byte[requestHeader.mAuthResp.length];
System.arraycopy(requestHeader.mAuthResp, 0, replyHeader.mAuthResp, 0,
replyHeader.mAuthResp.length);
requestHeader.mAuthResp = null;
requestHeader.mAuthChall = null;
}
if (mBodyBuffer.getLength() > 0) {
mPrivateInput.writeBytes(mBodyBuffer, 1);
} else {
while ((!mGetOperation) && (!finalBitSet)) {
sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
if (mPrivateInput.available() > 0) {
break;
}
}
}
}
while ((!mGetOperation) && (!finalBitSet) && (mPrivateInput.available() == 0)) {
sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
if (mPrivateInput.available() > 0) {
break;
}
}
// wait for get request finished !!!!
while (mGetOperation && !mRequestFinished) {
sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
}
}
public boolean isValidBody() {
return mHasBody;
}
/**
* Determines if the operation should continue or should wait. If it should
* continue, this method will continue the operation.
* @param sendEmpty if <code>true</code> then this will continue the
* operation even if no headers will be sent; if <code>false</code>
* then this method will only continue the operation if there are
* headers to send
* @param inStream if<code>true</code> the stream is input stream, otherwise
* output stream
* @return <code>true</code> if the operation was completed;
* <code>false</code> if no operation took place
*/
public synchronized boolean continueOperation(boolean sendEmpty, boolean inStream)
throws IOException {
if (!mGetOperation) {
if (!finalBitSet) {
if (sendEmpty) {
sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
return true;
} else {
if ((mResponseSize > 3) || (mPrivateOutput.size() > 0)) {
sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
return true;
} else {
return false;
}
}
} else {
return false;
}
} else {
sendReply(ResponseCodes.OBEX_HTTP_CONTINUE);
return true;
}
}
/**
* Sends a reply to the client. If the reply is a OBEX_HTTP_CONTINUE, it
* will wait for a response from the client before ending.
* @param type the response code to send back to the client
* @return <code>true</code> if the final bit was not set on the reply;
* <code>false</code> if no reply was received because the operation
* ended, an abort was received, or the final bit was set in the
* reply
* @throws IOException if an IO error occurs
*/
public synchronized boolean sendReply(int type) throws IOException {
mBodyBuffer.reset();
long id = mListener.getConnectionId();
if (id == -1) {
replyHeader.mConnectionID = null;
} else {
replyHeader.mConnectionID = ObexHelper.convertToByteArray(id);
}
byte[] headerArray = ObexHelper.createHeader(replyHeader, true);
int bodyLength = -1;
int orginalBodyLength = -1;
if (mPrivateOutput != null) {
bodyLength = mPrivateOutput.size();
orginalBodyLength = bodyLength;
}
if ((ObexHelper.BASE_PACKET_LENGTH + headerArray.length) > mMaxPacketLength) {
int end = 0;
int start = 0;
while (end != headerArray.length) {
end = ObexHelper.findHeaderEnd(headerArray, start, mMaxPacketLength
- ObexHelper.BASE_PACKET_LENGTH);
if (end == -1) {
mClosed = true;
if (mPrivateInput != null) {
mPrivateInput.close();
}
if (mPrivateOutput != null) {
mPrivateOutput.close();
}
mParent.sendResponse(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR, null);
throw new IOException("OBEX Packet exceeds max packet size");
}
mHeaderBuffer.reset();
mHeaderBuffer.write(headerArray, start, end - start);
mParent.sendResponse(type, mHeaderBuffer);
start = end;
}
if (bodyLength > 0) {
return true;
} else {
return false;
}
} else {
mBodyBuffer.write(headerArray);
}
// For Get operation: if response code is OBEX_HTTP_OK, then this is the
// last packet; so set finalBitSet to true.
if (mGetOperation && type == ResponseCodes.OBEX_HTTP_OK) {
finalBitSet = true;
}
if ((finalBitSet) || (headerArray.length < (mMaxPacketLength - 20))) {
if (bodyLength > 0) {
/*
* Determine if I can send the whole body or just part of
* the body. Remember that there is the 3 bytes for the
* response message and 3 bytes for the header ID and length
*/
if (bodyLength > (mMaxPacketLength - headerArray.length - 6)) {
bodyLength = mMaxPacketLength - headerArray.length - 6;
}
/*
* Since this is a put request if the final bit is set or
* the output stream is closed we need to send the 0x49
* (End of Body) otherwise, we need to send 0x48 (Body)
*/
if ((finalBitSet) || (mPrivateOutput.isClosed())) {
mBodyBuffer.write((byte)0x49);
if (mEndofBody) {
- mBodyBuffer.write(0x49);
+ mBodyBuffer.write((byte)0x49);
bodyLength += 3;
mBodyBuffer.write((byte)(bodyLength >> 8));
mBodyBuffer.write((byte)bodyLength);
mPrivateOutput.writeTo(mBodyBuffer, bodyLength - 3);
}
} else {
mBodyBuffer.write((byte)0x48);
bodyLength += 3;
mBodyBuffer.write((byte)(bodyLength >> 8));
mBodyBuffer.write((byte)bodyLength);
mPrivateOutput.writeTo(mBodyBuffer, bodyLength - 3);
}
}
}
if ((finalBitSet) && (type == ResponseCodes.OBEX_HTTP_OK) && (orginalBodyLength <= 0)) {
if (mEndofBody) {
mBodyBuffer.write((byte)0x49);
orginalBodyLength = 3;
mBodyBuffer.write((byte)(orginalBodyLength >> 8));
mBodyBuffer.write((byte)orginalBodyLength);
}
}
mResponseSize = 3;
mParent.sendResponse(type, mBodyBuffer);
if (type == ResponseCodes.OBEX_HTTP_CONTINUE) {
int headerID = mInput.read();
int length = mInput.read();
length = (length << 8) + mInput.read();
if ((headerID != ObexHelper.OBEX_OPCODE_PUT)
&& (headerID != ObexHelper.OBEX_OPCODE_PUT_FINAL)
&& (headerID != ObexHelper.OBEX_OPCODE_GET)
&& (headerID != ObexHelper.OBEX_OPCODE_GET_FINAL)) {
if (length > 3) {
mData.reset();
// First three bytes already read, compensating for this
mData.write(mInput, length - 3);
}
/*
* Determine if an ABORT was sent as the reply
*/
if (headerID == ObexHelper.OBEX_OPCODE_ABORT) {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_OK, null);
mClosed = true;
isAborted = true;
mExceptionString = "Abort Received";
throw new IOException("Abort Received");
} else {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_BAD_REQUEST, null);
mClosed = true;
mExceptionString = "Bad Request Received";
throw new IOException("Bad Request Received");
}
} else {
if ((headerID == ObexHelper.OBEX_OPCODE_PUT_FINAL)) {
finalBitSet = true;
} else if (headerID == ObexHelper.OBEX_OPCODE_GET_FINAL) {
mRequestFinished = true;
}
/*
* Determine if the packet length is larger then this device can receive
*/
if (length > ObexHelper.MAX_PACKET_SIZE_INT) {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE, null);
throw new IOException("Packet received was too large");
}
/*
* Determine if any headers were sent in the initial request
*/
if (length > 3) {
mData.reset();
mData.write(mInput, length - 3);
ObexHelper.updateHeaderSet(requestHeader, mData, mBodyBuffer, mHeaderBuffer);
if (mBodyBuffer.getLength() > 0) {
mHasBody = true;
}
if (mListener.getConnectionId() != -1 && requestHeader.mConnectionID != null) {
mListener.setConnectionId(ObexHelper
.convertToLong(requestHeader.mConnectionID));
} else {
mListener.setConnectionId(1);
}
if (requestHeader.mAuthResp != null) {
if (!mParent.handleAuthResp(requestHeader.mAuthResp)) {
mExceptionString = "Authentication Failed";
mParent.sendResponse(ResponseCodes.OBEX_HTTP_UNAUTHORIZED, null);
mClosed = true;
requestHeader.mAuthResp = null;
return false;
}
requestHeader.mAuthResp = null;
}
if (requestHeader.mAuthChall != null) {
mParent.handleAuthChall(requestHeader);
// send the auhtResp to the client
replyHeader.mAuthResp = new byte[requestHeader.mAuthResp.length];
System.arraycopy(requestHeader.mAuthResp, 0, replyHeader.mAuthResp, 0,
replyHeader.mAuthResp.length);
requestHeader.mAuthResp = null;
requestHeader.mAuthChall = null;
}
if (mBodyBuffer.getLength() > 0) {
mPrivateInput.writeBytes(mBodyBuffer, 1);
}
}
}
return true;
} else {
return false;
}
}
/**
* Sends an ABORT message to the server. By calling this method, the
* corresponding input and output streams will be closed along with this
* object.
* @throws IOException if the transaction has already ended or if an OBEX
* server called this method
*/
public void abort() throws IOException {
throw new IOException("Called from a server");
}
/**
* Returns the headers that have been received during the operation.
* Modifying the object returned has no effect on the headers that are sent
* or retrieved.
* @return the headers received during this <code>Operation</code>
* @throws IOException if this <code>Operation</code> has been closed
*/
public HeaderSet getReceivedHeader() throws IOException {
ensureOpen();
return requestHeader;
}
/**
* Specifies the headers that should be sent in the next OBEX message that
* is sent.
* @param headers the headers to send in the next message
* @throws IOException if this <code>Operation</code> has been closed or the
* transaction has ended and no further messages will be exchanged
* @throws IllegalArgumentException if <code>headers</code> was not created
* by a call to <code>ServerRequestHandler.createHeaderSet()</code>
*/
public void sendHeaders(HeaderSet headers) throws IOException {
ensureOpen();
if (headers == null) {
throw new IOException("Headers may not be null");
}
int[] headerList = headers.getHeaderList();
if (headerList != null) {
for (int i = 0; i < headerList.length; i++) {
replyHeader.setHeader(headerList[i], headers.getHeader(headerList[i]));
}
}
}
/**
* Retrieves the response code retrieved from the server. Response codes are
* defined in the <code>ResponseCodes</code> interface.
* @return the response code retrieved from the server
* @throws IOException if an error occurred in the transport layer during
* the transaction; if this method is called on a
* <code>HeaderSet</code> object created by calling
* <code>createHeaderSet</code> in a <code>ClientSession</code>
* object; if this is called from a server
*/
public int getResponseCode() throws IOException {
throw new IOException("Called from a server");
}
/**
* Always returns <code>null</code>
* @return <code>null</code>
*/
public String getEncoding() {
return null;
}
/**
* Returns the type of content that the resource connected to is providing.
* E.g. if the connection is via HTTP, then the value of the content-type
* header field is returned.
* @return the content type of the resource that the URL references, or
* <code>null</code> if not known
*/
public String getType() {
try {
return (String)requestHeader.getHeader(HeaderSet.TYPE);
} catch (IOException e) {
return null;
}
}
/**
* Returns the length of the content which is being provided. E.g. if the
* connection is via HTTP, then the value of the content-length header field
* is returned.
* @return the content length of the resource that this connection's URL
* references, or -1 if the content length is not known
*/
public long getLength() {
try {
Long temp = (Long)requestHeader.getHeader(HeaderSet.LENGTH);
if (temp == null) {
return -1;
} else {
return temp.longValue();
}
} catch (IOException e) {
return -1;
}
}
public int getMaxPacketSize() {
return mMaxPacketLength - 6 - getHeaderLength();
}
public int getHeaderLength() {
long id = mListener.getConnectionId();
if (id == -1) {
replyHeader.mConnectionID = null;
} else {
replyHeader.mConnectionID = ObexHelper.convertToByteArray(id);
}
byte[] headerArray = ObexHelper.createHeader(replyHeader, false);
return headerArray.length;
}
/**
* Open and return an input stream for a connection.
* @return an input stream
* @throws IOException if an I/O error occurs
*/
public InputStream openInputStream() throws IOException {
ensureOpen();
return mPrivateInput;
}
/**
* Open and return a data input stream for a connection.
* @return an input stream
* @throws IOException if an I/O error occurs
*/
public DataInputStream openDataInputStream() throws IOException {
return new DataInputStream(openInputStream());
}
/**
* Open and return an output stream for a connection.
* @return an output stream
* @throws IOException if an I/O error occurs
*/
public OutputStream openOutputStream() throws IOException {
ensureOpen();
if (mPrivateOutputOpen) {
throw new IOException("no more input streams available, stream already opened");
}
if (!mRequestFinished) {
throw new IOException("no output streams available ,request not finished");
}
if (mPrivateOutput == null) {
mPrivateOutput = new PrivateOutputStream(this, getMaxPacketSize());
}
mPrivateOutputOpen = true;
return mPrivateOutput;
}
/**
* Open and return a data output stream for a connection.
* @return an output stream
* @throws IOException if an I/O error occurs
*/
public DataOutputStream openDataOutputStream() throws IOException {
return new DataOutputStream(openOutputStream());
}
/**
* Closes the connection and ends the transaction
* @throws IOException if the operation has already ended or is closed
*/
public void close() throws IOException {
ensureOpen();
mClosed = true;
}
/**
* Verifies that the connection is open and no exceptions should be thrown.
* @throws IOException if an exception needs to be thrown
*/
public void ensureOpen() throws IOException {
if (mExceptionString != null) {
throw new IOException(mExceptionString);
}
if (mClosed) {
throw new IOException("Operation has already ended");
}
}
/**
* Verifies that additional information may be sent. In other words, the
* operation is not done.
* <P>
* Included to implement the BaseStream interface only. It does not do
* anything on the server side since the operation of the Operation object
* is not done until after the handler returns from its method.
* @throws IOException if the operation is completed
*/
public void ensureNotDone() throws IOException {
}
/**
* Called when the output or input stream is closed. It does not do anything
* on the server side since the operation of the Operation object is not
* done until after the handler returns from its method.
* @param inStream <code>true</code> if the input stream is closed;
* <code>false</code> if the output stream is closed
* @throws IOException if an IO error occurs
*/
public void streamClosed(boolean inStream) throws IOException {
}
public void noEndofBody() {
mEndofBody = false;
}
}
| true | true | public synchronized boolean sendReply(int type) throws IOException {
mBodyBuffer.reset();
long id = mListener.getConnectionId();
if (id == -1) {
replyHeader.mConnectionID = null;
} else {
replyHeader.mConnectionID = ObexHelper.convertToByteArray(id);
}
byte[] headerArray = ObexHelper.createHeader(replyHeader, true);
int bodyLength = -1;
int orginalBodyLength = -1;
if (mPrivateOutput != null) {
bodyLength = mPrivateOutput.size();
orginalBodyLength = bodyLength;
}
if ((ObexHelper.BASE_PACKET_LENGTH + headerArray.length) > mMaxPacketLength) {
int end = 0;
int start = 0;
while (end != headerArray.length) {
end = ObexHelper.findHeaderEnd(headerArray, start, mMaxPacketLength
- ObexHelper.BASE_PACKET_LENGTH);
if (end == -1) {
mClosed = true;
if (mPrivateInput != null) {
mPrivateInput.close();
}
if (mPrivateOutput != null) {
mPrivateOutput.close();
}
mParent.sendResponse(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR, null);
throw new IOException("OBEX Packet exceeds max packet size");
}
mHeaderBuffer.reset();
mHeaderBuffer.write(headerArray, start, end - start);
mParent.sendResponse(type, mHeaderBuffer);
start = end;
}
if (bodyLength > 0) {
return true;
} else {
return false;
}
} else {
mBodyBuffer.write(headerArray);
}
// For Get operation: if response code is OBEX_HTTP_OK, then this is the
// last packet; so set finalBitSet to true.
if (mGetOperation && type == ResponseCodes.OBEX_HTTP_OK) {
finalBitSet = true;
}
if ((finalBitSet) || (headerArray.length < (mMaxPacketLength - 20))) {
if (bodyLength > 0) {
/*
* Determine if I can send the whole body or just part of
* the body. Remember that there is the 3 bytes for the
* response message and 3 bytes for the header ID and length
*/
if (bodyLength > (mMaxPacketLength - headerArray.length - 6)) {
bodyLength = mMaxPacketLength - headerArray.length - 6;
}
/*
* Since this is a put request if the final bit is set or
* the output stream is closed we need to send the 0x49
* (End of Body) otherwise, we need to send 0x48 (Body)
*/
if ((finalBitSet) || (mPrivateOutput.isClosed())) {
mBodyBuffer.write((byte)0x49);
if (mEndofBody) {
mBodyBuffer.write(0x49);
bodyLength += 3;
mBodyBuffer.write((byte)(bodyLength >> 8));
mBodyBuffer.write((byte)bodyLength);
mPrivateOutput.writeTo(mBodyBuffer, bodyLength - 3);
}
} else {
mBodyBuffer.write((byte)0x48);
bodyLength += 3;
mBodyBuffer.write((byte)(bodyLength >> 8));
mBodyBuffer.write((byte)bodyLength);
mPrivateOutput.writeTo(mBodyBuffer, bodyLength - 3);
}
}
}
if ((finalBitSet) && (type == ResponseCodes.OBEX_HTTP_OK) && (orginalBodyLength <= 0)) {
if (mEndofBody) {
mBodyBuffer.write((byte)0x49);
orginalBodyLength = 3;
mBodyBuffer.write((byte)(orginalBodyLength >> 8));
mBodyBuffer.write((byte)orginalBodyLength);
}
}
mResponseSize = 3;
mParent.sendResponse(type, mBodyBuffer);
if (type == ResponseCodes.OBEX_HTTP_CONTINUE) {
int headerID = mInput.read();
int length = mInput.read();
length = (length << 8) + mInput.read();
if ((headerID != ObexHelper.OBEX_OPCODE_PUT)
&& (headerID != ObexHelper.OBEX_OPCODE_PUT_FINAL)
&& (headerID != ObexHelper.OBEX_OPCODE_GET)
&& (headerID != ObexHelper.OBEX_OPCODE_GET_FINAL)) {
if (length > 3) {
mData.reset();
// First three bytes already read, compensating for this
mData.write(mInput, length - 3);
}
/*
* Determine if an ABORT was sent as the reply
*/
if (headerID == ObexHelper.OBEX_OPCODE_ABORT) {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_OK, null);
mClosed = true;
isAborted = true;
mExceptionString = "Abort Received";
throw new IOException("Abort Received");
} else {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_BAD_REQUEST, null);
mClosed = true;
mExceptionString = "Bad Request Received";
throw new IOException("Bad Request Received");
}
} else {
if ((headerID == ObexHelper.OBEX_OPCODE_PUT_FINAL)) {
finalBitSet = true;
} else if (headerID == ObexHelper.OBEX_OPCODE_GET_FINAL) {
mRequestFinished = true;
}
/*
* Determine if the packet length is larger then this device can receive
*/
if (length > ObexHelper.MAX_PACKET_SIZE_INT) {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE, null);
throw new IOException("Packet received was too large");
}
/*
* Determine if any headers were sent in the initial request
*/
if (length > 3) {
mData.reset();
mData.write(mInput, length - 3);
ObexHelper.updateHeaderSet(requestHeader, mData, mBodyBuffer, mHeaderBuffer);
if (mBodyBuffer.getLength() > 0) {
mHasBody = true;
}
if (mListener.getConnectionId() != -1 && requestHeader.mConnectionID != null) {
mListener.setConnectionId(ObexHelper
.convertToLong(requestHeader.mConnectionID));
} else {
mListener.setConnectionId(1);
}
if (requestHeader.mAuthResp != null) {
if (!mParent.handleAuthResp(requestHeader.mAuthResp)) {
mExceptionString = "Authentication Failed";
mParent.sendResponse(ResponseCodes.OBEX_HTTP_UNAUTHORIZED, null);
mClosed = true;
requestHeader.mAuthResp = null;
return false;
}
requestHeader.mAuthResp = null;
}
if (requestHeader.mAuthChall != null) {
mParent.handleAuthChall(requestHeader);
// send the auhtResp to the client
replyHeader.mAuthResp = new byte[requestHeader.mAuthResp.length];
System.arraycopy(requestHeader.mAuthResp, 0, replyHeader.mAuthResp, 0,
replyHeader.mAuthResp.length);
requestHeader.mAuthResp = null;
requestHeader.mAuthChall = null;
}
if (mBodyBuffer.getLength() > 0) {
mPrivateInput.writeBytes(mBodyBuffer, 1);
}
}
}
return true;
} else {
return false;
}
}
| public synchronized boolean sendReply(int type) throws IOException {
mBodyBuffer.reset();
long id = mListener.getConnectionId();
if (id == -1) {
replyHeader.mConnectionID = null;
} else {
replyHeader.mConnectionID = ObexHelper.convertToByteArray(id);
}
byte[] headerArray = ObexHelper.createHeader(replyHeader, true);
int bodyLength = -1;
int orginalBodyLength = -1;
if (mPrivateOutput != null) {
bodyLength = mPrivateOutput.size();
orginalBodyLength = bodyLength;
}
if ((ObexHelper.BASE_PACKET_LENGTH + headerArray.length) > mMaxPacketLength) {
int end = 0;
int start = 0;
while (end != headerArray.length) {
end = ObexHelper.findHeaderEnd(headerArray, start, mMaxPacketLength
- ObexHelper.BASE_PACKET_LENGTH);
if (end == -1) {
mClosed = true;
if (mPrivateInput != null) {
mPrivateInput.close();
}
if (mPrivateOutput != null) {
mPrivateOutput.close();
}
mParent.sendResponse(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR, null);
throw new IOException("OBEX Packet exceeds max packet size");
}
mHeaderBuffer.reset();
mHeaderBuffer.write(headerArray, start, end - start);
mParent.sendResponse(type, mHeaderBuffer);
start = end;
}
if (bodyLength > 0) {
return true;
} else {
return false;
}
} else {
mBodyBuffer.write(headerArray);
}
// For Get operation: if response code is OBEX_HTTP_OK, then this is the
// last packet; so set finalBitSet to true.
if (mGetOperation && type == ResponseCodes.OBEX_HTTP_OK) {
finalBitSet = true;
}
if ((finalBitSet) || (headerArray.length < (mMaxPacketLength - 20))) {
if (bodyLength > 0) {
/*
* Determine if I can send the whole body or just part of
* the body. Remember that there is the 3 bytes for the
* response message and 3 bytes for the header ID and length
*/
if (bodyLength > (mMaxPacketLength - headerArray.length - 6)) {
bodyLength = mMaxPacketLength - headerArray.length - 6;
}
/*
* Since this is a put request if the final bit is set or
* the output stream is closed we need to send the 0x49
* (End of Body) otherwise, we need to send 0x48 (Body)
*/
if ((finalBitSet) || (mPrivateOutput.isClosed())) {
mBodyBuffer.write((byte)0x49);
if (mEndofBody) {
mBodyBuffer.write((byte)0x49);
bodyLength += 3;
mBodyBuffer.write((byte)(bodyLength >> 8));
mBodyBuffer.write((byte)bodyLength);
mPrivateOutput.writeTo(mBodyBuffer, bodyLength - 3);
}
} else {
mBodyBuffer.write((byte)0x48);
bodyLength += 3;
mBodyBuffer.write((byte)(bodyLength >> 8));
mBodyBuffer.write((byte)bodyLength);
mPrivateOutput.writeTo(mBodyBuffer, bodyLength - 3);
}
}
}
if ((finalBitSet) && (type == ResponseCodes.OBEX_HTTP_OK) && (orginalBodyLength <= 0)) {
if (mEndofBody) {
mBodyBuffer.write((byte)0x49);
orginalBodyLength = 3;
mBodyBuffer.write((byte)(orginalBodyLength >> 8));
mBodyBuffer.write((byte)orginalBodyLength);
}
}
mResponseSize = 3;
mParent.sendResponse(type, mBodyBuffer);
if (type == ResponseCodes.OBEX_HTTP_CONTINUE) {
int headerID = mInput.read();
int length = mInput.read();
length = (length << 8) + mInput.read();
if ((headerID != ObexHelper.OBEX_OPCODE_PUT)
&& (headerID != ObexHelper.OBEX_OPCODE_PUT_FINAL)
&& (headerID != ObexHelper.OBEX_OPCODE_GET)
&& (headerID != ObexHelper.OBEX_OPCODE_GET_FINAL)) {
if (length > 3) {
mData.reset();
// First three bytes already read, compensating for this
mData.write(mInput, length - 3);
}
/*
* Determine if an ABORT was sent as the reply
*/
if (headerID == ObexHelper.OBEX_OPCODE_ABORT) {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_OK, null);
mClosed = true;
isAborted = true;
mExceptionString = "Abort Received";
throw new IOException("Abort Received");
} else {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_BAD_REQUEST, null);
mClosed = true;
mExceptionString = "Bad Request Received";
throw new IOException("Bad Request Received");
}
} else {
if ((headerID == ObexHelper.OBEX_OPCODE_PUT_FINAL)) {
finalBitSet = true;
} else if (headerID == ObexHelper.OBEX_OPCODE_GET_FINAL) {
mRequestFinished = true;
}
/*
* Determine if the packet length is larger then this device can receive
*/
if (length > ObexHelper.MAX_PACKET_SIZE_INT) {
mParent.sendResponse(ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE, null);
throw new IOException("Packet received was too large");
}
/*
* Determine if any headers were sent in the initial request
*/
if (length > 3) {
mData.reset();
mData.write(mInput, length - 3);
ObexHelper.updateHeaderSet(requestHeader, mData, mBodyBuffer, mHeaderBuffer);
if (mBodyBuffer.getLength() > 0) {
mHasBody = true;
}
if (mListener.getConnectionId() != -1 && requestHeader.mConnectionID != null) {
mListener.setConnectionId(ObexHelper
.convertToLong(requestHeader.mConnectionID));
} else {
mListener.setConnectionId(1);
}
if (requestHeader.mAuthResp != null) {
if (!mParent.handleAuthResp(requestHeader.mAuthResp)) {
mExceptionString = "Authentication Failed";
mParent.sendResponse(ResponseCodes.OBEX_HTTP_UNAUTHORIZED, null);
mClosed = true;
requestHeader.mAuthResp = null;
return false;
}
requestHeader.mAuthResp = null;
}
if (requestHeader.mAuthChall != null) {
mParent.handleAuthChall(requestHeader);
// send the auhtResp to the client
replyHeader.mAuthResp = new byte[requestHeader.mAuthResp.length];
System.arraycopy(requestHeader.mAuthResp, 0, replyHeader.mAuthResp, 0,
replyHeader.mAuthResp.length);
requestHeader.mAuthResp = null;
requestHeader.mAuthChall = null;
}
if (mBodyBuffer.getLength() > 0) {
mPrivateInput.writeBytes(mBodyBuffer, 1);
}
}
}
return true;
} else {
return false;
}
}
|
diff --git a/src/test/java/com/sonyericsson/jenkins/plugins/externalresource/dispatcher/ReleaseRunListenerHudsonTest.java b/src/test/java/com/sonyericsson/jenkins/plugins/externalresource/dispatcher/ReleaseRunListenerHudsonTest.java
index 7b7a549..9339876 100644
--- a/src/test/java/com/sonyericsson/jenkins/plugins/externalresource/dispatcher/ReleaseRunListenerHudsonTest.java
+++ b/src/test/java/com/sonyericsson/jenkins/plugins/externalresource/dispatcher/ReleaseRunListenerHudsonTest.java
@@ -1,94 +1,93 @@
/*
* The MIT License
*
* Copyright 2011 Sony Ericsson Mobile Communications. All rights reserved.
*
* 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.
*/
package com.sonyericsson.jenkins.plugins.externalresource.dispatcher;
import com.sonyericsson.hudson.plugins.metadata.model.MetadataBuildAction;
import com.sonyericsson.hudson.plugins.metadata.model.MetadataNodeProperty;
import com.sonyericsson.hudson.plugins.metadata.model.values.MetadataValue;
import com.sonyericsson.hudson.plugins.metadata.model.values.TreeStructureUtil;
import com.sonyericsson.jenkins.plugins.externalresource.dispatcher.data.ExternalResource;
import com.sonyericsson.jenkins.plugins.externalresource.dispatcher.selection.AbstractDeviceSelection;
import com.sonyericsson.jenkins.plugins.externalresource.dispatcher.selection.StringDeviceSelection;
import hudson.model.Cause;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.labels.LabelAtom;
import hudson.slaves.DumbSlave;
import hudson.tasks.Mailer;
import hudson.tasks.Shell;
import org.jvnet.hudson.test.HudsonTestCase;
import java.util.Collections;
import java.util.LinkedList;
/**
* Hudson Tests for {@link ReleaseRunListener}.
*
* @author Robert Sandell <[email protected]>
*/
public class ReleaseRunListenerHudsonTest extends HudsonTestCase {
//CS IGNORE MagicNumber FOR NEXT 200 LINES. REASON: Test data.
private DumbSlave slave;
private MetadataNodeProperty property;
private ExternalResource resource;
@Override
protected void setUp() throws Exception {
super.setUp();
slave = this.createOnlineSlave(new LabelAtom("TEST"));
property = new MetadataNodeProperty((new LinkedList<MetadataValue>()));
slave.getNodeProperties().add(property);
resource = new ExternalResource("TestDevice", "description", "1", true,
new LinkedList<MetadataValue>());
TreeStructureUtil.addValue(resource, "yes", "description", "is", "matching");
TreeStructureUtil.addValue(property, resource, "attached-devices", "test");
Mailer.descriptor().setHudsonUrl(this.getURL().toString());
}
/**
* Happy Test for {@link ReleaseRunListener#onCompleted(hudson.model.AbstractBuild, hudson.model.TaskListener)}.
*
* @throws Exception if so.
*/
public void testOnCompleted() throws Exception {
FreeStyleProject project = this.createFreeStyleProject("testProject");
- Thread.sleep(1000); //TODO remove sleep when race condition is found and fixed.
project.setAssignedLabel(new LabelAtom("TEST"));
project.getBuildersList().add(new Shell("sleep 2"));
AbstractDeviceSelection selection = new StringDeviceSelection("is.matching", "yes");
project.addProperty(new SelectionCriteria(Collections.singletonList(selection)));
FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserCause()).get();
assertBuildStatusSuccess(build);
MetadataBuildAction metadata = build.getAction(MetadataBuildAction.class);
assertNotNull(metadata);
ExternalResource buildResource = (ExternalResource)TreeStructureUtil.getPath(metadata,
Constants.BUILD_LOCKED_RESOURCE_PATH);
assertNotNull(buildResource);
assertNull(buildResource.getLocked());
assertNull(resource.getLocked());
}
}
| true | true | public void testOnCompleted() throws Exception {
FreeStyleProject project = this.createFreeStyleProject("testProject");
Thread.sleep(1000); //TODO remove sleep when race condition is found and fixed.
project.setAssignedLabel(new LabelAtom("TEST"));
project.getBuildersList().add(new Shell("sleep 2"));
AbstractDeviceSelection selection = new StringDeviceSelection("is.matching", "yes");
project.addProperty(new SelectionCriteria(Collections.singletonList(selection)));
FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserCause()).get();
assertBuildStatusSuccess(build);
MetadataBuildAction metadata = build.getAction(MetadataBuildAction.class);
assertNotNull(metadata);
ExternalResource buildResource = (ExternalResource)TreeStructureUtil.getPath(metadata,
Constants.BUILD_LOCKED_RESOURCE_PATH);
assertNotNull(buildResource);
assertNull(buildResource.getLocked());
assertNull(resource.getLocked());
}
| public void testOnCompleted() throws Exception {
FreeStyleProject project = this.createFreeStyleProject("testProject");
project.setAssignedLabel(new LabelAtom("TEST"));
project.getBuildersList().add(new Shell("sleep 2"));
AbstractDeviceSelection selection = new StringDeviceSelection("is.matching", "yes");
project.addProperty(new SelectionCriteria(Collections.singletonList(selection)));
FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserCause()).get();
assertBuildStatusSuccess(build);
MetadataBuildAction metadata = build.getAction(MetadataBuildAction.class);
assertNotNull(metadata);
ExternalResource buildResource = (ExternalResource)TreeStructureUtil.getPath(metadata,
Constants.BUILD_LOCKED_RESOURCE_PATH);
assertNotNull(buildResource);
assertNull(buildResource.getLocked());
assertNull(resource.getLocked());
}
|
diff --git a/src/main/java/net/frontlinesms/smsdevice/internet/ClickatellInternetService.java b/src/main/java/net/frontlinesms/smsdevice/internet/ClickatellInternetService.java
index 729a543..10a39cb 100644
--- a/src/main/java/net/frontlinesms/smsdevice/internet/ClickatellInternetService.java
+++ b/src/main/java/net/frontlinesms/smsdevice/internet/ClickatellInternetService.java
@@ -1,313 +1,313 @@
/*
* FrontlineSMS <http://www.frontlinesms.com>
* Copyright 2007, 2008 kiwanja
*
* This file is part of FrontlineSMS.
*
* FrontlineSMS 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.
*
* FrontlineSMS 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 FrontlineSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package net.frontlinesms.smsdevice.internet;
import java.util.LinkedHashMap;
import net.frontlinesms.*;
import net.frontlinesms.data.domain.Message;
import net.frontlinesms.smsdevice.Provider;
import net.frontlinesms.smsdevice.properties.*;
import org.apache.log4j.Logger;
import org.smslib.ReceiveNotSupportedException;
import org.smslib.v3.*;
import org.smslib.v3.http.ClickatellHTTPGateway;
/**
* Implements the Clickatell Internet service.
*
* @author Carlos Eduardo Endler Genz
* @date 26/01/2009
*/
@Provider(name = "Clickatell", icon = "/icons/sms_http.png")
public class ClickatellInternetService extends AbstractSmsInternetService {
/** Prefix attached to every property name. */
private static final String PROPERTY_PREFIX = "smsdevice.internet.clickatell.";
protected static final String PROPERTY_USERNAME = PROPERTY_PREFIX + "username";
protected static final String PROPERTY_PASSWORD = PROPERTY_PREFIX + "password";
protected static final String PROPERTY_API = PROPERTY_PREFIX + "api";
protected static final String PROPERTY_FROM_MSISDN = PROPERTY_PREFIX + "from.msisdn";
protected static final String PROPERTY_SSL = PROPERTY_PREFIX + "ssl";
/** Logging object */
private static Logger LOG = Utils.getLogger(ClickatellInternetService.class);
private ClickatellHTTPGateway gateway;
private boolean connected;
private Service service;
/**
* Initialises the clickatell http gateway.
*/
private void initGateway() {
gateway = new ClickatellHTTPGateway(getIdentifier(), getApiId(), getUsername(), getPassword());
gateway.setOutbound(true);
gateway.setSecure(isEncrypted());
service = new Service();
service.addGateway(gateway);
}
/** @throws ReceiveNotSupportedException always, as {@link ClickatellInternetService} does not support receiving. */
protected void receiveSms() throws ReceiveNotSupportedException {
throw new ReceiveNotSupportedException();
}
/**
* Send an SMS message using this phone handler.
* @param message The message to be sent.
*/
protected void sendSmsDirect(Message message) {
LOG.trace("ENTER");
LOG.debug(Library.getLibraryDescription());
LOG.debug("Version: " + Library.getLibraryVersion());
LOG.debug("Sending [" + message.getTextContent() + "] to [" + message.getRecipientMsisdn() + "]");
OutboundMessage oMessage;
// FIXME if we are sending a binary message, we should create one of those here instead
if(message.isBinaryMessage()) {
oMessage = new OutboundMessage(message.getRecipientMsisdn(), message.getBinaryContent());
} else {
oMessage = new OutboundMessage(message.getRecipientMsisdn(), message.getTextContent());
}
- if(message.getRecipientSmsPort() != -1) {
+ if(message.getRecipientSmsPort() > 0) {
oMessage.setDstPort(message.getRecipientSmsPort());
}
String fromMsisdn = getMsisdn();
if (fromMsisdn != null && !fromMsisdn.equals("")) {
oMessage.setFrom(fromMsisdn);
}
try {
service.sendMessage(oMessage);
if (oMessage.getMessageStatus() == MessageStatuses.SENT) {
message.setDispatchDate(oMessage.getDispatchDate().getTime());
message.setStatus(Message.STATUS_SENT);
LOG.debug("Message [" + message + "] was sent!");
} else {
//message not sent
//failed to send
if (oMessage.getFailureCause() == FailureCauses.NO_CREDIT) {
setStatus(SmsInternetServiceStatus.LOW_CREDIT, Float.toString(gateway.queryBalance()));
creditLow();
}
message.setStatus(Message.STATUS_FAILED);
LOG.debug("Message [" + message + "] was not sent. Cause: [" + oMessage.getFailureCause() + "]");
}
} catch(Exception ex) {
message.setStatus(Message.STATUS_FAILED);
LOG.debug("Failed to send message [" + message + "]", ex);
LOG.info("Failed to send message");
} finally {
if (smsListener != null) {
smsListener.outgoingMessageEvent(this, message);
}
}
}
/**
* Starts the service. Normally we initialise the gateway.
*/
protected void init() throws SmsInternetServiceInitialisationException {
LOG.trace("ENTER");
initGateway();
try{
service.startService();
connected = true;
this.setStatus(SmsInternetServiceStatus.CONNECTED, null);
} catch (Throwable t) {
LOG.debug("Could not connect", t);
connected = false;
this.setStatus(SmsInternetServiceStatus.FAILED_TO_CONNECT, null);
throw new SmsInternetServiceInitialisationException(t);
}
LOG.trace("EXIT");
}
/**
* Stops the service showing the remaining credits
*/
public void creditLow() {
stopThisThing();
}
/**
* Forces the service to stop all gateways.
*/
protected void deinit() {
LOG.trace("ENTER");
try {
service.stopService();
} catch(Throwable t) {
// If anything goes wrong in the service stopping.
LOG.debug("Error stopping service", t);
}
connected = false;
this.setStatus(SmsInternetServiceStatus.DISCONNECTED, null);
LOG.trace("EXIT");
}
/**
* We do not currently support receive through Clickatell.
* @return <code>false</code>
*/
public boolean supportsReceive() {
return false;
}
/**
* Gets an identifier for this instance of {@link SmsInternetService}. Usually this
* will be the username used to login with the provider, or a similar identifer on
* the service.
*/
public String getIdentifier() {
return this.getUsername() + " (API " + this.getApiId() + ")";
}
/**
* Get the default properties for this class.
*/
public LinkedHashMap<String, Object> getPropertiesStructure() {
LinkedHashMap<String, Object> defaultSettings = new LinkedHashMap<String, Object>();
defaultSettings.put(PROPERTY_USERNAME, "");
defaultSettings.put(PROPERTY_PASSWORD, new PasswordString(""));
defaultSettings.put(PROPERTY_API, "");
defaultSettings.put(PROPERTY_FROM_MSISDN, new PhoneSection(""));
defaultSettings.put(PROPERTY_SSL, Boolean.FALSE);
defaultSettings.put(PROPERTY_USE_FOR_SENDING, Boolean.TRUE);
return defaultSettings;
}
/**
* Check if this service is encrypted using SSL.
*/
public boolean isEncrypted() {
return getPropertyValue(PROPERTY_SSL, Boolean.class);
}
/**
* Set this device to be used for receiving messages.
*/
public void setUseForReceiving(boolean use) {
throw new ReceiveNotSupportedException();
}
/**
* Set this device to be used for sending SMS messages.
*/
public void setUseForSending(boolean use) {
setProperty(PROPERTY_USE_FOR_SENDING, new Boolean(use));
}
/**
* @return The property value of {@value #PROPERTY_USERNAME}
*/
private String getUsername() {
return getPropertyValue(PROPERTY_USERNAME, String.class);
}
/**
* @return The property value of {@value #PROPERTY_PASSWORD}
*/
private String getPassword() {
return getPropertyValue(PROPERTY_PASSWORD, PasswordString.class).getValue();
}
/**
* @return The property value of {@value #PROPERTY_API}
*/
private String getApiId() {
return getPropertyValue(PROPERTY_API, String.class);
}
/**
* Check if this device is being used to receive SMS messages.
* Our implementation of Clickatell does not support SMS receiving.
*/
public boolean isUseForReceiving() {
return false;
}
/**
* Checks if this device is being used to send SMS messages.
*/
public boolean isUseForSending() {
return getPropertyValue(PROPERTY_USE_FOR_SENDING, Boolean.class);
}
/**
* Gets the MSISDN that numbers sent from this service will appear to be from.
*/
public String getMsisdn() {
return getPropertyValue(PROPERTY_FROM_MSISDN, PhoneSection.class).getValue();
}
/**
* Checks if the service is currently connected.
* TODO could rename this isLive().
* @return {@link #connected}.
*/
public boolean isConnected() {
verifyGatewayConnection();
return this.connected;
}
/**
* Verifies if the gateway is running okay or we need to restart it.
*/
private void verifyGatewayConnection() {
// Let's verify it is really connected
if (this.gateway != null
&& gateway.getGatewayStatus() != GatewayStatuses.OK) {
try {
if (gateway.getStarted()) {
this.setStatus(SmsInternetServiceStatus.TRYING_TO_RECONNECT, null);
service.stopService();
connected = false;
service.startService();
connected = true;
this.setStatus(SmsInternetServiceStatus.CONNECTED, null);
}
} catch (Throwable t) {
// We could not reconnect
LOG.error("Error reconnecting", t);
connected = false;
}
}
}
/**
* Check whether this device actually supports sending binary sms.
*/
public boolean isBinarySendingSupported() {
return true;
}
/**
* TODO this needs testing. If it works, this method can return true. If it doesn't work,
* this comment can be replaced with a more descriptive one.
*/
public boolean isUcs2SendingSupported() {
return false;
}
}
| true | true | protected void sendSmsDirect(Message message) {
LOG.trace("ENTER");
LOG.debug(Library.getLibraryDescription());
LOG.debug("Version: " + Library.getLibraryVersion());
LOG.debug("Sending [" + message.getTextContent() + "] to [" + message.getRecipientMsisdn() + "]");
OutboundMessage oMessage;
// FIXME if we are sending a binary message, we should create one of those here instead
if(message.isBinaryMessage()) {
oMessage = new OutboundMessage(message.getRecipientMsisdn(), message.getBinaryContent());
} else {
oMessage = new OutboundMessage(message.getRecipientMsisdn(), message.getTextContent());
}
if(message.getRecipientSmsPort() != -1) {
oMessage.setDstPort(message.getRecipientSmsPort());
}
String fromMsisdn = getMsisdn();
if (fromMsisdn != null && !fromMsisdn.equals("")) {
oMessage.setFrom(fromMsisdn);
}
try {
service.sendMessage(oMessage);
if (oMessage.getMessageStatus() == MessageStatuses.SENT) {
message.setDispatchDate(oMessage.getDispatchDate().getTime());
message.setStatus(Message.STATUS_SENT);
LOG.debug("Message [" + message + "] was sent!");
} else {
//message not sent
//failed to send
if (oMessage.getFailureCause() == FailureCauses.NO_CREDIT) {
setStatus(SmsInternetServiceStatus.LOW_CREDIT, Float.toString(gateway.queryBalance()));
creditLow();
}
message.setStatus(Message.STATUS_FAILED);
LOG.debug("Message [" + message + "] was not sent. Cause: [" + oMessage.getFailureCause() + "]");
}
} catch(Exception ex) {
message.setStatus(Message.STATUS_FAILED);
LOG.debug("Failed to send message [" + message + "]", ex);
LOG.info("Failed to send message");
} finally {
if (smsListener != null) {
smsListener.outgoingMessageEvent(this, message);
}
}
}
| protected void sendSmsDirect(Message message) {
LOG.trace("ENTER");
LOG.debug(Library.getLibraryDescription());
LOG.debug("Version: " + Library.getLibraryVersion());
LOG.debug("Sending [" + message.getTextContent() + "] to [" + message.getRecipientMsisdn() + "]");
OutboundMessage oMessage;
// FIXME if we are sending a binary message, we should create one of those here instead
if(message.isBinaryMessage()) {
oMessage = new OutboundMessage(message.getRecipientMsisdn(), message.getBinaryContent());
} else {
oMessage = new OutboundMessage(message.getRecipientMsisdn(), message.getTextContent());
}
if(message.getRecipientSmsPort() > 0) {
oMessage.setDstPort(message.getRecipientSmsPort());
}
String fromMsisdn = getMsisdn();
if (fromMsisdn != null && !fromMsisdn.equals("")) {
oMessage.setFrom(fromMsisdn);
}
try {
service.sendMessage(oMessage);
if (oMessage.getMessageStatus() == MessageStatuses.SENT) {
message.setDispatchDate(oMessage.getDispatchDate().getTime());
message.setStatus(Message.STATUS_SENT);
LOG.debug("Message [" + message + "] was sent!");
} else {
//message not sent
//failed to send
if (oMessage.getFailureCause() == FailureCauses.NO_CREDIT) {
setStatus(SmsInternetServiceStatus.LOW_CREDIT, Float.toString(gateway.queryBalance()));
creditLow();
}
message.setStatus(Message.STATUS_FAILED);
LOG.debug("Message [" + message + "] was not sent. Cause: [" + oMessage.getFailureCause() + "]");
}
} catch(Exception ex) {
message.setStatus(Message.STATUS_FAILED);
LOG.debug("Failed to send message [" + message + "]", ex);
LOG.info("Failed to send message");
} finally {
if (smsListener != null) {
smsListener.outgoingMessageEvent(this, message);
}
}
}
|
diff --git a/src/test/java/com/ning/billing/recurly/TestRecurlyClient.java b/src/test/java/com/ning/billing/recurly/TestRecurlyClient.java
index 18aba4f..57f638a 100644
--- a/src/test/java/com/ning/billing/recurly/TestRecurlyClient.java
+++ b/src/test/java/com/ning/billing/recurly/TestRecurlyClient.java
@@ -1,368 +1,369 @@
/*
* Copyright 2010-2012 Ning, Inc.
*
* Ning 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 com.ning.billing.recurly;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Minutes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.ning.billing.recurly.model.Account;
import com.ning.billing.recurly.model.Accounts;
import com.ning.billing.recurly.model.AddOn;
import com.ning.billing.recurly.model.BillingInfo;
import com.ning.billing.recurly.model.Coupon;
import com.ning.billing.recurly.model.Plan;
import com.ning.billing.recurly.model.Subscription;
import com.ning.billing.recurly.model.Subscriptions;
import com.ning.billing.recurly.model.Transaction;
import com.ning.billing.recurly.model.Transactions;
import static com.ning.billing.recurly.TestUtils.randomString;
public class TestRecurlyClient {
public static final String RECURLY_PAGE_SIZE = "recurly.page.size";
public static final String KILLBILL_PAYMENT_RECURLY_API_KEY = "killbill.payment.recurly.apiKey";
public static final String KILLBILL_PAYMENT_RECURLY_DEFAULT_CURRENCY_KEY = "killbill.payment.recurly.currency";
private static final Logger log = LoggerFactory.getLogger(TestRecurlyClient.class);
// Default to USD for all tests, which is expected to be supported by Recurly by default
// Multi Currency Support is an enterprise add-on
private static final String CURRENCY = System.getProperty(KILLBILL_PAYMENT_RECURLY_DEFAULT_CURRENCY_KEY, "USD");
private RecurlyClient recurlyClient;
@BeforeMethod(groups = "integration")
public void setUp() throws Exception {
//
final String apiKey = System.getProperty(KILLBILL_PAYMENT_RECURLY_API_KEY);
if (apiKey == null) {
Assert.fail("You need to set your Recurly api key to run integration tests:" +
" -Dkillbill.payment.recurly.apiKey=...");
}
recurlyClient = new RecurlyClient(apiKey);
recurlyClient.open();
}
@AfterMethod(groups = "integration")
public void tearDown() throws Exception {
//
recurlyClient.close();
}
@Test(groups = "integration")
public void testGetPageSize() throws Exception {
//
System.setProperty(RECURLY_PAGE_SIZE, "");
Assert.assertEquals(new Integer("20"), RecurlyClient.getPageSize());
System.setProperty(RECURLY_PAGE_SIZE, "350");
Assert.assertEquals(new Integer("350"), RecurlyClient.getPageSize());
}
@Test(groups = "integration")
public void testGetPageSizeGetParam() throws Exception {
//
System.setProperty(RECURLY_PAGE_SIZE, "");
Assert.assertEquals("per_page=20", RecurlyClient.getPageSizeGetParam());
System.setProperty(RECURLY_PAGE_SIZE, "350");
Assert.assertEquals("per_page=350", RecurlyClient.getPageSizeGetParam());
}
@Test(groups = "integration")
public void testCreateAccount() throws Exception {
//
final Account accountData = TestUtils.createRandomAccount();
final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo();
try {
//
final DateTime creationDateTime = new DateTime(DateTimeZone.UTC);
final Account account = recurlyClient.createAccount(accountData);
// Test account creation
Assert.assertNotNull(account);
Assert.assertEquals(accountData.getAccountCode(), account.getAccountCode());
Assert.assertEquals(accountData.getEmail(), account.getEmail());
Assert.assertEquals(accountData.getFirstName(), account.getFirstName());
Assert.assertEquals(accountData.getLastName(), account.getLastName());
Assert.assertEquals(accountData.getUsername(), account.getUsername());
Assert.assertEquals(accountData.getAcceptLanguage(), account.getAcceptLanguage());
Assert.assertEquals(accountData.getCompanyName(), account.getCompanyName());
// Verify we can serialize date times
Assert.assertEquals(Minutes.minutesBetween(account.getCreatedAt(), creationDateTime).getMinutes(), 0);
log.info("Created account: {}", account.getAccountCode());
// Test getting all
final Accounts retrievedAccounts = recurlyClient.getAccounts();
Assert.assertTrue(retrievedAccounts.size() > 0);
// Test an account lookup
final Account retrievedAccount = recurlyClient.getAccount(account.getAccountCode());
Assert.assertEquals(retrievedAccount, account);
// Create a BillingInfo
billingInfoData.setAccount(account);
final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData);
// Test BillingInfo creation
Assert.assertNotNull(billingInfo);
Assert.assertEquals(billingInfoData.getFirstName(), billingInfo.getFirstName());
Assert.assertEquals(billingInfoData.getLastName(), billingInfo.getLastName());
Assert.assertEquals(billingInfoData.getMonth(), billingInfo.getMonth());
Assert.assertEquals(billingInfoData.getYear(), billingInfo.getYear());
Assert.assertEquals(billingInfo.getCardType(), "Visa");
log.info("Added billing info: {}", billingInfo.getCardType());
// Test BillingInfo lookup
final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode());
Assert.assertEquals(retrievedBillingInfo, billingInfo);
} finally {
// Clean up
recurlyClient.clearBillingInfo(accountData.getAccountCode());
recurlyClient.closeAccount(accountData.getAccountCode());
}
}
@Test(groups = "integration")
public void testCreatePlan() throws Exception {
//
final Plan planData = TestUtils.createRandomPlan();
try {
// Create a plan
final DateTime creationDateTime = new DateTime(DateTimeZone.UTC);
final Plan plan = recurlyClient.createPlan(planData);
final Plan retPlan = recurlyClient.getPlan(plan.getPlanCode());
// test creation of plan
Assert.assertNotNull(plan);
Assert.assertEquals(retPlan, plan);
// Verify we can serialize date times
Assert.assertEquals(Minutes.minutesBetween(plan.getCreatedAt(), creationDateTime).getMinutes(), 0);
// Check that getting all the plans makes sense
Assert.assertTrue(recurlyClient.getPlans().size() > 0);
} finally {
// Delete the plan
recurlyClient.deletePlan(planData.getPlanCode());
// Check that we deleted it
final Plan retrievedPlan2 = recurlyClient.getPlan(planData.getPlanCode());
if (null != retrievedPlan2) {
Assert.fail("Failed to delete the Plan");
}
}
}
@Test(groups = "integration")
public void testCreateSubscriptions() throws Exception {
//
final Account accountData = TestUtils.createRandomAccount();
final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo();
final Plan planData = TestUtils.createRandomPlan();
try {
// Create a user
final Account account = recurlyClient.createAccount(accountData);
// Create BillingInfo
billingInfoData.setAccount(account);
final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData);
final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode());
// Create a plan
final Plan plan = recurlyClient.createPlan(planData);
// Subscribe the user to the plan
Subscription subscriptionData = new Subscription();
subscriptionData.setPlanCode(plan.getPlanCode());
subscriptionData.setAccount(accountData);
subscriptionData.setCurrency(CURRENCY);
+ subscriptionData.setUnitAmountInCents(1242);
final DateTime creationDateTime = new DateTime(DateTimeZone.UTC);
final Subscription subscription = recurlyClient.createSubscription(subscriptionData);
// Test subscription creation
Assert.assertNotNull(subscription);
Assert.assertEquals(subscription.getCurrency(), subscriptionData.getCurrency());
if (null == subscriptionData.getQuantity()) {
Assert.assertEquals(subscription.getQuantity(), new Integer(1));
} else {
Assert.assertEquals(subscription.getQuantity(), subscriptionData.getQuantity());
}
// Verify we can serialize date times
Assert.assertEquals(Minutes.minutesBetween(subscription.getActivatedAt(), creationDateTime).getMinutes(),
0);
log.info("Created subscription: {}", subscription.getUuid());
// Test lookup for subscription
Subscription sub1 = recurlyClient.getSubscription(subscription.getUuid());
Assert.assertNotNull(sub1);
Assert.assertEquals(sub1, subscription);
// Do a lookup for subs for given account
Subscriptions subs = recurlyClient.getAccountSubscriptions(accountData.getAccountCode());
// Check that the newly created sub is in the list
boolean found = false;
for (Subscription s : subs) {
if (s.getUuid().toString().equals(subscription.getUuid().toString())) {
found = true;
break;
}
}
if (!found) {
Assert.fail("Could not locate the subscription in the subscriptions associated with the account");
}
} finally {
// Clear up the BillingInfo
recurlyClient.clearBillingInfo(accountData.getAccountCode());
// Close the account
recurlyClient.closeAccount(accountData.getAccountCode());
// Delete the Plan
recurlyClient.deletePlan(planData.getPlanCode());
}
}
@Test(groups = "integration")
public void testCreateAndQueryTransactions() throws Exception {
//
final Account accountData = TestUtils.createRandomAccount();
final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo();
final Plan planData = TestUtils.createRandomPlan();
try {
// Create a user
final Account account = recurlyClient.createAccount(accountData);
// Create BillingInfo
billingInfoData.setAccount(account);
final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData);
final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode());
// Create a plan
final Plan plan = recurlyClient.createPlan(planData);
// Subscribe the user to the plan
Subscription subscriptionData = new Subscription();
subscriptionData.setPlanCode(plan.getPlanCode());
subscriptionData.setAccount(accountData);
subscriptionData.setCurrency(CURRENCY);
final Subscription subscription = recurlyClient.createSubscription(subscriptionData);
// Create a subscription
Transaction t = new Transaction();
accountData.setBillingInfo(billingInfoData);
t.setAccount(accountData);
t.setAmountInCents(10);
t.setCurrency(CURRENCY);
final DateTime creationDateTime = new DateTime(DateTimeZone.UTC);
Transaction createdT = recurlyClient.createTransaction(t);
// Test that the transaction created correctly
Assert.assertNotNull(createdT);
// Can't test for account equality yet as the account is only a ref and doesn't get mapped.
Assert.assertEquals(createdT.getAmountInCents(), t.getAmountInCents());
Assert.assertEquals(createdT.getCurrency(), t.getCurrency());
log.info("Created transaction: {}", createdT.getUuid());
// Test lookup on the transaction via the users account
Transactions trans = recurlyClient.getAccountTransactions(account.getAccountCode());
boolean found = false;
for (Transaction _t : trans) {
if (_t.getUuid().equals(createdT.getUuid())) {
found = true;
break;
}
}
if (!found) {
Assert.fail("Failed to locate the newly created transaction");
}
} finally {
// Clear up the BillingInfo
recurlyClient.clearBillingInfo(accountData.getAccountCode());
// Close the account
recurlyClient.closeAccount(accountData.getAccountCode());
// Delete the Plan
recurlyClient.deletePlan(planData.getPlanCode());
}
}
@Test(groups = "integration")
public void testAddons() throws Exception {
// Create a Plan
Plan planData = TestUtils.createRandomPlan();
AddOn addOn = TestUtils.createRandomAddOn();
try {
// Create an AddOn
Plan plan = recurlyClient.createPlan(planData);
AddOn addOnRecurly = recurlyClient.createPlanAddOn(plan.getPlanCode(), addOn);
// Test the creation
Assert.assertNotNull(addOnRecurly);
Assert.assertEquals(addOnRecurly.getAddOnCode(), addOn.getAddOnCode());
Assert.assertEquals(addOnRecurly.getName(), addOn.getName());
Assert.assertEquals(addOnRecurly.getUnitAmountInCents(), addOn.getUnitAmountInCents());
// Query for an AddOn
addOnRecurly = recurlyClient.getAddOn(plan.getPlanCode(), addOn.getAddOnCode());
// Check the 2 are the same
Assert.assertEquals(addOnRecurly.getAddOnCode(), addOn.getAddOnCode());
Assert.assertEquals(addOnRecurly.getName(), addOn.getName());
//Assert.assertEquals(addOnRecurly.getDefaultQuantity(), addOn.getDefaultQuantity());
//Assert.assertEquals(addOnRecurly.getDisplayQuantityOnHostedPage(), addOn.getDisplayQuantityOnHostedPage());
Assert.assertEquals(addOnRecurly.getUnitAmountInCents(), addOn.getUnitAmountInCents());
} finally {
// Delete an AddOn
recurlyClient.deleteAddOn(planData.getPlanCode(), addOn.getAddOnCode());
// Delete the plan
recurlyClient.deletePlan(planData.getPlanCode());
}
}
// todo: uncomment when the coupon code is fixed
//@Test(groups="integration")
public void testCreateCoupon() throws Exception {
// Create the coupon
Coupon c = new Coupon();
c.setName(randomString());
c.setCouponCode(randomString());
c.setDiscountType("percent");
c.setDiscountPercent("10");
// Save the coupon
Coupon coupon = recurlyClient.createCoupon(c);
if (null == coupon) {
Assert.fail("Returned coupon from Recurly was null");
}
// Tests
Assert.assertEquals(coupon.getName(), c.getName());
Assert.assertEquals(coupon.getCouponCode(), c.getCouponCode());
Assert.assertEquals(coupon.getDiscountType(), c.getDiscountType());
Assert.assertEquals(coupon.getDiscountPercent(), c.getDiscountPercent());
}
}
| true | true | public void testCreateSubscriptions() throws Exception {
//
final Account accountData = TestUtils.createRandomAccount();
final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo();
final Plan planData = TestUtils.createRandomPlan();
try {
// Create a user
final Account account = recurlyClient.createAccount(accountData);
// Create BillingInfo
billingInfoData.setAccount(account);
final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData);
final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode());
// Create a plan
final Plan plan = recurlyClient.createPlan(planData);
// Subscribe the user to the plan
Subscription subscriptionData = new Subscription();
subscriptionData.setPlanCode(plan.getPlanCode());
subscriptionData.setAccount(accountData);
subscriptionData.setCurrency(CURRENCY);
final DateTime creationDateTime = new DateTime(DateTimeZone.UTC);
final Subscription subscription = recurlyClient.createSubscription(subscriptionData);
// Test subscription creation
Assert.assertNotNull(subscription);
Assert.assertEquals(subscription.getCurrency(), subscriptionData.getCurrency());
if (null == subscriptionData.getQuantity()) {
Assert.assertEquals(subscription.getQuantity(), new Integer(1));
} else {
Assert.assertEquals(subscription.getQuantity(), subscriptionData.getQuantity());
}
// Verify we can serialize date times
Assert.assertEquals(Minutes.minutesBetween(subscription.getActivatedAt(), creationDateTime).getMinutes(),
0);
log.info("Created subscription: {}", subscription.getUuid());
// Test lookup for subscription
Subscription sub1 = recurlyClient.getSubscription(subscription.getUuid());
Assert.assertNotNull(sub1);
Assert.assertEquals(sub1, subscription);
// Do a lookup for subs for given account
Subscriptions subs = recurlyClient.getAccountSubscriptions(accountData.getAccountCode());
// Check that the newly created sub is in the list
boolean found = false;
for (Subscription s : subs) {
if (s.getUuid().toString().equals(subscription.getUuid().toString())) {
found = true;
break;
}
}
if (!found) {
Assert.fail("Could not locate the subscription in the subscriptions associated with the account");
}
} finally {
// Clear up the BillingInfo
recurlyClient.clearBillingInfo(accountData.getAccountCode());
// Close the account
recurlyClient.closeAccount(accountData.getAccountCode());
// Delete the Plan
recurlyClient.deletePlan(planData.getPlanCode());
}
}
| public void testCreateSubscriptions() throws Exception {
//
final Account accountData = TestUtils.createRandomAccount();
final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo();
final Plan planData = TestUtils.createRandomPlan();
try {
// Create a user
final Account account = recurlyClient.createAccount(accountData);
// Create BillingInfo
billingInfoData.setAccount(account);
final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData);
final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode());
// Create a plan
final Plan plan = recurlyClient.createPlan(planData);
// Subscribe the user to the plan
Subscription subscriptionData = new Subscription();
subscriptionData.setPlanCode(plan.getPlanCode());
subscriptionData.setAccount(accountData);
subscriptionData.setCurrency(CURRENCY);
subscriptionData.setUnitAmountInCents(1242);
final DateTime creationDateTime = new DateTime(DateTimeZone.UTC);
final Subscription subscription = recurlyClient.createSubscription(subscriptionData);
// Test subscription creation
Assert.assertNotNull(subscription);
Assert.assertEquals(subscription.getCurrency(), subscriptionData.getCurrency());
if (null == subscriptionData.getQuantity()) {
Assert.assertEquals(subscription.getQuantity(), new Integer(1));
} else {
Assert.assertEquals(subscription.getQuantity(), subscriptionData.getQuantity());
}
// Verify we can serialize date times
Assert.assertEquals(Minutes.minutesBetween(subscription.getActivatedAt(), creationDateTime).getMinutes(),
0);
log.info("Created subscription: {}", subscription.getUuid());
// Test lookup for subscription
Subscription sub1 = recurlyClient.getSubscription(subscription.getUuid());
Assert.assertNotNull(sub1);
Assert.assertEquals(sub1, subscription);
// Do a lookup for subs for given account
Subscriptions subs = recurlyClient.getAccountSubscriptions(accountData.getAccountCode());
// Check that the newly created sub is in the list
boolean found = false;
for (Subscription s : subs) {
if (s.getUuid().toString().equals(subscription.getUuid().toString())) {
found = true;
break;
}
}
if (!found) {
Assert.fail("Could not locate the subscription in the subscriptions associated with the account");
}
} finally {
// Clear up the BillingInfo
recurlyClient.clearBillingInfo(accountData.getAccountCode());
// Close the account
recurlyClient.closeAccount(accountData.getAccountCode());
// Delete the Plan
recurlyClient.deletePlan(planData.getPlanCode());
}
}
|
diff --git a/conan-ae-services/src/main/java/uk/ac/ebi/fgpt/conan/ae/lsf/AbstractLSFProcess.java b/conan-ae-services/src/main/java/uk/ac/ebi/fgpt/conan/ae/lsf/AbstractLSFProcess.java
index 44ceb8f..4239fbe 100644
--- a/conan-ae-services/src/main/java/uk/ac/ebi/fgpt/conan/ae/lsf/AbstractLSFProcess.java
+++ b/conan-ae-services/src/main/java/uk/ac/ebi/fgpt/conan/ae/lsf/AbstractLSFProcess.java
@@ -1,332 +1,332 @@
package uk.ac.ebi.fgpt.conan.ae.lsf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress2.exception.exceptions.AE2Exception;
import uk.ac.ebi.arrayexpress2.exception.manager.ExceptionManager;
import uk.ac.ebi.arrayexpress2.magetab.utils.CommandExecutionException;
import uk.ac.ebi.arrayexpress2.magetab.utils.ProcessRunner;
import uk.ac.ebi.fgpt.conan.ae.utils.ProcessUtils;
import uk.ac.ebi.fgpt.conan.model.ConanParameter;
import uk.ac.ebi.fgpt.conan.model.ConanProcess;
import uk.ac.ebi.fgpt.conan.properties.ConanProperties;
import uk.ac.ebi.fgpt.conan.service.exception.ProcessExecutionException;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
/**
* An abstract {@link uk.ac.ebi.fgpt.conan.model.ConanProcess} that is designed for dispatching operating system
* processes to the EBI LSF cluster for execution. You can tailor memory requirements by process.
*
* @author Tony Burdett
* @date 02-Nov-2010
*/
public abstract class AbstractLSFProcess implements ConanProcess {
public static final String BSUB_PATH = "/ebi/lsf/ebi/7.0/linux2.6-glibc2.3-x86_64/bin/bsub";
public static final int MONITOR_INTERVAL = 15;
private Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
/**
* Executes this process with the supplied parameters. This implementation executes a process by dispatching it to
* the EBI LSF cluster, and therefore it's <code>execute</code> method is split into two key parts, {@link
* #dispatch(String)} and a blocking call to an {@link LSFProcessListener} implementation to monitor the status of
* the underlying process and block until completion.
* <p/>
* The first part governs dispatch - after creation of the command, the command is wrapped inside a call to "bsub"
* (optionally with memory requirements specified) and executed as a native OS process. This process then runs
* independently of this JVM, so if Conan is shutdown the process will continue to run.
* <p/>
* The second part governs progress monitoring. This form of LSF submission is designed to write LSF output to a
* file, dictated by {@link #getLSFOutputFilePath(java.util.Map)}. This file is continuously monitored whilst this
* process is not interrupted until it detects content in this file compatible with a process exit.
* <p/>
* The dispatch part of the <code>execute()</code> operation cannot be interrupted - the native OS process should
* always be generated. However, the monitoring part can be interrupted and if so, Conan may shutdown without this
* process being terminated. Therefore, this process always checks for the presence of existing output files when
* executed. If an existing output file is found, this process goes into a "recovery" mode of operation. In this
* mode, dispatch is skipped and the process goes straight to monitoring, allowing JVM-independent "resumption" of
* processes.
* <p/>
* This method returns true if the task succeeds, false otherwise
*
* @param parameters maps parameters to the supplied values required in order to execute a process
* @return true if the execution completed successfully, false if not
* @throws ProcessExecutionException if the execution of the process caused an exception
* @throws IllegalArgumentException if an incorrect set of parameter values has been supplied, or if required
* values are null
* @throws InterruptedException if the execution of a process is interrupted, which causes it to terminate
* early
*/
public boolean execute(Map<ConanParameter, String> parameters)
throws IllegalArgumentException, ProcessExecutionException, InterruptedException {
getLog().debug("Executing an LSF process with parameters: " + parameters);
int memReq = getMemoryRequirement(parameters);
// get email address to use as backup in case process fails
String backupEmail = ConanProperties.getProperty("lsf.backup.email");
String bsubCommand;
if (memReq > 0) {
// generate actual bsub command from template
bsubCommand =
BSUB_PATH + " " +
"-M " + memReq + " " +
"-R \"rusage[mem=" + memReq + "]\" " +
"-q production " +
"-oo " + getLSFOutputFilePath(parameters) + " \"" +
"-u " + backupEmail + " " +
getCommand(parameters) + " " +
"2>&1\"";
}
else {
// generate actual bsub command from template excluding memory options
bsubCommand =
BSUB_PATH + " " +
"-q production " +
"-oo " + getLSFOutputFilePath(parameters) + " \"" +
- "-u " + backupEmail +
+ "-u " + backupEmail + " " +
getCommand(parameters) + " " +
"2>&1\"";
}
// cleanup any old copies of the output files and create a new one
String lsfOutputFilePath = getLSFOutputFilePath(parameters);
File lsfOutputFile = new File(lsfOutputFilePath);
// does an existing output file exist? if so, we need to go into recovery mode
boolean recoveryMode = lsfOutputFile.exists();
// only create our output file if we're not in recovery mode
if (!recoveryMode) {
getLog().debug("Creating " + lsfOutputFile.getAbsolutePath());
if (!ProcessUtils.createFiles(lsfOutputFile)) {
throw new ProcessExecutionException(
1,
"Unable to create LSF output file at " + lsfOutputFile.getAbsolutePath());
}
}
// set up monitoring of the lsfOutputFile
InvocationTrackingLSFProcessListener listener = new InvocationTrackingLSFProcessListener();
final LSFProcessAdapter adapter = new LSFProcessAdapter(lsfOutputFilePath, MONITOR_INTERVAL);
adapter.addLSFProcessListener(listener);
// process dispatch
boolean dispatched = false;
try {
// only dispatch if we're not in recovery mode
getLog().debug("In recovery mode? " + recoveryMode);
if (!recoveryMode) {
// dispatch the process to the cluster
getLog().debug("Dispatching command to LSF: " + bsubCommand);
dispatch(bsubCommand);
}
dispatched = true;
}
catch (CommandExecutionException e) {
// could not dispatch to LSF
getLog().error(
"Failed to dispatch job to the LSF cluster (exited with exit code " + e.getExitCode() + ")",
e);
ProcessExecutionException pex = new ProcessExecutionException(
e.getExitCode(),
"Failed to dispatch job to the LSF cluster (exited with exit code " + e.getExitCode() + ")",
e);
pex.setProcessOutput(e.getErrorOutput());
try {
pex.setProcessExecutionHost(InetAddress.getLocalHost().getHostName());
}
catch (UnknownHostException e1) {
getLog().debug("Unknown host", e1);
}
throw pex;
}
catch (IOException e) {
getLog().error("Failed to read output stream of native system process");
getLog().debug("IOException follows", e);
throw new ProcessExecutionException(1, "Failed to read output stream of native system process", e);
}
finally {
if (!dispatched) {
// this process didn't start, so delete output files to cleanup before throwing the exception
getLog().debug("Deleting " + lsfOutputFile.getAbsolutePath());
ProcessUtils.deleteFiles(lsfOutputFile);
}
}
// process exit value, initialise to -1
int exitValue = -1;
// process monitoring
try {
getLog().debug("Monitoring process, waiting for completion");
exitValue = listener.waitFor();
getLog().debug("LSF Process completed with exit value " + exitValue);
if (exitValue == 0) {
return true;
}
else {
AE2Exception cause = ExceptionManager.getException(getComponentName(), exitValue);
String message = "Failed at " + getName() + ": " + cause.getDefaultMessage();
getLog().debug("Generating ProcessExecutionException...\n" +
"exitValue = " + exitValue + ",\n" +
"message = " + message + ",\n" +
"cause = " + cause.getClass().getSimpleName());
ProcessExecutionException pex = new ProcessExecutionException(exitValue, message, cause);
pex.setProcessOutput(adapter.getProcessOutput());
pex.setProcessExecutionHost(adapter.getProcessExecutionHost());
throw pex;
}
}
finally {
// this process DID start, so only delete output files to cleanup if the process actually exited,
// and wasn't e.g. interrupted prior to completion
if (exitValue != -1) {
getLog().debug("Deleting " + lsfOutputFile.getAbsolutePath());
ProcessUtils.deleteFiles(lsfOutputFile);
}
}
}
/**
* Creates a native system process from the given command. This command should be an LSF dispatch command of the
* form "bsub -oo <file> -q production "<my command>". The result is an array of strings, where each element
* represents one line of stdout or stderr for the executed native process. Usually, this should just be a simple
* output indicating the machine your process was sent to
*
* @param lsfCommand the LSF command to execute
* @return the stdout.stderr of the process
* @throws CommandExecutionException if the process exits with a failure condition. This exception wraps the error
* output and the process exit code.
* @throws IOException if the stdout or stderr of the process could not be read
*/
protected String[] dispatch(String lsfCommand) throws CommandExecutionException, IOException {
getLog().debug("Issuing command: [" + lsfCommand + "]");
ProcessRunner runner = new ProcessRunner();
runner.redirectStderr(true);
String[] output = runner.runCommmand(lsfCommand);
if (output.length > 0) {
getLog().debug("Response from command [" + lsfCommand + "]: " +
output.length + " lines, first line was " + output[0]);
}
return output;
}
/**
* Returns the memory requirements, in MB, for the LSF process that will be dispatched. By default, this is not
* used and therefore processes run with environment defaults (8GB for the EBI LSF at the time of writing). You can
* override this for more memory hungry (or indeed, less memory hungry!) jobs.
*
* @param parameterStringMap the parameters supplied to this process, as this may potentially alter the
* requirements
* @return the number of MB required to run this process
*/
protected int getMemoryRequirement(Map<ConanParameter, String> parameterStringMap) {
return -1;
}
/**
* Returns the name of this component that this process implements, if any. This is designed to allow registration
* of error codes to process from ArrayExpress, meaning we can lookp the correct {@link AE2Exception} given the
* component name that the process implements. If this method returns any value apart from {@link
* LSFProcess#UNSPECIFIED_COMPONENT_NAME}, the exit code of the process must be used to extract information about
* the failure condition and a user-meaningful message displayed indicating the error.
*
* @return the name of the AE2 component this process implements, or LSFProcess.UNSPECIFIED_COMPONENT_NAME if
* something else.
*/
protected abstract String getComponentName();
/**
* The script to run on the LSF. This does not need to be a bsub command, just the commands you wish this
* ConanProcess to execute. Often, this will simply be the script to run
*
* @param parameters the parameters supplied to this ConanProcess
* @return the commands to run on the LSF
* @throws IllegalArgumentException if the parameters supplied were invalid
*/
protected abstract String getCommand(Map<ConanParameter, String> parameters)
throws IllegalArgumentException;
/**
* The output file LSF output should be written to. Each invocation of a ConanProcess with the given Conan
* parameter values should read/write to the same file to ensure it is possible to recover monitoring for
* re-executed tasks.
*
* @param parameters the parameters supplied to this ConanProcess
* @return the File that the LSF process should write it's output to
* @throws IllegalArgumentException if the parameters supplied were invalid
*/
protected abstract String getLSFOutputFilePath(Map<ConanParameter, String> parameters)
throws IllegalArgumentException;
/**
* An {@link LSFProcessListener} that encapsulates the state of each invocation of a process and updates flags for
* completion and success. Processes using this listener implementation can block on {@link #waitFor()}, which only
* returns once the LSF process being listened to is complete.
*/
private class InvocationTrackingLSFProcessListener implements LSFProcessListener {
private boolean complete;
private int exitValue;
private InvocationTrackingLSFProcessListener() {
complete = false;
exitValue = -1;
}
public void processComplete(LSFProcessEvent evt) {
getLog().debug("File finished writing, process exit value was " + evt.getExitValue());
exitValue = evt.getExitValue();
complete = true;
synchronized (this) {
notifyAll();
}
}
public void processUpdate(LSFProcessEvent evt) {
// do nothing, not yet finished
getLog().debug("File was modified");
synchronized (this) {
notifyAll();
}
}
public void processError(LSFProcessEvent evt) {
// something went wrong
getLog().debug("File was deleted by an external process");
exitValue = 1;
complete = true;
synchronized (this) {
notifyAll();
}
}
/**
* Returns the success of the LSFProcess being listened to, only once complete. This method blocks until
* completion or an interruption occurs.
*
* @return the exit value of the underlying process
* @throws InterruptedException if the thread was interrupted whilst waiting
*/
public int waitFor() throws InterruptedException {
while (!complete) {
synchronized (this) {
wait();
}
}
getLog().debug("Process completed: exitValue = " + exitValue);
return exitValue;
}
}
}
| true | true | public boolean execute(Map<ConanParameter, String> parameters)
throws IllegalArgumentException, ProcessExecutionException, InterruptedException {
getLog().debug("Executing an LSF process with parameters: " + parameters);
int memReq = getMemoryRequirement(parameters);
// get email address to use as backup in case process fails
String backupEmail = ConanProperties.getProperty("lsf.backup.email");
String bsubCommand;
if (memReq > 0) {
// generate actual bsub command from template
bsubCommand =
BSUB_PATH + " " +
"-M " + memReq + " " +
"-R \"rusage[mem=" + memReq + "]\" " +
"-q production " +
"-oo " + getLSFOutputFilePath(parameters) + " \"" +
"-u " + backupEmail + " " +
getCommand(parameters) + " " +
"2>&1\"";
}
else {
// generate actual bsub command from template excluding memory options
bsubCommand =
BSUB_PATH + " " +
"-q production " +
"-oo " + getLSFOutputFilePath(parameters) + " \"" +
"-u " + backupEmail +
getCommand(parameters) + " " +
"2>&1\"";
}
// cleanup any old copies of the output files and create a new one
String lsfOutputFilePath = getLSFOutputFilePath(parameters);
File lsfOutputFile = new File(lsfOutputFilePath);
// does an existing output file exist? if so, we need to go into recovery mode
boolean recoveryMode = lsfOutputFile.exists();
// only create our output file if we're not in recovery mode
if (!recoveryMode) {
getLog().debug("Creating " + lsfOutputFile.getAbsolutePath());
if (!ProcessUtils.createFiles(lsfOutputFile)) {
throw new ProcessExecutionException(
1,
"Unable to create LSF output file at " + lsfOutputFile.getAbsolutePath());
}
}
// set up monitoring of the lsfOutputFile
InvocationTrackingLSFProcessListener listener = new InvocationTrackingLSFProcessListener();
final LSFProcessAdapter adapter = new LSFProcessAdapter(lsfOutputFilePath, MONITOR_INTERVAL);
adapter.addLSFProcessListener(listener);
// process dispatch
boolean dispatched = false;
try {
// only dispatch if we're not in recovery mode
getLog().debug("In recovery mode? " + recoveryMode);
if (!recoveryMode) {
// dispatch the process to the cluster
getLog().debug("Dispatching command to LSF: " + bsubCommand);
dispatch(bsubCommand);
}
dispatched = true;
}
catch (CommandExecutionException e) {
// could not dispatch to LSF
getLog().error(
"Failed to dispatch job to the LSF cluster (exited with exit code " + e.getExitCode() + ")",
e);
ProcessExecutionException pex = new ProcessExecutionException(
e.getExitCode(),
"Failed to dispatch job to the LSF cluster (exited with exit code " + e.getExitCode() + ")",
e);
pex.setProcessOutput(e.getErrorOutput());
try {
pex.setProcessExecutionHost(InetAddress.getLocalHost().getHostName());
}
catch (UnknownHostException e1) {
getLog().debug("Unknown host", e1);
}
throw pex;
}
catch (IOException e) {
getLog().error("Failed to read output stream of native system process");
getLog().debug("IOException follows", e);
throw new ProcessExecutionException(1, "Failed to read output stream of native system process", e);
}
finally {
if (!dispatched) {
// this process didn't start, so delete output files to cleanup before throwing the exception
getLog().debug("Deleting " + lsfOutputFile.getAbsolutePath());
ProcessUtils.deleteFiles(lsfOutputFile);
}
}
// process exit value, initialise to -1
int exitValue = -1;
// process monitoring
try {
getLog().debug("Monitoring process, waiting for completion");
exitValue = listener.waitFor();
getLog().debug("LSF Process completed with exit value " + exitValue);
if (exitValue == 0) {
return true;
}
else {
AE2Exception cause = ExceptionManager.getException(getComponentName(), exitValue);
String message = "Failed at " + getName() + ": " + cause.getDefaultMessage();
getLog().debug("Generating ProcessExecutionException...\n" +
"exitValue = " + exitValue + ",\n" +
"message = " + message + ",\n" +
"cause = " + cause.getClass().getSimpleName());
ProcessExecutionException pex = new ProcessExecutionException(exitValue, message, cause);
pex.setProcessOutput(adapter.getProcessOutput());
pex.setProcessExecutionHost(adapter.getProcessExecutionHost());
throw pex;
}
}
finally {
// this process DID start, so only delete output files to cleanup if the process actually exited,
// and wasn't e.g. interrupted prior to completion
if (exitValue != -1) {
getLog().debug("Deleting " + lsfOutputFile.getAbsolutePath());
ProcessUtils.deleteFiles(lsfOutputFile);
}
}
}
| public boolean execute(Map<ConanParameter, String> parameters)
throws IllegalArgumentException, ProcessExecutionException, InterruptedException {
getLog().debug("Executing an LSF process with parameters: " + parameters);
int memReq = getMemoryRequirement(parameters);
// get email address to use as backup in case process fails
String backupEmail = ConanProperties.getProperty("lsf.backup.email");
String bsubCommand;
if (memReq > 0) {
// generate actual bsub command from template
bsubCommand =
BSUB_PATH + " " +
"-M " + memReq + " " +
"-R \"rusage[mem=" + memReq + "]\" " +
"-q production " +
"-oo " + getLSFOutputFilePath(parameters) + " \"" +
"-u " + backupEmail + " " +
getCommand(parameters) + " " +
"2>&1\"";
}
else {
// generate actual bsub command from template excluding memory options
bsubCommand =
BSUB_PATH + " " +
"-q production " +
"-oo " + getLSFOutputFilePath(parameters) + " \"" +
"-u " + backupEmail + " " +
getCommand(parameters) + " " +
"2>&1\"";
}
// cleanup any old copies of the output files and create a new one
String lsfOutputFilePath = getLSFOutputFilePath(parameters);
File lsfOutputFile = new File(lsfOutputFilePath);
// does an existing output file exist? if so, we need to go into recovery mode
boolean recoveryMode = lsfOutputFile.exists();
// only create our output file if we're not in recovery mode
if (!recoveryMode) {
getLog().debug("Creating " + lsfOutputFile.getAbsolutePath());
if (!ProcessUtils.createFiles(lsfOutputFile)) {
throw new ProcessExecutionException(
1,
"Unable to create LSF output file at " + lsfOutputFile.getAbsolutePath());
}
}
// set up monitoring of the lsfOutputFile
InvocationTrackingLSFProcessListener listener = new InvocationTrackingLSFProcessListener();
final LSFProcessAdapter adapter = new LSFProcessAdapter(lsfOutputFilePath, MONITOR_INTERVAL);
adapter.addLSFProcessListener(listener);
// process dispatch
boolean dispatched = false;
try {
// only dispatch if we're not in recovery mode
getLog().debug("In recovery mode? " + recoveryMode);
if (!recoveryMode) {
// dispatch the process to the cluster
getLog().debug("Dispatching command to LSF: " + bsubCommand);
dispatch(bsubCommand);
}
dispatched = true;
}
catch (CommandExecutionException e) {
// could not dispatch to LSF
getLog().error(
"Failed to dispatch job to the LSF cluster (exited with exit code " + e.getExitCode() + ")",
e);
ProcessExecutionException pex = new ProcessExecutionException(
e.getExitCode(),
"Failed to dispatch job to the LSF cluster (exited with exit code " + e.getExitCode() + ")",
e);
pex.setProcessOutput(e.getErrorOutput());
try {
pex.setProcessExecutionHost(InetAddress.getLocalHost().getHostName());
}
catch (UnknownHostException e1) {
getLog().debug("Unknown host", e1);
}
throw pex;
}
catch (IOException e) {
getLog().error("Failed to read output stream of native system process");
getLog().debug("IOException follows", e);
throw new ProcessExecutionException(1, "Failed to read output stream of native system process", e);
}
finally {
if (!dispatched) {
// this process didn't start, so delete output files to cleanup before throwing the exception
getLog().debug("Deleting " + lsfOutputFile.getAbsolutePath());
ProcessUtils.deleteFiles(lsfOutputFile);
}
}
// process exit value, initialise to -1
int exitValue = -1;
// process monitoring
try {
getLog().debug("Monitoring process, waiting for completion");
exitValue = listener.waitFor();
getLog().debug("LSF Process completed with exit value " + exitValue);
if (exitValue == 0) {
return true;
}
else {
AE2Exception cause = ExceptionManager.getException(getComponentName(), exitValue);
String message = "Failed at " + getName() + ": " + cause.getDefaultMessage();
getLog().debug("Generating ProcessExecutionException...\n" +
"exitValue = " + exitValue + ",\n" +
"message = " + message + ",\n" +
"cause = " + cause.getClass().getSimpleName());
ProcessExecutionException pex = new ProcessExecutionException(exitValue, message, cause);
pex.setProcessOutput(adapter.getProcessOutput());
pex.setProcessExecutionHost(adapter.getProcessExecutionHost());
throw pex;
}
}
finally {
// this process DID start, so only delete output files to cleanup if the process actually exited,
// and wasn't e.g. interrupted prior to completion
if (exitValue != -1) {
getLog().debug("Deleting " + lsfOutputFile.getAbsolutePath());
ProcessUtils.deleteFiles(lsfOutputFile);
}
}
}
|
diff --git a/solr/src/common/org/apache/solr/common/SolrDocumentList.java b/solr/src/common/org/apache/solr/common/SolrDocumentList.java
index 9aca8d778..a7f3d4b15 100644
--- a/solr/src/common/org/apache/solr/common/SolrDocumentList.java
+++ b/solr/src/common/org/apache/solr/common/SolrDocumentList.java
@@ -1,68 +1,68 @@
/**
* 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.solr.common;
import java.util.ArrayList;
/**
* Represent a list of SolrDocuments returned from a search. This includes
* position and offset information.
*
* @version $Id$
* @since solr 1.3
*/
public class SolrDocumentList extends ArrayList<SolrDocument>
{
private long numFound = 0;
private long start = 0;
private Float maxScore = null;
public Float getMaxScore() {
return maxScore;
}
public void setMaxScore(Float maxScore) {
this.maxScore = maxScore;
}
public long getNumFound() {
return numFound;
}
public void setNumFound(long numFound) {
this.numFound = numFound;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
@Override
public String toString() {
return "{numFound="+numFound
+",start="+start
- + (maxScore!=null ? ""+maxScore : "")
+ + (maxScore!=null ? ",maxScore="+maxScore : "")
+",docs="+super.toString()
+"}";
}
}
| true | true | public String toString() {
return "{numFound="+numFound
+",start="+start
+ (maxScore!=null ? ""+maxScore : "")
+",docs="+super.toString()
+"}";
}
| public String toString() {
return "{numFound="+numFound
+",start="+start
+ (maxScore!=null ? ",maxScore="+maxScore : "")
+",docs="+super.toString()
+"}";
}
|
diff --git a/hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java b/hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java
index d8bcb41..fbf32df 100644
--- a/hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java
+++ b/hazeltask-core/src/main/java/com/hazeltask/executor/task/HazeltaskTask.java
@@ -1,158 +1,161 @@
package com.hazeltask.executor.task;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;
import java.util.UUID;
import java.util.concurrent.Callable;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.nio.SerializationHelper;
import com.hazeltask.core.concurrent.collections.tracked.TrackCreated;
import com.yammer.metrics.core.Timer;
import com.yammer.metrics.core.TimerContext;
/**
* This class wraps a runnable and provides other metadata we need to searching work items
* in the distributed map.
*
* @author jclawson
*
*/
public class HazeltaskTask< G extends Serializable>
implements Runnable, Task<G>, HazelcastInstanceAware, TrackCreated {
private static final long serialVersionUID = 1L;
private Runnable runTask;
private Callable<?> callTask;
private long createdAtMillis;
private UUID id;
private G group;
private int submissionCount;
private transient HazelcastInstance hazelcastInstance;
private transient Timer taskExecutedTimer;
private volatile transient Object result;
private volatile transient Exception e;
//required for DataSerializable
protected HazeltaskTask(){}
public HazeltaskTask(UUID id, G group, Runnable task){
this.runTask = task;
this.id = id;
this.group = group;
createdAtMillis = System.currentTimeMillis();
this.submissionCount = 1;
}
public HazeltaskTask(UUID id, G group, Callable<?> task){
this.callTask = task;
this.id = id;
this.group = group;
createdAtMillis = System.currentTimeMillis();
this.submissionCount = 1;
}
public void setSubmissionCount(int submissionCount){
this.submissionCount = submissionCount;
}
public int getSubmissionCount(){
return this.submissionCount;
}
public void updateCreatedTime(){
this.createdAtMillis = System.currentTimeMillis();
}
public G getGroup() {
return group;
}
public Object getResult() {
return result;
}
public Exception getException() {
return e;
}
public long getTimeCreated(){
return createdAtMillis;
}
public void run() {
- TimerContext ctx = taskExecutedTimer.time();
+ TimerContext ctx = null;
+ if(taskExecutedTimer != null)
+ ctx = taskExecutedTimer.time();
try {
if(callTask != null) {
if(callTask instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance);
}
this.result = callTask.call();
} else {
if(runTask instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance);
}
runTask.run();
}
} catch (Exception t) {
this.e = t;
} finally {
- ctx.stop();
+ if(ctx != null)
+ ctx.stop();
}
}
public Runnable getInnerRunnable() {
return this.runTask;
}
public Callable<?> getInnerCallable() {
return this.callTask;
}
@Override
public UUID getId() {
return id;
}
@Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
@Override
public void writeData(DataOutput out) throws IOException {
out.writeLong(id.getMostSignificantBits());
out.writeLong(id.getLeastSignificantBits());
SerializationHelper.writeObject(out, group);
SerializationHelper.writeObject(out, runTask);
SerializationHelper.writeObject(out, callTask);
out.writeLong(createdAtMillis);
out.writeInt(submissionCount);
}
@SuppressWarnings("unchecked")
@Override
public void readData(DataInput in) throws IOException {
long m = in.readLong();
long l = in.readLong();
id = new UUID(m, l);
group = (G) SerializationHelper.readObject(in);
runTask = (Runnable) SerializationHelper.readObject(in);
callTask = (Callable<?>) SerializationHelper.readObject(in);
createdAtMillis = in.readLong();
submissionCount = in.readInt();
}
public void setExecutionTimer(Timer taskExecutedTimer) {
this.taskExecutedTimer = taskExecutedTimer;
}
}
| false | true | public void run() {
TimerContext ctx = taskExecutedTimer.time();
try {
if(callTask != null) {
if(callTask instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance);
}
this.result = callTask.call();
} else {
if(runTask instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance);
}
runTask.run();
}
} catch (Exception t) {
this.e = t;
} finally {
ctx.stop();
}
}
| public void run() {
TimerContext ctx = null;
if(taskExecutedTimer != null)
ctx = taskExecutedTimer.time();
try {
if(callTask != null) {
if(callTask instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) callTask).setHazelcastInstance(hazelcastInstance);
}
this.result = callTask.call();
} else {
if(runTask instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) runTask).setHazelcastInstance(hazelcastInstance);
}
runTask.run();
}
} catch (Exception t) {
this.e = t;
} finally {
if(ctx != null)
ctx.stop();
}
}
|
diff --git a/sventon/src/main/java/de/berlios/sventon/web/command/ConfigCommandValidator.java b/sventon/src/main/java/de/berlios/sventon/web/command/ConfigCommandValidator.java
index 06bcd65b..cd7f3c0a 100644
--- a/sventon/src/main/java/de/berlios/sventon/web/command/ConfigCommandValidator.java
+++ b/sventon/src/main/java/de/berlios/sventon/web/command/ConfigCommandValidator.java
@@ -1,135 +1,135 @@
/*
* ====================================================================
* Copyright (c) 2005-2008 sventon project. All rights reserved.
*
* This software is licensed as described in the file LICENSE, which
* you should have received as part of this distribution. The terms
* are also available at http://sventon.berlios.de.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package de.berlios.sventon.web.command;
import de.berlios.sventon.appl.Instance;
import de.berlios.sventon.appl.InstanceConfiguration;
import de.berlios.sventon.repository.RepositoryFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.io.SVNRepository;
/**
* ConfigCommandValidator.
*
* @author [email protected]
* @author [email protected]
*/
public final class ConfigCommandValidator implements Validator {
/**
* Logger for this class and subclasses
*/
private final Log logger = LogFactory.getLog(getClass());
/**
* Controls whether repository connection should be tested or not.
*/
private boolean testConnection = true;
/**
* The repository factory.
*/
private RepositoryFactory repositoryFactory;
/**
* Constructor.
*/
public ConfigCommandValidator() {
}
/**
* Constructor for testing purposes.
*
* @param testConnection If <tt>false</tt> repository
* connection will not be tested.
*/
protected ConfigCommandValidator(final boolean testConnection) {
this.testConnection = testConnection;
}
/**
* {@inheritDoc}
*/
public boolean supports(final Class clazz) {
return clazz.equals(ConfigCommand.class);
}
/**
* Sets the repository factory instance.
*
* @param repositoryFactory Factory.
*/
public void setRepositoryFactory(final RepositoryFactory repositoryFactory) {
this.repositoryFactory = repositoryFactory;
}
/**
* {@inheritDoc}
*/
public void validate(final Object obj, final Errors errors) {
final ConfigCommand command = (ConfigCommand) obj;
// Validate 'repository instance name'
final String instanceName = command.getName();
if (instanceName != null) {
if (!Instance.isValidName(instanceName)) {
final String msg = "Name must be in lower case a-z and/or 0-9";
logger.warn(msg);
errors.rejectValue("name", "config.error.illegal-name", msg);
}
}
// Validate 'repositoryUrl', 'username' and 'password'
final String repositoryUrl = command.getRepositoryUrl();
if (repositoryUrl != null) {
final String trimmedURL = repositoryUrl.trim();
SVNURL url = null;
try {
url = SVNURL.parseURIDecoded(trimmedURL);
} catch (SVNException ex) {
- final String msg = "Invalid repository URL: " + repositoryUrl;
+ final String msg = "Invalid repository URL!";
logger.warn(msg);
errors.rejectValue("repositoryUrl", "config.error.illegal-url", msg);
}
if (url != null && testConnection) {
logger.info("Testing repository connection");
final InstanceConfiguration configuration = new InstanceConfiguration(instanceName);
configuration.setRepositoryUrl(trimmedURL);
configuration.setUid(command.isEnableAccessControl() ?
command.getConnectionTestUid() : command.getUid());
configuration.setPwd(command.isEnableAccessControl() ?
command.getConnectionTestPwd() : command.getPwd());
SVNRepository repository = null;
try {
repository = repositoryFactory.getRepository(configuration.getSVNURL(), configuration.getUid(), configuration.getPwd());
repository.testConnection();
} catch (SVNException e) {
logger.warn("Unable to connect to repository", e);
errors.rejectValue("repositoryUrl", "config.error.connection-error",
"Unable to connect to repository. Check URL, user name and password.");
} finally {
if (repository != null) {
repository.closeSession();
}
}
}
}
}
}
| true | true | public void validate(final Object obj, final Errors errors) {
final ConfigCommand command = (ConfigCommand) obj;
// Validate 'repository instance name'
final String instanceName = command.getName();
if (instanceName != null) {
if (!Instance.isValidName(instanceName)) {
final String msg = "Name must be in lower case a-z and/or 0-9";
logger.warn(msg);
errors.rejectValue("name", "config.error.illegal-name", msg);
}
}
// Validate 'repositoryUrl', 'username' and 'password'
final String repositoryUrl = command.getRepositoryUrl();
if (repositoryUrl != null) {
final String trimmedURL = repositoryUrl.trim();
SVNURL url = null;
try {
url = SVNURL.parseURIDecoded(trimmedURL);
} catch (SVNException ex) {
final String msg = "Invalid repository URL: " + repositoryUrl;
logger.warn(msg);
errors.rejectValue("repositoryUrl", "config.error.illegal-url", msg);
}
if (url != null && testConnection) {
logger.info("Testing repository connection");
final InstanceConfiguration configuration = new InstanceConfiguration(instanceName);
configuration.setRepositoryUrl(trimmedURL);
configuration.setUid(command.isEnableAccessControl() ?
command.getConnectionTestUid() : command.getUid());
configuration.setPwd(command.isEnableAccessControl() ?
command.getConnectionTestPwd() : command.getPwd());
SVNRepository repository = null;
try {
repository = repositoryFactory.getRepository(configuration.getSVNURL(), configuration.getUid(), configuration.getPwd());
repository.testConnection();
} catch (SVNException e) {
logger.warn("Unable to connect to repository", e);
errors.rejectValue("repositoryUrl", "config.error.connection-error",
"Unable to connect to repository. Check URL, user name and password.");
} finally {
if (repository != null) {
repository.closeSession();
}
}
}
}
}
| public void validate(final Object obj, final Errors errors) {
final ConfigCommand command = (ConfigCommand) obj;
// Validate 'repository instance name'
final String instanceName = command.getName();
if (instanceName != null) {
if (!Instance.isValidName(instanceName)) {
final String msg = "Name must be in lower case a-z and/or 0-9";
logger.warn(msg);
errors.rejectValue("name", "config.error.illegal-name", msg);
}
}
// Validate 'repositoryUrl', 'username' and 'password'
final String repositoryUrl = command.getRepositoryUrl();
if (repositoryUrl != null) {
final String trimmedURL = repositoryUrl.trim();
SVNURL url = null;
try {
url = SVNURL.parseURIDecoded(trimmedURL);
} catch (SVNException ex) {
final String msg = "Invalid repository URL!";
logger.warn(msg);
errors.rejectValue("repositoryUrl", "config.error.illegal-url", msg);
}
if (url != null && testConnection) {
logger.info("Testing repository connection");
final InstanceConfiguration configuration = new InstanceConfiguration(instanceName);
configuration.setRepositoryUrl(trimmedURL);
configuration.setUid(command.isEnableAccessControl() ?
command.getConnectionTestUid() : command.getUid());
configuration.setPwd(command.isEnableAccessControl() ?
command.getConnectionTestPwd() : command.getPwd());
SVNRepository repository = null;
try {
repository = repositoryFactory.getRepository(configuration.getSVNURL(), configuration.getUid(), configuration.getPwd());
repository.testConnection();
} catch (SVNException e) {
logger.warn("Unable to connect to repository", e);
errors.rejectValue("repositoryUrl", "config.error.connection-error",
"Unable to connect to repository. Check URL, user name and password.");
} finally {
if (repository != null) {
repository.closeSession();
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.