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/hokan_ng-common/src/main/java/com/freakz/hokan_ng/common/engine/HokanCore.java b/hokan_ng-common/src/main/java/com/freakz/hokan_ng/common/engine/HokanCore.java
index 2221715..4ed40f9 100755
--- a/hokan_ng-common/src/main/java/com/freakz/hokan_ng/common/engine/HokanCore.java
+++ b/hokan_ng-common/src/main/java/com/freakz/hokan_ng/common/engine/HokanCore.java
@@ -1,471 +1,475 @@
package com.freakz.hokan_ng.common.engine;
import com.freakz.hokan_ng.common.entity.Channel;
import com.freakz.hokan_ng.common.entity.ChannelState;
import com.freakz.hokan_ng.common.entity.IrcServerConfig;
import com.freakz.hokan_ng.common.entity.Network;
import com.freakz.hokan_ng.common.entity.User;
import com.freakz.hokan_ng.common.entity.UserChannel;
import com.freakz.hokan_ng.common.exception.HokanException;
import com.freakz.hokan_ng.common.exception.HokanServiceException;
import com.freakz.hokan_ng.common.rest.EngineMethodCall;
import com.freakz.hokan_ng.common.rest.EngineRequest;
import com.freakz.hokan_ng.common.rest.EngineResponse;
import com.freakz.hokan_ng.common.rest.IrcEvent;
import com.freakz.hokan_ng.common.rest.IrcEventFactory;
import com.freakz.hokan_ng.common.rest.IrcMessageEvent;
import com.freakz.hokan_ng.common.service.AccessControlService;
import com.freakz.hokan_ng.common.service.ChannelService;
import com.freakz.hokan_ng.common.service.ChannelUsersService;
import com.freakz.hokan_ng.common.service.UserChannelService;
import com.freakz.hokan_ng.common.service.UserService;
import com.freakz.hokan_ng.common.util.IRCUtility;
import com.freakz.hokan_ng.common.util.StringStuff;
import lombok.extern.slf4j.Slf4j;
import org.jibble.pircbot.PircBot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Date: 3.6.2013
* Time: 9:15
*
* @author Petri Airio ([email protected])
*/
@Component
@Scope("prototype")
@Slf4j
public class HokanCore extends PircBot implements EngineEventHandler {
@Autowired
private ApplicationContext context;
@Autowired
private AccessControlService accessControlService;
@Autowired
private ChannelService channelService;
@Autowired
private ChannelUsersService channelUsersService;
@Autowired
private UserChannelService userChannelService;
@Autowired
private UserService userService;
//--------
private IrcServerConfig ircServerConfig;
private EngineConnector engineConnector;
private EngineCommunicator engineCommunicator;
private Map<String, String> serverProperties = new HashMap<>();
private Map<String, Method> methodMap = new HashMap<>();
private Map<String, List<String>> whoQueries = new HashMap<>();
private OutputQueue outputQueue;
public HokanCore() {
Class clazz = this.getClass();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
methodMap.put(method.getName(), method);
}
log.info("Built method map, size {}", methodMap.size());
}
public void init(String botName, IrcServerConfig ircServerConfig) {
this.ircServerConfig = ircServerConfig;
setVerbose(true);
setName(botName);
setVersion("Hokan NG");
setLogin("hokan");
setMessageDelay(1100);
}
private Method getEngineMethod(String name) { //}, int args) {
List<Method> matches = new ArrayList<>();
for (Method method : methodMap.values()) {
if (method.getName().equals(name)) { // && method.getGenericParameterTypes().length == args) {
matches.add(method);
}
}
if (matches.size() == 1) {
return matches.get(0);
} else if (matches.size() > 1) {
log.info("ffufu"); // TODO
return matches.get(0);
}
return null;
}
@Autowired
public void setEngineConnector(EngineConnector engineConnector) {
this.engineConnector = engineConnector;
}
@Autowired
public void setEngineCommunicator(EngineCommunicator engineCommunicator) {
this.engineCommunicator = engineCommunicator;
}
public IrcServerConfig getIrcServerConfig() {
return ircServerConfig;
}
public void setIrcServerConfig(IrcServerConfig ircServerConfig) {
this.ircServerConfig = ircServerConfig;
}
public void log(String message) {
if (!message.contains("PING") && !message.contains("PONG")) {
log.info(message);
}
}
// ---
@Override
public synchronized void dispose() {
outputQueue.stop();
List<Runnable> runnableList = executor.shutdownNow();
log.info("Runnables size: {}", runnableList.size());
super.dispose();
}
public Network getNetwork() {
return this.getIrcServerConfig().getNetwork();
}
public Channel getChannel(String channelName) {
Channel channel = channelService.findChannelByName(getNetwork(), channelName);
if (channel == null) {
channel = channelService.createChannel(getNetwork(), channelName);
}
return channel;
}
public Channel getChannel(IrcEvent ircEvent) {
return getChannel(ircEvent.getChannel());
}
public User getUser(IrcEvent ircEvent) {
try {
User user = this.userService.findUser(ircEvent.getSender());
if (user == null) {
user = new User(ircEvent.getSender());
user = userService.updateUser(user);
}
return user;
} catch (HokanException e) {
coreExceptionHandler(e);
}
return null;
}
public Map<String, String> getServerProperties() {
return serverProperties;
}
// --- PircBot
@Override
protected void onDisconnect() {
this.engineConnector.engineConnectorDisconnected(this);
}
@Override
protected void onUnknown(String line) {
log.info("UNKNOWN: {}", line);
if (line.startsWith("ERROR :Ping timeout:")) {
this.engineConnector.engineConnectorPingTimeout(this);
}
}
private void sendWhoQuery(String channel) {
log.info("Sending WHO query to: " + channel);
List<String> whoReplies = new ArrayList<>();
whoQueries.put(channel.toLowerCase(), whoReplies);
sendRawLineViaQueue("WHO " + channel);
}
@Override
protected void onUserList(String channel, org.jibble.pircbot.User[] users) {
sendWhoQuery(channel);
}
private void handleWhoList(String channelName, List<String> whoReplies) throws HokanException {
Channel channel = getChannel(channelName);
this.channelUsersService.clearChannelUsers(channel);
for (String whoLine : whoReplies) {
String[] split = whoLine.split(" ");
String nick = split[5];
String mask = split[5] + "!" + split[2] + "@" + split[3];
String fullName = StringStuff.joinStringArray(split, 8);
User user = this.userService.findUser(nick);
if (user == null) {
user = new User();
user.setNick(split[5]);
user.setMask(StringStuff.quoteRegExp(mask));
user.setPassword("1234");
user.setFullName(fullName);
user = this.userService.updateUser(user);
}
UserChannel userChannel = userChannelService.getUserChannel(user, channel);
if (userChannel == null) {
userChannelService.createUserChannel(user, channel);
}
this.channelUsersService.createChannelUser(channel, user);
}
}
@Override
protected void onServerResponse(int code, String line) {
if (code == RPL_WHOREPLY) {
String[] split = line.split(" ");
if (split.length >= 6) {
String channel = split[1];
List<String> whoReplies = whoQueries.get(channel.toLowerCase());
whoReplies.add(line);
} else {
log.info("SKIPPED WHO REPLY: {}", line);
}
} else if (code == RPL_ENDOFWHO) {
String[] split = line.split(" ");
String channel = split[1];
List<String> whoReplies = this.whoQueries.remove(channel.toLowerCase());
try {
handleWhoList(channel, whoReplies);
} catch (HokanException e) {
coreExceptionHandler(e);
}
log.info("Handled {} WHO lines!", whoReplies.size());
}
if (code == 5) {
String[] split = line.split(" ");
for (String str : split) {
if (str.contains("=")) {
String[] keyValue = str.split("=");
this.serverProperties.put(keyValue[0], keyValue[1]);
log.info("--> {}: {}", keyValue[0], keyValue[1]);
}
}
}
}
private void coreExceptionHandler(Exception e) {
log.error("---------------------------");
log.error("Exception", e);
log.error("---------------------------");
try {
List<User> masterUsers = accessControlService.getMasterUsers();
String message = "Exception caught: " + e;
for (User user : masterUsers) {
sendMessage(user.getNick(), message);
}
} catch (HokanException e1) {
e1.printStackTrace(); //ToDO epic fail?
}
}
@Override
protected void onMessage(String channel, String sender, String login, String hostname, String message) {
String toMe = getName() + ": ";
boolean isToMe = false;
if (message.startsWith(toMe)) {
message = message.replaceFirst(toMe, "");
isToMe = true;
}
IrcMessageEvent ircEvent = (IrcMessageEvent) IrcEventFactory.createIrcMessageEvent(channel, sender, login, hostname, message);
ircEvent.setToMe(isToMe);
Channel ch = getChannel(ircEvent);
ch.setLastWriter(sender);
ch.addToLinesReceived(1);
EngineRequest request = new EngineRequest(ircEvent);
this.engineCommunicator.sendEngineMessage(request, this);
this.channelService.updateChannel(ch);
}
@Override
protected void onPrivateMessage(String sender, String login, String hostname, String message) {
IrcMessageEvent ircEvent = (IrcMessageEvent) IrcEventFactory.createIrcMessageEvent(sender, sender, login, hostname, message);
ircEvent.setPrivate(true);
EngineRequest request = new EngineRequest(ircEvent);
this.engineCommunicator.sendEngineMessage(request, this);
log.info("Message: {}", ircEvent.getMessage());
}
@Override
public void handleEngineError(EngineResponse response) {
log.error("Engine request failed: {}", response);
coreExceptionHandler(new HokanException(response.getException()));
}
@Override
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
public void handleEngineResponse(EngineResponse response) {
if (response.getException() != null) {
String error = " failed: " + response.getException();
String message;
String target;
if (response.getRequest().getIrcEvent() instanceof IrcMessageEvent) {
message = response.getRequest().getIrcEvent().getSender() + ": " + error;
target = response.getRequest().getIrcEvent().getChannel();
} else {
message = error;
target = response.getRequest().getIrcEvent().getSender();
}
sendMessage(target, message);
return;
}
handleSendMessage(response);
for (EngineMethodCall methodCall : response.getEngineMethodCalls()) {
String methodName = methodCall.getMethodName();
String[] methodArgs = methodCall.getMethodArgs();
log.info("Executing engine method : " + methodName);
log.info("Engine method args : " + StringStuff.arrayToString(methodArgs, ", "));
Method method = getEngineMethod(methodName);
if (method != null) {
String[] args = new String[method.getParameterTypes().length];
- System.arraycopy(methodArgs, 0, args, 0, method.getParameterTypes().length);
+ int i = 0;
+ for (String arg : methodArgs) {
+ args[i] = arg;
+ i++;
+ }
log.info("Using method args : " + StringStuff.arrayToString(args, ", "));
try {
log.info("Invoking method : {}", method);
Object result = method.invoke(this, (Object[]) args);
log.info("Invoke result : {}", result);
} catch (Exception e) {
coreExceptionHandler(e);
log.error("Couldn't do engine method!", e);
}
} else {
log.error("Couldn't find method for: " + methodName);
}
}
}
public void startOutputQueue() {
this.outputQueue = this.context.getBean(OutputQueue.class);
this.outputQueue.init(this, getIrcServerConfig().isThrottleInUse());
}
private void handleSendMessage(EngineResponse response) {
String channel = response.getReplyTo();
String message = response.getResponseMessage();
if (message != null && message.trim().length() > 1) {
handleSendMessage(channel, message);
}
}
private void handleSendMessage(String channel, String message) {
String[] lines = message.split("\n");
for (String line : lines) {
String[] split = IRCUtility.breakUpMessageByIRCLineLength(channel, line);
for (String l : split) {
String raw = "PRIVMSG " + channel + " :" + l;
this.outputQueue.addLine(raw);
}
}
}
@Override
protected void onJoin(String channel, String sender, String login, String hostname) {
IrcEvent ircEvent = IrcEventFactory.createIrcEvent(channel, sender, login, hostname);
Channel ch = getChannel(ircEvent);
log.info("{} joined channel: {}", sender, channel);
if (sender.equalsIgnoreCase(getNick())) {
ch.setChannelState(ChannelState.JOINED);
if (ch.getFirstJoined() == null) {
ch.setFirstJoined(new Date());
}
} else {
try {
this.channelUsersService.createChannelUser(ch, getUser(ircEvent));
} catch (HokanServiceException e) {
coreExceptionHandler(e);
}
}
this.channelService.updateChannel(ch);
}
@Override
protected void onKick(String channel, String kickerNick, String kickerLogin, String kickerHostname, String recipientNick, String reason) {
sendWhoQuery(channel);
/* IrcEvent ircEvent = IrcEvent.create(channel, sender, login, hostname);
Channel ch = getChannel(IrcEvent.create(channel, sender, login, hostname));
super.onKick(channel, kickerNick, kickerLogin, kickerHostname, recipientNick, reason); //To change body of overridden methods use File | Settings | File Templates.*/
}
@Override
protected void onQuit(String sourceNick, String sourceLogin, String sourceHostname, String reason, String[] fromChannels) {
for (String channel : fromChannels) {
sendWhoQuery(channel);
}
}
@Override
protected void onPart(String channel, String sender, String login, String hostname) {
IrcEvent ircEvent = IrcEventFactory.createIrcEvent(channel, sender, login, hostname);
Channel ch = getChannel(ircEvent);
log.info("{} part channel: {}", sender, channel);
if (sender.equalsIgnoreCase(getNick())) {
ch.setChannelState(ChannelState.NOT_JOINED);
try {
this.channelUsersService.clearChannelUsers(ch);
} catch (HokanServiceException e) {
coreExceptionHandler(e);
}
} else {
try {
this.channelUsersService.removeChannelUser(ch, getUser(ircEvent));
} catch (HokanServiceException e) {
coreExceptionHandler(e);
}
}
this.channelService.updateChannel(ch);
}
@Override
protected void onNickChange(String oldNick, String login, String hostname, String newNick) {
for (String joined : getChannels()) {
sendWhoQuery(joined);
}
/* IrcEvent ircEvent = IrcEvent.create(channel, sender, login, hostname);
Channel ch = getChannel(IrcEvent.create(channel, sender, login, hostname));
this.channelUsersService.removeChannelUser(getUser(ircEvent))
TODO
*/
}
public String toString() {
String config = ircServerConfig.toString();
String props = getServerProperties().toString();
return String.format("%s: %s", config, props);
}
}
| true | true | public void handleEngineResponse(EngineResponse response) {
if (response.getException() != null) {
String error = " failed: " + response.getException();
String message;
String target;
if (response.getRequest().getIrcEvent() instanceof IrcMessageEvent) {
message = response.getRequest().getIrcEvent().getSender() + ": " + error;
target = response.getRequest().getIrcEvent().getChannel();
} else {
message = error;
target = response.getRequest().getIrcEvent().getSender();
}
sendMessage(target, message);
return;
}
handleSendMessage(response);
for (EngineMethodCall methodCall : response.getEngineMethodCalls()) {
String methodName = methodCall.getMethodName();
String[] methodArgs = methodCall.getMethodArgs();
log.info("Executing engine method : " + methodName);
log.info("Engine method args : " + StringStuff.arrayToString(methodArgs, ", "));
Method method = getEngineMethod(methodName);
if (method != null) {
String[] args = new String[method.getParameterTypes().length];
System.arraycopy(methodArgs, 0, args, 0, method.getParameterTypes().length);
log.info("Using method args : " + StringStuff.arrayToString(args, ", "));
try {
log.info("Invoking method : {}", method);
Object result = method.invoke(this, (Object[]) args);
log.info("Invoke result : {}", result);
} catch (Exception e) {
coreExceptionHandler(e);
log.error("Couldn't do engine method!", e);
}
} else {
log.error("Couldn't find method for: " + methodName);
}
}
}
| public void handleEngineResponse(EngineResponse response) {
if (response.getException() != null) {
String error = " failed: " + response.getException();
String message;
String target;
if (response.getRequest().getIrcEvent() instanceof IrcMessageEvent) {
message = response.getRequest().getIrcEvent().getSender() + ": " + error;
target = response.getRequest().getIrcEvent().getChannel();
} else {
message = error;
target = response.getRequest().getIrcEvent().getSender();
}
sendMessage(target, message);
return;
}
handleSendMessage(response);
for (EngineMethodCall methodCall : response.getEngineMethodCalls()) {
String methodName = methodCall.getMethodName();
String[] methodArgs = methodCall.getMethodArgs();
log.info("Executing engine method : " + methodName);
log.info("Engine method args : " + StringStuff.arrayToString(methodArgs, ", "));
Method method = getEngineMethod(methodName);
if (method != null) {
String[] args = new String[method.getParameterTypes().length];
int i = 0;
for (String arg : methodArgs) {
args[i] = arg;
i++;
}
log.info("Using method args : " + StringStuff.arrayToString(args, ", "));
try {
log.info("Invoking method : {}", method);
Object result = method.invoke(this, (Object[]) args);
log.info("Invoke result : {}", result);
} catch (Exception e) {
coreExceptionHandler(e);
log.error("Couldn't do engine method!", e);
}
} else {
log.error("Couldn't find method for: " + methodName);
}
}
}
|
diff --git a/monitorization/collector/src/pt/com/broker/monitorization/db/FaultsDB.java b/monitorization/collector/src/pt/com/broker/monitorization/db/FaultsDB.java
index 3e805e71..1247500d 100644
--- a/monitorization/collector/src/pt/com/broker/monitorization/db/FaultsDB.java
+++ b/monitorization/collector/src/pt/com/broker/monitorization/db/FaultsDB.java
@@ -1,146 +1,146 @@
package pt.com.broker.monitorization.db;
import java.io.ByteArrayInputStream;
import java.util.Date;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.caudexorigo.ErrorAnalyser;
import org.caudexorigo.jdbc.DbExecutor;
import org.caudexorigo.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class FaultsDB
{
private static Logger log = LoggerFactory.getLogger(FaultsDB.class);
/*
*
* CREATE TABLE IF NOT EXISTS fault(id INT PRIMARY KEY AUTO_INCREMENT, agentName VARCHAR(255) NOT NULL, time TIMESTAMP NOT NULL, message VARCHAR(8192), shortmessage VARCHAR(255));
*/
public static void add(String agent, Date sampleDate, String message)
{
if (log.isDebugEnabled())
{
log.debug(String.format("FaultsDB.processItem(%s, %s, %s)", agent, sampleDate, message));
}
try
{
String ins_sql = ("INSERT INTO fault_data (agent_name, event_time, message, short_message) VALUES (?, ?, ?, ?)");
ErrorInfo errorInfo = extractShortMessage(message);
String escapedMsg = StringEscapeUtils.escapeHtml(errorInfo.content.replace("\n", "\\n"));
String shortMessage = StringEscapeUtils.escapeHtml(errorInfo.shortMessage.replace("\n", "\\n"));
DbExecutor.runActionPreparedStatement(ins_sql, agent, sampleDate, escapedMsg, shortMessage);
}
catch (Throwable t)
{
log.error("Failed to insert new information item.", t);
}
}
private static class SoapFaultNS implements NamespaceContext
{
private static SoapFaultNS instance = new SoapFaultNS();
public static SoapFaultNS getInstance()
{
return instance;
}
public String getNamespaceURI(String prefix)
{
if (prefix.equals("soap"))
return "http://www.w3.org/2003/05/soap-envelope";
else
return XMLConstants.NULL_NS_URI;
}
public String getPrefix(String namespace)
{
if (namespace.equals("http://www.w3.org/2003/05/soap-envelope"))
return "soap";
else
return null;
}
public java.util.Iterator<Object> getPrefixes(String namespace)
{
return null;
}
}
private static class ErrorInfo
{
public String content;
public String shortMessage;
public ErrorInfo(String shortMessage, String content)
{
this.content = content;
this.shortMessage = shortMessage;
}
}
private static ErrorInfo extractShortMessage(String message)
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
- String shortMessage = "[failed to extract data from Fault message]";
+ String shortMessage = "";
String content = message;
try
{
DocumentBuilder documentBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(new ByteArrayInputStream(message.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(SoapFaultNS.getInstance());
NodeList n_code = (NodeList) xpath.evaluate("/Envelope/Body/Fault/Reason/Text", doc, XPathConstants.NODESET);
if (n_code != null && n_code.getLength() > 0)
{
Element codeElem = (Element) n_code.item(0);
shortMessage = codeElem.getTextContent();
}
NodeList n_detail = (NodeList) xpath.evaluate("/Envelope/Body/Fault/Detail", doc, XPathConstants.NODESET);
if (n_detail != null && n_detail.getLength() > 0)
{
Element contentElem = (Element) n_detail.item(0);
content = contentElem.getTextContent();
}
}
catch (Throwable t)
{
Throwable r = ErrorAnalyser.findRootCause(t);
log.error(r.getMessage(), r);
- return new ErrorInfo(r.getMessage(), message);
+ shortMessage = String.format("Unknown - (failed to extract data from Fault message. Reason: %s)", r.getMessage() );
}
return new ErrorInfo(shortMessage, content);
}
}
| false | true | private static ErrorInfo extractShortMessage(String message)
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
String shortMessage = "[failed to extract data from Fault message]";
String content = message;
try
{
DocumentBuilder documentBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(new ByteArrayInputStream(message.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(SoapFaultNS.getInstance());
NodeList n_code = (NodeList) xpath.evaluate("/Envelope/Body/Fault/Reason/Text", doc, XPathConstants.NODESET);
if (n_code != null && n_code.getLength() > 0)
{
Element codeElem = (Element) n_code.item(0);
shortMessage = codeElem.getTextContent();
}
NodeList n_detail = (NodeList) xpath.evaluate("/Envelope/Body/Fault/Detail", doc, XPathConstants.NODESET);
if (n_detail != null && n_detail.getLength() > 0)
{
Element contentElem = (Element) n_detail.item(0);
content = contentElem.getTextContent();
}
}
catch (Throwable t)
{
Throwable r = ErrorAnalyser.findRootCause(t);
log.error(r.getMessage(), r);
return new ErrorInfo(r.getMessage(), message);
}
return new ErrorInfo(shortMessage, content);
}
| private static ErrorInfo extractShortMessage(String message)
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
String shortMessage = "";
String content = message;
try
{
DocumentBuilder documentBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(new ByteArrayInputStream(message.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(SoapFaultNS.getInstance());
NodeList n_code = (NodeList) xpath.evaluate("/Envelope/Body/Fault/Reason/Text", doc, XPathConstants.NODESET);
if (n_code != null && n_code.getLength() > 0)
{
Element codeElem = (Element) n_code.item(0);
shortMessage = codeElem.getTextContent();
}
NodeList n_detail = (NodeList) xpath.evaluate("/Envelope/Body/Fault/Detail", doc, XPathConstants.NODESET);
if (n_detail != null && n_detail.getLength() > 0)
{
Element contentElem = (Element) n_detail.item(0);
content = contentElem.getTextContent();
}
}
catch (Throwable t)
{
Throwable r = ErrorAnalyser.findRootCause(t);
log.error(r.getMessage(), r);
shortMessage = String.format("Unknown - (failed to extract data from Fault message. Reason: %s)", r.getMessage() );
}
return new ErrorInfo(shortMessage, content);
}
|
diff --git a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
index c2fdd9c1..da0b244f 100644
--- a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
+++ b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java
@@ -1,182 +1,182 @@
/*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*/
package org.cubictest.recorder.ui;
import org.cubictest.common.utils.ErrorHandler;
import org.cubictest.common.utils.UserInfo;
import org.cubictest.export.exceptions.ExporterException;
import org.cubictest.export.utils.exported.ExportUtils;
import org.cubictest.exporters.selenium.ui.RunSeleniumRunnerAction;
import org.cubictest.model.ExtensionPoint;
import org.cubictest.model.ExtensionStartPoint;
import org.cubictest.model.ExtensionTransition;
import org.cubictest.model.Page;
import org.cubictest.model.SubTest;
import org.cubictest.model.SubTestStartPoint;
import org.cubictest.model.Test;
import org.cubictest.model.Transition;
import org.cubictest.model.UrlStartPoint;
import org.cubictest.recorder.CubicRecorder;
import org.cubictest.recorder.GUIAwareRecorder;
import org.cubictest.recorder.IRecorder;
import org.cubictest.recorder.selenium.SeleniumRecorder;
import org.cubictest.ui.gef.interfaces.exported.IDisposeListener;
import org.cubictest.ui.gef.interfaces.exported.ITestEditor;
import org.cubictest.ui.gef.layout.AutoLayout;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
/**
* Action for starting / stopping the CubicRecorder.
*
*/
public class RecordEditorAction implements IEditorActionDelegate {
IResource currentFile;
private boolean running;
private SeleniumRecorder seleniumRecorder;
private ITestEditor testEditor;
public RecordEditorAction() {
super();
}
/**
* @see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
Test test = testEditor.getTest();
if (test.getStartPoint() instanceof SubTestStartPoint) {
ErrorHandler.logAndShowErrorDialog("It is not possible to record from tests that start with a SubTest start point. ");
return;
}
test.resetStatus();
if(!running) {
setRunning(true);
if (test.getStartPoint() instanceof ExtensionStartPoint && test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) {
ErrorHandler.showWarnDialog("Could not record from extension start point, as test is not empty.\n\n" +
"Tip: Create a new test and record from there.");
return; //ModelUtil should show error message.
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (test.getStartPoint() instanceof ExtensionStartPoint) {
ErrorHandler.showInfoDialog("Test browser will be forwarded to start point for test." + "\n" +
"Press OK to continue.");
//play forward to extension start point
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (35 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
runner.setTest(((SubTest) test.getStartPoint()).getTest(true));
if (test.getStartPoint().getOutTransitions().size() == 0) {
ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point.");
}
ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint();
runner.setTargetExtensionPoint(targetExPoint);
runner.run(action);
- cubicRecorder.setEnabled(true);
- guiAwareRecorder.setEnabled(true);
}
+ cubicRecorder.setEnabled(true);
+ guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
return;
}
} else {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
}
}
private void stopSelenium(AutoLayout autoLayout) {
try {
setRunning(false);
if (seleniumRecorder != null) {
seleniumRecorder.stop();
}
if (autoLayout != null) {
autoLayout.setPageSelected(null);
}
}
catch(Exception e) {
ErrorHandler.logAndRethrow(e);
}
}
/**
* @see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {}
public void setActiveEditor(IAction action, IEditorPart targetEditor) {
this.testEditor = (ITestEditor) targetEditor;
}
private void setRunning(boolean run) {
running = run;
}
/**
* Get the initial URL start point of the test (expands subtests).
*/
private UrlStartPoint getInitialUrlStartPoint(Test test) {
if (test.getStartPoint() instanceof UrlStartPoint) {
return (UrlStartPoint) test.getStartPoint();
}
else {
//ExtensionStartPoint, get url start point recursively:
return getInitialUrlStartPoint(((ExtensionStartPoint) test.getStartPoint()).getTest(true));
}
}
public boolean firstPageIsEmpty(Test test) {
for(Transition t : test.getStartPoint().getOutTransitions()) {
if(t.getEnd() instanceof Page && ((Page)t.getEnd()).getElements().size() == 0) {
return true;
}
}
return false;
}
}
| false | true | public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
Test test = testEditor.getTest();
if (test.getStartPoint() instanceof SubTestStartPoint) {
ErrorHandler.logAndShowErrorDialog("It is not possible to record from tests that start with a SubTest start point. ");
return;
}
test.resetStatus();
if(!running) {
setRunning(true);
if (test.getStartPoint() instanceof ExtensionStartPoint && test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) {
ErrorHandler.showWarnDialog("Could not record from extension start point, as test is not empty.\n\n" +
"Tip: Create a new test and record from there.");
return; //ModelUtil should show error message.
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (test.getStartPoint() instanceof ExtensionStartPoint) {
ErrorHandler.showInfoDialog("Test browser will be forwarded to start point for test." + "\n" +
"Press OK to continue.");
//play forward to extension start point
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (35 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
runner.setTest(((SubTest) test.getStartPoint()).getTest(true));
if (test.getStartPoint().getOutTransitions().size() == 0) {
ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point.");
}
ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint();
runner.setTargetExtensionPoint(targetExPoint);
runner.run(action);
cubicRecorder.setEnabled(true);
guiAwareRecorder.setEnabled(true);
}
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
return;
}
} else {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
}
}
| public void run(IAction action) {
AutoLayout autoLayout = new AutoLayout(testEditor);
Test test = testEditor.getTest();
if (test.getStartPoint() instanceof SubTestStartPoint) {
ErrorHandler.logAndShowErrorDialog("It is not possible to record from tests that start with a SubTest start point. ");
return;
}
test.resetStatus();
if(!running) {
setRunning(true);
if (test.getStartPoint() instanceof ExtensionStartPoint && test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) {
ErrorHandler.showWarnDialog("Could not record from extension start point, as test is not empty.\n\n" +
"Tip: Create a new test and record from there.");
return; //ModelUtil should show error message.
}
IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout);
IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder);
seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt());
testEditor.addDisposeListener(new IDisposeListener() {
public void disposed() {
stopSelenium(null);
}
});
try {
new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder);
if (test.getStartPoint() instanceof ExtensionStartPoint) {
ErrorHandler.showInfoDialog("Test browser will be forwarded to start point for test." + "\n" +
"Press OK to continue.");
//play forward to extension start point
long now = System.currentTimeMillis();
while (!seleniumRecorder.isSeleniumStarted()) {
if (System.currentTimeMillis() > now + (35 * 1000)) {
throw new ExporterException("Timeout waiting for Selenium to start");
}
//wait for selenium (server & test system) to start
Thread.yield();
Thread.sleep(100);
}
RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction();
runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open).");
runner.setShowCompletedMessageInStatusLine(true);
runner.setStopSeleniumWhenFinished(false);
runner.setSelenium(seleniumRecorder.getSelenium());
runner.setTest(((SubTest) test.getStartPoint()).getTest(true));
if (test.getStartPoint().getOutTransitions().size() == 0) {
ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point.");
}
ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint();
runner.setTargetExtensionPoint(targetExPoint);
runner.run(action);
}
cubicRecorder.setEnabled(true);
guiAwareRecorder.setEnabled(true);
}
catch (Exception e) {
ErrorHandler.logAndShowErrorDialog(e);
stopSelenium(autoLayout);
UserInfo.setStatusLine(null);
return;
}
} else {
UserInfo.setStatusLine(null);
stopSelenium(autoLayout);
}
}
|
diff --git a/proxy/src/main/java/net/md_5/bungee/command/CommandList.java b/proxy/src/main/java/net/md_5/bungee/command/CommandList.java
index fbe40fd5..07d779c6 100644
--- a/proxy/src/main/java/net/md_5/bungee/command/CommandList.java
+++ b/proxy/src/main/java/net/md_5/bungee/command/CommandList.java
@@ -1,62 +1,63 @@
package net.md_5.bungee.command;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
/**
* Command to list all players connected to the proxy.
*/
public class CommandList extends Command
{
public CommandList()
{
super( "glist", "bungeecord.command.list" );
}
@Override
public void execute(CommandSender sender, String[] args)
{
for ( ServerInfo server : ProxyServer.getInstance().getServers().values() )
{
Collection<ProxiedPlayer> serverPlayers = server.getPlayers();
StringBuilder message = new StringBuilder();
message.append( ChatColor.GREEN );
message.append( "[" );
message.append( server.getName() );
message.append( "] " );
message.append( ChatColor.YELLOW );
message.append( "(" );
message.append( serverPlayers.size() );
message.append( "): " );
+ message.append( ChatColor.RESET );
List<String> players = new ArrayList<>();
for ( ProxiedPlayer player : serverPlayers )
{
players.add( player.getDisplayName() );
}
Collections.sort( players, String.CASE_INSENSITIVE_ORDER );
if ( !players.isEmpty() )
{
for ( String player : players )
{
message.append( player ).append( ChatColor.RESET ).append( ", " );
}
}
sender.sendMessage( message.substring( 0, message.length() - 2 ) );
}
sender.sendMessage( "Total players online: " + ProxyServer.getInstance().getPlayers().size() );
}
}
| true | true | public void execute(CommandSender sender, String[] args)
{
for ( ServerInfo server : ProxyServer.getInstance().getServers().values() )
{
Collection<ProxiedPlayer> serverPlayers = server.getPlayers();
StringBuilder message = new StringBuilder();
message.append( ChatColor.GREEN );
message.append( "[" );
message.append( server.getName() );
message.append( "] " );
message.append( ChatColor.YELLOW );
message.append( "(" );
message.append( serverPlayers.size() );
message.append( "): " );
List<String> players = new ArrayList<>();
for ( ProxiedPlayer player : serverPlayers )
{
players.add( player.getDisplayName() );
}
Collections.sort( players, String.CASE_INSENSITIVE_ORDER );
if ( !players.isEmpty() )
{
for ( String player : players )
{
message.append( player ).append( ChatColor.RESET ).append( ", " );
}
}
sender.sendMessage( message.substring( 0, message.length() - 2 ) );
}
sender.sendMessage( "Total players online: " + ProxyServer.getInstance().getPlayers().size() );
}
| public void execute(CommandSender sender, String[] args)
{
for ( ServerInfo server : ProxyServer.getInstance().getServers().values() )
{
Collection<ProxiedPlayer> serverPlayers = server.getPlayers();
StringBuilder message = new StringBuilder();
message.append( ChatColor.GREEN );
message.append( "[" );
message.append( server.getName() );
message.append( "] " );
message.append( ChatColor.YELLOW );
message.append( "(" );
message.append( serverPlayers.size() );
message.append( "): " );
message.append( ChatColor.RESET );
List<String> players = new ArrayList<>();
for ( ProxiedPlayer player : serverPlayers )
{
players.add( player.getDisplayName() );
}
Collections.sort( players, String.CASE_INSENSITIVE_ORDER );
if ( !players.isEmpty() )
{
for ( String player : players )
{
message.append( player ).append( ChatColor.RESET ).append( ", " );
}
}
sender.sendMessage( message.substring( 0, message.length() - 2 ) );
}
sender.sendMessage( "Total players online: " + ProxyServer.getInstance().getPlayers().size() );
}
|
diff --git a/src/edu/mit/rerun/view/EditFilterActivity.java b/src/edu/mit/rerun/view/EditFilterActivity.java
index 45bb267..2b02bd6 100644
--- a/src/edu/mit/rerun/view/EditFilterActivity.java
+++ b/src/edu/mit/rerun/view/EditFilterActivity.java
@@ -1,186 +1,188 @@
package edu.mit.rerun.view;
import java.util.ArrayList;
import java.util.HashSet;
import edu.mit.rerun.R;
import edu.mit.rerun.model.Filter;
import edu.mit.rerun.utils.DatabaseAdapter;
import edu.mit.rerun.utils.EditFilterListAdapter;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class EditFilterActivity extends ListActivity {
public static final String TAG = "EditFilterActivity";
private Context mContext = this;
private DatabaseAdapter mDbAdapter;
private String oldFilterName;
private boolean newFilter = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_filter);
Bundle extras = getIntent().getExtras();
mDbAdapter = new DatabaseAdapter(this);
TextView header = (TextView) findViewById(R.id.header);
final EditText filterName = (EditText) findViewById(R.id.new_filter_name);
// editing existing filter
if (extras != null) {
oldFilterName = extras.getString("filterName");
if (oldFilterName != null) {
header.setText("Filter: " + oldFilterName);
filterName.setText(oldFilterName);
newFilter = false;
}
}
final ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
View footer = inflater.inflate(R.layout.edit_filter_list_footer, null,
false);
lv.addFooterView(footer);
ImageButton addKeyword = (ImageButton) footer
.findViewById(R.id.add_keyword);
Button cancel = (Button) footer.findViewById(R.id.cancel_btn);
Button save = (Button) footer.findViewById(R.id.save_filter_btn);
// setListAdapter
final ArrayList<String> rows = new ArrayList<String>();
if (!newFilter) {
mDbAdapter.open();
Filter filter = mDbAdapter.getFilter(oldFilterName);
for (String keyword : filter.getKeyWords()) {
- rows.add(keyword);
+ if (keyword != null || keyword != "" || keyword.length() > 0) {
+ rows.add(keyword);
+ }
}
mDbAdapter.close();
}
EditFilterListAdapter adapter = new EditFilterListAdapter(this, rows,
getParent());
setListAdapter(adapter);
Log.i(TAG, "after setting list adapter");
// sample filter, to be retrieved from db later
addKeyword.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Dialog dialog = new Dialog(v.getContext());
dialog.setContentView(R.layout.dialog_keyword_input);
dialog.setTitle("Add Keyword");
dialog.setCancelable(false);
Button addBtn = (Button) dialog.findViewById(R.id.save_btn);
Button cancelBtn = (Button) dialog
.findViewById(R.id.cancel_btn);
final EditText input = (EditText) dialog
.findViewById(R.id.keyword_input);
addBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (checkKeywordInput(input.getText().toString().trim())) {
rows.add(input.getText().toString().trim());
setListAdapter(new EditFilterListAdapter(mContext,
rows, getParent()));
dialog.dismiss();
} else {
Toast.makeText(mContext,
"please enter a valid keyword",
Toast.LENGTH_SHORT).show();
}
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDbAdapter.close();
finish();
}
});
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// validates filter name as alphanumeric
String filterNameStr = filterName.getText().toString();
if (!filterNameStr.matches("[\\p{Alnum}[\\-]]*")) {
//error- non-alphanumerics found
Toast.makeText(v.getContext(), "Filter name contains invalid characters, please use alphanumeric characters only", Toast.LENGTH_SHORT).show();
}
else {
Filter filter = new Filter(filterNameStr,true, new HashSet<String>(rows));
mDbAdapter.open();
// removes old filter
if (!newFilter && oldFilterName != null) {
mDbAdapter.removeFilter(oldFilterName);
}
if (!mDbAdapter.filterExist(filter.getFiltername())) {
mDbAdapter.addFilter(filter);
mDbAdapter.close();
setResult(ItemListActivity.ADD_FILTER_RESULT);
finish();
} else {
Toast.makeText(v.getContext(), "Filter already exists, please enter another filter name",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ItemListActivity.ADD_FILTER_RESULT) {
Intent intent = new Intent((Context) this,
FilterSettingsActivity.class);
startActivity(intent);
}
}
// TODO, check to see that keyword is unique
private boolean checkKeywordInput(String input) {
boolean valid = true;
// validates keyword name as alphanumeric
if (!input.matches("[\\p{Alnum}[\\-]]*")) {
valid = false;
}
if (input == null || input.length() == 0) {
valid = false;
}
return valid;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_filter);
Bundle extras = getIntent().getExtras();
mDbAdapter = new DatabaseAdapter(this);
TextView header = (TextView) findViewById(R.id.header);
final EditText filterName = (EditText) findViewById(R.id.new_filter_name);
// editing existing filter
if (extras != null) {
oldFilterName = extras.getString("filterName");
if (oldFilterName != null) {
header.setText("Filter: " + oldFilterName);
filterName.setText(oldFilterName);
newFilter = false;
}
}
final ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
View footer = inflater.inflate(R.layout.edit_filter_list_footer, null,
false);
lv.addFooterView(footer);
ImageButton addKeyword = (ImageButton) footer
.findViewById(R.id.add_keyword);
Button cancel = (Button) footer.findViewById(R.id.cancel_btn);
Button save = (Button) footer.findViewById(R.id.save_filter_btn);
// setListAdapter
final ArrayList<String> rows = new ArrayList<String>();
if (!newFilter) {
mDbAdapter.open();
Filter filter = mDbAdapter.getFilter(oldFilterName);
for (String keyword : filter.getKeyWords()) {
rows.add(keyword);
}
mDbAdapter.close();
}
EditFilterListAdapter adapter = new EditFilterListAdapter(this, rows,
getParent());
setListAdapter(adapter);
Log.i(TAG, "after setting list adapter");
// sample filter, to be retrieved from db later
addKeyword.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Dialog dialog = new Dialog(v.getContext());
dialog.setContentView(R.layout.dialog_keyword_input);
dialog.setTitle("Add Keyword");
dialog.setCancelable(false);
Button addBtn = (Button) dialog.findViewById(R.id.save_btn);
Button cancelBtn = (Button) dialog
.findViewById(R.id.cancel_btn);
final EditText input = (EditText) dialog
.findViewById(R.id.keyword_input);
addBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (checkKeywordInput(input.getText().toString().trim())) {
rows.add(input.getText().toString().trim());
setListAdapter(new EditFilterListAdapter(mContext,
rows, getParent()));
dialog.dismiss();
} else {
Toast.makeText(mContext,
"please enter a valid keyword",
Toast.LENGTH_SHORT).show();
}
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDbAdapter.close();
finish();
}
});
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// validates filter name as alphanumeric
String filterNameStr = filterName.getText().toString();
if (!filterNameStr.matches("[\\p{Alnum}[\\-]]*")) {
//error- non-alphanumerics found
Toast.makeText(v.getContext(), "Filter name contains invalid characters, please use alphanumeric characters only", Toast.LENGTH_SHORT).show();
}
else {
Filter filter = new Filter(filterNameStr,true, new HashSet<String>(rows));
mDbAdapter.open();
// removes old filter
if (!newFilter && oldFilterName != null) {
mDbAdapter.removeFilter(oldFilterName);
}
if (!mDbAdapter.filterExist(filter.getFiltername())) {
mDbAdapter.addFilter(filter);
mDbAdapter.close();
setResult(ItemListActivity.ADD_FILTER_RESULT);
finish();
} else {
Toast.makeText(v.getContext(), "Filter already exists, please enter another filter name",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_filter);
Bundle extras = getIntent().getExtras();
mDbAdapter = new DatabaseAdapter(this);
TextView header = (TextView) findViewById(R.id.header);
final EditText filterName = (EditText) findViewById(R.id.new_filter_name);
// editing existing filter
if (extras != null) {
oldFilterName = extras.getString("filterName");
if (oldFilterName != null) {
header.setText("Filter: " + oldFilterName);
filterName.setText(oldFilterName);
newFilter = false;
}
}
final ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
View footer = inflater.inflate(R.layout.edit_filter_list_footer, null,
false);
lv.addFooterView(footer);
ImageButton addKeyword = (ImageButton) footer
.findViewById(R.id.add_keyword);
Button cancel = (Button) footer.findViewById(R.id.cancel_btn);
Button save = (Button) footer.findViewById(R.id.save_filter_btn);
// setListAdapter
final ArrayList<String> rows = new ArrayList<String>();
if (!newFilter) {
mDbAdapter.open();
Filter filter = mDbAdapter.getFilter(oldFilterName);
for (String keyword : filter.getKeyWords()) {
if (keyword != null || keyword != "" || keyword.length() > 0) {
rows.add(keyword);
}
}
mDbAdapter.close();
}
EditFilterListAdapter adapter = new EditFilterListAdapter(this, rows,
getParent());
setListAdapter(adapter);
Log.i(TAG, "after setting list adapter");
// sample filter, to be retrieved from db later
addKeyword.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Dialog dialog = new Dialog(v.getContext());
dialog.setContentView(R.layout.dialog_keyword_input);
dialog.setTitle("Add Keyword");
dialog.setCancelable(false);
Button addBtn = (Button) dialog.findViewById(R.id.save_btn);
Button cancelBtn = (Button) dialog
.findViewById(R.id.cancel_btn);
final EditText input = (EditText) dialog
.findViewById(R.id.keyword_input);
addBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (checkKeywordInput(input.getText().toString().trim())) {
rows.add(input.getText().toString().trim());
setListAdapter(new EditFilterListAdapter(mContext,
rows, getParent()));
dialog.dismiss();
} else {
Toast.makeText(mContext,
"please enter a valid keyword",
Toast.LENGTH_SHORT).show();
}
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDbAdapter.close();
finish();
}
});
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// validates filter name as alphanumeric
String filterNameStr = filterName.getText().toString();
if (!filterNameStr.matches("[\\p{Alnum}[\\-]]*")) {
//error- non-alphanumerics found
Toast.makeText(v.getContext(), "Filter name contains invalid characters, please use alphanumeric characters only", Toast.LENGTH_SHORT).show();
}
else {
Filter filter = new Filter(filterNameStr,true, new HashSet<String>(rows));
mDbAdapter.open();
// removes old filter
if (!newFilter && oldFilterName != null) {
mDbAdapter.removeFilter(oldFilterName);
}
if (!mDbAdapter.filterExist(filter.getFiltername())) {
mDbAdapter.addFilter(filter);
mDbAdapter.close();
setResult(ItemListActivity.ADD_FILTER_RESULT);
finish();
} else {
Toast.makeText(v.getContext(), "Filter already exists, please enter another filter name",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
|
diff --git a/plugins/org.eclipse.vjet.eclipse.ui/src/org/eclipse/vjet/eclipse/internal/ui/text/completion/VjoProposalAditionalInfoGenerator.java b/plugins/org.eclipse.vjet.eclipse.ui/src/org/eclipse/vjet/eclipse/internal/ui/text/completion/VjoProposalAditionalInfoGenerator.java
index 64ff4b71..db359062 100644
--- a/plugins/org.eclipse.vjet.eclipse.ui/src/org/eclipse/vjet/eclipse/internal/ui/text/completion/VjoProposalAditionalInfoGenerator.java
+++ b/plugins/org.eclipse.vjet.eclipse.ui/src/org/eclipse/vjet/eclipse/internal/ui/text/completion/VjoProposalAditionalInfoGenerator.java
@@ -1,606 +1,606 @@
/*******************************************************************************
* Copyright (c) 2005, 2012 eBay Inc.
* 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 org.eclipse.vjet.eclipse.internal.ui.text.completion;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.dltk.mod.ui.DLTKUIPlugin;
import org.eclipse.dltk.mod.ui.PreferenceConstants;
import org.eclipse.dltk.mod.ui.text.completion.HTMLPrinter;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.vjet.dsf.jst.BaseJstNode;
import org.eclipse.vjet.dsf.jst.IJstAnnotation;
import org.eclipse.vjet.dsf.jst.IJstMethod;
import org.eclipse.vjet.dsf.jst.IJstNode;
import org.eclipse.vjet.dsf.jst.IJstProperty;
import org.eclipse.vjet.dsf.jst.IJstType;
import org.eclipse.vjet.dsf.jst.declaration.JstAnnotation;
import org.eclipse.vjet.dsf.jst.declaration.JstArg;
import org.eclipse.vjet.dsf.jst.declaration.JstModifiers;
import org.eclipse.vjet.dsf.jst.expr.AssignExpr;
import org.eclipse.vjet.dsf.jst.expr.JstArrayInitializer;
import org.eclipse.vjet.dsf.jst.term.JstIdentifier;
import org.eclipse.vjet.dsf.jst.token.IExpr;
import org.eclipse.vjet.dsf.jst.util.JstCommentHelper;
import org.eclipse.vjet.dsf.jstojava.translator.JsDocHelper;
import org.eclipse.vjet.eclipse.internal.ui.scriptdoc.JavaDoc2HTMLTextReader;
import org.eclipse.vjet.eclipse.ui.VjetUIPlugin;
import org.osgi.framework.Bundle;
/**
* Generate additial info for vjo cc proposal
*
*
*
*/
public class VjoProposalAditionalInfoGenerator {
private static final String PERS_FILENAME = "additionalCompletionTemplate.html"; //$NON-NLS-1$
private static String PERS_FOLDER = "ccAdditionalPanel";
public static String getAdditionalPropesalInfo(IJstNode node) {
String info = null;
String css = getCSSStyles();
List<String> allSupportedExplorers = new ArrayList<String>();
IJstProperty property = null;
IJstMethod method = null;
if (node instanceof IJstProperty) {
property = (IJstProperty) node;
} else if (node instanceof IJstMethod) {
method = (IJstMethod) node;
}
String briefInfo = "";
- if (property != null && property.getCommentLocations() != null) {
+ if (property != null && property.getCommentLocations() != null && !node.getCommentLocations().isEmpty()) {
List<String> strings = JstCommentHelper.getCommentsAsString(node.getOwnerType(), node.getCommentLocations());
StringBuilder sb = new StringBuilder();
for(String str:strings){
if(str!=null)
sb.append(JsDocHelper.cleanJsDocComment(str));
sb.append("<br>");
}
info = sb.toString();
briefInfo = getElementBriefDesc(property);
fillAllSupportedExplorer(property, allSupportedExplorers);
} else {
if ((method != null) && (method.getDoc() != null)) {
info = method.getDoc().getComment();
briefInfo = getElementBriefDesc(method);
fillAllSupportedExplorer(method, allSupportedExplorers);
}
}
if (info != null) {
try {
File persFile = getTemplateFile();
if (!persFile.exists()) {
try {
persFile.createNewFile();
} catch (IOException e) {
}
copyHtmlTemplateFromBundleToTemp();
copyIconsFromBundleToTemp();
}
// Replace the invalid character.
info = info.replace("/", "");
info = info.replace("*", "");
if (persFile != null) {
FileReader readerSuc = new FileReader(persFile);
JavaDoc2HTMLTextReader reader2 = new JavaDoc2HTMLTextReader(
readerSuc);
String wholeInfo = getString(reader2);
wholeInfo = wholeInfo.replace("<%=browserSupported%>",
getSupportedTypesStirng(allSupportedExplorers,
"BrowserType."));
String domLevel = getSupportedTypesStirng(
allSupportedExplorers, "DomLevel.");
if (domLevel.length() > 0) {
wholeInfo = wholeInfo.replace("<%=DOMLevel%>",
"<b>DOM level</b><br>"
+ getSupportedTypesStirng(
allSupportedExplorers,
"DomLevel.") + "<br>");
}else{
wholeInfo = wholeInfo.replace("<%=DOMLevel%>",
"");
}
wholeInfo = wholeInfo.replace("<%=MinJSVersion%>",
translateCharacterToNumber(getSupportedTypesStirng(
allSupportedExplorers, "JsVersion.")));
wholeInfo = wholeInfo.replace("<%=briefInfo%>", briefInfo);
wholeInfo = wholeInfo.replace("<%=images%>",
getIcon(allSupportedExplorers));
wholeInfo = wholeInfo.replace("<%=description%>", info);
// Add the css and HTML tags at the beginning and
// end.
StringBuffer buffer = new StringBuffer();
HTMLPrinter.insertPageProlog(buffer, 0, css);
buffer.append(wholeInfo);
HTMLPrinter.addPageEpilog(buffer);
wholeInfo = buffer.toString();
return wholeInfo;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return info;
}
private static String fgCSSStyles;
private static String getCSSStyles() {
if (fgCSSStyles == null) {
Bundle bundle = Platform.getBundle(VjetUIPlugin.PLUGIN_ID);
URL url = bundle.getEntry("/DocumentationHoverStyleSheet.css"); //$NON-NLS-1$
if (url != null) {
try {
url = FileLocator.toFileURL(url);
BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer(200);
String line = reader.readLine();
while (line != null) {
buffer.append(line);
buffer.append('\n');
line = reader.readLine();
}
fgCSSStyles = buffer.toString();
} catch (IOException ex) {
DLTKUIPlugin.log(ex);
}
}
}
String css = fgCSSStyles;
if (css != null) {
FontData fontData = JFaceResources.getFontRegistry().getFontData(
PreferenceConstants.APPEARANCE_DOCUMENTATION_FONT)[0];
css = HTMLPrinter.convertTopLevelFont(css, fontData);
}
return css;
}
/**
* Gets the reader content as a String
*/
private static String getString(Reader reader) {
StringBuffer buf = new StringBuffer();
char[] buffer = new char[1024];
int count;
try {
while ((count = reader.read(buffer)) != -1)
buf.append(buffer, 0, count);
} catch (IOException e) {
return null;
}
return buf.toString();
}
public static String getElementBriefDesc(IJstProperty property) {
StringBuffer buffer = new StringBuffer();
buffer.append(property.getOwnerType().getName() + "\n");
// buffer.append("<dl><dt>");
buffer.append(getModifierListStr(property.getModifiers()) + " <b>");
buffer.append(property.getName() + "</b> ");
// buffer.append("</dt><dd></dd></dl>");
return buffer.toString();
}
public static String getElementBriefDesc(IJstMethod method) {
StringBuffer buffer = new StringBuffer();
// buffer.append("<dl><dt>");
String rtnTypeName = "";
IJstType rtnType = method.getRtnType();
if(rtnType!=null){
rtnTypeName = rtnType.getName();
}
buffer.append( " <b>" + rtnTypeName + "</b> ");
buffer.append(getModifierListStr(method.getModifiers()) + " "
+ method.getName());
// buffer.append("</dt></dl>");
buffer.append("(" + combineParameters(method) + ")");
return buffer.toString();
}
/**
* @param method
* @return
*/
private static String combineParameters(IJstMethod method) {
String par = "";
if (method != null) {
List<JstArg> args = method.getArgs();
String comma = "";
int i = 0;
for (JstArg arg : args) {
if (i != 0) {
comma = ", ";
}
par += comma + arg.getType().getSimpleName() + " "
+ arg.getName();
i++;
}
}
return par;
}
public static String getModifierListStr(JstModifiers jstModifiers) {
List<BaseJstNode> list = jstModifiers.getChildren();
if (list == null || list.isEmpty()) {
return "";
}
StringBuffer buffer = new StringBuffer();
Iterator<BaseJstNode> it = list.iterator();
while (it.hasNext()) {
BaseJstNode node = it.next();
buffer.append("");
}
return buffer.toString();
}
private static String getSupportedTypesStirng(List<String> supportedTypes,
String type) {
String imageLine = "";
String comma = "";
int i = 0;
for (Object oneType : supportedTypes) {
if (((String) oneType).startsWith(type)) {
if (i != 0) {
comma = ", ";
}
imageLine += comma
+ ((String) oneType).substring(type.length());
i++;
}
}
boolean noBrowserInfo = noBrowserInfo(supportedTypes);
if (noBrowserInfo && "BrowserType.".equals(type)) {
//imageLine = "FIREFOX,IE,OPERA,SAFARI,CHROME";
}
return imageLine;
}
/**
* @param supportedTypes
* @return
*/
private static String getIcon(List<String> supportedTypes) {
String imageLine = "";
String path = getDir().getPath();
boolean noBrowserInfo = false;
if (getDescOfSupport(supportedTypes, "FIREFOX").trim().length() > 0
|| noBrowserInfo) {
imageLine += "<img aligh=\"right\" src=\""
+ path
+ "/firefox.gif\" height=\"25\" width=\"25\" border=\"0\" title=\""
+ getDescOfSupport(supportedTypes, "MOZILLA") + "\">";
}
if (getDescOfSupport(supportedTypes, "IE").trim().length() > 0
|| noBrowserInfo) {
imageLine += "<img aligh=\"right\" src=\""
+ path
+ "/ie.gif\" height=\"25\" width=\"25\" border=\"0\" title=\""
+ getDescOfSupport(supportedTypes, "IE") + "\">";
}
if (getDescOfSupport(supportedTypes, "OPERA").trim().length() > 0
|| noBrowserInfo) {
imageLine += "<img aligh=\"right\" src=\""
+ path
+ "/opera.gif\" height=\"25\" width=\"25\" border=\"0\" title=\""
+ getDescOfSupport(supportedTypes, "OPERA") + "\">";
}
if (getDescOfSupport(supportedTypes, "SAFARI").trim().length() > 0
|| noBrowserInfo) {
imageLine += "<img aligh=\"right\" src=\""
+ path
+ "/safari.gif\" height=\"25\" width=\"25\" border=\"0\" title=\""
+ getDescOfSupport(supportedTypes, "SAFARI") + "\">";
}
if (getDescOfSupport(supportedTypes, "CHROME").trim().length() > 0
|| noBrowserInfo) {
imageLine += "<img aligh=\"right\" src=\""
+ path
+ "/chrome.gif\" height=\"25\" width=\"25\" border=\"0\" title=\""
+ getDescOfSupport(supportedTypes, "CHROME") + "\">";
}
return imageLine;
}
/**
* @param supportedTypes
* @return
*/
private static boolean noBrowserInfo(List supportedTypes) {
boolean noBrowserInfo = true;
for (Object type : supportedTypes) {
if (((String) type).contains("BrowserType.")) {
noBrowserInfo = false;
break;
}
}
return noBrowserInfo;
}
/**
* @param jstElement
* @return
*/
private static List<String> fillAllSupportedExplorer(Object jstElement,
List<String> allSupportedExplorers) {
if (jstElement instanceof IJstProperty) {
List<IJstAnnotation> annotations = ((IJstProperty) jstElement).getAnnotations();
getExplorerInfoFromAnnotation(allSupportedExplorers, annotations);
if (annotations.size() == 0) {
fillAllSupportedExplorer(((IJstProperty) jstElement)
.getOwnerType(), allSupportedExplorers);
}
} else if (jstElement instanceof IJstMethod) {
List<IJstAnnotation> annotations = ((IJstMethod) jstElement).getAnnotations();
getExplorerInfoFromAnnotation(allSupportedExplorers, annotations);
if (annotations.size() == 0) {
fillAllSupportedExplorer(((IJstMethod) jstElement)
.getOwnerType(), allSupportedExplorers);
}
} else if (jstElement instanceof IJstType) {
List<IJstAnnotation> annotations = ((IJstType) jstElement).getAnnotations();
getExplorerInfoFromAnnotation(allSupportedExplorers, annotations);
}
return allSupportedExplorers;
}
public static boolean isBrowserNoneNode(IJstNode node) {
if (!(node instanceof IJstMethod || node instanceof IJstProperty)) {
return false;
}
List<IJstAnnotation> annotations = node.getAnnotations();
if (annotations.size() != 1) {
return false;
}
List<String> allSupportedExplorers = new ArrayList<String>();
getExplorerInfoFromAnnotation(allSupportedExplorers, annotations);
if (allSupportedExplorers.size() != 0 && "BrowserType.NONE".equals(allSupportedExplorers.get(0))) {
return true;
} else {
return false;
}
}
/**
* @param allSupportedExplorers
* @param annotations
*/
static void getExplorerInfoFromAnnotation(
List<String> allSupportedExplorers, List<IJstAnnotation> annotations) {
for (Object annotation : annotations) {
if (annotation instanceof JstAnnotation
&& ("JsSupport".equals(((JstAnnotation) annotation)
.getName().getName())) ||
"BrowserSupport".equals(((JstAnnotation) annotation)
.getName().getName()) ||
"DOMSupport".equals(((JstAnnotation) annotation)
.getName().getName())) {
for (IExpr expr : ((JstAnnotation) annotation).values()) {
// array initializier
if(expr instanceof JstIdentifier){
String typeName = expr.toExprText();
if (!allSupportedExplorers
.contains(typeName)) {
allSupportedExplorers.add(typeName);
}
}
if(expr instanceof JstArrayInitializer){
JstArrayInitializer init = (JstArrayInitializer)expr;
String typeString = init.toExprText();
if (typeString.length() > 1) {
if (typeString.startsWith("[")
&& typeString.endsWith("]")) {
typeString = typeString.substring(1,
typeString.length() - 1);
}
String[] type = typeString.split(",");
for (String typeName : type) {
if (!allSupportedExplorers
.contains(typeName)) {
allSupportedExplorers.add(typeName);
}
}
}
}
if (expr instanceof AssignExpr) {
List<? extends IJstNode> supportTypes = ((AssignExpr) expr).getExpr()
.getChildren();
for (Object supportType : supportTypes) {
if (supportType instanceof JstIdentifier) {
String typeString = ((JstIdentifier) supportType)
.getParentNode().toString();
if (typeString.length() > 1) {
if (typeString.startsWith("[")
&& typeString.endsWith("]")) {
typeString = typeString.substring(1,
typeString.length() - 1);
}
String[] type = typeString.split(",");
for (String typeName : type) {
if (!allSupportedExplorers
.contains(typeName)) {
allSupportedExplorers.add(typeName);
}
}
}
}
}
}
}
}
}
}
/**
* Copy the html template to temporary folder.
*/
private static void copyHtmlTemplateFromBundleToTemp() {
String[] htmlFiles = new String[] { PERS_FILENAME };
for (String file : htmlFiles) {
copyFileFromBundleToTemp("templates", file);
}
}
/**
* Copy current icons to temporary folder.
*/
private static void copyIconsFromBundleToTemp() {
String[] icons = new String[] { "chrome.gif", "firefox.gif", "ie.gif",
"opera.gif", "safari.gif" };
for (String icon : icons) {
copyFileFromBundleToTemp("icons", icon);
}
}
private static File getDir() {
File dir = VjetUIPlugin.getDefault().getStateLocation().toFile();
dir = new File(dir, PERS_FOLDER);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
private static File getTemplateFile() {
File dir = getDir();
File persFile = new File(dir, PERS_FILENAME);
return persFile;
}
/**
* Copy specified icon to temporary folder.
*
* @param folderName
* TODO
*/
private static void copyFileFromBundleToTemp(String folderName,
String fileName) {
try {
File persFile = new File(getDir(), fileName);
URL url = VjetUIPlugin.getDefault().getBundle().getEntry(
folderName + "/" + fileName);
InputStream stream = url.openStream();
byte[] bs = new byte[stream.available()];
stream.read(bs);
FileOutputStream fop = new FileOutputStream(persFile);
if (persFile.exists()) {
fop.write(bs);
fop.flush();
fop.close();
}
} catch (IOException e) {
}
}
/**
* @param supportedTypes
* @param type
* @return
*/
private static String getDescOfSupport(List<String> supportedTypes,
String type) {
for (String everyType : supportedTypes) {
if (everyType.contains(type)) {
return everyType;
}
}
return "";
}
/**
* @param desc
* @return
*/
private static String translateCharacterToNumber(String desc) {
if (desc != null) {
String[] numbers = { "_ZERO", "_ONE", "_TWO", "_THREE", "_FOUR",
"_FIVE", "_SIX", "_SEVEN", "_EIGHT", "_NINE" };
for (int i = 0; i < numbers.length; i++) {
if (desc.contains(numbers[i])) {
desc = desc.replace(numbers[i], String.valueOf(i));
}
}
if (desc.contains("_DOT")) {
desc = desc.replace("_DOT", ".");
}
}
return desc;
}
/**
* @param baseUrl
* @param create
*/
private static void generateTempFolder(URL baseUrl, boolean create) {
if (baseUrl == null) {
return;
}
try {
// make sure the directory exists
URL url = new URL(baseUrl, PERS_FOLDER);
File dir = new File(url.getFile());
if (!dir.exists() && create) {
dir.mkdir();
}
} catch (IOException e) {
}
}
}
| true | true | public static String getAdditionalPropesalInfo(IJstNode node) {
String info = null;
String css = getCSSStyles();
List<String> allSupportedExplorers = new ArrayList<String>();
IJstProperty property = null;
IJstMethod method = null;
if (node instanceof IJstProperty) {
property = (IJstProperty) node;
} else if (node instanceof IJstMethod) {
method = (IJstMethod) node;
}
String briefInfo = "";
if (property != null && property.getCommentLocations() != null) {
List<String> strings = JstCommentHelper.getCommentsAsString(node.getOwnerType(), node.getCommentLocations());
StringBuilder sb = new StringBuilder();
for(String str:strings){
if(str!=null)
sb.append(JsDocHelper.cleanJsDocComment(str));
sb.append("<br>");
}
info = sb.toString();
briefInfo = getElementBriefDesc(property);
fillAllSupportedExplorer(property, allSupportedExplorers);
} else {
if ((method != null) && (method.getDoc() != null)) {
info = method.getDoc().getComment();
briefInfo = getElementBriefDesc(method);
fillAllSupportedExplorer(method, allSupportedExplorers);
}
}
if (info != null) {
try {
File persFile = getTemplateFile();
if (!persFile.exists()) {
try {
persFile.createNewFile();
} catch (IOException e) {
}
copyHtmlTemplateFromBundleToTemp();
copyIconsFromBundleToTemp();
}
// Replace the invalid character.
info = info.replace("/", "");
info = info.replace("*", "");
if (persFile != null) {
FileReader readerSuc = new FileReader(persFile);
JavaDoc2HTMLTextReader reader2 = new JavaDoc2HTMLTextReader(
readerSuc);
String wholeInfo = getString(reader2);
wholeInfo = wholeInfo.replace("<%=browserSupported%>",
getSupportedTypesStirng(allSupportedExplorers,
"BrowserType."));
String domLevel = getSupportedTypesStirng(
allSupportedExplorers, "DomLevel.");
if (domLevel.length() > 0) {
wholeInfo = wholeInfo.replace("<%=DOMLevel%>",
"<b>DOM level</b><br>"
+ getSupportedTypesStirng(
allSupportedExplorers,
"DomLevel.") + "<br>");
}else{
wholeInfo = wholeInfo.replace("<%=DOMLevel%>",
"");
}
wholeInfo = wholeInfo.replace("<%=MinJSVersion%>",
translateCharacterToNumber(getSupportedTypesStirng(
allSupportedExplorers, "JsVersion.")));
wholeInfo = wholeInfo.replace("<%=briefInfo%>", briefInfo);
wholeInfo = wholeInfo.replace("<%=images%>",
getIcon(allSupportedExplorers));
wholeInfo = wholeInfo.replace("<%=description%>", info);
// Add the css and HTML tags at the beginning and
// end.
StringBuffer buffer = new StringBuffer();
HTMLPrinter.insertPageProlog(buffer, 0, css);
buffer.append(wholeInfo);
HTMLPrinter.addPageEpilog(buffer);
wholeInfo = buffer.toString();
return wholeInfo;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return info;
}
| public static String getAdditionalPropesalInfo(IJstNode node) {
String info = null;
String css = getCSSStyles();
List<String> allSupportedExplorers = new ArrayList<String>();
IJstProperty property = null;
IJstMethod method = null;
if (node instanceof IJstProperty) {
property = (IJstProperty) node;
} else if (node instanceof IJstMethod) {
method = (IJstMethod) node;
}
String briefInfo = "";
if (property != null && property.getCommentLocations() != null && !node.getCommentLocations().isEmpty()) {
List<String> strings = JstCommentHelper.getCommentsAsString(node.getOwnerType(), node.getCommentLocations());
StringBuilder sb = new StringBuilder();
for(String str:strings){
if(str!=null)
sb.append(JsDocHelper.cleanJsDocComment(str));
sb.append("<br>");
}
info = sb.toString();
briefInfo = getElementBriefDesc(property);
fillAllSupportedExplorer(property, allSupportedExplorers);
} else {
if ((method != null) && (method.getDoc() != null)) {
info = method.getDoc().getComment();
briefInfo = getElementBriefDesc(method);
fillAllSupportedExplorer(method, allSupportedExplorers);
}
}
if (info != null) {
try {
File persFile = getTemplateFile();
if (!persFile.exists()) {
try {
persFile.createNewFile();
} catch (IOException e) {
}
copyHtmlTemplateFromBundleToTemp();
copyIconsFromBundleToTemp();
}
// Replace the invalid character.
info = info.replace("/", "");
info = info.replace("*", "");
if (persFile != null) {
FileReader readerSuc = new FileReader(persFile);
JavaDoc2HTMLTextReader reader2 = new JavaDoc2HTMLTextReader(
readerSuc);
String wholeInfo = getString(reader2);
wholeInfo = wholeInfo.replace("<%=browserSupported%>",
getSupportedTypesStirng(allSupportedExplorers,
"BrowserType."));
String domLevel = getSupportedTypesStirng(
allSupportedExplorers, "DomLevel.");
if (domLevel.length() > 0) {
wholeInfo = wholeInfo.replace("<%=DOMLevel%>",
"<b>DOM level</b><br>"
+ getSupportedTypesStirng(
allSupportedExplorers,
"DomLevel.") + "<br>");
}else{
wholeInfo = wholeInfo.replace("<%=DOMLevel%>",
"");
}
wholeInfo = wholeInfo.replace("<%=MinJSVersion%>",
translateCharacterToNumber(getSupportedTypesStirng(
allSupportedExplorers, "JsVersion.")));
wholeInfo = wholeInfo.replace("<%=briefInfo%>", briefInfo);
wholeInfo = wholeInfo.replace("<%=images%>",
getIcon(allSupportedExplorers));
wholeInfo = wholeInfo.replace("<%=description%>", info);
// Add the css and HTML tags at the beginning and
// end.
StringBuffer buffer = new StringBuffer();
HTMLPrinter.insertPageProlog(buffer, 0, css);
buffer.append(wholeInfo);
HTMLPrinter.addPageEpilog(buffer);
wholeInfo = buffer.toString();
return wholeInfo;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return info;
}
|
diff --git a/redis/modules/src/main/java/org/atmosphere/plugin/redis/RedisBroadcaster.java b/redis/modules/src/main/java/org/atmosphere/plugin/redis/RedisBroadcaster.java
index 185d4098..148913e9 100644
--- a/redis/modules/src/main/java/org/atmosphere/plugin/redis/RedisBroadcaster.java
+++ b/redis/modules/src/main/java/org/atmosphere/plugin/redis/RedisBroadcaster.java
@@ -1,100 +1,100 @@
/*
* Copyright 2013 Jeanfrancois Arcand
*
* 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.atmosphere.plugin.redis;
import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.Broadcaster;
import org.atmosphere.util.AbstractBroadcasterProxy;
import java.net.URI;
/**
* Simple {@link org.atmosphere.cpr.Broadcaster} implementation based on Jedis
*
* @author Jeanfrancois Arcand
*/
public class RedisBroadcaster extends AbstractBroadcasterProxy {
private RedisUtil redisUtil;
public RedisBroadcaster() {}
public Broadcaster initialize(String id, AtmosphereConfig config) {
return super.initialize(id, URI.create("http://localhost:6379"), config);
}
public Broadcaster initialize(String id, URI uri, AtmosphereConfig config) {
- super.initialize(id, URI.create("http://localhost:6379"), config);
+ super.initialize(id, uri, config);
this.redisUtil = new RedisUtil(uri, config, new RedisUtil.Callback() {
@Override
public String getID() {
return RedisBroadcaster.this.getID();
}
@Override
public void broadcastReceivedMessage(String message) {
RedisBroadcaster.this.broadcastReceivedMessage(message);
}
});
return this;
}
public String getAuth() {
return redisUtil.getAuth();
}
public void setAuth(String auth) {
redisUtil.setAuth(auth);
}
public synchronized void setUp() {
redisUtil.configure();
}
@Override
public synchronized void setID(String id) {
super.setID(id);
setUp();
reconfigure();
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() {
super.destroy();
redisUtil.destroy();
}
/**
* {@inheritDoc}
*/
@Override
public void incomingBroadcast() {
redisUtil.incomingBroadcast();
}
/**
* {@inheritDoc}
*/
@Override
public void outgoingBroadcast(Object message) {
redisUtil.outgoingBroadcast(message);
}
}
| true | true | public Broadcaster initialize(String id, URI uri, AtmosphereConfig config) {
super.initialize(id, URI.create("http://localhost:6379"), config);
this.redisUtil = new RedisUtil(uri, config, new RedisUtil.Callback() {
@Override
public String getID() {
return RedisBroadcaster.this.getID();
}
@Override
public void broadcastReceivedMessage(String message) {
RedisBroadcaster.this.broadcastReceivedMessage(message);
}
});
return this;
}
| public Broadcaster initialize(String id, URI uri, AtmosphereConfig config) {
super.initialize(id, uri, config);
this.redisUtil = new RedisUtil(uri, config, new RedisUtil.Callback() {
@Override
public String getID() {
return RedisBroadcaster.this.getID();
}
@Override
public void broadcastReceivedMessage(String message) {
RedisBroadcaster.this.broadcastReceivedMessage(message);
}
});
return this;
}
|
diff --git a/ratpack-groovy/src/main/java/org/ratpackframework/groovy/templating/internal/TemplateRenderingClientErrorHandler.java b/ratpack-groovy/src/main/java/org/ratpackframework/groovy/templating/internal/TemplateRenderingClientErrorHandler.java
index 3dc9864d2..f84458cb2 100644
--- a/ratpack-groovy/src/main/java/org/ratpackframework/groovy/templating/internal/TemplateRenderingClientErrorHandler.java
+++ b/ratpack-groovy/src/main/java/org/ratpackframework/groovy/templating/internal/TemplateRenderingClientErrorHandler.java
@@ -1,48 +1,49 @@
/*
* Copyright 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.ratpackframework.groovy.templating.internal;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.ratpackframework.error.ClientErrorHandler;
import org.ratpackframework.groovy.templating.TemplateRenderer;
import org.ratpackframework.handling.Exchange;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class TemplateRenderingClientErrorHandler implements ClientErrorHandler {
public void error(Exchange exchange, int statusCode) {
TemplateRenderer renderer = exchange.get(TemplateRenderer.class);
Map<String, Object> model = new HashMap<String, Object>();
HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode);
model.put("title", status.reasonPhrase());
model.put("message", status.reasonPhrase());
Map<String, Object> metadata = new LinkedHashMap<String, Object>();
metadata.put("Request Method", exchange.getRequest().getMethod().getName());
metadata.put("Request URL", exchange.getRequest().getUri());
+ model.put("metadata", metadata);
exchange.getResponse().status(statusCode);
renderer.error(model);
}
}
| true | true | public void error(Exchange exchange, int statusCode) {
TemplateRenderer renderer = exchange.get(TemplateRenderer.class);
Map<String, Object> model = new HashMap<String, Object>();
HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode);
model.put("title", status.reasonPhrase());
model.put("message", status.reasonPhrase());
Map<String, Object> metadata = new LinkedHashMap<String, Object>();
metadata.put("Request Method", exchange.getRequest().getMethod().getName());
metadata.put("Request URL", exchange.getRequest().getUri());
exchange.getResponse().status(statusCode);
renderer.error(model);
}
| public void error(Exchange exchange, int statusCode) {
TemplateRenderer renderer = exchange.get(TemplateRenderer.class);
Map<String, Object> model = new HashMap<String, Object>();
HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode);
model.put("title", status.reasonPhrase());
model.put("message", status.reasonPhrase());
Map<String, Object> metadata = new LinkedHashMap<String, Object>();
metadata.put("Request Method", exchange.getRequest().getMethod().getName());
metadata.put("Request URL", exchange.getRequest().getUri());
model.put("metadata", metadata);
exchange.getResponse().status(statusCode);
renderer.error(model);
}
|
diff --git a/org.eclipse.mylyn.bugzilla.tests/src/org/eclipse/mylyn/bugzilla/tests/core/BugzillaFlagsTest.java b/org.eclipse.mylyn.bugzilla.tests/src/org/eclipse/mylyn/bugzilla/tests/core/BugzillaFlagsTest.java
index 6e1b870a1..dfe622dcc 100644
--- a/org.eclipse.mylyn.bugzilla.tests/src/org/eclipse/mylyn/bugzilla/tests/core/BugzillaFlagsTest.java
+++ b/org.eclipse.mylyn.bugzilla.tests/src/org/eclipse/mylyn/bugzilla/tests/core/BugzillaFlagsTest.java
@@ -1,242 +1,242 @@
/*******************************************************************************
* Copyright (c) 2010 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.bugzilla.tests.core;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
import org.eclipse.mylyn.bugzilla.tests.support.BugzillaFixture;
import org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskData;
/**
* Tests should be run against Bugzilla 3.2.4 or greater
*
* @author Frank Becker
* @author Robert Elves
*/
public class BugzillaFlagsTest extends TestCase {
private BugzillaClient client;
@Override
protected void setUp() throws Exception {
client = BugzillaFixture.current().client();
}
@SuppressWarnings("null")
public void testFlags() throws Exception {
String taskNumber = "2";
TaskData taskData = BugzillaFixture.current().getTask(taskNumber, client);
assertNotNull(taskData);
Collection<TaskAttribute> a = taskData.getRoot().getAttributes().values();
TaskAttribute flagA = null;
TaskAttribute flagB = null;
TaskAttribute flagC = null;
TaskAttribute flagD = null;
TaskAttribute stateA = null;
TaskAttribute stateB = null;
TaskAttribute stateC = null;
TaskAttribute stateD = null;
for (TaskAttribute taskAttribute : a) {
if (taskAttribute.getId().startsWith("task.common.kind.flag")) {
TaskAttribute state = taskAttribute.getAttribute("state");
if (state.getMetaData().getLabel().equals("BugFlag1")) {
flagA = taskAttribute;
stateA = state;
} else if (state.getMetaData().getLabel().equals("BugFlag2")) {
flagB = taskAttribute;
stateB = state;
} else if (state.getMetaData().getLabel().equals("BugFlag3")) {
flagC = taskAttribute;
stateC = state;
} else if (state.getMetaData().getLabel().equals("BugFlag4")) {
flagD = taskAttribute;
stateD = state;
}
}
}
assertNotNull(flagA);
assertNotNull(flagB);
assertNotNull(flagC);
assertNotNull(flagD);
assertNotNull(stateA);
assertNotNull(stateB);
assertNotNull(stateC);
assertNotNull(stateD);
assertEquals("flagA is set(wrong precondidion)", " ", stateA.getValue());
assertEquals("flagB is set(wrong precondidion)", " ", stateB.getValue());
assertEquals("flagC is set(wrong precondidion)", " ", stateC.getValue());
assertEquals("flagD is set(wrong precondidion)", " ", stateD.getValue());
assertEquals("task.common.kind.flag_type1", flagA.getId());
assertEquals("task.common.kind.flag_type2", flagB.getId());
assertEquals("task.common.kind.flag_type5", flagC.getId());
assertEquals("task.common.kind.flag_type6", flagD.getId());
Map<String, String> optionA = stateA.getOptions();
Map<String, String> optionB = stateB.getOptions();
Map<String, String> optionC = stateC.getOptions();
Map<String, String> optionD = stateD.getOptions();
assertEquals(true, optionA.containsKey(""));
assertEquals(false, optionA.containsKey("?"));
assertEquals(true, optionA.containsKey("+"));
assertEquals(true, optionA.containsKey("-"));
assertEquals(true, optionB.containsKey(""));
assertEquals(true, optionB.containsKey("?"));
assertEquals(true, optionB.containsKey("+"));
assertEquals(true, optionB.containsKey("-"));
assertEquals(true, optionC.containsKey(""));
assertEquals(true, optionC.containsKey("?"));
assertEquals(true, optionC.containsKey("+"));
assertEquals(true, optionC.containsKey("-"));
assertEquals(true, optionD.containsKey(""));
assertEquals(true, optionD.containsKey("?"));
assertEquals(true, optionD.containsKey("+"));
assertEquals(true, optionD.containsKey("-"));
Set<TaskAttribute> changed = new HashSet<TaskAttribute>();
stateA.setValue("+");
stateB.setValue("?");
stateC.setValue("?");
stateD.setValue("?");
TaskAttribute requesteeD = flagD.getAttribute("requestee");
requesteeD.setValue("[email protected]");
changed.add(flagA);
changed.add(flagB);
changed.add(flagC);
changed.add(flagD);
BugzillaFixture.current().submitTask(taskData, client);
taskData = BugzillaFixture.current().getTask(taskNumber, client);
assertNotNull(taskData);
a = taskData.getRoot().getAttributes().values();
flagA = null;
flagB = null;
flagC = null;
TaskAttribute flagC2 = null;
flagD = null;
stateA = null;
stateB = null;
stateC = null;
TaskAttribute stateC2 = null;
stateD = null;
for (TaskAttribute taskAttribute : a) {
if (taskAttribute.getId().startsWith("task.common.kind.flag")) {
TaskAttribute state = taskAttribute.getAttribute("state");
if (state.getMetaData().getLabel().equals("BugFlag1")) {
flagA = taskAttribute;
stateA = state;
} else if (state.getMetaData().getLabel().equals("BugFlag2")) {
flagB = taskAttribute;
stateB = state;
} else if (state.getMetaData().getLabel().equals("BugFlag3")) {
if (flagC == null) {
flagC = taskAttribute;
stateC = state;
} else {
flagC2 = taskAttribute;
stateC2 = state;
}
} else if (state.getMetaData().getLabel().equals("BugFlag4")) {
flagD = taskAttribute;
stateD = state;
}
}
}
assertNotNull(flagA);
assertNotNull(flagB);
assertNotNull(flagC);
assertNotNull(flagC2);
assertNotNull(flagD);
assertNotNull(stateA);
assertNotNull(stateB);
assertNotNull(stateC);
assertNotNull(stateC2);
assertNotNull(stateD);
assertEquals("+", stateA.getValue());
assertEquals("?", stateB.getValue());
assertEquals("?", stateC.getValue());
assertEquals(" ", stateC2.getValue());
assertEquals("?", stateD.getValue());
requesteeD = flagD.getAttribute("requestee");
assertNotNull(requesteeD);
assertEquals("[email protected]", requesteeD.getValue());
stateA.setValue(" ");
- stateB.setValue(" ");
+ stateB.setValue("");
stateC.setValue(" ");
- stateD.setValue(" ");
+ stateD.setValue("");
changed.add(flagA);
changed.add(flagB);
changed.add(flagC);
changed.add(flagD);
BugzillaFixture.current().submitTask(taskData, client);
taskData = BugzillaFixture.current().getTask(taskNumber, client);
assertNotNull(taskData);
a = taskData.getRoot().getAttributes().values();
flagA = null;
flagB = null;
flagC = null;
flagC2 = null;
flagD = null;
stateA = null;
stateB = null;
stateC = null;
stateC2 = null;
stateD = null;
for (TaskAttribute taskAttribute : a) {
if (taskAttribute.getId().startsWith("task.common.kind.flag")) {
TaskAttribute state = taskAttribute.getAttribute("state");
if (state.getMetaData().getLabel().equals("BugFlag1")) {
flagA = taskAttribute;
stateA = state;
} else if (state.getMetaData().getLabel().equals("BugFlag2")) {
flagB = taskAttribute;
stateB = state;
} else if (state.getMetaData().getLabel().equals("BugFlag3")) {
if (flagC == null) {
flagC = taskAttribute;
stateC = state;
} else {
flagC2 = taskAttribute;
stateC2 = state;
}
} else if (state.getMetaData().getLabel().equals("BugFlag4")) {
flagD = taskAttribute;
stateD = state;
}
}
}
assertNotNull(flagA);
assertNotNull(flagB);
assertNotNull(flagC);
assertNull(flagC2);
assertNotNull(flagD);
assertNotNull(stateA);
assertNotNull(stateB);
assertNotNull(stateC);
assertNull(stateC2);
assertNotNull(stateD);
assertEquals(" ", stateA.getValue());
assertEquals(" ", stateB.getValue());
assertEquals(" ", stateC.getValue());
assertEquals(" ", stateD.getValue());
requesteeD = flagD.getAttribute("requestee");
assertNotNull(requesteeD);
assertEquals("", requesteeD.getValue());
}
}
| false | true | public void testFlags() throws Exception {
String taskNumber = "2";
TaskData taskData = BugzillaFixture.current().getTask(taskNumber, client);
assertNotNull(taskData);
Collection<TaskAttribute> a = taskData.getRoot().getAttributes().values();
TaskAttribute flagA = null;
TaskAttribute flagB = null;
TaskAttribute flagC = null;
TaskAttribute flagD = null;
TaskAttribute stateA = null;
TaskAttribute stateB = null;
TaskAttribute stateC = null;
TaskAttribute stateD = null;
for (TaskAttribute taskAttribute : a) {
if (taskAttribute.getId().startsWith("task.common.kind.flag")) {
TaskAttribute state = taskAttribute.getAttribute("state");
if (state.getMetaData().getLabel().equals("BugFlag1")) {
flagA = taskAttribute;
stateA = state;
} else if (state.getMetaData().getLabel().equals("BugFlag2")) {
flagB = taskAttribute;
stateB = state;
} else if (state.getMetaData().getLabel().equals("BugFlag3")) {
flagC = taskAttribute;
stateC = state;
} else if (state.getMetaData().getLabel().equals("BugFlag4")) {
flagD = taskAttribute;
stateD = state;
}
}
}
assertNotNull(flagA);
assertNotNull(flagB);
assertNotNull(flagC);
assertNotNull(flagD);
assertNotNull(stateA);
assertNotNull(stateB);
assertNotNull(stateC);
assertNotNull(stateD);
assertEquals("flagA is set(wrong precondidion)", " ", stateA.getValue());
assertEquals("flagB is set(wrong precondidion)", " ", stateB.getValue());
assertEquals("flagC is set(wrong precondidion)", " ", stateC.getValue());
assertEquals("flagD is set(wrong precondidion)", " ", stateD.getValue());
assertEquals("task.common.kind.flag_type1", flagA.getId());
assertEquals("task.common.kind.flag_type2", flagB.getId());
assertEquals("task.common.kind.flag_type5", flagC.getId());
assertEquals("task.common.kind.flag_type6", flagD.getId());
Map<String, String> optionA = stateA.getOptions();
Map<String, String> optionB = stateB.getOptions();
Map<String, String> optionC = stateC.getOptions();
Map<String, String> optionD = stateD.getOptions();
assertEquals(true, optionA.containsKey(""));
assertEquals(false, optionA.containsKey("?"));
assertEquals(true, optionA.containsKey("+"));
assertEquals(true, optionA.containsKey("-"));
assertEquals(true, optionB.containsKey(""));
assertEquals(true, optionB.containsKey("?"));
assertEquals(true, optionB.containsKey("+"));
assertEquals(true, optionB.containsKey("-"));
assertEquals(true, optionC.containsKey(""));
assertEquals(true, optionC.containsKey("?"));
assertEquals(true, optionC.containsKey("+"));
assertEquals(true, optionC.containsKey("-"));
assertEquals(true, optionD.containsKey(""));
assertEquals(true, optionD.containsKey("?"));
assertEquals(true, optionD.containsKey("+"));
assertEquals(true, optionD.containsKey("-"));
Set<TaskAttribute> changed = new HashSet<TaskAttribute>();
stateA.setValue("+");
stateB.setValue("?");
stateC.setValue("?");
stateD.setValue("?");
TaskAttribute requesteeD = flagD.getAttribute("requestee");
requesteeD.setValue("[email protected]");
changed.add(flagA);
changed.add(flagB);
changed.add(flagC);
changed.add(flagD);
BugzillaFixture.current().submitTask(taskData, client);
taskData = BugzillaFixture.current().getTask(taskNumber, client);
assertNotNull(taskData);
a = taskData.getRoot().getAttributes().values();
flagA = null;
flagB = null;
flagC = null;
TaskAttribute flagC2 = null;
flagD = null;
stateA = null;
stateB = null;
stateC = null;
TaskAttribute stateC2 = null;
stateD = null;
for (TaskAttribute taskAttribute : a) {
if (taskAttribute.getId().startsWith("task.common.kind.flag")) {
TaskAttribute state = taskAttribute.getAttribute("state");
if (state.getMetaData().getLabel().equals("BugFlag1")) {
flagA = taskAttribute;
stateA = state;
} else if (state.getMetaData().getLabel().equals("BugFlag2")) {
flagB = taskAttribute;
stateB = state;
} else if (state.getMetaData().getLabel().equals("BugFlag3")) {
if (flagC == null) {
flagC = taskAttribute;
stateC = state;
} else {
flagC2 = taskAttribute;
stateC2 = state;
}
} else if (state.getMetaData().getLabel().equals("BugFlag4")) {
flagD = taskAttribute;
stateD = state;
}
}
}
assertNotNull(flagA);
assertNotNull(flagB);
assertNotNull(flagC);
assertNotNull(flagC2);
assertNotNull(flagD);
assertNotNull(stateA);
assertNotNull(stateB);
assertNotNull(stateC);
assertNotNull(stateC2);
assertNotNull(stateD);
assertEquals("+", stateA.getValue());
assertEquals("?", stateB.getValue());
assertEquals("?", stateC.getValue());
assertEquals(" ", stateC2.getValue());
assertEquals("?", stateD.getValue());
requesteeD = flagD.getAttribute("requestee");
assertNotNull(requesteeD);
assertEquals("[email protected]", requesteeD.getValue());
stateA.setValue(" ");
stateB.setValue(" ");
stateC.setValue(" ");
stateD.setValue(" ");
changed.add(flagA);
changed.add(flagB);
changed.add(flagC);
changed.add(flagD);
BugzillaFixture.current().submitTask(taskData, client);
taskData = BugzillaFixture.current().getTask(taskNumber, client);
assertNotNull(taskData);
a = taskData.getRoot().getAttributes().values();
flagA = null;
flagB = null;
flagC = null;
flagC2 = null;
flagD = null;
stateA = null;
stateB = null;
stateC = null;
stateC2 = null;
stateD = null;
for (TaskAttribute taskAttribute : a) {
if (taskAttribute.getId().startsWith("task.common.kind.flag")) {
TaskAttribute state = taskAttribute.getAttribute("state");
if (state.getMetaData().getLabel().equals("BugFlag1")) {
flagA = taskAttribute;
stateA = state;
} else if (state.getMetaData().getLabel().equals("BugFlag2")) {
flagB = taskAttribute;
stateB = state;
} else if (state.getMetaData().getLabel().equals("BugFlag3")) {
if (flagC == null) {
flagC = taskAttribute;
stateC = state;
} else {
flagC2 = taskAttribute;
stateC2 = state;
}
} else if (state.getMetaData().getLabel().equals("BugFlag4")) {
flagD = taskAttribute;
stateD = state;
}
}
}
assertNotNull(flagA);
assertNotNull(flagB);
assertNotNull(flagC);
assertNull(flagC2);
assertNotNull(flagD);
assertNotNull(stateA);
assertNotNull(stateB);
assertNotNull(stateC);
assertNull(stateC2);
assertNotNull(stateD);
assertEquals(" ", stateA.getValue());
assertEquals(" ", stateB.getValue());
assertEquals(" ", stateC.getValue());
assertEquals(" ", stateD.getValue());
requesteeD = flagD.getAttribute("requestee");
assertNotNull(requesteeD);
assertEquals("", requesteeD.getValue());
}
| public void testFlags() throws Exception {
String taskNumber = "2";
TaskData taskData = BugzillaFixture.current().getTask(taskNumber, client);
assertNotNull(taskData);
Collection<TaskAttribute> a = taskData.getRoot().getAttributes().values();
TaskAttribute flagA = null;
TaskAttribute flagB = null;
TaskAttribute flagC = null;
TaskAttribute flagD = null;
TaskAttribute stateA = null;
TaskAttribute stateB = null;
TaskAttribute stateC = null;
TaskAttribute stateD = null;
for (TaskAttribute taskAttribute : a) {
if (taskAttribute.getId().startsWith("task.common.kind.flag")) {
TaskAttribute state = taskAttribute.getAttribute("state");
if (state.getMetaData().getLabel().equals("BugFlag1")) {
flagA = taskAttribute;
stateA = state;
} else if (state.getMetaData().getLabel().equals("BugFlag2")) {
flagB = taskAttribute;
stateB = state;
} else if (state.getMetaData().getLabel().equals("BugFlag3")) {
flagC = taskAttribute;
stateC = state;
} else if (state.getMetaData().getLabel().equals("BugFlag4")) {
flagD = taskAttribute;
stateD = state;
}
}
}
assertNotNull(flagA);
assertNotNull(flagB);
assertNotNull(flagC);
assertNotNull(flagD);
assertNotNull(stateA);
assertNotNull(stateB);
assertNotNull(stateC);
assertNotNull(stateD);
assertEquals("flagA is set(wrong precondidion)", " ", stateA.getValue());
assertEquals("flagB is set(wrong precondidion)", " ", stateB.getValue());
assertEquals("flagC is set(wrong precondidion)", " ", stateC.getValue());
assertEquals("flagD is set(wrong precondidion)", " ", stateD.getValue());
assertEquals("task.common.kind.flag_type1", flagA.getId());
assertEquals("task.common.kind.flag_type2", flagB.getId());
assertEquals("task.common.kind.flag_type5", flagC.getId());
assertEquals("task.common.kind.flag_type6", flagD.getId());
Map<String, String> optionA = stateA.getOptions();
Map<String, String> optionB = stateB.getOptions();
Map<String, String> optionC = stateC.getOptions();
Map<String, String> optionD = stateD.getOptions();
assertEquals(true, optionA.containsKey(""));
assertEquals(false, optionA.containsKey("?"));
assertEquals(true, optionA.containsKey("+"));
assertEquals(true, optionA.containsKey("-"));
assertEquals(true, optionB.containsKey(""));
assertEquals(true, optionB.containsKey("?"));
assertEquals(true, optionB.containsKey("+"));
assertEquals(true, optionB.containsKey("-"));
assertEquals(true, optionC.containsKey(""));
assertEquals(true, optionC.containsKey("?"));
assertEquals(true, optionC.containsKey("+"));
assertEquals(true, optionC.containsKey("-"));
assertEquals(true, optionD.containsKey(""));
assertEquals(true, optionD.containsKey("?"));
assertEquals(true, optionD.containsKey("+"));
assertEquals(true, optionD.containsKey("-"));
Set<TaskAttribute> changed = new HashSet<TaskAttribute>();
stateA.setValue("+");
stateB.setValue("?");
stateC.setValue("?");
stateD.setValue("?");
TaskAttribute requesteeD = flagD.getAttribute("requestee");
requesteeD.setValue("[email protected]");
changed.add(flagA);
changed.add(flagB);
changed.add(flagC);
changed.add(flagD);
BugzillaFixture.current().submitTask(taskData, client);
taskData = BugzillaFixture.current().getTask(taskNumber, client);
assertNotNull(taskData);
a = taskData.getRoot().getAttributes().values();
flagA = null;
flagB = null;
flagC = null;
TaskAttribute flagC2 = null;
flagD = null;
stateA = null;
stateB = null;
stateC = null;
TaskAttribute stateC2 = null;
stateD = null;
for (TaskAttribute taskAttribute : a) {
if (taskAttribute.getId().startsWith("task.common.kind.flag")) {
TaskAttribute state = taskAttribute.getAttribute("state");
if (state.getMetaData().getLabel().equals("BugFlag1")) {
flagA = taskAttribute;
stateA = state;
} else if (state.getMetaData().getLabel().equals("BugFlag2")) {
flagB = taskAttribute;
stateB = state;
} else if (state.getMetaData().getLabel().equals("BugFlag3")) {
if (flagC == null) {
flagC = taskAttribute;
stateC = state;
} else {
flagC2 = taskAttribute;
stateC2 = state;
}
} else if (state.getMetaData().getLabel().equals("BugFlag4")) {
flagD = taskAttribute;
stateD = state;
}
}
}
assertNotNull(flagA);
assertNotNull(flagB);
assertNotNull(flagC);
assertNotNull(flagC2);
assertNotNull(flagD);
assertNotNull(stateA);
assertNotNull(stateB);
assertNotNull(stateC);
assertNotNull(stateC2);
assertNotNull(stateD);
assertEquals("+", stateA.getValue());
assertEquals("?", stateB.getValue());
assertEquals("?", stateC.getValue());
assertEquals(" ", stateC2.getValue());
assertEquals("?", stateD.getValue());
requesteeD = flagD.getAttribute("requestee");
assertNotNull(requesteeD);
assertEquals("[email protected]", requesteeD.getValue());
stateA.setValue(" ");
stateB.setValue("");
stateC.setValue(" ");
stateD.setValue("");
changed.add(flagA);
changed.add(flagB);
changed.add(flagC);
changed.add(flagD);
BugzillaFixture.current().submitTask(taskData, client);
taskData = BugzillaFixture.current().getTask(taskNumber, client);
assertNotNull(taskData);
a = taskData.getRoot().getAttributes().values();
flagA = null;
flagB = null;
flagC = null;
flagC2 = null;
flagD = null;
stateA = null;
stateB = null;
stateC = null;
stateC2 = null;
stateD = null;
for (TaskAttribute taskAttribute : a) {
if (taskAttribute.getId().startsWith("task.common.kind.flag")) {
TaskAttribute state = taskAttribute.getAttribute("state");
if (state.getMetaData().getLabel().equals("BugFlag1")) {
flagA = taskAttribute;
stateA = state;
} else if (state.getMetaData().getLabel().equals("BugFlag2")) {
flagB = taskAttribute;
stateB = state;
} else if (state.getMetaData().getLabel().equals("BugFlag3")) {
if (flagC == null) {
flagC = taskAttribute;
stateC = state;
} else {
flagC2 = taskAttribute;
stateC2 = state;
}
} else if (state.getMetaData().getLabel().equals("BugFlag4")) {
flagD = taskAttribute;
stateD = state;
}
}
}
assertNotNull(flagA);
assertNotNull(flagB);
assertNotNull(flagC);
assertNull(flagC2);
assertNotNull(flagD);
assertNotNull(stateA);
assertNotNull(stateB);
assertNotNull(stateC);
assertNull(stateC2);
assertNotNull(stateD);
assertEquals(" ", stateA.getValue());
assertEquals(" ", stateB.getValue());
assertEquals(" ", stateC.getValue());
assertEquals(" ", stateD.getValue());
requesteeD = flagD.getAttribute("requestee");
assertNotNull(requesteeD);
assertEquals("", requesteeD.getValue());
}
|
diff --git a/src/main/java/water/api/RequestBuilders.java b/src/main/java/water/api/RequestBuilders.java
index a85cfb924..8b5a20a87 100644
--- a/src/main/java/water/api/RequestBuilders.java
+++ b/src/main/java/water/api/RequestBuilders.java
@@ -1,1139 +1,1139 @@
package water.api;
import com.google.gson.*;
import water.AutoBuffer;
import water.H2O;
import water.Iced;
import water.PrettyPrint;
import water.api.Request.API;
import water.api.RequestBuilders.Response.Status;
import water.util.JsonUtil;
import water.util.Log;
import water.util.RString;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/** Builders & response object.
*
* It just has a stuff of simple builders that walk through the JSON response
* and format the stuff into basic html. Understands simplest form of tables,
* objects and elements.
*
* Also defines the response object that contains the response JSON, response
* state, other response related automatic variables (timing, etc) and the
* custom builders.
*
* TODO work in progress.
*
* @author peta
*/
public class RequestBuilders extends RequestQueries {
public static final String ROOT_OBJECT = "";
public static final Gson GSON_BUILDER = new GsonBuilder().setPrettyPrinting().create();
private static final ThreadLocal<DecimalFormat> _format = new ThreadLocal<DecimalFormat>() {
@Override protected DecimalFormat initialValue() {
return new DecimalFormat("###.####");
}
};
static final ThreadLocal<SimpleDateFormat> ISO8601 = new ThreadLocal<SimpleDateFormat>() {
@Override protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
}
};
/** Builds the HTML for the given response.
*
* This is the root of the HTML. Should display all what is needed, including
* the status, timing, etc. Then call the recursive builders for the
* response's JSON.
*/
protected String build(Response response) {
StringBuilder sb = new StringBuilder();
sb.append("<div class='container'>");
sb.append("<div class='row-fluid'>");
sb.append("<div class='span12'>");
sb.append(buildJSONResponseBox(response));
if( response._status == Response.Status.done ) response.toJava(sb);
sb.append(buildResponseHeader(response));
Builder builder = response.getBuilderFor(ROOT_OBJECT);
if (builder == null) {
sb.append("<h3>"+name()+"</h3>");
builder = OBJECT_BUILDER;
}
for( String h : response.getHeaders() ) sb.append(h);
if( response._response==null ) {
boolean done = response._req.toHTML(sb);
if(!done) {
JsonParser parser = new JsonParser();
String json = new String(response._req.writeJSON(new AutoBuffer()).buf());
JsonObject o = (JsonObject) parser.parse(json);
sb.append(builder.build(response, o, ""));
}
} else sb.append(builder.build(response,response._response,""));
sb.append("</div></div></div>");
return sb.toString();
}
protected String name() {
return getClass().getSimpleName();
}
private static final String _responseHeader =
"<table class='table table-bordered'><tr><td><table style='font-size:12px;margin:0px;' class='table-borderless'>"
+ " <tr>"
+ " <td style='border:0px' rowspan='2' style='vertical-align:top;'>%BUTTON </td>"
+ " <td style='border:0px' colspan='6'>"
+ " %TEXT"
+ " </td>"
+ " </tr>"
+ " <tr>"
+ " <td style='border:0px'><b>Cloud:</b></td>"
+ " <td style='padding-right:70px;border:0px'>%CLOUD_NAME</td>"
+ " <td style='border:0px'><b>Node:</b></td>"
+ " <td style='padding-right:70px;border:0px'>%NODE_NAME</td>"
+ " <td style='border:0px'><b>Time:</b></td>"
+ " <td style='padding-right:70px;border:0px'>%TIME</td>"
+ " </tr>"
+ "</table></td></tr></table>"
+ "<script type='text/javascript'>"
+ "%JSSTUFF"
+ "</script>"
;
private static final String _redirectJs =
"var timer = setTimeout('redirect()',000);\n"
+ "function countdown_stop() {\n"
+ " clearTimeout(timer);\n"
+ "}\n"
+ "function redirect() {\n"
+ " window.location.replace('%REDIRECT_URL');\n"
+ "}\n"
;
private static final String _pollJs =
"var timer = setTimeout(redirect,%TIMEOUT);\n"
+ "function countdown_stop() {\n"
+ " clearTimeout(timer);\n"
+ "}\n"
+ "function redirect() {\n"
+ " document.location.reload(true);\n"
+ "}\n"
;
private static final String _jsonResponseBox =
"<div class='pull-right'><a href='#' onclick='$(\"#json_box\").toggleClass(\"hide\");' class='btn btn-inverse btn-mini'>JSON</a></div>"
+ "<div class='hide' id='json_box'><pre><code class=\"language-json\">"
+ "%JSON_RESPONSE_BOX"
+ "</code></pre></div>";
protected String buildJSONResponseBox(Response response) {
switch (response._status) {
case done :
RString result = new RString(_jsonResponseBox);
result.replace("JSON_RESPONSE_BOX", response._response == null
? new String(response._req.writeJSON(new AutoBuffer()).buf())
: GSON_BUILDER.toJson(response.toJson()));
return result.toString();
case error :
case redirect:
case poll :
default : return "";
}
}
protected String buildResponseHeader(Response response) {
RString result = new RString(_responseHeader);
JsonObject obj = response.responseToJson();
result.replace("CLOUD_NAME",obj.get(JSON_H2O).getAsString());
result.replace("NODE_NAME",obj.get(NODE).getAsString());
result.replace("TIME", PrettyPrint.msecs(obj.get(REQUEST_TIME).getAsLong(), true));
switch (response._status) {
case error:
result.replace("BUTTON","<button class='btn btn-danger disabled'>"+response._status.toString()+"</button>");
- result.replace("TEXT","An error has occured during the creation of the response. Details follow:");
+ result.replace("TEXT","An error has occurred during the creation of the response. Details follow:");
break;
case done:
//result.replace("BUTTON","<button class='btn btn-success disabled'>"+response._status.toString()+"</button>");
//result.replace("TEXT","The result was a success and no further action is needed. JSON results are prettyprinted below.");
result = new RString("");
break;
case redirect:
result.replace("BUTTON","<button class='btn btn-primary' onclick='redirect()'>"+response._status.toString()+"</button>");
result.replace("TEXT","Request was successful and the process was started. You will be redirected to the new page in 1 seconds, or when you click on the redirect"
+ " button on the left. If you want to keep this page for longer you can <a href='#' onclick='countdown_stop()'>stop the countdown</a>.");
RString redirect = new RString(_redirectJs);
redirect.replace("REDIRECT_URL",response._redirectName+".html"+encodeRedirectArgs(response._redirectArgs,response._redirArgs));
result.replace("JSSTUFF", redirect.toString());
break;
case poll:
if (response._redirectArgs != null) {
RString poll = new RString(_redirectJs);
poll.replace("REDIRECT_URL",requestName()+".html"+encodeRedirectArgs(response._redirectArgs,response._redirArgs));
result.replace("JSSTUFF", poll.toString());
} else {
RString poll = new RString(_pollJs);
poll.replace("TIMEOUT", response._pollProgress==0 ? 1500 : 2000);
result.replace("JSSTUFF", poll.toString());
}
int pct = (int) ((double)response._pollProgress / response._pollProgressElements * 100);
result.replace("BUTTON","<button class='btn btn-primary' onclick='redirect()'>"+response._status.toString()+"</button>");
result.replace("TEXT","<div style='margin-bottom:0px;padding-bottom:0xp;height:5px;' class='progress progress-stripped'><div class='bar' style='width:"+pct+"%;'></div></div>"
+ "Request was successful, but the process has not yet finished. The page will refresh every 2 seconds, or you can click the button"
+ " on the left. If you want you can <a href='#' onclick='countdown_stop()'>disable the automatic refresh</a>.");
break;
default:
result.replace("BUTTON","<button class='btn btn-inverse disabled'>"+response._status.toString()+"</button>");
result.replace("TEXT","This is an unknown response state not recognized by the automatic formatter. The rest of the response is displayed below.");
break;
}
return result.toString();
}
/** Basic builder for objects. ()
*/
public static final Builder OBJECT_BUILDER = new ObjectBuilder();
/** Basic builder for arrays. (table)
*/
public static final Builder ARRAY_BUILDER = new ArrayBuilder();
/** Basic builder for array rows. (tr)
*/
public static final Builder ARRAY_ROW_BUILDER = new ArrayRowBuilder();
/** Basic build for shaded array rows. (tr class='..')
*/
public static final Builder ARRAY_HEADER_ROW_BUILDER = new ArrayHeaderRowBuilder();
/** Basic builder for elements inside objects. (dl,dt,dd)
*/
public static final ElementBuilder ELEMENT_BUILDER = new ElementBuilder();
/** Basic builder for elements in array row objects. (td)
*/
public static final Builder ARRAY_ROW_ELEMENT_BUILDER = new ArrayRowElementBuilder();
/** Basic builder for elements in array rows single col. (tr & td)
*/
public static final Builder ARRAY_ROW_SINGLECOL_BUILDER = new ArrayRowSingleColBuilder();
// ===========================================================================
// Response
// ===========================================================================
/** This is a response class for the JSON.
*
* Instead of simply returning a JsonObject, each request returns a new
* response object that it must create. This is (a) cleaner (b) more
* explicit and (c) allows to specify response states used for proper
* error reporting, stateless and statefull processed and so on, and (d)
* allows specification of HTML builder hooks in a nice clean interface.
*
* The work pattern should be that in the serve() method, a JsonObject is
* created and populated with the variables. Then if any error occurs, an
* error response should be returned.
*
* Otherwise a correct state response should be created at the end from the
* json object and returned.
*
* JSON response structure:
*
* response -> status = (done,error,redirect, ...)
* h2o = name of the cloud
* node = answering node
* time = time in MS it took to process the request serve()
* other fields as per the response type
* other fields that should go to the user
* if error:
* error -> error reported
*/
public static final class Response {
/** Status of the response.
*
* Defines the state of the response so that it can be nicely reported to
* the user in either in JSON or in HTML in a meaningful manner.
*/
public static enum Status {
done, ///< Indicates that the request has completed and no further action from the user is required
poll, ///< Indicates that the same request should be repeated to see some progress
redirect, ///< Indicates that the request was successful, but new request must be filled to obtain results
error ///< The request was an error.
}
/** Time it took the request to finish. In ms.
*/
protected long _time;
/** Status of the request.
*/
protected final Status _status;
/** Name of the redirected request. This is only valid if the response is
* redirect status.
*/
protected final String _redirectName;
/** Arguments of the redirect object. These will be given to the redirect
* object when called.
*/
protected final JsonObject _redirectArgs;
protected final Object[] _redirArgs;
/** Poll progress in terms of finished elements.
*/
protected final int _pollProgress;
/** Total elements to be finished before the poll will be done.
*/
protected final int _pollProgressElements;
/** Response object for JSON requests.
*/
protected final JsonObject _response;
protected final Request _req;
protected boolean _strictJsonCompliance = true;
/** Custom builders for JSON elements when converting to HTML automatically.
*/
protected final HashMap<String,Builder> _builders = new HashMap();
/** Custom headers to show in the html.
*/
protected final List<String> _headers = new ArrayList();
/** Private constructor creating the request with given type and response
* JSON object.
*
* Use the static methods to construct the response objects. (looks better
* when we have a lot of them).
*/
private Response(Status status, JsonObject response) {
_status = status;
_response = response;
_redirectName = null;
_redirectArgs = null;
_redirArgs = null;
_pollProgress = -1;
_pollProgressElements = -1;
_req = null;
}
private Response(Status status, JsonObject response, String redirectName, JsonObject redirectArgs) {
assert (status == Status.redirect);
_status = status;
_response = response;
_redirectName = redirectName;
_redirectArgs = redirectArgs;
_redirArgs = null;
_pollProgress = -1;
_pollProgressElements = -1;
_req = null;
}
private Response(Status status, JsonObject response, int progress, int total, JsonObject pollArgs) {
assert (status == Status.poll);
_status = status;
_response = response;
_redirectName = null;
_redirectArgs = pollArgs;
_redirArgs = null;
_pollProgress = progress;
_pollProgressElements = total;
_req = null;
}
private Response(Status status, Request req, int progress, int total, Object...pollArgs) {
assert (status == Status.poll);
_status = status;
_response = null;
_redirectName = null;
_redirectArgs = null;
_redirArgs = pollArgs;
_pollProgress = progress;
_pollProgressElements = total;
_req = req;
}
/** Response v2 constructor */
private Response(Status status, Request req, int progress, int total, String redirTo, Object... args) {
_status = status;
_response = null;
_redirectName = redirTo;
_redirectArgs = null;
_redirArgs = args;
_pollProgress = progress;
_pollProgressElements = total;
_req = req;
}
/** Returns new error response with given error message.
*/
public static Response error(Throwable e) {
if( !(e instanceof IllegalAccessException ))
Log.err(e);
String message = e.getMessage();
if( message == null ) message = e.getClass().toString();
return error(message);
}
public static Response error(String message) {
if( message == null ) message = "no error message";
JsonObject obj = new JsonObject();
obj.addProperty(ERROR,message);
Response r = new Response(Status.error,obj);
r.setBuilder(ERROR, new PreFormattedBuilder());
return r;
}
/** Returns new done response with given JSON response object.
*/
public static Response done(JsonObject response) {
assert response != null : "Called Response.done with null JSON response - perhaps you should call Response.doneEmpty";
return new Response(Status.done, response);
}
/** Response done v2. */
public static Response done(Request req) {
return new Response(Response.Status.done,req,-1,-1,(String) null);
}
/** A unique empty response which carries an empty JSON object */
public static final Response EMPTY_RESPONSE = Response.done(new JsonObject());
/** Returns new done empty done response.
* Should be called only in cases which does not need json response.
* @See {@link HTMLOnlyRequest}
*/
public static Response doneEmpty() {
return EMPTY_RESPONSE;
}
/** Creates the new response with status redirect. This response will be
* redirected to another request specified by redirectRequest with the
* redirection arguments provided in redirectArgs.
*/
public static Response redirect(JsonObject response,
Class<? extends Request> req, JsonObject args) {
return new Response(Status.redirect, response,
req.getSimpleName(), args);
}
/** Redirect for v2 API */
public static Response redirect(Request req, String redirectName, Object...redirectArgs) {
return new Response(Response.Status.redirect, req, -1, -1, redirectName, redirectArgs);
}
/** Returns the poll response object.
*/
public static Response poll(JsonObject response, int progress, int total) {
return new Response(Status.poll,response, progress, total, null);
}
/** Returns the poll response object initialized by percents completed.
*/
public static Response poll(JsonObject response, float progress) {
int p = (int) (progress * 100);
return Response.poll(response, p, 100);
}
/** returns the poll response object with different arguments that was
* this call.
*/
public static Response poll(JsonObject response, int progress, int total, JsonObject pollArgs) {
return new Response(Status.poll,response, progress, total, pollArgs);
}
/** Returns the poll response object.
*/
public static Response poll(Request req, int progress, int total, Object...pollArgs) {
return new Response(Status.poll,req, progress, total, pollArgs);
}
/** Sets the time of the response as a difference between the given time and
* now. Called automatically by serving request. Only available in JSON and
* HTML.
*/
public final void setTimeStart(long timeStart) {
_time = System.currentTimeMillis() - timeStart;
}
/** Associates a given builder with the specified JSON context. JSON context
* is a dot separated path to the JSON object/element starting from root.
*
* One exception is an array row element, which does not really have a
* distinct name in JSON and is thus identified as the context name of the
* array + "_ROW" appended to it.
*
* The builder object will then be called to build the HTML for the
* particular JSON element. By wise subclassing of the preexisting builders
* and changing their behavior an arbitrarily complex webpage can be
* created.
*/
public Response setBuilder(String contextName, Builder builder) {
_builders.put(contextName, builder);
return this;
}
/** Returns the builder for given JSON context element. Null if not found
* in which case a default builder object will be used. These default
* builders are specified by the builders themselves.
*/
protected Builder getBuilderFor(String contextName) {
return _builders.get(contextName);
}
public void addHeader(String h) { _headers.add(h); }
public List<String> getHeaders() { return _headers; }
/** Returns the response system json. That is the response type, time,
* h2o basics and other automatic stuff.
* @return
*/
protected JsonObject responseToJson() {
JsonObject resp = new JsonObject();
resp.addProperty(STATUS,_status.toString());
resp.addProperty(JSON_H2O, H2O.NAME);
resp.addProperty(NODE, H2O.SELF.toString());
resp.addProperty(REQUEST_TIME, _time);
switch (_status) {
case done:
case error:
break;
case redirect:
resp.addProperty(REDIRECT,_redirectName);
if (_redirectArgs != null)
resp.add(REDIRECT_ARGS,_redirectArgs);
break;
case poll:
resp.addProperty(PROGRESS, _pollProgress);
resp.addProperty(PROGRESS_TOTAL, _pollProgressElements);
break;
default:
assert(false): "Unknown response type "+_status.toString();
}
return resp;
}
/** Returns the JSONified version of the request. At the moment just
* returns the response.
*/
public JsonObject toJson() {
JsonObject res = _response;
if( _strictJsonCompliance ) res = JsonUtil.escape(res);
// in this case, creating a cyclical structure would kill us.
if( _response != null && _response == _redirectArgs ) {
res = new JsonObject();
for( Entry<String, JsonElement> e : _response.entrySet() ) {
res.add(e.getKey(), e.getValue());
}
}
res.add(RESPONSE, responseToJson());
return res;
}
public void toJava(StringBuilder sb) {
if( _req != null ) _req.toJava(sb);
}
/** Returns the error of the request object if any. Returns null if the
* response is not in error state.
*/
public String error() {
if (_status != Status.error)
return null;
return _response.get(ERROR).getAsString();
}
public void escapeIllegalJsonElements() {
_strictJsonCompliance = true;
}
public ResponseInfo extractInfo() {
String redirectUrl = null;
if (_status == Status.redirect) redirectUrl = _redirectName+".json"+encodeRedirectArgs(_redirectArgs,_redirArgs);
if (_status == Status.poll) redirectUrl = _req.href()+".json"+encodeRedirectArgs(_redirectArgs,_redirArgs);
return new ResponseInfo(redirectUrl, _time, _status);
}
}
/** Class holding technical information about request/response. It will be served as a part of Request2's
* response.
*/
public static class ResponseInfo extends Iced {
static final int API_WEAVER=1;
static public DocGen.FieldDoc[] DOC_FIELDS;
final @API(help="H2O cloud name.") String h2o;
final @API(help="Node serving the response.") String node;
final @API(help="Request processing time.") long time;
final @API(help="Response status") Response.Status status;
final @API(help="Redirect name.") String redirect_url;
public ResponseInfo(String redirect_url, long time, Status status) {
this.h2o = H2O.NAME;
this.node = H2O.SELF.toString();
this.redirect_url = redirect_url;
this.time = time;
this.status = status;
}
}
// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------
/** An abstract class to build the HTML page automatically from JSON.
*
* The idea is that every JSON element in the response structure (dot
* separated) may be a unique context that might be displayed in a different
* way. By creating specialized builders and assigning them to the JSON
* element contexts you can build arbitrarily complex HTML page.
*
* The basic builders for elements, arrays, array rows and elements inside
* array rows are provided by default.
*
* Each builder can also specify default builders for its components to make
* sure for instance that tables in arrays do not recurse and so on.
*/
public static abstract class Builder {
/** Override this method to provide HTML for the given json element.
*
* The arguments are the response object, the element whose HTML should be
* produced and the contextName of the element.
*/
public abstract String build(Response response, JsonElement element, String contextName);
/** Adds the given element name to the existing context. Dot concatenates
* the names.
*/
public static String addToContext(String oldContext, String name) {
if (oldContext.isEmpty())
return name;
return oldContext+"."+name;
}
/** For a given context returns the element name. That is the last word
* after a dot, or the full string if dot is not present.
*/
public static String elementName(String context) {
int idx = context.lastIndexOf(".");
return context.substring(idx+1);
}
/** Returns the default builders.
*
* These are element builder, object builder and array builder.
*/
public Builder defaultBuilder(JsonElement element) {
if (element instanceof JsonArray)
return ARRAY_BUILDER;
else if (element instanceof JsonObject)
return OBJECT_BUILDER;
else
return ELEMENT_BUILDER;
}
}
// ---------------------------------------------------------------------------
// ObjectBuilder
// ---------------------------------------------------------------------------
/** Object builder.
*
* By default objects are displayed as a horizontal dl elements with their
* heading preceding any of the values. Methods for caption, header,
* footer as well as element building are provided so that the behavior can
* easily be customized.
*/
public static class ObjectBuilder extends Builder {
/** Displays the caption of the object.
*/
public String caption(JsonObject object, String objectName) {
return objectName.isEmpty() ? "" : "<h4>"+objectName+"</h4>";
}
/** Returns the header of the object.
*
* That is any HTML displayed after caption and before any object's
* contents.
*/
public String header(JsonObject object, String objectName) {
return "";
}
/** Returns the footer of the object.
*
* That is any HTML displayed after any object's contents.
*/
public String footer(JsonObject object, String objectName) {
return "";
}
/** Creates the HTML of the object.
*
* That is the caption, header, all its contents in order they were
* added and then the footer. There should be no need to overload this
* function, rather override the provided hooks above.
*/
public String build(Response response, JsonObject object, String contextName) {
StringBuilder sb = new StringBuilder();
String name = elementName(contextName);
sb.append(caption(object, name));
sb.append(header(object, name));
for (Map.Entry<String,JsonElement> entry : object.entrySet()) {
JsonElement e = entry.getValue();
String elementContext = addToContext(contextName, entry.getKey());
Builder builder = response.getBuilderFor(elementContext);
if (builder == null)
builder = defaultBuilder(e);
sb.append(builder.build(response, e, elementContext));
}
sb.append(footer(object, elementName(contextName)));
return sb.toString();
}
/** The original build method. Calls build with json object, if not an
* object, displays an alert box with the JSON contents.
*/
public String build(Response response, JsonElement element, String contextName) {
if (element instanceof JsonObject)
return build(response, (JsonObject) element, contextName);
return "<div class='alert alert-error'>Response element "+contextName+" expected to be JsonObject. Automatic display not available</div><pre>"+element.toString()+"</pre>";
}
}
public static class NoCaptionObjectBuilder extends ObjectBuilder {
public String caption(JsonObject object, String objectName) { return ""; }
}
// ---------------------------------------------------------------------------
// Array builder
// ---------------------------------------------------------------------------
/** Builds the HTML for an array. Arrays generally go to a table. Is similar
* to the object, but rather than a horizontal dl generally displays as
* a table.
*
* Can produce a header of the table and has hooks for rows.
*/
public static class ArrayBuilder extends Builder {
/** Caption of the table.
*/
public String caption(JsonArray array, String name) {
return "<h4>"+name+"</h4>";
}
/** Header of the table. Produces header off the first element if it is
* object, or a single column header named value if it is a primitive. Also
* includes the table tag.
*/
public String header(JsonArray array) {
StringBuilder sb = new StringBuilder();
sb.append("<span style='display: inline-block;'>");
sb.append("<table class='table table-striped table-bordered'>");
if (array.get(0) instanceof JsonObject) {
sb.append("<tr>");
for (Map.Entry<String,JsonElement> entry : ((JsonObject)array.get(0)).entrySet())
sb.append("<th>").append(header(entry.getKey())).append("</th>");
sb.append("</tr>");
}
return sb.toString();
}
public String header(String key) {
return JSON2HTML(key);
}
/** Footer of the table, the end of table tag.
*/
public String footer(JsonArray array) {
return "</table></span>";
}
/** Default builders for the table. It is either a table row builder if the
* row is an object, or a row single column builder if it is a primitive
* or another array.
*/
@Override public Builder defaultBuilder(JsonElement element) {
return element instanceof JsonObject ? ARRAY_ROW_BUILDER : ARRAY_ROW_SINGLECOL_BUILDER;
}
/** Builds the array. Creates the caption, header, all the rows and the
* footer or determines that the array is empty.
*/
public String build(Response response, JsonArray array, String contextName) {
StringBuilder sb = new StringBuilder();
sb.append(caption(array, elementName(contextName)));
if (array.size() == 0) {
sb.append("<div class='alert alert-info'>empty array</div>");
} else {
sb.append(header(array));
for (JsonElement e : array) {
Builder builder = response.getBuilderFor(contextName+"_ROW");
if (builder == null)
builder = defaultBuilder(e);
sb.append(builder.build(response, e, contextName));
}
sb.append(footer(array));
}
return sb.toString();
}
/** Calls the build method with array. If not an array, displays an alert
* with the JSON contents of the element.
*/
public String build(Response response, JsonElement element, String contextName) {
if (element instanceof JsonArray)
return build(response, (JsonArray)element, contextName);
return "<div class='alert alert-error'>Response element "+contextName+" expected to be JsonArray. Automatic display not available</div><pre>"+element.toString()+"</pre>";
}
}
// ---------------------------------------------------------------------------
// ElementBuilder
// ---------------------------------------------------------------------------
/** A basic element builder.
*
* Elements are displayed as their string values, everything else as their
* JSON values.
*/
public static class ElementBuilder extends Builder {
/** Displays the element in the horizontal dl layout. Override this method
* to change the layout.
*/
public String build(String elementContents, String elementName) {
return "<dl class='dl-horizontal'><dt>"+elementName+"</dt><dd>"+elementContents+"</dd></dl>";
}
public String arrayToString(JsonArray array, String contextName) {
return array.toString();
}
public String objectToString(JsonObject obj, String contextName) {
return obj.toString();
}
public String elementToString(JsonElement elm, String contextName) {
String elementName = elementName(contextName);
if( elementName.endsWith(Suffixes.BYTES_PER_SECOND) ) {
return PrettyPrint.bytesPerSecond(elm.getAsLong());
} else if( elementName.endsWith(Suffixes.BYTES) ) {
return PrettyPrint.bytes(elm.getAsLong());
} else if( elementName.endsWith(Suffixes.MILLIS) ) {
return PrettyPrint.msecs(elm.getAsLong(), true);
} else if( elm instanceof JsonPrimitive && ((JsonPrimitive)elm).isString() ) {
return elm.getAsString();
} else if( elm instanceof JsonPrimitive && ((JsonPrimitive)elm).isNumber() ) {
Number n = elm.getAsNumber();
if( n instanceof Double ) {
Double d = (Double) n;
return format(d);
}
return elm.getAsString();
} else {
return elm.toString();
}
}
public static String format(double value) {
if( Double.isNaN(value) )
return "";
return _format.get().format(value);
}
public String elementToName(String contextName) {
String base = elementName(contextName);
for( String s : new String[] {
Suffixes.BYTES_PER_SECOND,
Suffixes.BYTES,
Suffixes.MILLIS,
}) {
if( base.endsWith(s) )
return base.substring(0, base.length() - s.length());
}
return base;
}
/** Based of the element type determines its string value and then calls
* the string build version.
*/
@Override public String build(Response response, JsonElement element, String contextName) {
String base;
if (element instanceof JsonArray) {
base = arrayToString((JsonArray)element, contextName);
} else if (element instanceof JsonObject) {
base = objectToString((JsonObject)element, contextName);
} else {
base = elementToString(element, contextName);
}
return build(base, elementToName(contextName));
}
}
public static class KeyElementBuilder extends ElementBuilder {
@Override
public String build(String content, String name) {
try {
String k = URLEncoder.encode(content, "UTF-8");
return super.build("<a href='Inspect.html?key="+k+"'>"+content+"</a>", name);
} catch( UnsupportedEncodingException e ) {
throw Log.errRTExcept(e);
}
}
}
public static class PreFormattedBuilder extends ElementBuilder {
@Override
public String build(String content, String name) {
return super.build("<pre>"+content+"</pre>", name);
}
}
// Just the Key as a link, without any other cruft
public static class KeyLinkElementBuilder extends ElementBuilder {
@Override public String build(Response response, JsonElement element, String contextName) {
try {
String key = element.getAsString();
String k = URLEncoder.encode(key, "UTF-8");
return "<a href='Inspect.html?key="+k+"'>"+key+"</a>";
} catch( UnsupportedEncodingException e ) {
throw Log.errRTExcept(e);
}
}
}
public static class BooleanStringBuilder extends ElementBuilder {
final String _t, _f;
public BooleanStringBuilder(String t, String f) { _t=t; _f=f; }
@Override public String build(Response response, JsonElement element, String contextName) {
boolean b = element.getAsBoolean();
return "<dl class='dl-horizontal'><dt></dt><dd>"+(b?_t:_f)+"</dd></dl>";
}
}
public static class HideBuilder extends ElementBuilder {
@Override public String build(Response response, JsonElement element, String contextName) {
return "";
}
}
// ---------------------------------------------------------------------------
// ArrayRowBuilder
// ---------------------------------------------------------------------------
/** A row in the array table.
*
* Is an object builder with no caption and header & footer being the
* table row tags. Default builder is array row element (td).
*/
public static class ArrayRowBuilder extends ObjectBuilder {
@Override public String caption(JsonObject object, String objectName) {
return "";
}
@Override public String header(JsonObject object, String objectName) {
//Gson g = new Gson();
//Log.info(g.toJson(object));
return "<tr id='row_"+object.get("row")+"'>";
}
@Override public String footer(JsonObject object, String objectName) {
return "</tr>";
}
@Override public Builder defaultBuilder(JsonElement element) {
return ARRAY_ROW_ELEMENT_BUILDER;
}
}
public static class ArrayHeaderRowBuilder extends ArrayRowBuilder {
@Override public String header(JsonObject object, String objectName) {
return "<tr class='warning'>";
}
}
// ---------------------------------------------------------------------------
// ArrayRowElementBuilder
// ---------------------------------------------------------------------------
/** Default array row element.
*
* A simple element builder than encapsulates into a td.
*/
public static class ArrayRowElementBuilder extends ElementBuilder {
public String build(String elementContents, String elementName) {
return "<td>"+elementContents+"</td>";
}
}
// ---------------------------------------------------------------------------
// ArrayRowSingleColBuilder
// ---------------------------------------------------------------------------
/** Array row for primitives.
*
* A row with single td element.
*/
public static class ArrayRowSingleColBuilder extends ElementBuilder {
public String build(String elementContents, String elementName) {
return "<tr><td>"+elementContents+"</td></tr>";
}
}
// ---------------------------------------------------------------------------
// PaginatedTable
// ---------------------------------------------------------------------------
/** A table with pagination controls.
*
* Use this builder when large data is returned not at once.
*/
public static class PaginatedTable extends ArrayBuilder {
protected final String _offsetJSON;
protected final String _viewJSON;
protected final JsonObject _query;
protected final long _max;
protected final boolean _allowInfo;
protected final long _offset;
protected final int _view;
public PaginatedTable(JsonObject query, long offset, int view, long max, boolean allowInfo, String offsetJSON, String viewJSON) {
_offsetJSON = offsetJSON;
_viewJSON = viewJSON;
_query = query;
_max = max;
_allowInfo = allowInfo;
_offset = offset;
_view = view;
}
public PaginatedTable(JsonObject query, long offset, int view, long max, boolean allowInfo) {
this(query, offset, view, max, allowInfo, OFFSET, VIEW);
}
protected String link(String caption, long offset, int view, boolean disabled) {
_query.addProperty(_offsetJSON, offset);
_query.addProperty(_viewJSON, view);
if (disabled)
return "<li class='disabled'><a>"+caption+"</a></li>";
else
return "<li><a href='"+RequestStatics.encodeRedirectArgs(_query,null)+"'>"+caption+"</a></li>";
}
protected String infoButton() {
if (!_allowInfo)
return "";
return "<span class='pagination'><ul>"+link("info",-1,_view,_offset==1)+"</ul></span> ";
}
protected String pagination() {
StringBuilder sb = new StringBuilder();
sb.append("<div style='text-align:center;'>");
sb.append(infoButton());
long lastOffset = (_max / _view) * _view;
long lastIdx = (_max / _view);
long currentIdx = _offset / _view;
long startIdx = Math.max(currentIdx-5,0);
long endIdx = Math.min(startIdx + 11, lastIdx);
if (_offset == -1)
currentIdx = -1;
sb.append("<span class='pagination'><ul>");
sb.append(link("|<",0,_view, _offset == 0));
sb.append(link("<",_offset-_view,_view, _offset-_view <0));
if (startIdx>0)
sb.append(link("...",0,0,true));
for (long i = startIdx; i <= endIdx; ++i)
sb.append(link(String.valueOf(i),_view*i,_view,i == currentIdx));
if (endIdx<lastIdx)
sb.append(link("...",0,0,true));
sb.append(link(">",_offset+_view,_view, _offset+_view >lastOffset));
sb.append(link(">|",lastOffset,_view, _offset == lastOffset));
sb.append("</ul></span>");
sb.append("</div>");
return sb.toString();
}
@Override public String header(JsonArray array) {
StringBuilder sb = new StringBuilder();
sb.append(pagination());
sb.append(super.header(array));
return sb.toString();
}
@Override public String footer(JsonArray array) {
StringBuilder sb = new StringBuilder();
sb.append(super.footer(array));
sb.append(pagination());
return sb.toString();
}
}
public class WarningCellBuilder extends ArrayRowElementBuilder {
@Override public String arrayToString(JsonArray arr, String contextName) {
StringBuilder sb = new StringBuilder();
String sep = "";
for( JsonElement e : arr ) {
sb.append(sep).append(e.getAsString());
sep = "</br>";
}
return sb.toString();
}
}
public class KeyCellBuilder extends ArrayRowElementBuilder {
@Override public String elementToString(JsonElement element, String contextName) {
String str = element.getAsString();
try {
String key = URLEncoder.encode(str,"UTF-8");
String delete = "<a href='RemoveAck.html?"+KEY+"="+key+"'><button class='btn btn-danger btn-mini'>X</button></a>";
return delete + " <a href='Inspect.html?"+KEY+"="+key+"'>"+str+"</a>";
} catch( UnsupportedEncodingException e ) {
throw Log.errRTExcept(e);
}
}
}
public class KeyMinAvgMaxBuilder extends ArrayRowElementBuilder {
private String trunc(JsonObject obj, String fld, int n) {
JsonElement je = obj.get(fld);
if( je == null || je instanceof JsonNull ) return "<br>";
String s1 = je.getAsString();
String s2 = (s1.length() > n ? s1.substring(0,n) : s1);
String s3 = s2.replace(" "," ");
return s3+"<br>";
}
@Override public String objectToString(JsonObject obj, String contextName) {
if (!obj.has(MIN)) return "";
return "<strong>"+trunc(obj,HEADER,10)+"</strong>"+trunc(obj,MIN,6)+trunc(obj,MEAN,6)+trunc(obj,MAX,6);
}
}
}
| true | true | protected String buildResponseHeader(Response response) {
RString result = new RString(_responseHeader);
JsonObject obj = response.responseToJson();
result.replace("CLOUD_NAME",obj.get(JSON_H2O).getAsString());
result.replace("NODE_NAME",obj.get(NODE).getAsString());
result.replace("TIME", PrettyPrint.msecs(obj.get(REQUEST_TIME).getAsLong(), true));
switch (response._status) {
case error:
result.replace("BUTTON","<button class='btn btn-danger disabled'>"+response._status.toString()+"</button>");
result.replace("TEXT","An error has occured during the creation of the response. Details follow:");
break;
case done:
//result.replace("BUTTON","<button class='btn btn-success disabled'>"+response._status.toString()+"</button>");
//result.replace("TEXT","The result was a success and no further action is needed. JSON results are prettyprinted below.");
result = new RString("");
break;
case redirect:
result.replace("BUTTON","<button class='btn btn-primary' onclick='redirect()'>"+response._status.toString()+"</button>");
result.replace("TEXT","Request was successful and the process was started. You will be redirected to the new page in 1 seconds, or when you click on the redirect"
+ " button on the left. If you want to keep this page for longer you can <a href='#' onclick='countdown_stop()'>stop the countdown</a>.");
RString redirect = new RString(_redirectJs);
redirect.replace("REDIRECT_URL",response._redirectName+".html"+encodeRedirectArgs(response._redirectArgs,response._redirArgs));
result.replace("JSSTUFF", redirect.toString());
break;
case poll:
if (response._redirectArgs != null) {
RString poll = new RString(_redirectJs);
poll.replace("REDIRECT_URL",requestName()+".html"+encodeRedirectArgs(response._redirectArgs,response._redirArgs));
result.replace("JSSTUFF", poll.toString());
} else {
RString poll = new RString(_pollJs);
poll.replace("TIMEOUT", response._pollProgress==0 ? 1500 : 2000);
result.replace("JSSTUFF", poll.toString());
}
int pct = (int) ((double)response._pollProgress / response._pollProgressElements * 100);
result.replace("BUTTON","<button class='btn btn-primary' onclick='redirect()'>"+response._status.toString()+"</button>");
result.replace("TEXT","<div style='margin-bottom:0px;padding-bottom:0xp;height:5px;' class='progress progress-stripped'><div class='bar' style='width:"+pct+"%;'></div></div>"
+ "Request was successful, but the process has not yet finished. The page will refresh every 2 seconds, or you can click the button"
+ " on the left. If you want you can <a href='#' onclick='countdown_stop()'>disable the automatic refresh</a>.");
break;
default:
result.replace("BUTTON","<button class='btn btn-inverse disabled'>"+response._status.toString()+"</button>");
result.replace("TEXT","This is an unknown response state not recognized by the automatic formatter. The rest of the response is displayed below.");
break;
}
return result.toString();
}
| protected String buildResponseHeader(Response response) {
RString result = new RString(_responseHeader);
JsonObject obj = response.responseToJson();
result.replace("CLOUD_NAME",obj.get(JSON_H2O).getAsString());
result.replace("NODE_NAME",obj.get(NODE).getAsString());
result.replace("TIME", PrettyPrint.msecs(obj.get(REQUEST_TIME).getAsLong(), true));
switch (response._status) {
case error:
result.replace("BUTTON","<button class='btn btn-danger disabled'>"+response._status.toString()+"</button>");
result.replace("TEXT","An error has occurred during the creation of the response. Details follow:");
break;
case done:
//result.replace("BUTTON","<button class='btn btn-success disabled'>"+response._status.toString()+"</button>");
//result.replace("TEXT","The result was a success and no further action is needed. JSON results are prettyprinted below.");
result = new RString("");
break;
case redirect:
result.replace("BUTTON","<button class='btn btn-primary' onclick='redirect()'>"+response._status.toString()+"</button>");
result.replace("TEXT","Request was successful and the process was started. You will be redirected to the new page in 1 seconds, or when you click on the redirect"
+ " button on the left. If you want to keep this page for longer you can <a href='#' onclick='countdown_stop()'>stop the countdown</a>.");
RString redirect = new RString(_redirectJs);
redirect.replace("REDIRECT_URL",response._redirectName+".html"+encodeRedirectArgs(response._redirectArgs,response._redirArgs));
result.replace("JSSTUFF", redirect.toString());
break;
case poll:
if (response._redirectArgs != null) {
RString poll = new RString(_redirectJs);
poll.replace("REDIRECT_URL",requestName()+".html"+encodeRedirectArgs(response._redirectArgs,response._redirArgs));
result.replace("JSSTUFF", poll.toString());
} else {
RString poll = new RString(_pollJs);
poll.replace("TIMEOUT", response._pollProgress==0 ? 1500 : 2000);
result.replace("JSSTUFF", poll.toString());
}
int pct = (int) ((double)response._pollProgress / response._pollProgressElements * 100);
result.replace("BUTTON","<button class='btn btn-primary' onclick='redirect()'>"+response._status.toString()+"</button>");
result.replace("TEXT","<div style='margin-bottom:0px;padding-bottom:0xp;height:5px;' class='progress progress-stripped'><div class='bar' style='width:"+pct+"%;'></div></div>"
+ "Request was successful, but the process has not yet finished. The page will refresh every 2 seconds, or you can click the button"
+ " on the left. If you want you can <a href='#' onclick='countdown_stop()'>disable the automatic refresh</a>.");
break;
default:
result.replace("BUTTON","<button class='btn btn-inverse disabled'>"+response._status.toString()+"</button>");
result.replace("TEXT","This is an unknown response state not recognized by the automatic formatter. The rest of the response is displayed below.");
break;
}
return result.toString();
}
|
diff --git a/src/org/CreeperCoders/InfectedPlugin/Commands/Command_name.java b/src/org/CreeperCoders/InfectedPlugin/Commands/Command_name.java
index a9f4ff6..d2ae20f 100644
--- a/src/org/CreeperCoders/InfectedPlugin/Commands/Command_name.java
+++ b/src/org/CreeperCoders/InfectedPlugin/Commands/Command_name.java
@@ -1,68 +1,69 @@
package org.CreeperCoders.InfectedPlugin.Commands;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class Command_name extends IP_Command implements Listener
{
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
final Player p = event.getPlayer();
if (message.startsWith("."))
{
String[] args = message.split(" ");
if (args == null)
{
return;
}
if (args[0].equalsIgnoreCase(".name"))
{
if (args.length == 1)
{
p.sendMessage(ChatColor.RED + "Usage: .name <player> <name>");
event.setCancelled(true);
return;
}
Player target;
String name = null;
if (args.length == 2)
{
try
{
p.sendMessage(ChatColor.RED + "Usage: .name <player> <name>");
event.setCancelled(true);
return;
}
catch (PlayerNotFoundException ex)
{
p.sendMessage(ChatColor.RED + ex.getMessage());
}
}
if (args.length >= 3)
{
try
{
target = getPlayer(args[1]);
target.setDisplayName(name);
target.setCustomName(name);
target.setCustomNameVisible(true);
+ p.sendMessage(ChatColor.GREEN + "Your name has been set to: " + name);
}
catch (PlayerNotFoundException ex)
{
p.sendMessage(ChatColor.RED + ex.getMessage());
}
}
event.setCancelled(true);
return;
}
}
}
}
| true | true | public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
final Player p = event.getPlayer();
if (message.startsWith("."))
{
String[] args = message.split(" ");
if (args == null)
{
return;
}
if (args[0].equalsIgnoreCase(".name"))
{
if (args.length == 1)
{
p.sendMessage(ChatColor.RED + "Usage: .name <player> <name>");
event.setCancelled(true);
return;
}
Player target;
String name = null;
if (args.length == 2)
{
try
{
p.sendMessage(ChatColor.RED + "Usage: .name <player> <name>");
event.setCancelled(true);
return;
}
catch (PlayerNotFoundException ex)
{
p.sendMessage(ChatColor.RED + ex.getMessage());
}
}
if (args.length >= 3)
{
try
{
target = getPlayer(args[1]);
target.setDisplayName(name);
target.setCustomName(name);
target.setCustomNameVisible(true);
}
catch (PlayerNotFoundException ex)
{
p.sendMessage(ChatColor.RED + ex.getMessage());
}
}
event.setCancelled(true);
return;
}
}
}
| public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
final Player p = event.getPlayer();
if (message.startsWith("."))
{
String[] args = message.split(" ");
if (args == null)
{
return;
}
if (args[0].equalsIgnoreCase(".name"))
{
if (args.length == 1)
{
p.sendMessage(ChatColor.RED + "Usage: .name <player> <name>");
event.setCancelled(true);
return;
}
Player target;
String name = null;
if (args.length == 2)
{
try
{
p.sendMessage(ChatColor.RED + "Usage: .name <player> <name>");
event.setCancelled(true);
return;
}
catch (PlayerNotFoundException ex)
{
p.sendMessage(ChatColor.RED + ex.getMessage());
}
}
if (args.length >= 3)
{
try
{
target = getPlayer(args[1]);
target.setDisplayName(name);
target.setCustomName(name);
target.setCustomNameVisible(true);
p.sendMessage(ChatColor.GREEN + "Your name has been set to: " + name);
}
catch (PlayerNotFoundException ex)
{
p.sendMessage(ChatColor.RED + ex.getMessage());
}
}
event.setCancelled(true);
return;
}
}
}
|
diff --git a/src/com/simplechat/server/CommandHandler.java b/src/com/simplechat/server/CommandHandler.java
index 159a222..801b860 100644
--- a/src/com/simplechat/server/CommandHandler.java
+++ b/src/com/simplechat/server/CommandHandler.java
@@ -1,486 +1,486 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @date Apr 30, 2011
* @author Techjar
* @version
*/
package com.simplechat.server;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import com.simplechat.protocol.*;
public class CommandHandler {
private ClientData client;
private List clients;
private DatagramSocket socket;
public CommandHandler(ClientData client, List clients, DatagramSocket socket) {
this.client = client;
this.clients = clients;
this.socket = socket;
}
public void parseCommand(String cmd, String[] args) {
PacketHandler ph = new PacketHandler();
DataManager dm = new DataManager();
if(cmd.equalsIgnoreCase("help")) {
ph.sendPacket(new Packet5Message("/quit [message] - Disconnects you from the server."), client, this.socket);
ph.sendPacket(new Packet5Message("/stop - Stops the server. (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/say <message> - Broadcasts a server message."), client, this.socket);
ph.sendPacket(new Packet5Message("/ping - Ping! Pong!"), client, this.socket);
ph.sendPacket(new Packet5Message("/kill <name> - Kills a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/nuke - NUKE THE CHAT!!!!! (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/whois <name> - Gets information on a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/list - Lists users in the chat."), client, this.socket);
ph.sendPacket(new Packet5Message("/me <message> - Makes you do an action."), client, this.socket);
ph.sendPacket(new Packet5Message("/nick <name> - Changes your name!"), client, this.socket);
- ph.sendPacket(new Packet5Message("/op <name> - Ops a user."), client, this.socket);
- ph.sendPacket(new Packet5Message("/deop <name> - De-ops a user."), client, this.socket);
- ph.sendPacket(new Packet5Message("/kick <name> - Kicks a user."), client, this.socket);
- ph.sendPacket(new Packet5Message("/ban <name> - Bans a user."), client, this.socket);
- ph.sendPacket(new Packet5Message("/unban <name> - Unbans a user."), client, this.socket);
- ph.sendPacket(new Packet5Message("/banip <ip> - Bans an IP."), client, this.socket);
- ph.sendPacket(new Packet5Message("/unbanip <ip> - Unbans an IP."), client, this.socket);
+ ph.sendPacket(new Packet5Message("/op <name> - Ops a user. (Op-only)"), client, this.socket);
+ ph.sendPacket(new Packet5Message("/deop <name> - De-ops a user. (Op-only)"), client, this.socket);
+ ph.sendPacket(new Packet5Message("/kick <name> - Kicks a user. (Op-only)"), client, this.socket);
+ ph.sendPacket(new Packet5Message("/ban <name> - Bans a user. (Op-only)"), client, this.socket);
+ ph.sendPacket(new Packet5Message("/unban <name> - Unbans a user. (Op-only)"), client, this.socket);
+ ph.sendPacket(new Packet5Message("/banip <ip> - Bans an IP. (Op-only)"), client, this.socket);
+ ph.sendPacket(new Packet5Message("/unbanip <ip> - Unbans an IP. (Op-only)"), client, this.socket);
}
else if(cmd.equalsIgnoreCase("quit")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " quit. Reason: " + msg) ;
Packet4Kick packet = new Packet4Kick("Quitting. Reason: " + msg);
Packet5Message packet2 = new Packet5Message(client.getUsername() + " quit. (" + msg + ")");
ph.sendPacket(packet, client, this.socket);
client.stopKeepAliveThread();
client.stopKeepAliveSendThread();
clients.remove(client);
ph.sendAllPacket(packet2, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("stop")) {
if(dm.isOp(client.getUsername())) {
System.out.println(client.getUsername() + " stopped the server.");
System.exit(0);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("say")) {
if(dm.isOp(client.getUsername())) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
Packet5Message packet = new Packet5Message("[Server] " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ping")) {
Packet5Message packet = new Packet5Message("Pong!");
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("kill")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
Packet5Message packet = new Packet5Message(client.getUsername() + " was kicked for killing " + args[0] + ". " + args[0] + " will be missed. :(");
Packet4Kick packet2 = new Packet4Kick("YOU MURDERER, YOU KILLED " + args[0].toUpperCase() + "! GET OUT!!!!!");
ph.sendAllExcludePacket(packet, clients, client, this.socket);
ph.sendPacket(packet2, client, this.socket);
client.stopKeepAliveThread();
client.stopKeepAliveSendThread();
clients.remove(client);
}
}
else if(cmd.equalsIgnoreCase("nuke")) {
if(!dm.isOp(client.getUsername())) {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
try {
System.out.println("Nuke started!");
Packet5Message packet = new Packet5Message("IT'S NUKE TIME OH BOY!!!!!");
ph.sendAllPacket(packet, clients, this.socket);
packet = new Packet5Message("NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE");
for(int i = 0; i < 1000; i++) {
if((i % 100) == 0) System.out.println("Packets left: " + (1000 - i));
ph.sendAllPacket(packet, clients, this.socket);
Thread.sleep(10);
}
System.out.println("Nuke ended!");
packet = new Packet5Message("Phew, now that the nuke is over, continue chatting!");
ph.sendAllPacket(packet, clients, this.socket);
}
catch(InterruptedException e) {
System.out.println("Nuke command thread was interrupted.");
}
}
}
else if(cmd.equalsIgnoreCase("whois")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
ClientData client2 = findClient(args[0]);
if(client2 != null) {
String msg = "IP: " + client2.getIP().getHostAddress() + "\n";
msg += "Port: " + client2.getPort() + "\n";
msg += "Hostname: " + client2.getIP().getCanonicalHostName();
Packet5Message packet = new Packet5Message(msg);
ph.sendPacket(packet, client, this.socket);
}
else {
Packet5Message packet = new Packet5Message("User not found.");
ph.sendPacket(packet, client, this.socket);
}
}
}
else if(cmd.equalsIgnoreCase("list")) {
String msg = "Online Users: ";
for(int i = 0; i < clients.size(); i++) {
ClientData client2 = (ClientData)clients.get(i);
msg += client2.getUsername() + ", ";
}
Packet5Message packet = new Packet5Message(msg.substring(0, Math.min(msg.length() - 2, 500)));
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("me")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " did action: " + msg);
Packet5Message packet = new Packet5Message("*" + client.getUsername() + " " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("nick")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("Your name is already " + args[0] + ".");
ph.sendPacket(packet, client, this.socket);
}
else if(nameTaken(args[0])) {
Packet5Message packet = new Packet5Message("That name is taken.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0]) && !dm.isOp(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can't /nick to an op's name if you aren't an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
System.out.println(client.getUsername() + " has changed name to " + args[0]);
Packet5Message packet = new Packet5Message(client.getUsername() + " is now known as " + args[0]);
clients.remove(client);
client.setUsername(args[0]);
clients.add(client);
Packet6NameChange packet2 = new Packet6NameChange(args[0]);
ph.sendAllPacket(packet, clients, this.socket);
ph.sendPacket(packet2, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("op")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not op yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is already an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.addOp(args[0]);
System.out.println(client.getUsername() + " opped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been opped.");
Packet5Message packet2 = new Packet5Message("You are now an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("deop")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not deop yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is not an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeOp(args[0]);
System.out.println(client.getUsername() + " deopped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been deopped.");
Packet5Message packet2 = new Packet5Message("You are no longer an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("kick")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not kick yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(findClient(args[0]) == null) {
Packet5Message packet = new Packet5Message("That user isn't in the chat.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " kicked " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been kicked. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You were kicked: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
client2.stopKeepAliveSendThread();
clients.remove(client2);
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not ban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addBan(args[0]);
System.out.println(client.getUsername() + " banned " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You have been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
client2.stopKeepAliveSendThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not unban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeBan(args[0]);
System.out.println(client.getUsername() + " unbanned " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("banip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
//System.err.println("An invalid IP was entered.");
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not ban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " banned the IP " + ip.getHostAddress() + " with reason: " + msg);
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("Your IP has been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(ip);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
client2.stopKeepAliveSendThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unbanip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
//System.err.println("An invalid IP was entered.");
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not unban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " unbanned the IP " + ip.getHostAddress() + ".");
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
System.out.println("Command \"" + cmd + "\" not found.");
Packet5Message packet = new Packet5Message("Unknown command.");
ph.sendPacket(packet, client, this.socket);
}
}
private boolean nameTaken(String name) {
for(int i = 0; i < clients.size(); i++) {
ClientData client2 = (ClientData)clients.get(i);
if(client2.getUsername().equalsIgnoreCase(name)) return true;
}
return false;
}
private ClientData findClient(String name) {
for(int i = 0; i < clients.size(); i++) {
ClientData client2 = (ClientData)clients.get(i);
if(client2.getUsername().equalsIgnoreCase(name)) return client2;
}
return null;
}
private ClientData findClient(InetAddress ip) {
for(int i = 0; i < clients.size(); i++) {
ClientData client2 = (ClientData)clients.get(i);
if(client2.getIP() == ip) return client2;
}
return null;
}
}
| true | true | public void parseCommand(String cmd, String[] args) {
PacketHandler ph = new PacketHandler();
DataManager dm = new DataManager();
if(cmd.equalsIgnoreCase("help")) {
ph.sendPacket(new Packet5Message("/quit [message] - Disconnects you from the server."), client, this.socket);
ph.sendPacket(new Packet5Message("/stop - Stops the server. (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/say <message> - Broadcasts a server message."), client, this.socket);
ph.sendPacket(new Packet5Message("/ping - Ping! Pong!"), client, this.socket);
ph.sendPacket(new Packet5Message("/kill <name> - Kills a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/nuke - NUKE THE CHAT!!!!! (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/whois <name> - Gets information on a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/list - Lists users in the chat."), client, this.socket);
ph.sendPacket(new Packet5Message("/me <message> - Makes you do an action."), client, this.socket);
ph.sendPacket(new Packet5Message("/nick <name> - Changes your name!"), client, this.socket);
ph.sendPacket(new Packet5Message("/op <name> - Ops a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/deop <name> - De-ops a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/kick <name> - Kicks a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/ban <name> - Bans a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/unban <name> - Unbans a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/banip <ip> - Bans an IP."), client, this.socket);
ph.sendPacket(new Packet5Message("/unbanip <ip> - Unbans an IP."), client, this.socket);
}
else if(cmd.equalsIgnoreCase("quit")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " quit. Reason: " + msg) ;
Packet4Kick packet = new Packet4Kick("Quitting. Reason: " + msg);
Packet5Message packet2 = new Packet5Message(client.getUsername() + " quit. (" + msg + ")");
ph.sendPacket(packet, client, this.socket);
client.stopKeepAliveThread();
client.stopKeepAliveSendThread();
clients.remove(client);
ph.sendAllPacket(packet2, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("stop")) {
if(dm.isOp(client.getUsername())) {
System.out.println(client.getUsername() + " stopped the server.");
System.exit(0);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("say")) {
if(dm.isOp(client.getUsername())) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
Packet5Message packet = new Packet5Message("[Server] " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ping")) {
Packet5Message packet = new Packet5Message("Pong!");
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("kill")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
Packet5Message packet = new Packet5Message(client.getUsername() + " was kicked for killing " + args[0] + ". " + args[0] + " will be missed. :(");
Packet4Kick packet2 = new Packet4Kick("YOU MURDERER, YOU KILLED " + args[0].toUpperCase() + "! GET OUT!!!!!");
ph.sendAllExcludePacket(packet, clients, client, this.socket);
ph.sendPacket(packet2, client, this.socket);
client.stopKeepAliveThread();
client.stopKeepAliveSendThread();
clients.remove(client);
}
}
else if(cmd.equalsIgnoreCase("nuke")) {
if(!dm.isOp(client.getUsername())) {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
try {
System.out.println("Nuke started!");
Packet5Message packet = new Packet5Message("IT'S NUKE TIME OH BOY!!!!!");
ph.sendAllPacket(packet, clients, this.socket);
packet = new Packet5Message("NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE");
for(int i = 0; i < 1000; i++) {
if((i % 100) == 0) System.out.println("Packets left: " + (1000 - i));
ph.sendAllPacket(packet, clients, this.socket);
Thread.sleep(10);
}
System.out.println("Nuke ended!");
packet = new Packet5Message("Phew, now that the nuke is over, continue chatting!");
ph.sendAllPacket(packet, clients, this.socket);
}
catch(InterruptedException e) {
System.out.println("Nuke command thread was interrupted.");
}
}
}
else if(cmd.equalsIgnoreCase("whois")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
ClientData client2 = findClient(args[0]);
if(client2 != null) {
String msg = "IP: " + client2.getIP().getHostAddress() + "\n";
msg += "Port: " + client2.getPort() + "\n";
msg += "Hostname: " + client2.getIP().getCanonicalHostName();
Packet5Message packet = new Packet5Message(msg);
ph.sendPacket(packet, client, this.socket);
}
else {
Packet5Message packet = new Packet5Message("User not found.");
ph.sendPacket(packet, client, this.socket);
}
}
}
else if(cmd.equalsIgnoreCase("list")) {
String msg = "Online Users: ";
for(int i = 0; i < clients.size(); i++) {
ClientData client2 = (ClientData)clients.get(i);
msg += client2.getUsername() + ", ";
}
Packet5Message packet = new Packet5Message(msg.substring(0, Math.min(msg.length() - 2, 500)));
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("me")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " did action: " + msg);
Packet5Message packet = new Packet5Message("*" + client.getUsername() + " " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("nick")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("Your name is already " + args[0] + ".");
ph.sendPacket(packet, client, this.socket);
}
else if(nameTaken(args[0])) {
Packet5Message packet = new Packet5Message("That name is taken.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0]) && !dm.isOp(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can't /nick to an op's name if you aren't an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
System.out.println(client.getUsername() + " has changed name to " + args[0]);
Packet5Message packet = new Packet5Message(client.getUsername() + " is now known as " + args[0]);
clients.remove(client);
client.setUsername(args[0]);
clients.add(client);
Packet6NameChange packet2 = new Packet6NameChange(args[0]);
ph.sendAllPacket(packet, clients, this.socket);
ph.sendPacket(packet2, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("op")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not op yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is already an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.addOp(args[0]);
System.out.println(client.getUsername() + " opped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been opped.");
Packet5Message packet2 = new Packet5Message("You are now an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("deop")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not deop yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is not an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeOp(args[0]);
System.out.println(client.getUsername() + " deopped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been deopped.");
Packet5Message packet2 = new Packet5Message("You are no longer an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("kick")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not kick yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(findClient(args[0]) == null) {
Packet5Message packet = new Packet5Message("That user isn't in the chat.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " kicked " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been kicked. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You were kicked: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
client2.stopKeepAliveSendThread();
clients.remove(client2);
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not ban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addBan(args[0]);
System.out.println(client.getUsername() + " banned " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You have been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
client2.stopKeepAliveSendThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not unban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeBan(args[0]);
System.out.println(client.getUsername() + " unbanned " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("banip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
//System.err.println("An invalid IP was entered.");
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not ban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " banned the IP " + ip.getHostAddress() + " with reason: " + msg);
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("Your IP has been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(ip);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
client2.stopKeepAliveSendThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unbanip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
//System.err.println("An invalid IP was entered.");
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not unban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " unbanned the IP " + ip.getHostAddress() + ".");
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
System.out.println("Command \"" + cmd + "\" not found.");
Packet5Message packet = new Packet5Message("Unknown command.");
ph.sendPacket(packet, client, this.socket);
}
}
| public void parseCommand(String cmd, String[] args) {
PacketHandler ph = new PacketHandler();
DataManager dm = new DataManager();
if(cmd.equalsIgnoreCase("help")) {
ph.sendPacket(new Packet5Message("/quit [message] - Disconnects you from the server."), client, this.socket);
ph.sendPacket(new Packet5Message("/stop - Stops the server. (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/say <message> - Broadcasts a server message."), client, this.socket);
ph.sendPacket(new Packet5Message("/ping - Ping! Pong!"), client, this.socket);
ph.sendPacket(new Packet5Message("/kill <name> - Kills a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/nuke - NUKE THE CHAT!!!!! (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/whois <name> - Gets information on a user."), client, this.socket);
ph.sendPacket(new Packet5Message("/list - Lists users in the chat."), client, this.socket);
ph.sendPacket(new Packet5Message("/me <message> - Makes you do an action."), client, this.socket);
ph.sendPacket(new Packet5Message("/nick <name> - Changes your name!"), client, this.socket);
ph.sendPacket(new Packet5Message("/op <name> - Ops a user. (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/deop <name> - De-ops a user. (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/kick <name> - Kicks a user. (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/ban <name> - Bans a user. (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/unban <name> - Unbans a user. (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/banip <ip> - Bans an IP. (Op-only)"), client, this.socket);
ph.sendPacket(new Packet5Message("/unbanip <ip> - Unbans an IP. (Op-only)"), client, this.socket);
}
else if(cmd.equalsIgnoreCase("quit")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " quit. Reason: " + msg) ;
Packet4Kick packet = new Packet4Kick("Quitting. Reason: " + msg);
Packet5Message packet2 = new Packet5Message(client.getUsername() + " quit. (" + msg + ")");
ph.sendPacket(packet, client, this.socket);
client.stopKeepAliveThread();
client.stopKeepAliveSendThread();
clients.remove(client);
ph.sendAllPacket(packet2, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("stop")) {
if(dm.isOp(client.getUsername())) {
System.out.println(client.getUsername() + " stopped the server.");
System.exit(0);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("say")) {
if(dm.isOp(client.getUsername())) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
Packet5Message packet = new Packet5Message("[Server] " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ping")) {
Packet5Message packet = new Packet5Message("Pong!");
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("kill")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
Packet5Message packet = new Packet5Message(client.getUsername() + " was kicked for killing " + args[0] + ". " + args[0] + " will be missed. :(");
Packet4Kick packet2 = new Packet4Kick("YOU MURDERER, YOU KILLED " + args[0].toUpperCase() + "! GET OUT!!!!!");
ph.sendAllExcludePacket(packet, clients, client, this.socket);
ph.sendPacket(packet2, client, this.socket);
client.stopKeepAliveThread();
client.stopKeepAliveSendThread();
clients.remove(client);
}
}
else if(cmd.equalsIgnoreCase("nuke")) {
if(!dm.isOp(client.getUsername())) {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
try {
System.out.println("Nuke started!");
Packet5Message packet = new Packet5Message("IT'S NUKE TIME OH BOY!!!!!");
ph.sendAllPacket(packet, clients, this.socket);
packet = new Packet5Message("NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE NUKE");
for(int i = 0; i < 1000; i++) {
if((i % 100) == 0) System.out.println("Packets left: " + (1000 - i));
ph.sendAllPacket(packet, clients, this.socket);
Thread.sleep(10);
}
System.out.println("Nuke ended!");
packet = new Packet5Message("Phew, now that the nuke is over, continue chatting!");
ph.sendAllPacket(packet, clients, this.socket);
}
catch(InterruptedException e) {
System.out.println("Nuke command thread was interrupted.");
}
}
}
else if(cmd.equalsIgnoreCase("whois")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
ClientData client2 = findClient(args[0]);
if(client2 != null) {
String msg = "IP: " + client2.getIP().getHostAddress() + "\n";
msg += "Port: " + client2.getPort() + "\n";
msg += "Hostname: " + client2.getIP().getCanonicalHostName();
Packet5Message packet = new Packet5Message(msg);
ph.sendPacket(packet, client, this.socket);
}
else {
Packet5Message packet = new Packet5Message("User not found.");
ph.sendPacket(packet, client, this.socket);
}
}
}
else if(cmd.equalsIgnoreCase("list")) {
String msg = "Online Users: ";
for(int i = 0; i < clients.size(); i++) {
ClientData client2 = (ClientData)clients.get(i);
msg += client2.getUsername() + ", ";
}
Packet5Message packet = new Packet5Message(msg.substring(0, Math.min(msg.length() - 2, 500)));
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("me")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " did action: " + msg);
Packet5Message packet = new Packet5Message("*" + client.getUsername() + " " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("nick")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("Your name is already " + args[0] + ".");
ph.sendPacket(packet, client, this.socket);
}
else if(nameTaken(args[0])) {
Packet5Message packet = new Packet5Message("That name is taken.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0]) && !dm.isOp(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can't /nick to an op's name if you aren't an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
System.out.println(client.getUsername() + " has changed name to " + args[0]);
Packet5Message packet = new Packet5Message(client.getUsername() + " is now known as " + args[0]);
clients.remove(client);
client.setUsername(args[0]);
clients.add(client);
Packet6NameChange packet2 = new Packet6NameChange(args[0]);
ph.sendAllPacket(packet, clients, this.socket);
ph.sendPacket(packet2, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("op")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not op yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is already an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.addOp(args[0]);
System.out.println(client.getUsername() + " opped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been opped.");
Packet5Message packet2 = new Packet5Message("You are now an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("deop")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not deop yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is not an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeOp(args[0]);
System.out.println(client.getUsername() + " deopped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been deopped.");
Packet5Message packet2 = new Packet5Message("You are no longer an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("kick")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not kick yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(findClient(args[0]) == null) {
Packet5Message packet = new Packet5Message("That user isn't in the chat.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " kicked " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been kicked. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You were kicked: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
client2.stopKeepAliveSendThread();
clients.remove(client2);
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not ban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addBan(args[0]);
System.out.println(client.getUsername() + " banned " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You have been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
client2.stopKeepAliveSendThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not unban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeBan(args[0]);
System.out.println(client.getUsername() + " unbanned " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("banip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
//System.err.println("An invalid IP was entered.");
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not ban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " banned the IP " + ip.getHostAddress() + " with reason: " + msg);
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("Your IP has been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(ip);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
client2.stopKeepAliveSendThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unbanip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
//System.err.println("An invalid IP was entered.");
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not unban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " unbanned the IP " + ip.getHostAddress() + ".");
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
System.out.println("Command \"" + cmd + "\" not found.");
Packet5Message packet = new Packet5Message("Unknown command.");
ph.sendPacket(packet, client, this.socket);
}
}
|
diff --git a/core/src/main/java/org/apache/mahout/classifier/sgd/CrossFoldLearner.java b/core/src/main/java/org/apache/mahout/classifier/sgd/CrossFoldLearner.java
index 09967070..0975ad38 100644
--- a/core/src/main/java/org/apache/mahout/classifier/sgd/CrossFoldLearner.java
+++ b/core/src/main/java/org/apache/mahout/classifier/sgd/CrossFoldLearner.java
@@ -1,235 +1,237 @@
package org.apache.mahout.classifier.sgd;
import com.google.common.collect.Lists;
import org.apache.mahout.classifier.AbstractVectorClassifier;
import org.apache.mahout.classifier.OnlineLearner;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.function.Functions;
import org.apache.mahout.math.stats.OnlineAuc;
import java.util.List;
/**
* Does cross-fold validation of log-likelihood and AUC on several online logistic regression
* models. Each record is passed to all but one of the models for training and to the remaining
* model for evaluation. In order to maintain proper segregation between the different folds across
* training data iterations, data should either be passed to this learner in the same order each
* time the training data is traversed or a tracking key such as the file offset of the training
* record should be passed with each training example.
*/
public class CrossFoldLearner extends AbstractVectorClassifier implements OnlineLearner {
// minimum score to be used for computing log likelihood
private static final double MIN_SCORE = 1e-50;
private int record = 0;
private OnlineAuc auc = new OnlineAuc();
private double logLikelihood;
private final List<OnlineLogisticRegression> models = Lists.newArrayList();
// lambda, learningRate, perTermOffset, perTermExponent
private double[] parameters = new double[4];
private int numFeatures;
private PriorFunction prior;
// pretty much just for GSON
public CrossFoldLearner() {
}
public CrossFoldLearner(int folds, int numCategories, int numFeatures, PriorFunction prior) {
this.numFeatures = numFeatures;
this.prior = prior;
for (int i = 0; i < folds; i++) {
OnlineLogisticRegression model = new OnlineLogisticRegression(numCategories, numFeatures, prior);
model.alpha(1).stepOffset(0).decayExponent(0);
models.add(model);
}
}
// -------- builder-like configuration methods
public CrossFoldLearner lambda(double v) {
for (OnlineLogisticRegression model : models) {
model.lambda(v);
}
return this;
}
public CrossFoldLearner learningRate(double x) {
for (OnlineLogisticRegression model : models) {
model.learningRate(x);
}
return this;
}
public CrossFoldLearner stepOffset(int x) {
for (OnlineLogisticRegression model : models) {
model.stepOffset(x);
}
return this;
}
public CrossFoldLearner decayExponent(double x) {
for (OnlineLogisticRegression model : models) {
model.decayExponent(x);
}
return this;
}
public CrossFoldLearner alpha(double alpha) {
for (OnlineLogisticRegression model : models) {
model.alpha(alpha);
}
return this;
}
// -------- training methods
@Override
public void train(int actual, Vector instance) {
train(record, actual, instance);
}
@Override
public void train(long trackingKey, int actual, Vector instance) {
record++;
int k = 0;
for (OnlineLogisticRegression model : models) {
if (k == trackingKey % models.size()) {
Vector v = model.classifyFull(instance);
- double score = v.get(actual);
+ double score = Math.max(v.get(actual), MIN_SCORE);
logLikelihood += (Math.log(score) - logLikelihood) / record;
- auc.addSample(actual, v.get(1));
+ if (numCategories() == 2) {
+ auc.addSample(actual, v.get(1));
+ }
} else {
model.train(trackingKey, actual, instance);
}
k++;
}
}
@Override
public void close() {
for (OnlineLogisticRegression m : models) {
m.close();
}
}
public void resetLineCounter() {
record = 0;
}
public boolean validModel() {
boolean r = true;
for (OnlineLogisticRegression model : models) {
r &= model.validModel();
}
return r;
}
// -------- classification methods
@Override
public Vector classify(Vector instance) {
Vector r = new DenseVector(numCategories() - 1);
double scale = 1.0 / models.size();
for (OnlineLogisticRegression model : models) {
r.assign(model.classify(instance), Functions.plusMult(scale));
}
return r;
}
@Override
public double classifyScalar(Vector instance) {
double r = 0;
int n = 0;
for (OnlineLogisticRegression model : models) {
n++;
r += model.classifyScalar(instance);
}
return r / n;
}
// -------- status reporting methods
@Override
public int numCategories() {
return models.get(0).numCategories();
}
public double auc() {
return auc.auc();
}
public double logLikelihood() {
return logLikelihood;
}
// -------- evolutionary optimization
public CrossFoldLearner copy() {
CrossFoldLearner r = new CrossFoldLearner(models.size(), numCategories(), numFeatures, prior);
r.models.clear();
for (OnlineLogisticRegression model : models) {
model.close();
OnlineLogisticRegression newModel = new OnlineLogisticRegression(model.numCategories(), model.numFeatures(), model.prior);
newModel.copyFrom(model);
r.models.add(newModel);
}
return r;
}
public int getRecord() {
return record;
}
public void setRecord(int record) {
this.record = record;
}
public OnlineAuc getAuc() {
return auc;
}
public void setAuc(OnlineAuc auc) {
this.auc = auc;
}
public double getLogLikelihood() {
return logLikelihood;
}
public void setLogLikelihood(double logLikelihood) {
this.logLikelihood = logLikelihood;
}
public List<OnlineLogisticRegression> getModels() {
return models;
}
public void addModel(OnlineLogisticRegression model) {
models.add(model);
}
public double[] getParameters() {
return parameters;
}
public void setParameters(double[] parameters) {
this.parameters = parameters;
}
public int getNumFeatures() {
return numFeatures;
}
public void setNumFeatures(int numFeatures) {
this.numFeatures = numFeatures;
}
public PriorFunction getPrior() {
return prior;
}
public void setPrior(PriorFunction prior) {
this.prior = prior;
}
}
| false | true | public void train(long trackingKey, int actual, Vector instance) {
record++;
int k = 0;
for (OnlineLogisticRegression model : models) {
if (k == trackingKey % models.size()) {
Vector v = model.classifyFull(instance);
double score = v.get(actual);
logLikelihood += (Math.log(score) - logLikelihood) / record;
auc.addSample(actual, v.get(1));
} else {
model.train(trackingKey, actual, instance);
}
k++;
}
}
| public void train(long trackingKey, int actual, Vector instance) {
record++;
int k = 0;
for (OnlineLogisticRegression model : models) {
if (k == trackingKey % models.size()) {
Vector v = model.classifyFull(instance);
double score = Math.max(v.get(actual), MIN_SCORE);
logLikelihood += (Math.log(score) - logLikelihood) / record;
if (numCategories() == 2) {
auc.addSample(actual, v.get(1));
}
} else {
model.train(trackingKey, actual, instance);
}
k++;
}
}
|
diff --git a/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java b/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java
index e011dc42..f45749c4 100644
--- a/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java
+++ b/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java
@@ -1,69 +1,69 @@
/**
* 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.mahout.clustering.kmeans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.mahout.clustering.WeightedVectorWritable;
import org.apache.mahout.common.distance.DistanceMeasure;
import org.apache.mahout.math.VectorWritable;
public class KMeansClusterMapper extends Mapper<WritableComparable<?>,VectorWritable,IntWritable,WeightedVectorWritable> {
private final List<Cluster> clusters = new ArrayList<Cluster>();
private KMeansClusterer clusterer;
@Override
protected void map(WritableComparable<?> key, VectorWritable point, Context context) throws IOException, InterruptedException {
clusterer.outputPointWithClusterInfo(point.get(), clusters, context);
}
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Configuration conf = context.getConfiguration();
try {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY))
.asSubclass(DistanceMeasure.class).newInstance();
measure.configure(conf);
String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY);
if ((clusterPath != null) && (clusterPath.length() > 0)) {
KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters);
if (clusters.isEmpty()) {
- throw new IllegalStateException("Cluster is empty!");
+ throw new IllegalStateException("No clusters found. Check your -c path.");
}
}
this.clusterer = new KMeansClusterer(measure);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
}
| true | true | protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Configuration conf = context.getConfiguration();
try {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY))
.asSubclass(DistanceMeasure.class).newInstance();
measure.configure(conf);
String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY);
if ((clusterPath != null) && (clusterPath.length() > 0)) {
KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters);
if (clusters.isEmpty()) {
throw new IllegalStateException("Cluster is empty!");
}
}
this.clusterer = new KMeansClusterer(measure);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
| protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Configuration conf = context.getConfiguration();
try {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY))
.asSubclass(DistanceMeasure.class).newInstance();
measure.configure(conf);
String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY);
if ((clusterPath != null) && (clusterPath.length() > 0)) {
KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters);
if (clusters.isEmpty()) {
throw new IllegalStateException("No clusters found. Check your -c path.");
}
}
this.clusterer = new KMeansClusterer(measure);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
|
diff --git a/src/main/java/com/acclivyx/rules/sequenceintegerrules/TwoArgsSpanGreaterThenRule.java b/src/main/java/com/acclivyx/rules/sequenceintegerrules/TwoArgsSpanGreaterThenRule.java
index 59f65b5..9da1c42 100644
--- a/src/main/java/com/acclivyx/rules/sequenceintegerrules/TwoArgsSpanGreaterThenRule.java
+++ b/src/main/java/com/acclivyx/rules/sequenceintegerrules/TwoArgsSpanGreaterThenRule.java
@@ -1,46 +1,46 @@
package com.acclivyx.rules.sequenceintegerrules;
import java.math.BigInteger;
import java.util.Iterator;
import com.acclivyx.rules.RuleResult;
import com.acclivyx.rules.SequenceIntegerRule;
import com.acclivyx.rules.args.RuleIntegerArgs;
/**
* If any two sequential integers in the sequence add up to 1000 or greater,
* the rule is "passed". If not, the rule is "failed".
*/
public class TwoArgsSpanGreaterThenRule extends SequenceIntegerRule{
private final BigInteger MIN = BigInteger.valueOf(1000);
public TwoArgsSpanGreaterThenRule() {
super("RuleA");
}
/**
* @param args of specific type
* @return results
*/
public RuleResult process(RuleIntegerArgs args) {
Integer first = null;
Integer second = null;
for (Iterator<Integer> iter = args.getArgs().iterator(); iter.hasNext();) {
if (first == null) {
first = second = iter.next();
continue;
}
first = second;
second = iter.next();
BigInteger result = BigInteger.valueOf(first);
- result = result.add(result);
+ result = result.add(BigInteger.valueOf(second));
if (result.compareTo(MIN) >= 0) {
return new RuleResult(true,this.name);
}
}
return new RuleResult(false,this.name);
}
}
| true | true | public RuleResult process(RuleIntegerArgs args) {
Integer first = null;
Integer second = null;
for (Iterator<Integer> iter = args.getArgs().iterator(); iter.hasNext();) {
if (first == null) {
first = second = iter.next();
continue;
}
first = second;
second = iter.next();
BigInteger result = BigInteger.valueOf(first);
result = result.add(result);
if (result.compareTo(MIN) >= 0) {
return new RuleResult(true,this.name);
}
}
return new RuleResult(false,this.name);
}
| public RuleResult process(RuleIntegerArgs args) {
Integer first = null;
Integer second = null;
for (Iterator<Integer> iter = args.getArgs().iterator(); iter.hasNext();) {
if (first == null) {
first = second = iter.next();
continue;
}
first = second;
second = iter.next();
BigInteger result = BigInteger.valueOf(first);
result = result.add(BigInteger.valueOf(second));
if (result.compareTo(MIN) >= 0) {
return new RuleResult(true,this.name);
}
}
return new RuleResult(false,this.name);
}
|
diff --git a/alchemy-midlet/src/alchemy/evm/EFunction.java b/alchemy-midlet/src/alchemy/evm/EFunction.java
index 04e3093..88ccd30 100644
--- a/alchemy-midlet/src/alchemy/evm/EFunction.java
+++ b/alchemy-midlet/src/alchemy/evm/EFunction.java
@@ -1,709 +1,709 @@
/*
* This file is a part of Alchemy OS project.
* Copyright (C) 2011-2012, Sergey Basalaev <[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 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 alchemy.evm;
import alchemy.core.AlchemyException;
import alchemy.core.Context;
import alchemy.core.Function;
import alchemy.core.Int;
/**
* Embedded Virtual Machine.
* @author Sergey Basalaev
*/
class EFunction extends Function {
private final int stacksize;
private final int localsize;
private final byte[] bcode;
private final char[] dbgtable;
private final char[] errtable;
private final Object[] cpool;
private final String libname;
public EFunction(String libname, String funcname, Object[] cpool, int stacksize, int localsize, byte[] code, char[] dbgtable, char[] errtable) {
super(funcname);
this.libname = libname;
this.stacksize = stacksize;
this.localsize = localsize;
this.bcode = code;
this.cpool = cpool;
this.dbgtable = dbgtable;
this.errtable = errtable;
}
public Object exec(Context c, Object[] args) throws AlchemyException {
//initializing
final Object[] stack = new Object[stacksize];
int head = -1;
final byte[] code = this.bcode;
Object[] locals;
if (args.length == localsize) {
locals = args;
} else {
locals = new Object[localsize];
System.arraycopy(args, 0, locals, 0, args.length);
}
int ct = 0;
while (true) {
try {
int instr = code[ct++];
switch (instr) {
// CONSTANTS
case Opcodes.ACONST_NULL: {
stack[++head] = null;
break;
}
case Opcodes.ICONST_M1: {
stack[++head] = Int.M_ONE;
break;
}
case Opcodes.ICONST_0: {
stack[++head] = Int.ZERO;
break;
}
case Opcodes.ICONST_1: {
stack[++head] = Int.ONE;
break;
}
case Opcodes.ICONST_2: {
stack[++head] = Int.toInt(2);
break;
}
case Opcodes.ICONST_3: {
stack[++head] = Int.toInt(3);
break;
}
case Opcodes.ICONST_4: {
stack[++head] = Int.toInt(4);
break;
}
case Opcodes.ICONST_5: {
stack[++head] = Int.toInt(5);
break;
}
case Opcodes.LCONST_0: {
stack[++head] = Lval(0l);
break;
}
case Opcodes.LCONST_1: {
stack[++head] = Lval(1l);
break;
}
case Opcodes.FCONST_0: {
stack[++head] = Fval(0f);
break;
}
case Opcodes.FCONST_1: {
stack[++head] = Fval(1f);
break;
}
case Opcodes.FCONST_2: {
stack[++head] = Fval(2f);
break;
}
case Opcodes.DCONST_0: {
stack[++head] = Dval(0d);
break;
}
case Opcodes.DCONST_1: {
stack[++head] = Dval(1d);
break;
}
//CONVERSIONS
case Opcodes.I2L: {
stack[head] = Lval(ival(stack[head]));
break;
}
case Opcodes.I2F: {
stack[head] = Fval(ival(stack[head]));
break;
}
case Opcodes.I2D: {
stack[head] = Dval(ival(stack[head]));
break;
}
case Opcodes.L2F: {
stack[head] = Fval(lval(stack[head]));
break;
}
case Opcodes.L2D: {
stack[head] = Dval(lval(stack[head]));
break;
}
case Opcodes.L2I: {
stack[head] = Ival((int)lval(stack[head]));
break;
}
case Opcodes.F2D: {
stack[head] = Dval(fval(stack[head]));
break;
}
case Opcodes.F2I: {
stack[head] = Ival((int)fval(stack[head]));
break;
}
case Opcodes.F2L: {
stack[head] = Lval((long)fval(stack[head]));
break;
}
case Opcodes.D2I: {
stack[head] = Ival((int)dval(stack[head]));
break;
}
case Opcodes.D2L: {
stack[head] = Lval((long)dval(stack[head]));
break;
}
case Opcodes.D2F: {
stack[head] = Fval((float)dval(stack[head]));
break;
}
//INTEGER ARITHMETICS
case Opcodes.IADD: {
Object atmp = Ival(ival(stack[--head]) + ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.ISUB: {
Object atmp = Ival(ival(stack[--head]) - ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IMUL: {
Object atmp = Ival(ival(stack[--head]) * ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IDIV: {
Object atmp = Ival(ival(stack[--head]) / ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IMOD: {
Object atmp = Ival(ival(stack[--head]) % ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.INEG: {
stack[head] = Ival(-ival(stack[head]));
break;
}
case Opcodes.ICMP: {
int itmp = ival(stack[--head]) - ival(stack[++head]);
stack[--head] = (itmp > 0) ? Int.ONE : (itmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.ISHL: {
Object atmp = Ival(ival(stack[--head]) << ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.ISHR: {
Object atmp = Ival(ival(stack[--head]) >> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IUSHR: {
Object atmp = Ival(ival(stack[--head]) >>> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IAND: {
Object atmp = Ival(ival(stack[--head]) & ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IOR: {
Object atmp = Ival(ival(stack[--head]) | ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IXOR: {
Object atmp = Ival(ival(stack[--head]) ^ ival(stack[++head]));
stack[--head] = atmp;
break;
}
//LONG ARITHMETICS
case Opcodes.LADD: {
Object atmp = Lval(lval(stack[--head]) + lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LSUB: {
Object atmp = Lval(lval(stack[--head]) - lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LMUL: {
Object atmp = Lval(lval(stack[--head]) * lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LDIV: {
Object atmp = Lval(lval(stack[--head]) / lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LMOD: {
Object atmp = Lval(lval(stack[--head]) % lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LNEG: {
stack[head] = Lval(-lval(stack[head]));
break;
}
case Opcodes.LCMP: {
long ltmp = lval(stack[--head]) - lval(stack[++head]);
stack[--head] = (ltmp > 0) ? Int.ONE : (ltmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.LSHL: {
Object atmp = Lval(lval(stack[--head]) << ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LSHR: {
Object atmp = Lval(lval(stack[--head]) >> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LUSHR: {
Object atmp = Lval(lval(stack[--head]) >>> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LAND: {
Object atmp = Lval(lval(stack[--head]) & lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LOR: {
Object atmp = Lval(lval(stack[--head]) | lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LXOR: {
Object atmp = Lval(lval(stack[--head]) ^ lval(stack[++head]));
stack[--head] = atmp;
break;
}
//FLOAT ARITHMETICS
case Opcodes.FADD: {
Object atmp = Fval(fval(stack[--head]) + fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FSUB: {
Object atmp = Fval(fval(stack[--head]) - fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FMUL: {
Object atmp = Fval(fval(stack[--head]) * fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FDIV: {
Object atmp = Fval(fval(stack[--head]) / fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FMOD: {
Object atmp = Fval(fval(stack[--head]) % fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FNEG: {
stack[head] = Fval(-fval(stack[head]));
break;
}
case Opcodes.FCMP: {
float ftmp = fval(stack[--head]) - fval(stack[++head]);
stack[--head] = (ftmp > 0) ? Int.ONE : (ftmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//DOUBLE ARITHMETICS
case Opcodes.DADD: {
Object atmp = Dval(dval(stack[--head]) + dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DSUB: {
Object atmp = Dval(dval(stack[--head]) - dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DMUL: {
Object atmp = Dval(dval(stack[--head]) * dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DDIV: {
Object atmp = Dval(dval(stack[--head]) / dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DMOD: {
Object atmp = Dval(dval(stack[--head]) % dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DNEG: {
stack[head] = Dval(-dval(stack[head]));
break;
}
case Opcodes.DCMP: {
double dtmp = dval(stack[--head]) - dval(stack[++head]);
stack[--head] = (dtmp > 0) ? Int.ONE : (dtmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//LOCALS LOADERS AND SAVERS
case Opcodes.LOAD_0:
case Opcodes.LOAD_1:
case Opcodes.LOAD_2:
case Opcodes.LOAD_3:
case Opcodes.LOAD_4:
case Opcodes.LOAD_5:
case Opcodes.LOAD_6:
case Opcodes.LOAD_7:
stack[++head] = locals[instr & 7]; break;
case Opcodes.LOAD: { //load <ubyte>
stack[++head] = locals[code[ct++] & 0xff];
break;
}
//variable savers
case Opcodes.STORE_0:
case Opcodes.STORE_1:
case Opcodes.STORE_2:
case Opcodes.STORE_3:
case Opcodes.STORE_4:
case Opcodes.STORE_5:
case Opcodes.STORE_6:
case Opcodes.STORE_7:{
locals[instr & 7] = stack[head];
head--;
break;
}
case Opcodes.STORE: { //store <ubyte>
locals[code[ct++] & 0xff] = stack[head];
head--;
break;
}
//BRANCHING
case Opcodes.IFEQ: { //ifeq <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) == 0) ct = itmp;
break;
}
case Opcodes.IFNE: { //ifne <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) != 0) ct = itmp;
break;
}
case Opcodes.IFLT: { //iflt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) < 0) ct = itmp;
break;
}
case Opcodes.IFGE: { //ifge <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) >= 0) ct = itmp;
break;
}
case Opcodes.IFGT: { //ifgt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) > 0) ct = itmp;
break;
}
case Opcodes.IFLE: { //ifle <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) <= 0) ct = itmp;
break;
}
case Opcodes.GOTO: { //goto <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
ct = itmp;
break;
}
case Opcodes.IFNULL: { //ifnull <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (stack[head--] == null) ct = itmp;
break;
}
case Opcodes.IFNNULL: { //ifnnull <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (stack[head--] != null) ct = itmp;
break;
}
case Opcodes.IF_ICMPLT: { //if_icmplt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) > ival(stack[head--])) ct = itmp;
break;
}
case Opcodes.IF_ICMPGE: { //if_icmpge <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) <= ival(stack[head--])) ct = itmp;
break;
}
case Opcodes.IF_ICMPGT: { //if_icmpgt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) < ival(stack[head--])) ct = itmp;
break;
}
case Opcodes.IF_ICMPLE: { //if_icmple <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) >= ival(stack[head--])) ct = itmp;
break;
}
//FUNCTION CALLS
case Opcodes.CALL_0:
case Opcodes.CALL_1:
case Opcodes.CALL_2:
case Opcodes.CALL_3:
case Opcodes.CALL_4:
case Opcodes.CALL_5:
case Opcodes.CALL_6:
case Opcodes.CALL_7:
case Opcodes.CALV_0:
case Opcodes.CALV_1:
case Opcodes.CALV_2:
case Opcodes.CALV_3:
case Opcodes.CALV_4:
case Opcodes.CALV_5:
case Opcodes.CALV_6:
case Opcodes.CALV_7: {
int paramlen = instr & 7;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
if ((instr & 8) != 0) head--;
break;
}
case Opcodes.CALL: {//call <ubyte>
int paramlen = code[ct++] & 0xff;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
break;
}
case Opcodes.CALV: {//calv <ubyte>
int paramlen = code[ct++] & 0xff;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
((Function)stack[head]).exec(c, params);
head--;
break;
}
//ARRAY INSTRUCTIONS
case Opcodes.NEWARRAY: {
stack[head] = new Object[ival(stack[head])];
break;
}
case Opcodes.ALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = ((Object[])stack[head])[at];
break;
}
case Opcodes.ASTORE: {
Object val = stack[head];
int at = ival(stack[head-1]);
Object[] array = (Object[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.ALEN: {
stack[head] = Ival(((Object[])stack[head]).length);
break;
}
case Opcodes.NEWBA: {
stack[head] = new byte[ival(stack[head])];
break;
}
case Opcodes.BALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((byte[])stack[head])[at] );
break;
}
case Opcodes.BASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
byte[] array = (byte[])stack[head-2];
array[at] = (byte)val;
head -= 3;
break;
}
case Opcodes.BALEN: {
stack[head] = Ival(((byte[])stack[head]).length);
break;
}
case Opcodes.NEWCA: {
stack[head] = new char[ival(stack[head])];
break;
}
case Opcodes.CALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((char[])stack[head])[at] );
break;
}
case Opcodes.CASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
char[] array = (char[])stack[head-2];
array[at] = (char)val;
head -= 3;
break;
}
case Opcodes.CALEN: {
stack[head] = Ival(((char[])stack[head]).length);
break;
}
//SWITCH BRANCHING
case Opcodes.TABLESWITCH: {
int dflt = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
int min = ((code[ct++] & 0xff) << 24)
| ((code[ct++] & 0xff) << 16)
| ((code[ct++] & 0xff) << 8)
| (code[ct++] & 0xff);
int max = ((code[ct++] & 0xff) << 24)
| ((code[ct++] & 0xff) << 16)
| ((code[ct++] & 0xff) << 8)
| (code[ct++] & 0xff);
int val = ival(stack[head--]);
if (val >= min && val <= max) {
ct += (val-min)*2;
ct = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
} else {
ct = dflt;
}
break;
}
case Opcodes.LOOKUPSWITCH: {
int dflt = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
int count = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
int val = ival(stack[head--]);
boolean matched = false;
for (int i=0; i<count && !matched; i++) {
int cand = ((code[ct++] & 0xff) << 24)
| ((code[ct++] & 0xff) << 16)
| ((code[ct++] & 0xff) << 8)
| (code[ct++] & 0xff);
if (val == cand) {
ct = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
matched = true;
} else {
ct += 2;
}
}
if (!matched) ct = dflt;
break;
}
//OTHERS
case Opcodes.ACMP: {
boolean btmp = stack[head] == null ? stack[head-1] == null : stack[head].equals(stack[head-1]);
stack[--head] = Ival(!btmp);
break;
}
case Opcodes.RET_NULL:
return null;
case Opcodes.RETURN:
return stack[head];
case Opcodes.DUP: {
stack[head+1] = stack[head];
head++;
break;
}
case Opcodes.DUP2: {
stack[head+2] = stack[head+1] = stack[head];
head += 2;
break;
}
case Opcodes.SWAP: {
Object atmp = stack[head-1];
stack[head-1] = stack[head];
stack[head] = atmp;
break;
}
case Opcodes.LDC: { //ldc <ushort>
stack[++head] = cpool[((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff)];
break;
}
case Opcodes.POP:
head--;
break;
case Opcodes.BIPUSH: //bipush <byte>
stack[++head] = Ival(code[ct++]);
break;
case Opcodes.SIPUSH: //sipush <short>
stack[++head] = Ival((code[ct++] << 8) | (code[ct++]& 0xff));
break;
} /* the big switch */
- } catch (Exception e) {
+ } catch (Throwable e) {
// the instruction on which error occured
ct--;
// filling exception with debug info
AlchemyException ae = (e instanceof AlchemyException) ? (AlchemyException)e : new AlchemyException(e);
if (dbgtable != null) {
int srcline = 0;
for (int i=1; i<dbgtable.length; i += 2) {
if (dbgtable[i] <= ct) srcline = dbgtable[i+1];
}
ae.addTraceElement(this, cpool[dbgtable[0]]+":"+srcline);
} else {
ae.addTraceElement(this, "+"+ct);
}
// catching or rethrowing
int jumpto = -1;
if (errtable != null) {
for (int i=0; i<errtable.length && jumpto < 0; i += 3) {
if (ct >= errtable[i] && ct <= errtable[i+1]) jumpto = errtable[i+2];
}
}
if (jumpto >= 0) {
stack[++head] = ae;
ct = jumpto;
} else {
throw ae;
}
}
} /* the great while */
}
public String toString() {
if (libname != null) return libname+':'+signature;
else return signature;
}
}
| true | true | public Object exec(Context c, Object[] args) throws AlchemyException {
//initializing
final Object[] stack = new Object[stacksize];
int head = -1;
final byte[] code = this.bcode;
Object[] locals;
if (args.length == localsize) {
locals = args;
} else {
locals = new Object[localsize];
System.arraycopy(args, 0, locals, 0, args.length);
}
int ct = 0;
while (true) {
try {
int instr = code[ct++];
switch (instr) {
// CONSTANTS
case Opcodes.ACONST_NULL: {
stack[++head] = null;
break;
}
case Opcodes.ICONST_M1: {
stack[++head] = Int.M_ONE;
break;
}
case Opcodes.ICONST_0: {
stack[++head] = Int.ZERO;
break;
}
case Opcodes.ICONST_1: {
stack[++head] = Int.ONE;
break;
}
case Opcodes.ICONST_2: {
stack[++head] = Int.toInt(2);
break;
}
case Opcodes.ICONST_3: {
stack[++head] = Int.toInt(3);
break;
}
case Opcodes.ICONST_4: {
stack[++head] = Int.toInt(4);
break;
}
case Opcodes.ICONST_5: {
stack[++head] = Int.toInt(5);
break;
}
case Opcodes.LCONST_0: {
stack[++head] = Lval(0l);
break;
}
case Opcodes.LCONST_1: {
stack[++head] = Lval(1l);
break;
}
case Opcodes.FCONST_0: {
stack[++head] = Fval(0f);
break;
}
case Opcodes.FCONST_1: {
stack[++head] = Fval(1f);
break;
}
case Opcodes.FCONST_2: {
stack[++head] = Fval(2f);
break;
}
case Opcodes.DCONST_0: {
stack[++head] = Dval(0d);
break;
}
case Opcodes.DCONST_1: {
stack[++head] = Dval(1d);
break;
}
//CONVERSIONS
case Opcodes.I2L: {
stack[head] = Lval(ival(stack[head]));
break;
}
case Opcodes.I2F: {
stack[head] = Fval(ival(stack[head]));
break;
}
case Opcodes.I2D: {
stack[head] = Dval(ival(stack[head]));
break;
}
case Opcodes.L2F: {
stack[head] = Fval(lval(stack[head]));
break;
}
case Opcodes.L2D: {
stack[head] = Dval(lval(stack[head]));
break;
}
case Opcodes.L2I: {
stack[head] = Ival((int)lval(stack[head]));
break;
}
case Opcodes.F2D: {
stack[head] = Dval(fval(stack[head]));
break;
}
case Opcodes.F2I: {
stack[head] = Ival((int)fval(stack[head]));
break;
}
case Opcodes.F2L: {
stack[head] = Lval((long)fval(stack[head]));
break;
}
case Opcodes.D2I: {
stack[head] = Ival((int)dval(stack[head]));
break;
}
case Opcodes.D2L: {
stack[head] = Lval((long)dval(stack[head]));
break;
}
case Opcodes.D2F: {
stack[head] = Fval((float)dval(stack[head]));
break;
}
//INTEGER ARITHMETICS
case Opcodes.IADD: {
Object atmp = Ival(ival(stack[--head]) + ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.ISUB: {
Object atmp = Ival(ival(stack[--head]) - ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IMUL: {
Object atmp = Ival(ival(stack[--head]) * ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IDIV: {
Object atmp = Ival(ival(stack[--head]) / ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IMOD: {
Object atmp = Ival(ival(stack[--head]) % ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.INEG: {
stack[head] = Ival(-ival(stack[head]));
break;
}
case Opcodes.ICMP: {
int itmp = ival(stack[--head]) - ival(stack[++head]);
stack[--head] = (itmp > 0) ? Int.ONE : (itmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.ISHL: {
Object atmp = Ival(ival(stack[--head]) << ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.ISHR: {
Object atmp = Ival(ival(stack[--head]) >> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IUSHR: {
Object atmp = Ival(ival(stack[--head]) >>> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IAND: {
Object atmp = Ival(ival(stack[--head]) & ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IOR: {
Object atmp = Ival(ival(stack[--head]) | ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IXOR: {
Object atmp = Ival(ival(stack[--head]) ^ ival(stack[++head]));
stack[--head] = atmp;
break;
}
//LONG ARITHMETICS
case Opcodes.LADD: {
Object atmp = Lval(lval(stack[--head]) + lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LSUB: {
Object atmp = Lval(lval(stack[--head]) - lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LMUL: {
Object atmp = Lval(lval(stack[--head]) * lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LDIV: {
Object atmp = Lval(lval(stack[--head]) / lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LMOD: {
Object atmp = Lval(lval(stack[--head]) % lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LNEG: {
stack[head] = Lval(-lval(stack[head]));
break;
}
case Opcodes.LCMP: {
long ltmp = lval(stack[--head]) - lval(stack[++head]);
stack[--head] = (ltmp > 0) ? Int.ONE : (ltmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.LSHL: {
Object atmp = Lval(lval(stack[--head]) << ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LSHR: {
Object atmp = Lval(lval(stack[--head]) >> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LUSHR: {
Object atmp = Lval(lval(stack[--head]) >>> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LAND: {
Object atmp = Lval(lval(stack[--head]) & lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LOR: {
Object atmp = Lval(lval(stack[--head]) | lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LXOR: {
Object atmp = Lval(lval(stack[--head]) ^ lval(stack[++head]));
stack[--head] = atmp;
break;
}
//FLOAT ARITHMETICS
case Opcodes.FADD: {
Object atmp = Fval(fval(stack[--head]) + fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FSUB: {
Object atmp = Fval(fval(stack[--head]) - fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FMUL: {
Object atmp = Fval(fval(stack[--head]) * fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FDIV: {
Object atmp = Fval(fval(stack[--head]) / fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FMOD: {
Object atmp = Fval(fval(stack[--head]) % fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FNEG: {
stack[head] = Fval(-fval(stack[head]));
break;
}
case Opcodes.FCMP: {
float ftmp = fval(stack[--head]) - fval(stack[++head]);
stack[--head] = (ftmp > 0) ? Int.ONE : (ftmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//DOUBLE ARITHMETICS
case Opcodes.DADD: {
Object atmp = Dval(dval(stack[--head]) + dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DSUB: {
Object atmp = Dval(dval(stack[--head]) - dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DMUL: {
Object atmp = Dval(dval(stack[--head]) * dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DDIV: {
Object atmp = Dval(dval(stack[--head]) / dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DMOD: {
Object atmp = Dval(dval(stack[--head]) % dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DNEG: {
stack[head] = Dval(-dval(stack[head]));
break;
}
case Opcodes.DCMP: {
double dtmp = dval(stack[--head]) - dval(stack[++head]);
stack[--head] = (dtmp > 0) ? Int.ONE : (dtmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//LOCALS LOADERS AND SAVERS
case Opcodes.LOAD_0:
case Opcodes.LOAD_1:
case Opcodes.LOAD_2:
case Opcodes.LOAD_3:
case Opcodes.LOAD_4:
case Opcodes.LOAD_5:
case Opcodes.LOAD_6:
case Opcodes.LOAD_7:
stack[++head] = locals[instr & 7]; break;
case Opcodes.LOAD: { //load <ubyte>
stack[++head] = locals[code[ct++] & 0xff];
break;
}
//variable savers
case Opcodes.STORE_0:
case Opcodes.STORE_1:
case Opcodes.STORE_2:
case Opcodes.STORE_3:
case Opcodes.STORE_4:
case Opcodes.STORE_5:
case Opcodes.STORE_6:
case Opcodes.STORE_7:{
locals[instr & 7] = stack[head];
head--;
break;
}
case Opcodes.STORE: { //store <ubyte>
locals[code[ct++] & 0xff] = stack[head];
head--;
break;
}
//BRANCHING
case Opcodes.IFEQ: { //ifeq <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) == 0) ct = itmp;
break;
}
case Opcodes.IFNE: { //ifne <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) != 0) ct = itmp;
break;
}
case Opcodes.IFLT: { //iflt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) < 0) ct = itmp;
break;
}
case Opcodes.IFGE: { //ifge <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) >= 0) ct = itmp;
break;
}
case Opcodes.IFGT: { //ifgt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) > 0) ct = itmp;
break;
}
case Opcodes.IFLE: { //ifle <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) <= 0) ct = itmp;
break;
}
case Opcodes.GOTO: { //goto <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
ct = itmp;
break;
}
case Opcodes.IFNULL: { //ifnull <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (stack[head--] == null) ct = itmp;
break;
}
case Opcodes.IFNNULL: { //ifnnull <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (stack[head--] != null) ct = itmp;
break;
}
case Opcodes.IF_ICMPLT: { //if_icmplt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) > ival(stack[head--])) ct = itmp;
break;
}
case Opcodes.IF_ICMPGE: { //if_icmpge <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) <= ival(stack[head--])) ct = itmp;
break;
}
case Opcodes.IF_ICMPGT: { //if_icmpgt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) < ival(stack[head--])) ct = itmp;
break;
}
case Opcodes.IF_ICMPLE: { //if_icmple <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) >= ival(stack[head--])) ct = itmp;
break;
}
//FUNCTION CALLS
case Opcodes.CALL_0:
case Opcodes.CALL_1:
case Opcodes.CALL_2:
case Opcodes.CALL_3:
case Opcodes.CALL_4:
case Opcodes.CALL_5:
case Opcodes.CALL_6:
case Opcodes.CALL_7:
case Opcodes.CALV_0:
case Opcodes.CALV_1:
case Opcodes.CALV_2:
case Opcodes.CALV_3:
case Opcodes.CALV_4:
case Opcodes.CALV_5:
case Opcodes.CALV_6:
case Opcodes.CALV_7: {
int paramlen = instr & 7;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
if ((instr & 8) != 0) head--;
break;
}
case Opcodes.CALL: {//call <ubyte>
int paramlen = code[ct++] & 0xff;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
break;
}
case Opcodes.CALV: {//calv <ubyte>
int paramlen = code[ct++] & 0xff;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
((Function)stack[head]).exec(c, params);
head--;
break;
}
//ARRAY INSTRUCTIONS
case Opcodes.NEWARRAY: {
stack[head] = new Object[ival(stack[head])];
break;
}
case Opcodes.ALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = ((Object[])stack[head])[at];
break;
}
case Opcodes.ASTORE: {
Object val = stack[head];
int at = ival(stack[head-1]);
Object[] array = (Object[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.ALEN: {
stack[head] = Ival(((Object[])stack[head]).length);
break;
}
case Opcodes.NEWBA: {
stack[head] = new byte[ival(stack[head])];
break;
}
case Opcodes.BALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((byte[])stack[head])[at] );
break;
}
case Opcodes.BASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
byte[] array = (byte[])stack[head-2];
array[at] = (byte)val;
head -= 3;
break;
}
case Opcodes.BALEN: {
stack[head] = Ival(((byte[])stack[head]).length);
break;
}
case Opcodes.NEWCA: {
stack[head] = new char[ival(stack[head])];
break;
}
case Opcodes.CALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((char[])stack[head])[at] );
break;
}
case Opcodes.CASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
char[] array = (char[])stack[head-2];
array[at] = (char)val;
head -= 3;
break;
}
case Opcodes.CALEN: {
stack[head] = Ival(((char[])stack[head]).length);
break;
}
//SWITCH BRANCHING
case Opcodes.TABLESWITCH: {
int dflt = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
int min = ((code[ct++] & 0xff) << 24)
| ((code[ct++] & 0xff) << 16)
| ((code[ct++] & 0xff) << 8)
| (code[ct++] & 0xff);
int max = ((code[ct++] & 0xff) << 24)
| ((code[ct++] & 0xff) << 16)
| ((code[ct++] & 0xff) << 8)
| (code[ct++] & 0xff);
int val = ival(stack[head--]);
if (val >= min && val <= max) {
ct += (val-min)*2;
ct = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
} else {
ct = dflt;
}
break;
}
case Opcodes.LOOKUPSWITCH: {
int dflt = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
int count = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
int val = ival(stack[head--]);
boolean matched = false;
for (int i=0; i<count && !matched; i++) {
int cand = ((code[ct++] & 0xff) << 24)
| ((code[ct++] & 0xff) << 16)
| ((code[ct++] & 0xff) << 8)
| (code[ct++] & 0xff);
if (val == cand) {
ct = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
matched = true;
} else {
ct += 2;
}
}
if (!matched) ct = dflt;
break;
}
//OTHERS
case Opcodes.ACMP: {
boolean btmp = stack[head] == null ? stack[head-1] == null : stack[head].equals(stack[head-1]);
stack[--head] = Ival(!btmp);
break;
}
case Opcodes.RET_NULL:
return null;
case Opcodes.RETURN:
return stack[head];
case Opcodes.DUP: {
stack[head+1] = stack[head];
head++;
break;
}
case Opcodes.DUP2: {
stack[head+2] = stack[head+1] = stack[head];
head += 2;
break;
}
case Opcodes.SWAP: {
Object atmp = stack[head-1];
stack[head-1] = stack[head];
stack[head] = atmp;
break;
}
case Opcodes.LDC: { //ldc <ushort>
stack[++head] = cpool[((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff)];
break;
}
case Opcodes.POP:
head--;
break;
case Opcodes.BIPUSH: //bipush <byte>
stack[++head] = Ival(code[ct++]);
break;
case Opcodes.SIPUSH: //sipush <short>
stack[++head] = Ival((code[ct++] << 8) | (code[ct++]& 0xff));
break;
} /* the big switch */
} catch (Exception e) {
// the instruction on which error occured
ct--;
// filling exception with debug info
AlchemyException ae = (e instanceof AlchemyException) ? (AlchemyException)e : new AlchemyException(e);
if (dbgtable != null) {
int srcline = 0;
for (int i=1; i<dbgtable.length; i += 2) {
if (dbgtable[i] <= ct) srcline = dbgtable[i+1];
}
ae.addTraceElement(this, cpool[dbgtable[0]]+":"+srcline);
} else {
ae.addTraceElement(this, "+"+ct);
}
// catching or rethrowing
int jumpto = -1;
if (errtable != null) {
for (int i=0; i<errtable.length && jumpto < 0; i += 3) {
if (ct >= errtable[i] && ct <= errtable[i+1]) jumpto = errtable[i+2];
}
}
if (jumpto >= 0) {
stack[++head] = ae;
ct = jumpto;
} else {
throw ae;
}
}
} /* the great while */
}
| public Object exec(Context c, Object[] args) throws AlchemyException {
//initializing
final Object[] stack = new Object[stacksize];
int head = -1;
final byte[] code = this.bcode;
Object[] locals;
if (args.length == localsize) {
locals = args;
} else {
locals = new Object[localsize];
System.arraycopy(args, 0, locals, 0, args.length);
}
int ct = 0;
while (true) {
try {
int instr = code[ct++];
switch (instr) {
// CONSTANTS
case Opcodes.ACONST_NULL: {
stack[++head] = null;
break;
}
case Opcodes.ICONST_M1: {
stack[++head] = Int.M_ONE;
break;
}
case Opcodes.ICONST_0: {
stack[++head] = Int.ZERO;
break;
}
case Opcodes.ICONST_1: {
stack[++head] = Int.ONE;
break;
}
case Opcodes.ICONST_2: {
stack[++head] = Int.toInt(2);
break;
}
case Opcodes.ICONST_3: {
stack[++head] = Int.toInt(3);
break;
}
case Opcodes.ICONST_4: {
stack[++head] = Int.toInt(4);
break;
}
case Opcodes.ICONST_5: {
stack[++head] = Int.toInt(5);
break;
}
case Opcodes.LCONST_0: {
stack[++head] = Lval(0l);
break;
}
case Opcodes.LCONST_1: {
stack[++head] = Lval(1l);
break;
}
case Opcodes.FCONST_0: {
stack[++head] = Fval(0f);
break;
}
case Opcodes.FCONST_1: {
stack[++head] = Fval(1f);
break;
}
case Opcodes.FCONST_2: {
stack[++head] = Fval(2f);
break;
}
case Opcodes.DCONST_0: {
stack[++head] = Dval(0d);
break;
}
case Opcodes.DCONST_1: {
stack[++head] = Dval(1d);
break;
}
//CONVERSIONS
case Opcodes.I2L: {
stack[head] = Lval(ival(stack[head]));
break;
}
case Opcodes.I2F: {
stack[head] = Fval(ival(stack[head]));
break;
}
case Opcodes.I2D: {
stack[head] = Dval(ival(stack[head]));
break;
}
case Opcodes.L2F: {
stack[head] = Fval(lval(stack[head]));
break;
}
case Opcodes.L2D: {
stack[head] = Dval(lval(stack[head]));
break;
}
case Opcodes.L2I: {
stack[head] = Ival((int)lval(stack[head]));
break;
}
case Opcodes.F2D: {
stack[head] = Dval(fval(stack[head]));
break;
}
case Opcodes.F2I: {
stack[head] = Ival((int)fval(stack[head]));
break;
}
case Opcodes.F2L: {
stack[head] = Lval((long)fval(stack[head]));
break;
}
case Opcodes.D2I: {
stack[head] = Ival((int)dval(stack[head]));
break;
}
case Opcodes.D2L: {
stack[head] = Lval((long)dval(stack[head]));
break;
}
case Opcodes.D2F: {
stack[head] = Fval((float)dval(stack[head]));
break;
}
//INTEGER ARITHMETICS
case Opcodes.IADD: {
Object atmp = Ival(ival(stack[--head]) + ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.ISUB: {
Object atmp = Ival(ival(stack[--head]) - ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IMUL: {
Object atmp = Ival(ival(stack[--head]) * ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IDIV: {
Object atmp = Ival(ival(stack[--head]) / ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IMOD: {
Object atmp = Ival(ival(stack[--head]) % ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.INEG: {
stack[head] = Ival(-ival(stack[head]));
break;
}
case Opcodes.ICMP: {
int itmp = ival(stack[--head]) - ival(stack[++head]);
stack[--head] = (itmp > 0) ? Int.ONE : (itmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.ISHL: {
Object atmp = Ival(ival(stack[--head]) << ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.ISHR: {
Object atmp = Ival(ival(stack[--head]) >> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IUSHR: {
Object atmp = Ival(ival(stack[--head]) >>> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IAND: {
Object atmp = Ival(ival(stack[--head]) & ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IOR: {
Object atmp = Ival(ival(stack[--head]) | ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.IXOR: {
Object atmp = Ival(ival(stack[--head]) ^ ival(stack[++head]));
stack[--head] = atmp;
break;
}
//LONG ARITHMETICS
case Opcodes.LADD: {
Object atmp = Lval(lval(stack[--head]) + lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LSUB: {
Object atmp = Lval(lval(stack[--head]) - lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LMUL: {
Object atmp = Lval(lval(stack[--head]) * lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LDIV: {
Object atmp = Lval(lval(stack[--head]) / lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LMOD: {
Object atmp = Lval(lval(stack[--head]) % lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LNEG: {
stack[head] = Lval(-lval(stack[head]));
break;
}
case Opcodes.LCMP: {
long ltmp = lval(stack[--head]) - lval(stack[++head]);
stack[--head] = (ltmp > 0) ? Int.ONE : (ltmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.LSHL: {
Object atmp = Lval(lval(stack[--head]) << ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LSHR: {
Object atmp = Lval(lval(stack[--head]) >> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LUSHR: {
Object atmp = Lval(lval(stack[--head]) >>> ival(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LAND: {
Object atmp = Lval(lval(stack[--head]) & lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LOR: {
Object atmp = Lval(lval(stack[--head]) | lval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.LXOR: {
Object atmp = Lval(lval(stack[--head]) ^ lval(stack[++head]));
stack[--head] = atmp;
break;
}
//FLOAT ARITHMETICS
case Opcodes.FADD: {
Object atmp = Fval(fval(stack[--head]) + fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FSUB: {
Object atmp = Fval(fval(stack[--head]) - fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FMUL: {
Object atmp = Fval(fval(stack[--head]) * fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FDIV: {
Object atmp = Fval(fval(stack[--head]) / fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FMOD: {
Object atmp = Fval(fval(stack[--head]) % fval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.FNEG: {
stack[head] = Fval(-fval(stack[head]));
break;
}
case Opcodes.FCMP: {
float ftmp = fval(stack[--head]) - fval(stack[++head]);
stack[--head] = (ftmp > 0) ? Int.ONE : (ftmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//DOUBLE ARITHMETICS
case Opcodes.DADD: {
Object atmp = Dval(dval(stack[--head]) + dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DSUB: {
Object atmp = Dval(dval(stack[--head]) - dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DMUL: {
Object atmp = Dval(dval(stack[--head]) * dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DDIV: {
Object atmp = Dval(dval(stack[--head]) / dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DMOD: {
Object atmp = Dval(dval(stack[--head]) % dval(stack[++head]));
stack[--head] = atmp;
break;
}
case Opcodes.DNEG: {
stack[head] = Dval(-dval(stack[head]));
break;
}
case Opcodes.DCMP: {
double dtmp = dval(stack[--head]) - dval(stack[++head]);
stack[--head] = (dtmp > 0) ? Int.ONE : (dtmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//LOCALS LOADERS AND SAVERS
case Opcodes.LOAD_0:
case Opcodes.LOAD_1:
case Opcodes.LOAD_2:
case Opcodes.LOAD_3:
case Opcodes.LOAD_4:
case Opcodes.LOAD_5:
case Opcodes.LOAD_6:
case Opcodes.LOAD_7:
stack[++head] = locals[instr & 7]; break;
case Opcodes.LOAD: { //load <ubyte>
stack[++head] = locals[code[ct++] & 0xff];
break;
}
//variable savers
case Opcodes.STORE_0:
case Opcodes.STORE_1:
case Opcodes.STORE_2:
case Opcodes.STORE_3:
case Opcodes.STORE_4:
case Opcodes.STORE_5:
case Opcodes.STORE_6:
case Opcodes.STORE_7:{
locals[instr & 7] = stack[head];
head--;
break;
}
case Opcodes.STORE: { //store <ubyte>
locals[code[ct++] & 0xff] = stack[head];
head--;
break;
}
//BRANCHING
case Opcodes.IFEQ: { //ifeq <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) == 0) ct = itmp;
break;
}
case Opcodes.IFNE: { //ifne <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) != 0) ct = itmp;
break;
}
case Opcodes.IFLT: { //iflt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) < 0) ct = itmp;
break;
}
case Opcodes.IFGE: { //ifge <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) >= 0) ct = itmp;
break;
}
case Opcodes.IFGT: { //ifgt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) > 0) ct = itmp;
break;
}
case Opcodes.IFLE: { //ifle <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) <= 0) ct = itmp;
break;
}
case Opcodes.GOTO: { //goto <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
ct = itmp;
break;
}
case Opcodes.IFNULL: { //ifnull <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (stack[head--] == null) ct = itmp;
break;
}
case Opcodes.IFNNULL: { //ifnnull <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (stack[head--] != null) ct = itmp;
break;
}
case Opcodes.IF_ICMPLT: { //if_icmplt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) > ival(stack[head--])) ct = itmp;
break;
}
case Opcodes.IF_ICMPGE: { //if_icmpge <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) <= ival(stack[head--])) ct = itmp;
break;
}
case Opcodes.IF_ICMPGT: { //if_icmpgt <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) < ival(stack[head--])) ct = itmp;
break;
}
case Opcodes.IF_ICMPLE: { //if_icmple <ushort>
int itmp = (code[ct++] & 0xff) << 8 | (code[ct++] & 0xff);
if (ival(stack[head--]) >= ival(stack[head--])) ct = itmp;
break;
}
//FUNCTION CALLS
case Opcodes.CALL_0:
case Opcodes.CALL_1:
case Opcodes.CALL_2:
case Opcodes.CALL_3:
case Opcodes.CALL_4:
case Opcodes.CALL_5:
case Opcodes.CALL_6:
case Opcodes.CALL_7:
case Opcodes.CALV_0:
case Opcodes.CALV_1:
case Opcodes.CALV_2:
case Opcodes.CALV_3:
case Opcodes.CALV_4:
case Opcodes.CALV_5:
case Opcodes.CALV_6:
case Opcodes.CALV_7: {
int paramlen = instr & 7;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
if ((instr & 8) != 0) head--;
break;
}
case Opcodes.CALL: {//call <ubyte>
int paramlen = code[ct++] & 0xff;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
break;
}
case Opcodes.CALV: {//calv <ubyte>
int paramlen = code[ct++] & 0xff;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
((Function)stack[head]).exec(c, params);
head--;
break;
}
//ARRAY INSTRUCTIONS
case Opcodes.NEWARRAY: {
stack[head] = new Object[ival(stack[head])];
break;
}
case Opcodes.ALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = ((Object[])stack[head])[at];
break;
}
case Opcodes.ASTORE: {
Object val = stack[head];
int at = ival(stack[head-1]);
Object[] array = (Object[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.ALEN: {
stack[head] = Ival(((Object[])stack[head]).length);
break;
}
case Opcodes.NEWBA: {
stack[head] = new byte[ival(stack[head])];
break;
}
case Opcodes.BALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((byte[])stack[head])[at] );
break;
}
case Opcodes.BASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
byte[] array = (byte[])stack[head-2];
array[at] = (byte)val;
head -= 3;
break;
}
case Opcodes.BALEN: {
stack[head] = Ival(((byte[])stack[head]).length);
break;
}
case Opcodes.NEWCA: {
stack[head] = new char[ival(stack[head])];
break;
}
case Opcodes.CALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((char[])stack[head])[at] );
break;
}
case Opcodes.CASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
char[] array = (char[])stack[head-2];
array[at] = (char)val;
head -= 3;
break;
}
case Opcodes.CALEN: {
stack[head] = Ival(((char[])stack[head]).length);
break;
}
//SWITCH BRANCHING
case Opcodes.TABLESWITCH: {
int dflt = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
int min = ((code[ct++] & 0xff) << 24)
| ((code[ct++] & 0xff) << 16)
| ((code[ct++] & 0xff) << 8)
| (code[ct++] & 0xff);
int max = ((code[ct++] & 0xff) << 24)
| ((code[ct++] & 0xff) << 16)
| ((code[ct++] & 0xff) << 8)
| (code[ct++] & 0xff);
int val = ival(stack[head--]);
if (val >= min && val <= max) {
ct += (val-min)*2;
ct = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
} else {
ct = dflt;
}
break;
}
case Opcodes.LOOKUPSWITCH: {
int dflt = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
int count = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
int val = ival(stack[head--]);
boolean matched = false;
for (int i=0; i<count && !matched; i++) {
int cand = ((code[ct++] & 0xff) << 24)
| ((code[ct++] & 0xff) << 16)
| ((code[ct++] & 0xff) << 8)
| (code[ct++] & 0xff);
if (val == cand) {
ct = ((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff);
matched = true;
} else {
ct += 2;
}
}
if (!matched) ct = dflt;
break;
}
//OTHERS
case Opcodes.ACMP: {
boolean btmp = stack[head] == null ? stack[head-1] == null : stack[head].equals(stack[head-1]);
stack[--head] = Ival(!btmp);
break;
}
case Opcodes.RET_NULL:
return null;
case Opcodes.RETURN:
return stack[head];
case Opcodes.DUP: {
stack[head+1] = stack[head];
head++;
break;
}
case Opcodes.DUP2: {
stack[head+2] = stack[head+1] = stack[head];
head += 2;
break;
}
case Opcodes.SWAP: {
Object atmp = stack[head-1];
stack[head-1] = stack[head];
stack[head] = atmp;
break;
}
case Opcodes.LDC: { //ldc <ushort>
stack[++head] = cpool[((code[ct++] & 0xff) << 8) | (code[ct++] & 0xff)];
break;
}
case Opcodes.POP:
head--;
break;
case Opcodes.BIPUSH: //bipush <byte>
stack[++head] = Ival(code[ct++]);
break;
case Opcodes.SIPUSH: //sipush <short>
stack[++head] = Ival((code[ct++] << 8) | (code[ct++]& 0xff));
break;
} /* the big switch */
} catch (Throwable e) {
// the instruction on which error occured
ct--;
// filling exception with debug info
AlchemyException ae = (e instanceof AlchemyException) ? (AlchemyException)e : new AlchemyException(e);
if (dbgtable != null) {
int srcline = 0;
for (int i=1; i<dbgtable.length; i += 2) {
if (dbgtable[i] <= ct) srcline = dbgtable[i+1];
}
ae.addTraceElement(this, cpool[dbgtable[0]]+":"+srcline);
} else {
ae.addTraceElement(this, "+"+ct);
}
// catching or rethrowing
int jumpto = -1;
if (errtable != null) {
for (int i=0; i<errtable.length && jumpto < 0; i += 3) {
if (ct >= errtable[i] && ct <= errtable[i+1]) jumpto = errtable[i+2];
}
}
if (jumpto >= 0) {
stack[++head] = ae;
ct = jumpto;
} else {
throw ae;
}
}
} /* the great while */
}
|
diff --git a/src/com/android/browser/TitleBarXLarge.java b/src/com/android/browser/TitleBarXLarge.java
index 5296ed1c..76f57d00 100644
--- a/src/com/android/browser/TitleBarXLarge.java
+++ b/src/com/android/browser/TitleBarXLarge.java
@@ -1,170 +1,172 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.common.speech.LoggingEvents;
/**
* This class represents a title bar for a particular "tab" or "window" in the
* browser.
*/
public class TitleBarXLarge extends TitleBarBase {
private Drawable mCircularProgress;
private ProgressBar mHorizontalProgress;
private Drawable mStopDrawable;
private Drawable mReloadDrawable;
private boolean mInLoad;
private BrowserActivity mBrowserActivity;
private final View mBackButton;
private final View mForwardButton;
private final View mStar;
private final View mMenu;
private final ImageView mStopButton;
private final TextView mTitle;
private final View mAllButton;
public TitleBarXLarge(BrowserActivity context) {
super(context);
Resources resources = context.getResources();
LayoutInflater factory = LayoutInflater.from(context);
factory.inflate(R.layout.title_bar_xlarge, this);
mBrowserActivity = context;
mTitle = (TextView) findViewById(R.id.title);
mTitle.setCompoundDrawablePadding(5);
mTitle.setLongClickable(true);
mLockIcon = (ImageView) findViewById(R.id.lock);
mFavicon = (ImageView) findViewById(R.id.favicon);
mStopButton = (ImageView) findViewById(R.id.stop);
mStopDrawable = mStopButton.getDrawable();
mReloadDrawable = resources.getDrawable(R.drawable.ic_reload);
mAllButton = (ImageView) findViewById(R.id.all_btn);
mCircularProgress = (Drawable) resources.getDrawable(
com.android.internal.R.drawable.search_spinner);
DisplayMetrics metrics = resources.getDisplayMetrics();
int iconDimension = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 20f, metrics);
mCircularProgress.setBounds(0, 0, iconDimension, iconDimension);
mHorizontalProgress = (ProgressBar) findViewById(
R.id.progress_horizontal);
+ mHorizontalProgress.setProgressDrawable(
+ resources.getDrawable(R.drawable.progress));
// FIXME: Change enabled states based on whether you can go
// back/forward. Probably should be done inside onPageStarted.
mBackButton = findViewById(R.id.back);
mForwardButton = findViewById(R.id.forward);
mStar = findViewById(R.id.star);
mMenu = findViewById(R.id.menu);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
if (mBackButton == v) {
mBrowserActivity.getTopWindow().goBack();
} else if (mForwardButton == v) {
mBrowserActivity.getTopWindow().goForward();
} else if (mStar == v) {
// FIXME: Show a menu with option to bookmark or
// save to home page
mBrowserActivity.bookmarkCurrentPage();
} else if (mMenu == v) {
mBrowserActivity.openOptionsMenu();
} else if (mStopButton == v) {
if (mInLoad) {
mBrowserActivity.stopLoading();
} else {
mBrowserActivity.getTopWindow().reload();
}
} else if (mTitle == v) {
mBrowserActivity.editUrl();
} else if (mAllButton == v) {
// FIXME: Show the new bookmarks/windows view.
mBrowserActivity.bookmarksOrHistoryPicker(false);
}
}
};
mBackButton.setOnClickListener(listener);
mForwardButton.setOnClickListener(listener);
mStar.setOnClickListener(listener);
mStopButton.setOnClickListener(listener);
mTitle.setOnClickListener(listener);
mAllButton.setOnClickListener(listener);
mMenu.setOnClickListener(listener);
}
@Override
public void createContextMenu(ContextMenu menu) {
MenuInflater inflater = mBrowserActivity.getMenuInflater();
inflater.inflate(R.menu.title_context, menu);
mBrowserActivity.onCreateContextMenu(menu, this, null);
}
/**
* Update the progress, from 0 to 100.
*/
/* package */ void setProgress(int newProgress) {
if (newProgress >= mHorizontalProgress.getMax()) {
mTitle.setCompoundDrawables(null, null, null, null);
((Animatable) mCircularProgress).stop();
mHorizontalProgress.setVisibility(View.GONE);
mInLoad = false;
mStopButton.setImageDrawable(mReloadDrawable);
} else {
mHorizontalProgress.setProgress(newProgress);
if (!mInLoad && getWindowToken() != null) {
// checking the window token lets us be sure that we
// are attached to a window before starting the animation,
// preventing a potential race condition
// (fix for bug http://b/2115736)
mTitle.setCompoundDrawables(null, null, mCircularProgress,
null);
((Animatable) mCircularProgress).start();
mHorizontalProgress.setVisibility(View.VISIBLE);
mInLoad = true;
mStopButton.setImageDrawable(mStopDrawable);
}
}
}
/**
* Update the text displayed in the title bar.
* @param title String to display. If null, the loading string will be
* shown.
*/
/* package */ void setDisplayTitle(String title) {
if (title == null) {
mTitle.setText(R.string.title_bar_loading);
} else {
mTitle.setText(title);
}
}
}
| true | true | public TitleBarXLarge(BrowserActivity context) {
super(context);
Resources resources = context.getResources();
LayoutInflater factory = LayoutInflater.from(context);
factory.inflate(R.layout.title_bar_xlarge, this);
mBrowserActivity = context;
mTitle = (TextView) findViewById(R.id.title);
mTitle.setCompoundDrawablePadding(5);
mTitle.setLongClickable(true);
mLockIcon = (ImageView) findViewById(R.id.lock);
mFavicon = (ImageView) findViewById(R.id.favicon);
mStopButton = (ImageView) findViewById(R.id.stop);
mStopDrawable = mStopButton.getDrawable();
mReloadDrawable = resources.getDrawable(R.drawable.ic_reload);
mAllButton = (ImageView) findViewById(R.id.all_btn);
mCircularProgress = (Drawable) resources.getDrawable(
com.android.internal.R.drawable.search_spinner);
DisplayMetrics metrics = resources.getDisplayMetrics();
int iconDimension = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 20f, metrics);
mCircularProgress.setBounds(0, 0, iconDimension, iconDimension);
mHorizontalProgress = (ProgressBar) findViewById(
R.id.progress_horizontal);
// FIXME: Change enabled states based on whether you can go
// back/forward. Probably should be done inside onPageStarted.
mBackButton = findViewById(R.id.back);
mForwardButton = findViewById(R.id.forward);
mStar = findViewById(R.id.star);
mMenu = findViewById(R.id.menu);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
if (mBackButton == v) {
mBrowserActivity.getTopWindow().goBack();
} else if (mForwardButton == v) {
mBrowserActivity.getTopWindow().goForward();
} else if (mStar == v) {
// FIXME: Show a menu with option to bookmark or
// save to home page
mBrowserActivity.bookmarkCurrentPage();
} else if (mMenu == v) {
mBrowserActivity.openOptionsMenu();
} else if (mStopButton == v) {
if (mInLoad) {
mBrowserActivity.stopLoading();
} else {
mBrowserActivity.getTopWindow().reload();
}
} else if (mTitle == v) {
mBrowserActivity.editUrl();
} else if (mAllButton == v) {
// FIXME: Show the new bookmarks/windows view.
mBrowserActivity.bookmarksOrHistoryPicker(false);
}
}
};
mBackButton.setOnClickListener(listener);
mForwardButton.setOnClickListener(listener);
mStar.setOnClickListener(listener);
mStopButton.setOnClickListener(listener);
mTitle.setOnClickListener(listener);
mAllButton.setOnClickListener(listener);
mMenu.setOnClickListener(listener);
}
| public TitleBarXLarge(BrowserActivity context) {
super(context);
Resources resources = context.getResources();
LayoutInflater factory = LayoutInflater.from(context);
factory.inflate(R.layout.title_bar_xlarge, this);
mBrowserActivity = context;
mTitle = (TextView) findViewById(R.id.title);
mTitle.setCompoundDrawablePadding(5);
mTitle.setLongClickable(true);
mLockIcon = (ImageView) findViewById(R.id.lock);
mFavicon = (ImageView) findViewById(R.id.favicon);
mStopButton = (ImageView) findViewById(R.id.stop);
mStopDrawable = mStopButton.getDrawable();
mReloadDrawable = resources.getDrawable(R.drawable.ic_reload);
mAllButton = (ImageView) findViewById(R.id.all_btn);
mCircularProgress = (Drawable) resources.getDrawable(
com.android.internal.R.drawable.search_spinner);
DisplayMetrics metrics = resources.getDisplayMetrics();
int iconDimension = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 20f, metrics);
mCircularProgress.setBounds(0, 0, iconDimension, iconDimension);
mHorizontalProgress = (ProgressBar) findViewById(
R.id.progress_horizontal);
mHorizontalProgress.setProgressDrawable(
resources.getDrawable(R.drawable.progress));
// FIXME: Change enabled states based on whether you can go
// back/forward. Probably should be done inside onPageStarted.
mBackButton = findViewById(R.id.back);
mForwardButton = findViewById(R.id.forward);
mStar = findViewById(R.id.star);
mMenu = findViewById(R.id.menu);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
if (mBackButton == v) {
mBrowserActivity.getTopWindow().goBack();
} else if (mForwardButton == v) {
mBrowserActivity.getTopWindow().goForward();
} else if (mStar == v) {
// FIXME: Show a menu with option to bookmark or
// save to home page
mBrowserActivity.bookmarkCurrentPage();
} else if (mMenu == v) {
mBrowserActivity.openOptionsMenu();
} else if (mStopButton == v) {
if (mInLoad) {
mBrowserActivity.stopLoading();
} else {
mBrowserActivity.getTopWindow().reload();
}
} else if (mTitle == v) {
mBrowserActivity.editUrl();
} else if (mAllButton == v) {
// FIXME: Show the new bookmarks/windows view.
mBrowserActivity.bookmarksOrHistoryPicker(false);
}
}
};
mBackButton.setOnClickListener(listener);
mForwardButton.setOnClickListener(listener);
mStar.setOnClickListener(listener);
mStopButton.setOnClickListener(listener);
mTitle.setOnClickListener(listener);
mAllButton.setOnClickListener(listener);
mMenu.setOnClickListener(listener);
}
|
diff --git a/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ANTLRScannerGenerator.java b/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ANTLRScannerGenerator.java
index 95591117e..6190b91d6 100644
--- a/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ANTLRScannerGenerator.java
+++ b/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ANTLRScannerGenerator.java
@@ -1,103 +1,107 @@
package org.emftext.sdk.codegen.generators;
import static org.emftext.sdk.codegen.generators.IClassNameConstants.ABSTRACT_EMF_TEXT_SCANNER;
import static org.emftext.sdk.codegen.generators.IClassNameConstants.COMMON_TOKEN;
import static org.emftext.sdk.codegen.generators.IClassNameConstants.I_TEXT_TOKEN;
import static org.emftext.sdk.codegen.generators.IClassNameConstants.LEXER;
import static org.emftext.sdk.codegen.generators.IClassNameConstants.STRING;
import static org.emftext.sdk.codegen.generators.IClassNameConstants.I_TEXT_RESOURCE_PLUGIN_META_INFORMATION;
import static org.emftext.sdk.codegen.generators.IClassNameConstants.TOKEN;
import static org.emftext.sdk.codegen.generators.IClassNameConstants.ANTLR_STRING_STREAM;
import java.io.PrintWriter;
import org.emftext.sdk.codegen.EArtifact;
import org.emftext.sdk.codegen.GenerationContext;
import org.emftext.sdk.codegen.composites.JavaComposite;
import org.emftext.sdk.codegen.composites.StringComposite;
public class ANTLRScannerGenerator extends BaseGenerator {
public ANTLRScannerGenerator(GenerationContext context) {
super(context.getPackageName(), context.getClassName(EArtifact.ANTLR_SCANNER));
}
@Override
public boolean generate(PrintWriter out) {
StringComposite sc = new JavaComposite();
sc.add("package " + getResourcePackageName() + ";");
sc.addLineBreak();
sc.add("public class " + getResourceClassName() + " extends " + ABSTRACT_EMF_TEXT_SCANNER + " {");
sc.addLineBreak();
sc.add("private " + STRING + "[] tokenNames;");
sc.add("private " + LEXER + " antlrLexer;");
sc.addLineBreak();
sc.add("public " + getResourceClassName() + "(" + I_TEXT_RESOURCE_PLUGIN_META_INFORMATION + " metaInformation, " + LEXER + " antlrLexer) {");
sc.add("this.tokenNames = metaInformation.getTokenNames();");
sc.add("this.antlrLexer = antlrLexer;");
sc.add("}");
sc.addLineBreak();
sc.add("public " + I_TEXT_TOKEN + " getNextToken() {");
sc.add("final " + TOKEN + " current = antlrLexer.nextToken();");
+ sc.add("if (current.getTokenIndex() < 0) {");
+ sc.add("return null;");
+ sc.add("}");
sc.add(I_TEXT_TOKEN + " result = new " + I_TEXT_TOKEN + "() {");
sc.addLineBreak();
sc.add("public " + STRING + " getName() {");
sc.add("return getTokenName(tokenNames, current.getType());");
sc.add("}");
sc.addLineBreak();
sc.add("public int getOffset() {");
sc.add("return ((" + COMMON_TOKEN + ") current).getStartIndex();");
sc.add("}");
sc.addLineBreak();
sc.add("public int getLength() {");
sc.add("return ((" + COMMON_TOKEN + ") current).getStopIndex() - ((" + COMMON_TOKEN + ") current).getStartIndex() + 1;");
sc.add("}");
sc.addLineBreak();
sc.add("public boolean canBeUsedForSyntaxHighlighting() {");
sc.add("int tokenType = current.getType();");
sc.add("if (tokenType == " + TOKEN + ".EOF) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".UP) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".DOWN) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".EOR_TOKEN_TYPE) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".INVALID_TOKEN_TYPE) {");
sc.add("return false;");
sc.add("}");
sc.add("return true;");
sc.add("}");
sc.add("public " + STRING + " getText() {");
sc.add("return current.getText();");
sc.add("}");
sc.add("};");
sc.add("return result;");
sc.add("}");
sc.addLineBreak();
sc.add("public void setText(" + STRING + " text) {");
sc.add("antlrLexer.setCharStream(new " + ANTLR_STRING_STREAM + "(text));");
sc.add("}");
+ sc.addLineBreak();
sc.add("public " + STRING + " getTokenName(" + STRING + "[] tokenNames, int index) {");
sc.add("if (tokenNames == null) {");
sc.add("return null;");
sc.add("}");
sc.add(STRING + " tokenName = tokenNames[index];");
sc.add("if (tokenName != null && tokenName.startsWith(\"'\")) {");
sc.add("tokenName = tokenName.substring(1, tokenName.length() - 1).trim();");
sc.add("}");
sc.add("return tokenName;");
sc.add("}");
sc.add("}");
out.write(sc.toString());
return true;
}
}
| false | true | public boolean generate(PrintWriter out) {
StringComposite sc = new JavaComposite();
sc.add("package " + getResourcePackageName() + ";");
sc.addLineBreak();
sc.add("public class " + getResourceClassName() + " extends " + ABSTRACT_EMF_TEXT_SCANNER + " {");
sc.addLineBreak();
sc.add("private " + STRING + "[] tokenNames;");
sc.add("private " + LEXER + " antlrLexer;");
sc.addLineBreak();
sc.add("public " + getResourceClassName() + "(" + I_TEXT_RESOURCE_PLUGIN_META_INFORMATION + " metaInformation, " + LEXER + " antlrLexer) {");
sc.add("this.tokenNames = metaInformation.getTokenNames();");
sc.add("this.antlrLexer = antlrLexer;");
sc.add("}");
sc.addLineBreak();
sc.add("public " + I_TEXT_TOKEN + " getNextToken() {");
sc.add("final " + TOKEN + " current = antlrLexer.nextToken();");
sc.add(I_TEXT_TOKEN + " result = new " + I_TEXT_TOKEN + "() {");
sc.addLineBreak();
sc.add("public " + STRING + " getName() {");
sc.add("return getTokenName(tokenNames, current.getType());");
sc.add("}");
sc.addLineBreak();
sc.add("public int getOffset() {");
sc.add("return ((" + COMMON_TOKEN + ") current).getStartIndex();");
sc.add("}");
sc.addLineBreak();
sc.add("public int getLength() {");
sc.add("return ((" + COMMON_TOKEN + ") current).getStopIndex() - ((" + COMMON_TOKEN + ") current).getStartIndex() + 1;");
sc.add("}");
sc.addLineBreak();
sc.add("public boolean canBeUsedForSyntaxHighlighting() {");
sc.add("int tokenType = current.getType();");
sc.add("if (tokenType == " + TOKEN + ".EOF) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".UP) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".DOWN) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".EOR_TOKEN_TYPE) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".INVALID_TOKEN_TYPE) {");
sc.add("return false;");
sc.add("}");
sc.add("return true;");
sc.add("}");
sc.add("public " + STRING + " getText() {");
sc.add("return current.getText();");
sc.add("}");
sc.add("};");
sc.add("return result;");
sc.add("}");
sc.addLineBreak();
sc.add("public void setText(" + STRING + " text) {");
sc.add("antlrLexer.setCharStream(new " + ANTLR_STRING_STREAM + "(text));");
sc.add("}");
sc.add("public " + STRING + " getTokenName(" + STRING + "[] tokenNames, int index) {");
sc.add("if (tokenNames == null) {");
sc.add("return null;");
sc.add("}");
sc.add(STRING + " tokenName = tokenNames[index];");
sc.add("if (tokenName != null && tokenName.startsWith(\"'\")) {");
sc.add("tokenName = tokenName.substring(1, tokenName.length() - 1).trim();");
sc.add("}");
sc.add("return tokenName;");
sc.add("}");
sc.add("}");
out.write(sc.toString());
return true;
}
| public boolean generate(PrintWriter out) {
StringComposite sc = new JavaComposite();
sc.add("package " + getResourcePackageName() + ";");
sc.addLineBreak();
sc.add("public class " + getResourceClassName() + " extends " + ABSTRACT_EMF_TEXT_SCANNER + " {");
sc.addLineBreak();
sc.add("private " + STRING + "[] tokenNames;");
sc.add("private " + LEXER + " antlrLexer;");
sc.addLineBreak();
sc.add("public " + getResourceClassName() + "(" + I_TEXT_RESOURCE_PLUGIN_META_INFORMATION + " metaInformation, " + LEXER + " antlrLexer) {");
sc.add("this.tokenNames = metaInformation.getTokenNames();");
sc.add("this.antlrLexer = antlrLexer;");
sc.add("}");
sc.addLineBreak();
sc.add("public " + I_TEXT_TOKEN + " getNextToken() {");
sc.add("final " + TOKEN + " current = antlrLexer.nextToken();");
sc.add("if (current.getTokenIndex() < 0) {");
sc.add("return null;");
sc.add("}");
sc.add(I_TEXT_TOKEN + " result = new " + I_TEXT_TOKEN + "() {");
sc.addLineBreak();
sc.add("public " + STRING + " getName() {");
sc.add("return getTokenName(tokenNames, current.getType());");
sc.add("}");
sc.addLineBreak();
sc.add("public int getOffset() {");
sc.add("return ((" + COMMON_TOKEN + ") current).getStartIndex();");
sc.add("}");
sc.addLineBreak();
sc.add("public int getLength() {");
sc.add("return ((" + COMMON_TOKEN + ") current).getStopIndex() - ((" + COMMON_TOKEN + ") current).getStartIndex() + 1;");
sc.add("}");
sc.addLineBreak();
sc.add("public boolean canBeUsedForSyntaxHighlighting() {");
sc.add("int tokenType = current.getType();");
sc.add("if (tokenType == " + TOKEN + ".EOF) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".UP) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".DOWN) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".EOR_TOKEN_TYPE) {");
sc.add("return false;");
sc.add("}");
sc.add("if (tokenType == " + TOKEN + ".INVALID_TOKEN_TYPE) {");
sc.add("return false;");
sc.add("}");
sc.add("return true;");
sc.add("}");
sc.add("public " + STRING + " getText() {");
sc.add("return current.getText();");
sc.add("}");
sc.add("};");
sc.add("return result;");
sc.add("}");
sc.addLineBreak();
sc.add("public void setText(" + STRING + " text) {");
sc.add("antlrLexer.setCharStream(new " + ANTLR_STRING_STREAM + "(text));");
sc.add("}");
sc.addLineBreak();
sc.add("public " + STRING + " getTokenName(" + STRING + "[] tokenNames, int index) {");
sc.add("if (tokenNames == null) {");
sc.add("return null;");
sc.add("}");
sc.add(STRING + " tokenName = tokenNames[index];");
sc.add("if (tokenName != null && tokenName.startsWith(\"'\")) {");
sc.add("tokenName = tokenName.substring(1, tokenName.length() - 1).trim();");
sc.add("}");
sc.add("return tokenName;");
sc.add("}");
sc.add("}");
out.write(sc.toString());
return true;
}
|
diff --git a/src/main/java/org/dynjs/runtime/GlobalObject.java b/src/main/java/org/dynjs/runtime/GlobalObject.java
index 7156a995..b693556d 100644
--- a/src/main/java/org/dynjs/runtime/GlobalObject.java
+++ b/src/main/java/org/dynjs/runtime/GlobalObject.java
@@ -1,175 +1,176 @@
package org.dynjs.runtime;
import org.dynjs.Config;
import org.dynjs.compiler.JSCompiler;
import org.dynjs.runtime.PropertyDescriptor.Names;
import org.dynjs.runtime.builtins.*;
import org.dynjs.runtime.builtins.Math;
import org.dynjs.runtime.builtins.types.*;
import org.dynjs.runtime.java.JSAdapter;
import org.dynjs.runtime.java.JavaPackage;
import java.util.ArrayList;
import java.util.List;
public class GlobalObject extends DynObject {
private DynJS runtime;
private BlockManager blockManager;
private List<AbstractBuiltinType> builtinTypes = new ArrayList<>();
public GlobalObject(DynJS runtime) {
super(null);
this.runtime = runtime;
this.blockManager = new BlockManager();
defineReadOnlyGlobalProperty("__throwTypeError", new ThrowTypeError(this));
// ----------------------------------------
// Built-in types
// ----------------------------------------
registerBuiltinType("Object", new BuiltinObject(this));
registerBuiltinType("Function", new BuiltinFunction(this));
registerBuiltinType("Boolean", new BuiltinBoolean(this));
registerBuiltinType("Number", new BuiltinNumber(this));
registerBuiltinType("Array", new BuiltinArray(this));
registerBuiltinType("String", new BuiltinString(this));
registerBuiltinType("RegExp", new BuiltinRegExp(this));
registerBuiltinType("Date", new BuiltinDate(this));
registerBuiltinType("Error", new BuiltinError(this));
registerBuiltinType("ReferenceError", new BuiltinReferenceError(this));
registerBuiltinType("RangeError", new BuiltinRangeError(this));
registerBuiltinType("SyntaxError", new BuiltinSyntaxError(this));
registerBuiltinType("TypeError", new BuiltinTypeError(this));
registerBuiltinType("URIError", new BuiltinURIError(this));
registerBuiltinType("EvalError", new BuiltinEvalError(this));
if (runtime.getConfig().isRhinoCompatible()) {
registerBuiltinType("JSAdapter", new JSAdapter(this));
}
initializeBuiltinTypes();
// ----------------------------------------
// Built-in global functions
// ----------------------------------------
defineReadOnlyGlobalProperty("undefined", Types.UNDEFINED);
defineGlobalProperty("parseFloat", new ParseFloat(this));
defineGlobalProperty("parseInt", new ParseInt(this));
defineGlobalProperty("eval", new Eval(this));
defineGlobalProperty("isNaN", new IsNaN(this));
defineGlobalProperty("isFinite", new IsFinite(this));
defineGlobalProperty("encodeURI", new EncodeUri(this));
defineGlobalProperty("decodeURI", new DecodeUri(this));
defineGlobalProperty("encodeURIComponent", new EncodeUriComponent(this));
defineGlobalProperty("decodeURIComponent", new DecodeUriComponent(this));
if (runtime.getConfig().isNodePackageManagerEnabled()) {
defineGlobalProperty("require", new Require(this));
}
defineGlobalProperty("include", new Include(this));
defineGlobalProperty("load", new Include(this)); // hackety hack
defineGlobalProperty("escape", new Escape(this));
defineGlobalProperty("unescape", new Unescape(this));
defineGlobalProperty("print", new Print(this));
defineGlobalProperty("dynjs", new DynJSBuiltin(this.runtime));
// ----------------------------------------
// Built-in global objects
// ----------------------------------------
put(null, "JSON", new JSON(this), false);
defineGlobalProperty("Math", new Math(this));
defineGlobalProperty("Intl", new Intl(this));
// ----------------------------------------
// Java integration
// ----------------------------------------
defineGlobalProperty("Packages", new JavaPackage(this, null));
defineGlobalProperty("java", new JavaPackage(this, "java"));
+ defineGlobalProperty("javax", new JavaPackage(this, "javax"));
defineGlobalProperty("org", new JavaPackage(this, "org"));
defineGlobalProperty("com", new JavaPackage(this, "com"));
defineGlobalProperty("io", new JavaPackage(this, "io"));
setPrototype(getPrototypeFor("Object"));
}
private void registerBuiltinType(String name, final AbstractBuiltinType type) {
PropertyDescriptor desc = new PropertyDescriptor();
desc.set(Names.VALUE, type);
desc.set(Names.ENUMERABLE, false);
desc.set(Names.WRITABLE, true);
desc.set(Names.CONFIGURABLE, true);
defineOwnProperty(null, name, desc, false);
put(null, "__Builtin_" + name, type, false);
this.builtinTypes.add(type);
}
private void initializeBuiltinTypes() {
for (AbstractBuiltinType each : this.builtinTypes) {
each.setPrototype(getPrototypeFor("Function"));
each.initialize(this);
}
}
public static GlobalObject newGlobalObject(DynJS runtime) {
return runtime.getConfig().getGlobalObjectFactory().newGlobalObject(runtime);
}
public DynJS getRuntime() {
return this.runtime;
}
public Config getConfig() {
return getRuntime().getConfig();
}
public JSCompiler getCompiler() {
return this.runtime.getCompiler();
}
public BlockManager getBlockManager() {
return this.blockManager;
}
public org.dynjs.runtime.BlockManager.Entry retrieveBlockEntry(int statementNumber) {
return this.blockManager.retrieve(statementNumber);
}
public void defineGlobalProperty(final String name, final Object value) {
PropertyDescriptor desc = new PropertyDescriptor();
desc.set(Names.VALUE, value);
desc.set(Names.WRITABLE, true);
desc.set(Names.ENUMERABLE, false);
desc.set(Names.CONFIGURABLE, true);
defineOwnProperty(null, name, desc, false);
}
public void defineReadOnlyGlobalProperty(final String name, final Object value) {
PropertyDescriptor desc = new PropertyDescriptor();
desc.set(Names.VALUE, value);
desc.set(Names.WRITABLE, false);
desc.set(Names.CONFIGURABLE, false);
desc.set(Names.ENUMERABLE, false);
defineOwnProperty(null, name, desc, false);
}
public JSObject getPrototypeFor(String type) {
Object typeObj = get(null, type);
if (typeObj == Types.UNDEFINED) {
return null;
}
Object prototype = ((JSObject) typeObj).get(null, "prototype");
if (prototype == Types.UNDEFINED) {
return null;
}
return (JSObject) prototype;
}
}
| true | true | public GlobalObject(DynJS runtime) {
super(null);
this.runtime = runtime;
this.blockManager = new BlockManager();
defineReadOnlyGlobalProperty("__throwTypeError", new ThrowTypeError(this));
// ----------------------------------------
// Built-in types
// ----------------------------------------
registerBuiltinType("Object", new BuiltinObject(this));
registerBuiltinType("Function", new BuiltinFunction(this));
registerBuiltinType("Boolean", new BuiltinBoolean(this));
registerBuiltinType("Number", new BuiltinNumber(this));
registerBuiltinType("Array", new BuiltinArray(this));
registerBuiltinType("String", new BuiltinString(this));
registerBuiltinType("RegExp", new BuiltinRegExp(this));
registerBuiltinType("Date", new BuiltinDate(this));
registerBuiltinType("Error", new BuiltinError(this));
registerBuiltinType("ReferenceError", new BuiltinReferenceError(this));
registerBuiltinType("RangeError", new BuiltinRangeError(this));
registerBuiltinType("SyntaxError", new BuiltinSyntaxError(this));
registerBuiltinType("TypeError", new BuiltinTypeError(this));
registerBuiltinType("URIError", new BuiltinURIError(this));
registerBuiltinType("EvalError", new BuiltinEvalError(this));
if (runtime.getConfig().isRhinoCompatible()) {
registerBuiltinType("JSAdapter", new JSAdapter(this));
}
initializeBuiltinTypes();
// ----------------------------------------
// Built-in global functions
// ----------------------------------------
defineReadOnlyGlobalProperty("undefined", Types.UNDEFINED);
defineGlobalProperty("parseFloat", new ParseFloat(this));
defineGlobalProperty("parseInt", new ParseInt(this));
defineGlobalProperty("eval", new Eval(this));
defineGlobalProperty("isNaN", new IsNaN(this));
defineGlobalProperty("isFinite", new IsFinite(this));
defineGlobalProperty("encodeURI", new EncodeUri(this));
defineGlobalProperty("decodeURI", new DecodeUri(this));
defineGlobalProperty("encodeURIComponent", new EncodeUriComponent(this));
defineGlobalProperty("decodeURIComponent", new DecodeUriComponent(this));
if (runtime.getConfig().isNodePackageManagerEnabled()) {
defineGlobalProperty("require", new Require(this));
}
defineGlobalProperty("include", new Include(this));
defineGlobalProperty("load", new Include(this)); // hackety hack
defineGlobalProperty("escape", new Escape(this));
defineGlobalProperty("unescape", new Unescape(this));
defineGlobalProperty("print", new Print(this));
defineGlobalProperty("dynjs", new DynJSBuiltin(this.runtime));
// ----------------------------------------
// Built-in global objects
// ----------------------------------------
put(null, "JSON", new JSON(this), false);
defineGlobalProperty("Math", new Math(this));
defineGlobalProperty("Intl", new Intl(this));
// ----------------------------------------
// Java integration
// ----------------------------------------
defineGlobalProperty("Packages", new JavaPackage(this, null));
defineGlobalProperty("java", new JavaPackage(this, "java"));
defineGlobalProperty("org", new JavaPackage(this, "org"));
defineGlobalProperty("com", new JavaPackage(this, "com"));
defineGlobalProperty("io", new JavaPackage(this, "io"));
setPrototype(getPrototypeFor("Object"));
}
| public GlobalObject(DynJS runtime) {
super(null);
this.runtime = runtime;
this.blockManager = new BlockManager();
defineReadOnlyGlobalProperty("__throwTypeError", new ThrowTypeError(this));
// ----------------------------------------
// Built-in types
// ----------------------------------------
registerBuiltinType("Object", new BuiltinObject(this));
registerBuiltinType("Function", new BuiltinFunction(this));
registerBuiltinType("Boolean", new BuiltinBoolean(this));
registerBuiltinType("Number", new BuiltinNumber(this));
registerBuiltinType("Array", new BuiltinArray(this));
registerBuiltinType("String", new BuiltinString(this));
registerBuiltinType("RegExp", new BuiltinRegExp(this));
registerBuiltinType("Date", new BuiltinDate(this));
registerBuiltinType("Error", new BuiltinError(this));
registerBuiltinType("ReferenceError", new BuiltinReferenceError(this));
registerBuiltinType("RangeError", new BuiltinRangeError(this));
registerBuiltinType("SyntaxError", new BuiltinSyntaxError(this));
registerBuiltinType("TypeError", new BuiltinTypeError(this));
registerBuiltinType("URIError", new BuiltinURIError(this));
registerBuiltinType("EvalError", new BuiltinEvalError(this));
if (runtime.getConfig().isRhinoCompatible()) {
registerBuiltinType("JSAdapter", new JSAdapter(this));
}
initializeBuiltinTypes();
// ----------------------------------------
// Built-in global functions
// ----------------------------------------
defineReadOnlyGlobalProperty("undefined", Types.UNDEFINED);
defineGlobalProperty("parseFloat", new ParseFloat(this));
defineGlobalProperty("parseInt", new ParseInt(this));
defineGlobalProperty("eval", new Eval(this));
defineGlobalProperty("isNaN", new IsNaN(this));
defineGlobalProperty("isFinite", new IsFinite(this));
defineGlobalProperty("encodeURI", new EncodeUri(this));
defineGlobalProperty("decodeURI", new DecodeUri(this));
defineGlobalProperty("encodeURIComponent", new EncodeUriComponent(this));
defineGlobalProperty("decodeURIComponent", new DecodeUriComponent(this));
if (runtime.getConfig().isNodePackageManagerEnabled()) {
defineGlobalProperty("require", new Require(this));
}
defineGlobalProperty("include", new Include(this));
defineGlobalProperty("load", new Include(this)); // hackety hack
defineGlobalProperty("escape", new Escape(this));
defineGlobalProperty("unescape", new Unescape(this));
defineGlobalProperty("print", new Print(this));
defineGlobalProperty("dynjs", new DynJSBuiltin(this.runtime));
// ----------------------------------------
// Built-in global objects
// ----------------------------------------
put(null, "JSON", new JSON(this), false);
defineGlobalProperty("Math", new Math(this));
defineGlobalProperty("Intl", new Intl(this));
// ----------------------------------------
// Java integration
// ----------------------------------------
defineGlobalProperty("Packages", new JavaPackage(this, null));
defineGlobalProperty("java", new JavaPackage(this, "java"));
defineGlobalProperty("javax", new JavaPackage(this, "javax"));
defineGlobalProperty("org", new JavaPackage(this, "org"));
defineGlobalProperty("com", new JavaPackage(this, "com"));
defineGlobalProperty("io", new JavaPackage(this, "io"));
setPrototype(getPrototypeFor("Object"));
}
|
diff --git a/src/main/java/net/t7seven7t/swornguard/commands/CmdFHistory.java b/src/main/java/net/t7seven7t/swornguard/commands/CmdFHistory.java
index ec77da6..3259c51 100644
--- a/src/main/java/net/t7seven7t/swornguard/commands/CmdFHistory.java
+++ b/src/main/java/net/t7seven7t/swornguard/commands/CmdFHistory.java
@@ -1,68 +1,68 @@
package net.t7seven7t.swornguard.commands;
import java.util.ArrayList;
import java.util.List;
import net.t7seven7t.swornguard.SwornGuard;
import net.t7seven7t.swornguard.permissions.PermissionType;
import net.t7seven7t.swornguard.types.PlayerData;
import net.t7seven7t.util.FormatUtil;
import org.bukkit.OfflinePlayer;
/**
* @author dmulloy2
*/
public class CmdFHistory extends PaginatedCommand {
private OfflinePlayer target = null;
private List<String> factionHistory = null;
public CmdFHistory(SwornGuard plugin) {
super(plugin);
this.name = "fhistory";
this.aliases.add("fh");
this.description = "show a player's faction history";
this.permission = PermissionType.CMD_SHOW.permission;
this.optionalArgs.add("player");
this.optionalArgs.add("page");
this.pageArgIndex = 1;
this.usesPrefix = true;
}
@Override
public void perform() {
- OfflinePlayer target = getTarget(0);
+ target = getTarget(0);
if (target == null)
return;
PlayerData data = getPlayerData(target);
if (data.getFactionLog() != null) {
factionHistory = new ArrayList<String>();
for (int i = data.getFactionLog().size() - 1; i >= 0; i--) {
factionHistory.add(data.getFactionLog().get(i));
}
super.perform();
} else {
err(plugin.getMessage("fhistory_no_data"), target.getName());
}
}
@Override
public int getListSize() {
return factionHistory.size();
}
@Override
public String getHeader(int index) {
return FormatUtil.format(plugin.getMessage("fhistory_header"), target.getName(), index, getPageCount());
}
@Override
public String getLine(int index) {
return FormatUtil.format(factionHistory.get(index));
}
}
| true | true | public void perform() {
OfflinePlayer target = getTarget(0);
if (target == null)
return;
PlayerData data = getPlayerData(target);
if (data.getFactionLog() != null) {
factionHistory = new ArrayList<String>();
for (int i = data.getFactionLog().size() - 1; i >= 0; i--) {
factionHistory.add(data.getFactionLog().get(i));
}
super.perform();
} else {
err(plugin.getMessage("fhistory_no_data"), target.getName());
}
}
| public void perform() {
target = getTarget(0);
if (target == null)
return;
PlayerData data = getPlayerData(target);
if (data.getFactionLog() != null) {
factionHistory = new ArrayList<String>();
for (int i = data.getFactionLog().size() - 1; i >= 0; i--) {
factionHistory.add(data.getFactionLog().get(i));
}
super.perform();
} else {
err(plugin.getMessage("fhistory_no_data"), target.getName());
}
}
|
diff --git a/xfire-core/src/main/org/codehaus/xfire/util/Resolver.java b/xfire-core/src/main/org/codehaus/xfire/util/Resolver.java
index 40e49385..f6c91081 100644
--- a/xfire-core/src/main/org/codehaus/xfire/util/Resolver.java
+++ b/xfire-core/src/main/org/codehaus/xfire/util/Resolver.java
@@ -1,140 +1,140 @@
package org.codehaus.xfire.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.codehaus.xfire.XFireRuntimeException;
/**
* Resolves a File, classpath resource, or URL according to the follow rules:
* <ul>
* <li>Check to see if a file exists, relative to the base URI.</li>
* <li>If the file doesn't exist, check the classpath</li>
* <li>If the classpath doesn't exist, try to create URL from the URI.</li>
* </ul>
* @author Dan Diephouse
*/
public class Resolver
{
private File file;
private URI uri;
private InputStream is;
public Resolver(String path) throws IOException
{
this("", path);
}
public Resolver(String baseUriStr, String uriStr)
throws IOException
{
try
{
URI relative;
File uriFile = new File(uriStr);
uriFile = new File(uriFile.getAbsolutePath());
if (uriFile.exists())
{
relative = uriFile.toURI();
}
else
relative = new URI(uriStr);
if (relative.isAbsolute())
{
uri = relative;
is = relative.toURL().openStream();
}
else if (baseUriStr != null)
{
URI base;
File baseFile = new File(baseUriStr);
if (baseFile.exists())
base = baseFile.toURI();
else
base = new URI(baseUriStr);
base = base.resolve(relative);
if (base.isAbsolute())
{
is = base.toURL().openStream();
uri = base;
}
}
} catch (URISyntaxException e) {
}
if (uri != null && "file".equals(uri.getScheme()))
{
file = new File(uri);
}
if (is == null && file != null && file.exists())
{
uri = file.toURI();
try
{
is = new FileInputStream(file);
}
catch (FileNotFoundException e)
{
throw new XFireRuntimeException("File was deleted! " + uriStr, e);
}
}
else if (is == null)
{
URL url = ClassLoaderUtils.getResource(uriStr, getClass());
if (url == null)
{
try
{
url = new URL(uriStr);
- uri = url.toURI();
+ uri = new URI(url.toString());
is = url.openStream();
}
catch (MalformedURLException e)
{
}
catch (URISyntaxException e)
{
}
}
else
{
is = url.openStream();
}
}
if (is == null)
throw new IOException("Could not find resource '" + uriStr +
"' relative to '" + baseUriStr + "'");
}
public URI getURI()
{
return uri;
}
public InputStream getInputStream()
{
return is;
}
public boolean isFile()
{
return file.exists();
}
public File getFile()
{
return file;
}
}
| true | true | public Resolver(String baseUriStr, String uriStr)
throws IOException
{
try
{
URI relative;
File uriFile = new File(uriStr);
uriFile = new File(uriFile.getAbsolutePath());
if (uriFile.exists())
{
relative = uriFile.toURI();
}
else
relative = new URI(uriStr);
if (relative.isAbsolute())
{
uri = relative;
is = relative.toURL().openStream();
}
else if (baseUriStr != null)
{
URI base;
File baseFile = new File(baseUriStr);
if (baseFile.exists())
base = baseFile.toURI();
else
base = new URI(baseUriStr);
base = base.resolve(relative);
if (base.isAbsolute())
{
is = base.toURL().openStream();
uri = base;
}
}
} catch (URISyntaxException e) {
}
if (uri != null && "file".equals(uri.getScheme()))
{
file = new File(uri);
}
if (is == null && file != null && file.exists())
{
uri = file.toURI();
try
{
is = new FileInputStream(file);
}
catch (FileNotFoundException e)
{
throw new XFireRuntimeException("File was deleted! " + uriStr, e);
}
}
else if (is == null)
{
URL url = ClassLoaderUtils.getResource(uriStr, getClass());
if (url == null)
{
try
{
url = new URL(uriStr);
uri = url.toURI();
is = url.openStream();
}
catch (MalformedURLException e)
{
}
catch (URISyntaxException e)
{
}
}
else
{
is = url.openStream();
}
}
if (is == null)
throw new IOException("Could not find resource '" + uriStr +
"' relative to '" + baseUriStr + "'");
}
| public Resolver(String baseUriStr, String uriStr)
throws IOException
{
try
{
URI relative;
File uriFile = new File(uriStr);
uriFile = new File(uriFile.getAbsolutePath());
if (uriFile.exists())
{
relative = uriFile.toURI();
}
else
relative = new URI(uriStr);
if (relative.isAbsolute())
{
uri = relative;
is = relative.toURL().openStream();
}
else if (baseUriStr != null)
{
URI base;
File baseFile = new File(baseUriStr);
if (baseFile.exists())
base = baseFile.toURI();
else
base = new URI(baseUriStr);
base = base.resolve(relative);
if (base.isAbsolute())
{
is = base.toURL().openStream();
uri = base;
}
}
} catch (URISyntaxException e) {
}
if (uri != null && "file".equals(uri.getScheme()))
{
file = new File(uri);
}
if (is == null && file != null && file.exists())
{
uri = file.toURI();
try
{
is = new FileInputStream(file);
}
catch (FileNotFoundException e)
{
throw new XFireRuntimeException("File was deleted! " + uriStr, e);
}
}
else if (is == null)
{
URL url = ClassLoaderUtils.getResource(uriStr, getClass());
if (url == null)
{
try
{
url = new URL(uriStr);
uri = new URI(url.toString());
is = url.openStream();
}
catch (MalformedURLException e)
{
}
catch (URISyntaxException e)
{
}
}
else
{
is = url.openStream();
}
}
if (is == null)
throw new IOException("Could not find resource '" + uriStr +
"' relative to '" + baseUriStr + "'");
}
|
diff --git a/src/GuessNumber.java b/src/GuessNumber.java
index ca2b253..fd785e6 100644
--- a/src/GuessNumber.java
+++ b/src/GuessNumber.java
@@ -1,135 +1,135 @@
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
/**
* The max range in the randomize method.
*/
protected static int maxRange = 10;
/**
* The scanner.
*/
private static Scanner scanner;
public static void main(String[] args) {
String userName = getUserName();
System.out.println("Welcome " + userName
+ ", lets play a game. Guess a number bwtween 1 and 10.");
int randomInt = getRandomNumber(maxRange);
// Control if the user have entered the correct value.
boolean passed = false;
int tries = 0;
while (tries < 3 && !passed) {
int userGuess;
try {
userGuess = getUserGuess();
}
catch (Exception e) {
System.out.println("Your guess must be a number between 1 and 10");
continue;
}
if (userGuess == randomInt) {
System.out.println("Correct " + userName + "! Random number = "
+ randomInt);
passed = true;
break;
}
else if (userGuess > randomInt) {
System.out.println("Wrong! The random number is lower.");
}
else {
System.out.println("Wrong! The random number is higher.");
}
scanner.next();
tries++;
}
// If the user havent found the correct number after three tries,
// print Game Over and what the random number were.
if (!passed) {
System.out.println("Game over!");
- System.out.println("The radnom number was " + randomInt);
+ System.out.println("The random number was " + randomInt);
}
// Close the scanner.
scanner.close();
System.exit(0);
}
/**
* Get a random number (int) between 0 and [max]
*
* @param max
* The highest number in the range.
*
* @return An int with a random number in the specific range.
*/
private static int getRandomNumber(int max) {
Random r = new Random();
int randomInt = r.nextInt(max);
randomInt++;
return randomInt;
}
/**
* Get the user input.
*
* @param text
* The text to print before the user input.
* @return A Scanner object.
*/
private static Scanner getUserInput(String text) {
System.out.print(text);
if (scanner == null) {
scanner = new Scanner(System.in);
}
return scanner;
}
/**
* Get the users guess.
*
* @throws Exception
*/
private static int getUserGuess() throws Exception {
Scanner scanner = getUserInput("Guess a number: ");
// Validate that we have an int.
if (scanner.hasNextInt()) {
int guess = scanner.nextInt();
// Validate the range.
if (guess > maxRange || guess < 1) {
throw new Exception();
}
return guess;
}
else {
throw new Exception();
}
}
/**
* Get the users name.
*/
private static String getUserName() {
// Scanner scanner = getUserInput("What is your name? ");
// return scanner.nextLine();
return System.getProperty("user.name");
}
}
| true | true | public static void main(String[] args) {
String userName = getUserName();
System.out.println("Welcome " + userName
+ ", lets play a game. Guess a number bwtween 1 and 10.");
int randomInt = getRandomNumber(maxRange);
// Control if the user have entered the correct value.
boolean passed = false;
int tries = 0;
while (tries < 3 && !passed) {
int userGuess;
try {
userGuess = getUserGuess();
}
catch (Exception e) {
System.out.println("Your guess must be a number between 1 and 10");
continue;
}
if (userGuess == randomInt) {
System.out.println("Correct " + userName + "! Random number = "
+ randomInt);
passed = true;
break;
}
else if (userGuess > randomInt) {
System.out.println("Wrong! The random number is lower.");
}
else {
System.out.println("Wrong! The random number is higher.");
}
scanner.next();
tries++;
}
// If the user havent found the correct number after three tries,
// print Game Over and what the random number were.
if (!passed) {
System.out.println("Game over!");
System.out.println("The radnom number was " + randomInt);
}
// Close the scanner.
scanner.close();
System.exit(0);
}
| public static void main(String[] args) {
String userName = getUserName();
System.out.println("Welcome " + userName
+ ", lets play a game. Guess a number bwtween 1 and 10.");
int randomInt = getRandomNumber(maxRange);
// Control if the user have entered the correct value.
boolean passed = false;
int tries = 0;
while (tries < 3 && !passed) {
int userGuess;
try {
userGuess = getUserGuess();
}
catch (Exception e) {
System.out.println("Your guess must be a number between 1 and 10");
continue;
}
if (userGuess == randomInt) {
System.out.println("Correct " + userName + "! Random number = "
+ randomInt);
passed = true;
break;
}
else if (userGuess > randomInt) {
System.out.println("Wrong! The random number is lower.");
}
else {
System.out.println("Wrong! The random number is higher.");
}
scanner.next();
tries++;
}
// If the user havent found the correct number after three tries,
// print Game Over and what the random number were.
if (!passed) {
System.out.println("Game over!");
System.out.println("The random number was " + randomInt);
}
// Close the scanner.
scanner.close();
System.exit(0);
}
|
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/ui/actions/ContextAttachAction.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/ui/actions/ContextAttachAction.java
index 5413cf62b..35341cf5e 100644
--- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/ui/actions/ContextAttachAction.java
+++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/ui/actions/ContextAttachAction.java
@@ -1,75 +1,75 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.ui.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.mylar.internal.core.util.MylarStatusHandler;
import org.eclipse.mylar.internal.tasklist.ui.views.TaskListView;
import org.eclipse.mylar.internal.tasklist.ui.wizards.ContextAttachWizard;
import org.eclipse.mylar.provisional.core.MylarPlugin;
import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryTask;
import org.eclipse.mylar.provisional.tasklist.ITask;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PlatformUI;
/**
* @author Mik Kersten
* @author Rob Elves
*/
public class ContextAttachAction implements IViewActionDelegate {
ISelection selection = null;
IViewPart view = null;
public void init(IViewPart view) {
this.view = view;
}
public void run(IAction action) {
ITask task = TaskListView.getDefault().getSelectedTask();
if (task instanceof AbstractRepositoryTask) {
try {
if (!MylarPlugin.getContextManager().hasContext(task.getHandleIdentifier())) {
- MessageDialog.openError(null, "Attach Context", "No context exists for selected task.");
+ MessageDialog.openInformation(null, "Attach Context", "No context exists for selected task.");
return;
}
ContextAttachWizard wizard = new ContextAttachWizard((AbstractRepositoryTask)task);
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
if (wizard != null && shell != null && !shell.isDisposed()) {
WizardDialog dialog = new WizardDialog(shell, wizard);
dialog.create();
dialog.setTitle(ContextAttachWizard.WIZARD_TITLE);
dialog.setBlockOnOpen(true);
if (dialog.open() == Dialog.CANCEL) {
dialog.close();
return;
}
}
} catch (Exception e) {
MylarStatusHandler.fail(e, e.getMessage(), true);
}
}
}
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
}
}
| true | true | public void run(IAction action) {
ITask task = TaskListView.getDefault().getSelectedTask();
if (task instanceof AbstractRepositoryTask) {
try {
if (!MylarPlugin.getContextManager().hasContext(task.getHandleIdentifier())) {
MessageDialog.openError(null, "Attach Context", "No context exists for selected task.");
return;
}
ContextAttachWizard wizard = new ContextAttachWizard((AbstractRepositoryTask)task);
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
if (wizard != null && shell != null && !shell.isDisposed()) {
WizardDialog dialog = new WizardDialog(shell, wizard);
dialog.create();
dialog.setTitle(ContextAttachWizard.WIZARD_TITLE);
dialog.setBlockOnOpen(true);
if (dialog.open() == Dialog.CANCEL) {
dialog.close();
return;
}
}
} catch (Exception e) {
MylarStatusHandler.fail(e, e.getMessage(), true);
}
}
}
| public void run(IAction action) {
ITask task = TaskListView.getDefault().getSelectedTask();
if (task instanceof AbstractRepositoryTask) {
try {
if (!MylarPlugin.getContextManager().hasContext(task.getHandleIdentifier())) {
MessageDialog.openInformation(null, "Attach Context", "No context exists for selected task.");
return;
}
ContextAttachWizard wizard = new ContextAttachWizard((AbstractRepositoryTask)task);
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
if (wizard != null && shell != null && !shell.isDisposed()) {
WizardDialog dialog = new WizardDialog(shell, wizard);
dialog.create();
dialog.setTitle(ContextAttachWizard.WIZARD_TITLE);
dialog.setBlockOnOpen(true);
if (dialog.open() == Dialog.CANCEL) {
dialog.close();
return;
}
}
} catch (Exception e) {
MylarStatusHandler.fail(e, e.getMessage(), true);
}
}
}
|
diff --git a/appsolut/src/com/appsolut/composition/pitch_detection/WaveToMidi.java b/appsolut/src/com/appsolut/composition/pitch_detection/WaveToMidi.java
index 03733af..d7fc93e 100644
--- a/appsolut/src/com/appsolut/composition/pitch_detection/WaveToMidi.java
+++ b/appsolut/src/com/appsolut/composition/pitch_detection/WaveToMidi.java
@@ -1,181 +1,181 @@
package com.appsolut.composition.pitch_detection;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.String;
import com.leff.midi.MidiFile;
import com.leff.midi.MidiTrack;
import com.leff.midi.event.meta.Tempo;
import com.leff.midi.event.meta.TimeSignature;
import android.util.Log;
public class WaveToMidi {
private final static double[] FREQS_MIDI_OCT_0 = { 261.6255653006,
277.1826309769,
293.6647679174,
311.1269837221,
329.6275569129,
349.2282314330,
369.9944227116,
391.9954359817,
415.3046975799,
440.0000000000,
466.1637615181,
493.8833012561};
private static final String TAG = "HerbleGerble";
private final static int DEFAULT_CLIP_RATE = 5;//Number of frequencies/second
private int bpm;
private int ppq = 192;
private static final int OFF_VAL = -1;
// MIDI resources
private MidiFile midiFile;
private MidiTrack tempoTrack;
private MidiTrack noteTrack;
public WaveToMidi(int _bpm) {
// MIDI Instantiation
midiFile = new MidiFile(MidiFile.DEFAULT_RESOLUTION);
tempoTrack = new MidiTrack();
noteTrack = new MidiTrack();
bpm=_bpm;
// Tempo track
TimeSignature ts = new TimeSignature();
ts.setTimeSignature(4, 4, TimeSignature.DEFAULT_METER, TimeSignature.DEFAULT_DIVISION);
Tempo t = new Tempo();
t.setBpm(_bpm);
tempoTrack.insertEvent(ts);
tempoTrack.insertEvent(t);
midiFile.addTrack(tempoTrack);
}
public MidiFile audioToMidiFile(double[] audio, long sampleRate) {
return audioToMidiFile(audio,sampleRate,DEFAULT_CLIP_RATE);
}
/**
* Taking the output from getMidiNumsWithTicks schedules midi events and produces a midi file
*
* @param audio The audio to be converted to midi
* @param sampleRate The sample rate the audio was recorded at
* @param clipRate The number of frequencies found in the audio per second
* @return
*/
public MidiFile audioToMidiFile(double[] audio, long sampleRate, int clipRate){
Pair<Integer[],Long[]> midiNums = getMidiNumsWithTicks(audioToMidiNums(audio,sampleRate,clipRate),clipRate);
long onTick = 0;
int midiNum = OFF_VAL;
for(int i=0;i<midiNums.left.length;i++){
midiNum = midiNums.left[i];
if(midiNum != OFF_VAL){
noteTrack.insertNote(0, midiNum, 127, onTick,midiNums.right[i]);
}
onTick += midiNums.right[i];
}
midiFile.addTrack(noteTrack);
return midiFile;
}
/**
* Takes an array of midi numbers without explicitly specified durations and explicitly defines their durations.
*
* @param midiNums an array of midiNumbers each corresponding to a single unit of duration. OFF_VAL indicates silence.
* @param clipRate the number of frequencies found per second
* @return A pair of arrays representing midi numbers and their durations in ticks
*/
public Pair<Integer[],Long[]> getMidiNumsWithTicks(int[] midiNums,int clipRate){
- long TICKS_PER_OCCURRENCE = bpm*ppq/(6*10*1000*clipRate);
+ long TICKS_PER_OCCURRENCE = bpm*ppq/(60*clipRate);
ArrayList<Integer> newMidiNums = new ArrayList<Integer>();
ArrayList<Long> ticksPerMidiNum = new ArrayList<Long>();
int lastNum = midiNums[0];
int dur = 1;
for(int m: midiNums){
if(m != lastNum){
newMidiNums.add(m);
ticksPerMidiNum.add(dur*TICKS_PER_OCCURRENCE);
lastNum = m;
dur = 1;
}else{
dur++;
}
}
// for(int m: midiNums){
// newMidiNums.add(m);
// ticksPerMidiNum.add(TICKS_PER_OCCURRENCE);
// }
Integer[] outMidiNums= new Integer[0];
outMidiNums = newMidiNums.toArray(outMidiNums);
Long[] outTicksPer = new Long[0];
outTicksPer = ticksPerMidiNum.toArray(outTicksPer);
return new Pair<Integer[],Long[]>(outMidiNums,outTicksPer);
}
/**
* Simple wrapper function that (using not so simple functions) turns input audio into a series of midi numbers without explicit duration.
*
* @param audio The audio to be converted to midi
* @param sampleRate The sample rate the audio was recorded at
* @param clipRate The number of frequencies found in the audio per second
* @return an array of midi numbers
*/
static int[] audioToMidiNums(double[] audio, long sampleRate, int clipRate){
return snapIntervals(
freqsToRawIntervals(
PlotTones.audioToFreqs(audio, sampleRate, clipRate)));
}
/**
* Takes an array of frequencies drawn from input audio and turns it into a set of intervals from the first frequency
*
* @param freqs
* @return The first frequency and an array of intervals. The first note itself is included in the array of intervals as 0.
*/
static Pair<Integer,double[]> freqsToRawIntervals(int[] freqs){
int baseFreq = freqs[0];
double[] intervals = new double[freqs.length];
Log.v(TAG, Arrays.toString(freqs));
for(int i=0; i<freqs.length; i++){
intervals[i] = 12*Math.log(1.0*freqs[i]/baseFreq)/Math.log(2);//The number of half steps from baseFreq
}
return new Pair<Integer,double[]>(baseFreq,intervals);
}
/**
* Takes a base note and array of intervals and produces an array of midi numbers.
*
* @param inp
* @return an array of midi numbers
*/
static int[] snapIntervals(Pair<Integer,double[]> inp){
int baseFreq = inp.left;
double[] intervals = inp.right;
int octaveNum = (int) Math.round(Math.log(baseFreq/FREQS_MIDI_OCT_0[9])/Math.log(2));
double[] octave = new double[12];
for(int i=0;i<octave.length;i++){
octave[i] = Math.pow(2, octaveNum)*FREQS_MIDI_OCT_0[i];
}
double min = Integer.MAX_VALUE;
int closestTone = 0;
for(int i=0;i<octave.length; i++ ){
if(Math.abs(baseFreq-octave[i])<min){
min = Math.abs(baseFreq-octave[i]);
closestTone = i;
}
}
closestTone = closestTone + 60 + octaveNum*12;
int[] midiNums = new int[intervals.length];
for(int i=0; i<intervals.length; i++){
midiNums[i] = (int) Math.round(intervals[i])+ closestTone;
}
return midiNums;
}
}
| true | true | public Pair<Integer[],Long[]> getMidiNumsWithTicks(int[] midiNums,int clipRate){
long TICKS_PER_OCCURRENCE = bpm*ppq/(6*10*1000*clipRate);
ArrayList<Integer> newMidiNums = new ArrayList<Integer>();
ArrayList<Long> ticksPerMidiNum = new ArrayList<Long>();
int lastNum = midiNums[0];
int dur = 1;
for(int m: midiNums){
if(m != lastNum){
newMidiNums.add(m);
ticksPerMidiNum.add(dur*TICKS_PER_OCCURRENCE);
lastNum = m;
dur = 1;
}else{
dur++;
}
}
// for(int m: midiNums){
// newMidiNums.add(m);
// ticksPerMidiNum.add(TICKS_PER_OCCURRENCE);
// }
Integer[] outMidiNums= new Integer[0];
outMidiNums = newMidiNums.toArray(outMidiNums);
Long[] outTicksPer = new Long[0];
outTicksPer = ticksPerMidiNum.toArray(outTicksPer);
return new Pair<Integer[],Long[]>(outMidiNums,outTicksPer);
}
| public Pair<Integer[],Long[]> getMidiNumsWithTicks(int[] midiNums,int clipRate){
long TICKS_PER_OCCURRENCE = bpm*ppq/(60*clipRate);
ArrayList<Integer> newMidiNums = new ArrayList<Integer>();
ArrayList<Long> ticksPerMidiNum = new ArrayList<Long>();
int lastNum = midiNums[0];
int dur = 1;
for(int m: midiNums){
if(m != lastNum){
newMidiNums.add(m);
ticksPerMidiNum.add(dur*TICKS_PER_OCCURRENCE);
lastNum = m;
dur = 1;
}else{
dur++;
}
}
// for(int m: midiNums){
// newMidiNums.add(m);
// ticksPerMidiNum.add(TICKS_PER_OCCURRENCE);
// }
Integer[] outMidiNums= new Integer[0];
outMidiNums = newMidiNums.toArray(outMidiNums);
Long[] outTicksPer = new Long[0];
outTicksPer = ticksPerMidiNum.toArray(outTicksPer);
return new Pair<Integer[],Long[]>(outMidiNums,outTicksPer);
}
|
diff --git a/Meetster/src/com/russia/meetster/data/MeetsterSyncAdapter.java b/Meetster/src/com/russia/meetster/data/MeetsterSyncAdapter.java
index d0fb51d..95d8d12 100644
--- a/Meetster/src/com/russia/meetster/data/MeetsterSyncAdapter.java
+++ b/Meetster/src/com/russia/meetster/data/MeetsterSyncAdapter.java
@@ -1,79 +1,79 @@
package com.russia.meetster.data;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import com.russia.meetster.MeetsterApplication;
import com.russia.meetster.utils.NetworkUtils;
import com.russia.meetster.utils.YLSQLRow;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
public class MeetsterSyncAdapter extends AbstractThreadedSyncAdapter {
private Context mContext;
public MeetsterSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
this.mContext = context;
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
MeetsterApplication mApp = ((MeetsterApplication) mContext.getApplicationContext());
List<MeetsterEvent> unsyncedLocalEvents = MeetsterDataManager.getUnsyncedEvents(mContext);
List<MeetsterEvent> unsyncedRemoteEvents;
try {
// Get events...
unsyncedRemoteEvents = NetworkUtils.syncEvents(mContext, mApp.getCurrentUserId(), mApp.getLastSyncTime(), unsyncedLocalEvents);
Date latestEventSynced = new Date(mApp.getLastSyncTime());
for (MeetsterEvent e : unsyncedRemoteEvents) {
e.setSynced(true);
MeetsterDataManager.writeEvent(mContext, e);
Date newDate = e.getCreationTime();
if (latestEventSynced.before(newDate))
- latestEventSynced = newDate;
+ latestEventSynced = new Date(newDate.getTime() + 1);
}
mApp.setLastSyncTime(latestEventSynced);
// Get any new users we might need from these events
List<Long> unsyncedInviters = MeetsterDataManager.getUnsyncedInviterIds(mContext);
if (unsyncedInviters.size() > 0) {
List<MeetsterFriend> newUsers = NetworkUtils.downloadUsers(unsyncedInviters);
for (MeetsterFriend f : newUsers) {
MeetsterDataManager.writeUser(mContext, f);
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true | true | public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
MeetsterApplication mApp = ((MeetsterApplication) mContext.getApplicationContext());
List<MeetsterEvent> unsyncedLocalEvents = MeetsterDataManager.getUnsyncedEvents(mContext);
List<MeetsterEvent> unsyncedRemoteEvents;
try {
// Get events...
unsyncedRemoteEvents = NetworkUtils.syncEvents(mContext, mApp.getCurrentUserId(), mApp.getLastSyncTime(), unsyncedLocalEvents);
Date latestEventSynced = new Date(mApp.getLastSyncTime());
for (MeetsterEvent e : unsyncedRemoteEvents) {
e.setSynced(true);
MeetsterDataManager.writeEvent(mContext, e);
Date newDate = e.getCreationTime();
if (latestEventSynced.before(newDate))
latestEventSynced = newDate;
}
mApp.setLastSyncTime(latestEventSynced);
// Get any new users we might need from these events
List<Long> unsyncedInviters = MeetsterDataManager.getUnsyncedInviterIds(mContext);
if (unsyncedInviters.size() > 0) {
List<MeetsterFriend> newUsers = NetworkUtils.downloadUsers(unsyncedInviters);
for (MeetsterFriend f : newUsers) {
MeetsterDataManager.writeUser(mContext, f);
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
MeetsterApplication mApp = ((MeetsterApplication) mContext.getApplicationContext());
List<MeetsterEvent> unsyncedLocalEvents = MeetsterDataManager.getUnsyncedEvents(mContext);
List<MeetsterEvent> unsyncedRemoteEvents;
try {
// Get events...
unsyncedRemoteEvents = NetworkUtils.syncEvents(mContext, mApp.getCurrentUserId(), mApp.getLastSyncTime(), unsyncedLocalEvents);
Date latestEventSynced = new Date(mApp.getLastSyncTime());
for (MeetsterEvent e : unsyncedRemoteEvents) {
e.setSynced(true);
MeetsterDataManager.writeEvent(mContext, e);
Date newDate = e.getCreationTime();
if (latestEventSynced.before(newDate))
latestEventSynced = new Date(newDate.getTime() + 1);
}
mApp.setLastSyncTime(latestEventSynced);
// Get any new users we might need from these events
List<Long> unsyncedInviters = MeetsterDataManager.getUnsyncedInviterIds(mContext);
if (unsyncedInviters.size() > 0) {
List<MeetsterFriend> newUsers = NetworkUtils.downloadUsers(unsyncedInviters);
for (MeetsterFriend f : newUsers) {
MeetsterDataManager.writeUser(mContext, f);
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/src/main/java/ca/delmar/api/controller/NoticeController.java b/src/main/java/ca/delmar/api/controller/NoticeController.java
index 4a9a098..8300248 100644
--- a/src/main/java/ca/delmar/api/controller/NoticeController.java
+++ b/src/main/java/ca/delmar/api/controller/NoticeController.java
@@ -1,74 +1,65 @@
package ca.delmar.api.controller;
import ca.delmar.api.domain.Notice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: jinw
* Date: 06/09/13
* Time: 2:17 PM
* To change this template use File | Settings | File Templates.
*/
@Controller
@RequestMapping("/notices")
public class NoticeController {
private JdbcTemplate jdbcTemplate;
private LobHandler lobHandler;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Autowired
public void setLobHandler(LobHandler lobHandler) {
this.lobHandler = lobHandler;
}
@RequestMapping(value = "/list")
@ResponseBody
- public List<Notice> getList(@RequestParam(value = "lang", required = false, defaultValue = "en") String language,
- @RequestParam(value = "count", required = false, defaultValue = "20") int count) {
+ public List<Notice> getJsonList(@RequestParam(value = "lang", required = false, defaultValue = "en") String language,
+ @RequestParam(value = "count", required = false, defaultValue = "20") int count) {
int languageId = language.equalsIgnoreCase("en") ? 1 : 2;
jdbcTemplate.setMaxRows(count);
- String query =
- "SELECT n.* " +
- " FROM TBLNOTICE n " +
- " WHERE n.LANGUAGEID = :languageId " +
- "AND n.ISACTIVE = 1 " +
- "AND n.ISTEMPLATE = 0 " +
- "AND n.NOTICEPRIVATE = 0 " +
- "AND n.NOTICEDRAFT = 0 " +
- "AND n.DATESENT IS NOT NULL " +
- "ORDER BY n.DATESENT DESC";
+ String query = "SELECT n.* FROM TBLNOTICE n WHERE n.LANGUAGEID = :languageId AND n.ISACTIVE = 1 AND n.ISTEMPLATE = 0 AND n.NOTICEPRIVATE = 0 AND n.NOTICEDRAFT = 0 AND n.DATESENT IS NOT NULL ORDER BY n.DATESENT DESC";
List<Notice> list = jdbcTemplate.query(query, new Object[]{languageId}, new NoticeMapper());
jdbcTemplate.setMaxRows(0);
return list;
}
private final class NoticeMapper implements RowMapper<Notice> {
public Notice mapRow(ResultSet rs, int rowNum) throws SQLException {
Notice result = new Notice();
result.id = rs.getString("noticeid");
result.title = rs.getString("noticesubject");
result.date = rs.getDate("DATESENT");
// result.html = lobHandler.getClobAsString(rs, "noticehtml");
return result;
}
}
}
| false | true | public List<Notice> getList(@RequestParam(value = "lang", required = false, defaultValue = "en") String language,
@RequestParam(value = "count", required = false, defaultValue = "20") int count) {
int languageId = language.equalsIgnoreCase("en") ? 1 : 2;
jdbcTemplate.setMaxRows(count);
String query =
"SELECT n.* " +
" FROM TBLNOTICE n " +
" WHERE n.LANGUAGEID = :languageId " +
"AND n.ISACTIVE = 1 " +
"AND n.ISTEMPLATE = 0 " +
"AND n.NOTICEPRIVATE = 0 " +
"AND n.NOTICEDRAFT = 0 " +
"AND n.DATESENT IS NOT NULL " +
"ORDER BY n.DATESENT DESC";
List<Notice> list = jdbcTemplate.query(query, new Object[]{languageId}, new NoticeMapper());
jdbcTemplate.setMaxRows(0);
return list;
}
| public List<Notice> getJsonList(@RequestParam(value = "lang", required = false, defaultValue = "en") String language,
@RequestParam(value = "count", required = false, defaultValue = "20") int count) {
int languageId = language.equalsIgnoreCase("en") ? 1 : 2;
jdbcTemplate.setMaxRows(count);
String query = "SELECT n.* FROM TBLNOTICE n WHERE n.LANGUAGEID = :languageId AND n.ISACTIVE = 1 AND n.ISTEMPLATE = 0 AND n.NOTICEPRIVATE = 0 AND n.NOTICEDRAFT = 0 AND n.DATESENT IS NOT NULL ORDER BY n.DATESENT DESC";
List<Notice> list = jdbcTemplate.query(query, new Object[]{languageId}, new NoticeMapper());
jdbcTemplate.setMaxRows(0);
return list;
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index b261a75b..fae1d17f 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1139 +1,1139 @@
/*
* Copyright (C) 2008 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.launcher2;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import static android.util.Log.*;
import android.util.Log;
import android.os.Process;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel {
static final boolean DEBUG_LOADERS = true;
static final String TAG = "Launcher.Model";
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private Loader mLoader = new Loader();
private WeakReference<Callbacks> mCallbacks;
private AllAppsList mAllAppsList = new AllAppsList();
public interface Callbacks {
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindPackageAdded(ArrayList<ApplicationInfo> apps);
public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps);
public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps);
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
int cellX, int cellY) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceiveIntent(Context context, Intent intent) {
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList();
}
- final Callbacks callbacks = mCallbacks.get();
+ final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList();
final HashMap<Long, FolderInfo> folders = new HashMap();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.post(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
bindAllApps();
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
return;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(folders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(folders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(folders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// TODO: Bind the folders
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList();
mHandler.post(new Runnable() {
public void run() {
long t = SystemClock.uptimeMillis();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
| true | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceiveIntent(Context context, Intent intent) {
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList();
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList();
final HashMap<Long, FolderInfo> folders = new HashMap();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.post(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
bindAllApps();
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
return;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(folders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(folders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(folders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// TODO: Bind the folders
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList();
mHandler.post(new Runnable() {
public void run() {
long t = SystemClock.uptimeMillis();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceiveIntent(Context context, Intent intent) {
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList();
final HashMap<Long, FolderInfo> folders = new HashMap();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.post(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
bindAllApps();
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
return;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(folders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(folders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(folders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// TODO: Bind the folders
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList();
mHandler.post(new Runnable() {
public void run() {
long t = SystemClock.uptimeMillis();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
|
diff --git a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverBundle.java b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverBundle.java
index 11e3c436..0331b29a 100644
--- a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverBundle.java
+++ b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverBundle.java
@@ -1,408 +1,409 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.osgi.internal.module;
import java.util.*;
import org.eclipse.osgi.service.resolver.*;
import org.osgi.framework.Constants;
/*
* A companion to BundleDescription from the state used while resolving.
*/
public class ResolverBundle extends VersionSupplier {
public static final int UNRESOLVED = 0;
public static final int RESOLVING = 1;
public static final int RESOLVED = 2;
private Long bundleID;
private BundleConstraint host;
private ResolverImport[] imports;
private ResolverExport[] exports;
private BundleConstraint[] requires;
// Fragment support
private ArrayList fragments;
private HashMap fragmentExports;
private HashMap fragmentImports;
private HashMap fragmentRequires;
// Flag specifying whether this bundle is resolvable
private boolean resolvable = true;
// Internal resolver state for this bundle
private int state = UNRESOLVED;
private ResolverImpl resolver;
private boolean newFragmentExports;
ResolverBundle(BundleDescription bundle, ResolverImpl resolver) {
super(bundle);
this.bundleID = new Long(bundle.getBundleId());
this.resolver = resolver;
initialize(bundle.isResolved());
}
void initialize(boolean useSelectedExports) {
if (getBundle().getHost() != null) {
host = new BundleConstraint(this, getBundle().getHost());
exports = new ResolverExport[0];
imports = new ResolverImport[0];
requires = new BundleConstraint[0];
return;
}
ImportPackageSpecification[] actualImports = getBundle().getImportPackages();
// Reorder imports so that optionals are at the end so that we wire statics before optionals
ArrayList importList = new ArrayList(actualImports.length);
for (int i = actualImports.length - 1; i >= 0; i--)
if (ImportPackageSpecification.RESOLUTION_OPTIONAL.equals(actualImports[i].getDirective(Constants.RESOLUTION_DIRECTIVE)))
importList.add(new ResolverImport(this, actualImports[i]));
else
importList.add(0, new ResolverImport(this, actualImports[i]));
imports = (ResolverImport[]) importList.toArray(new ResolverImport[importList.size()]);
ExportPackageDescription[] actualExports = useSelectedExports ? getBundle().getSelectedExports() : getBundle().getExportPackages();
exports = new ResolverExport[actualExports.length];
for (int i = 0; i < actualExports.length; i++)
exports[i] = new ResolverExport(this, actualExports[i]);
BundleSpecification[] actualRequires = getBundle().getRequiredBundles();
requires = new BundleConstraint[actualRequires.length];
for (int i = 0; i < requires.length; i++)
requires[i] = new BundleConstraint(this, actualRequires[i]);
fragments = null;
fragmentExports = null;
fragmentImports = null;
fragmentRequires = null;
}
ResolverExport getExport(String name) {
ResolverExport[] allExports = getExportPackages();
for (int i = 0; i < allExports.length; i++)
if (name.equals(allExports[i].getName()))
return allExports[i];
return null;
}
ResolverExport[] getExports(String name) {
ArrayList results = new ArrayList(1); // rare to have more than one
for (int i = 0; i < exports.length; i++)
if (name.equals(exports[i].getName()))
results.add(exports[i]);
return (ResolverExport[]) results.toArray(new ResolverExport[results.size()]);
}
// Iterate thru the imports making sure they are wired
boolean isFullyWired() {
if (host != null && host.foundMatchingBundles())
return false;
ResolverImport[] allImports = getImportPackages();
for (int i = 0; i < allImports.length; i++)
if (allImports[i].getMatchingExport() == null && !allImports[i].isOptional() && !allImports[i].isDynamic())
return false;
BundleConstraint[] allRequires = getRequires();
for (int i = 0; i < allRequires.length; i++)
if (allRequires[i].getMatchingBundle() == null && !allRequires[i].isOptional())
return false;
return true;
}
void clearWires(boolean clearUnresolvable) {
ResolverImport[] allImports = getImportPackages();
for (int i = 0; i < allImports.length; i++) {
allImports[i].setMatchingExport(null);
if (clearUnresolvable)
allImports[i].clearUnresolvableWirings();
}
if (host != null)
host.removeAllMatchingBundles();
BundleConstraint[] allRequires = getRequires();
for (int i = 0; i < allRequires.length; i++)
allRequires[i].setMatchingBundle(null);
}
boolean isResolved() {
return getState() == ResolverBundle.RESOLVED;
}
boolean isFragment() {
return host != null;
}
int getState() {
return state;
}
void setState(int state) {
this.state = state;
}
ResolverImport[] getImportPackages() {
if (isFragment())
return new ResolverImport[0];
if (fragments == null || fragments.size() == 0)
return imports;
ArrayList resultList = new ArrayList(imports.length);
for (int i = 0; i < imports.length; i++)
resultList.add(imports[i]);
for (Iterator iter = fragments.iterator(); iter.hasNext();) {
ResolverBundle fragment = (ResolverBundle) iter.next();
ArrayList fragImports = (ArrayList) fragmentImports.get(fragment.bundleID);
if (fragImports != null)
resultList.addAll(fragImports);
}
return (ResolverImport[]) resultList.toArray(new ResolverImport[resultList.size()]);
}
ResolverExport[] getExportPackages() {
if (isFragment())
return new ResolverExport[0];
if (fragments == null || fragments.size() == 0)
return exports;
ArrayList resultList = new ArrayList(exports.length);
for (int i = 0; i < exports.length; i++)
resultList.add(exports[i]);
for (Iterator iter = fragments.iterator(); iter.hasNext();) {
ResolverBundle fragment = (ResolverBundle) iter.next();
ArrayList fragExports = (ArrayList) fragmentExports.get(fragment.bundleID);
if (fragExports != null)
resultList.addAll(fragExports);
}
return (ResolverExport[]) resultList.toArray(new ResolverExport[resultList.size()]);
}
ResolverExport[] getSelectedExports() {
ResolverExport[] allExports = getExportPackages();
int removedExports = 0;
for (int i = 0; i < allExports.length; i++)
if (allExports[i].isDropped())
removedExports++;
if (removedExports == 0)
return allExports;
ResolverExport[] selectedExports = new ResolverExport[allExports.length - removedExports];
int index = 0;
for (int i = 0; i < allExports.length; i++) {
if (allExports[i].isDropped())
continue;
selectedExports[index] = allExports[i];
index++;
}
return selectedExports;
}
BundleConstraint getHost() {
return host;
}
BundleConstraint[] getRequires() {
if (isFragment())
return new BundleConstraint[0];
if (fragments == null || fragments.size() == 0)
return requires;
ArrayList resultList = new ArrayList(requires.length);
for (int i = 0; i < requires.length; i++)
resultList.add(requires[i]);
for (Iterator iter = fragments.iterator(); iter.hasNext();) {
ResolverBundle fragment = (ResolverBundle) iter.next();
ArrayList fragRequires = (ArrayList) fragmentRequires.get(fragment.bundleID);
if (fragRequires != null)
resultList.addAll(fragRequires);
}
return (BundleConstraint[]) resultList.toArray(new BundleConstraint[resultList.size()]);
}
BundleConstraint getRequire(String name) {
BundleConstraint[] allRequires = getRequires();
for (int i = 0; i < allRequires.length; i++)
if (allRequires[i].getVersionConstraint().getName().equals(name))
return allRequires[i];
return null;
}
public BundleDescription getBundle() {
return (BundleDescription) getBaseDescription();
}
ResolverImport getImport(String name) {
ResolverImport[] allImports = getImportPackages();
for (int i = 0; i < allImports.length; i++) {
if (allImports[i].getName().equals(name)) {
return allImports[i];
}
}
return null;
}
public String toString() {
return "[" + getBundle() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
private void initFragments() {
if (fragments == null)
fragments = new ArrayList(1);
if (fragmentExports == null)
fragmentExports = new HashMap(1);
if (fragmentImports == null)
fragmentImports = new HashMap(1);
if (fragmentRequires == null)
fragmentRequires = new HashMap(1);
}
private boolean isImported(String packageName) {
ResolverImport[] allImports = getImportPackages();
for (int i = 0; i < allImports.length; i++)
if (packageName.equals(allImports[i].getName()))
return true;
return false;
}
private boolean isExported(String packageName) {
return getExport(packageName) != null;
}
private boolean isRequired(String bundleName) {
return getRequire(bundleName) != null;
}
- ResolverExport[] attachFragment(ResolverBundle fragment, boolean addExports) {
+ ResolverExport[] attachFragment(ResolverBundle fragment, boolean dynamicAttach) {
if (isFragment())
return new ResolverExport[0]; // cannot attach to fragments;
if (!getBundle().attachFragments() || (isResolved() && !getBundle().dynamicFragments()))
return new ResolverExport[0]; // host is restricting attachment
if (fragment.getHost().getMatchingBundles() != null && !((HostSpecification) fragment.getHost().getVersionConstraint()).isMultiHost())
return new ResolverExport[0]; // fragment is restricting attachment
ImportPackageSpecification[] newImports = fragment.getBundle().getImportPackages();
BundleSpecification[] newRequires = fragment.getBundle().getRequiredBundles();
ExportPackageDescription[] newExports = fragment.getBundle().getExportPackages();
- if (constraintsConflict(newImports, newRequires))
+ // if this is not during initialization then check if constraints conflict
+ if (dynamicAttach && constraintsConflict(newImports, newRequires))
return new ResolverExport[0]; // do not allow fragments with conflicting constraints
if (isResolved() && newExports.length > 0)
fragment.setNewFragmentExports(true);
initFragments();
if (fragments.contains(fragment))
return new ResolverExport[0];
fragments.add(fragment);
fragment.getHost().addMatchingBundle(this);
if (newImports.length > 0) {
ArrayList hostImports = new ArrayList(newImports.length);
for (int i = 0; i < newImports.length; i++)
if (!isImported(newImports[i].getName()))
hostImports.add(new ResolverImport(this, newImports[i]));
fragmentImports.put(fragment.bundleID, hostImports);
}
if (newRequires.length > 0) {
ArrayList hostRequires = new ArrayList(newRequires.length);
for (int i = 0; i < newRequires.length; i++)
if (!isRequired(newRequires[i].getName()))
hostRequires.add(new BundleConstraint(this, newRequires[i]));
fragmentRequires.put(fragment.bundleID, hostRequires);
}
ArrayList hostExports = new ArrayList(newExports.length);
- if (newExports.length > 0 && addExports) {
+ if (newExports.length > 0 && dynamicAttach) {
StateObjectFactory factory = resolver.getState().getFactory();
for (int i = 0; i < newExports.length; i++) {
if (!isExported(newExports[i].getName())) {
ExportPackageDescription hostExport = factory.createExportPackageDescription(newExports[i].getName(), newExports[i].getVersion(), newExports[i].getDirectives(), newExports[i].getAttributes(), newExports[i].isRoot(), getBundle());
hostExports.add(new ResolverExport(this, hostExport));
}
}
fragmentExports.put(fragment.bundleID, hostExports);
}
return (ResolverExport[]) hostExports.toArray(new ResolverExport[hostExports.size()]);
}
private boolean constraintsConflict(ImportPackageSpecification[] newImports, BundleSpecification[] newRequires) {
for (int i = 0; i < newImports.length; i++) {
ResolverImport importPkg = getImport(newImports[i].getName());
if (importPkg == null && isResolved())
return true; // do not allow additional constraints when host is already resolved
if (importPkg != null && !isIncluded(newImports[i].getVersionRange(), importPkg.getVersionConstraint().getVersionRange()))
return true; // do not allow conflicting constraints from fragment
}
for (int i = 0; i < newRequires.length; i++) {
BundleConstraint constraint = getRequire(newRequires[i].getName());
if (constraint == null && isResolved())
return true; // do not allow additional constraints when host is already resolved
if (constraint != null && !isIncluded(newRequires[i].getVersionRange(), constraint.getVersionConstraint().getVersionRange()))
return true; // do not allow conflicting constraints from fragment
}
return false;
}
// checks that the inner VersionRange is included in the outer VersionRange
private static boolean isIncluded(VersionRange outer, VersionRange inner) {
if (!outer.isIncluded(inner.getMinimum()) && (!inner.getMinimum().equals(outer.getMinimum()) || inner.getIncludeMinimum() != outer.getIncludeMinimum()))
return false;
if (!outer.isIncluded(inner.getMaximum()) && (!inner.getMaximum().equals(outer.getMaximum()) || inner.getIncludeMaximum() != outer.getIncludeMaximum()))
return false;
return true;
}
private void setNewFragmentExports(boolean newFragmentExports) {
this.newFragmentExports = newFragmentExports;
}
boolean isNewFragmentExports() {
return newFragmentExports;
}
ResolverExport[] detachFragment(ResolverBundle fragment) {
if (isFragment())
return new ResolverExport[0];
initFragments();
if (!fragments.remove(fragment))
return new ResolverExport[0];
fragment.getHost().removeMatchingBundle(this);
fragmentImports.remove(fragment.bundleID);
fragmentRequires.remove(fragment.bundleID);
ArrayList removedExports = (ArrayList) fragmentExports.remove(fragment.bundleID);
return removedExports == null ? new ResolverExport[0] : (ResolverExport[]) removedExports.toArray(new ResolverExport[removedExports.size()]);
}
void detachAllFragments() {
if (fragments == null)
return;
ResolverBundle[] allFragments = (ResolverBundle[]) fragments.toArray(new ResolverBundle[fragments.size()]);
for (int i = 0; i < allFragments.length; i++)
detachFragment(allFragments[i]);
}
boolean isResolvable() {
return resolvable;
}
void setResolvable(boolean resolvable) {
this.resolvable = resolvable;
}
void addExport(ResolverExport re) {
ResolverExport[] newExports = new ResolverExport[exports.length + 1];
for (int i = 0; i < exports.length; i++)
newExports[i] = exports[i];
newExports[exports.length] = re;
exports = newExports;
}
ResolverImpl getResolver() {
return resolver;
}
}
| false | true | ResolverExport[] attachFragment(ResolverBundle fragment, boolean addExports) {
if (isFragment())
return new ResolverExport[0]; // cannot attach to fragments;
if (!getBundle().attachFragments() || (isResolved() && !getBundle().dynamicFragments()))
return new ResolverExport[0]; // host is restricting attachment
if (fragment.getHost().getMatchingBundles() != null && !((HostSpecification) fragment.getHost().getVersionConstraint()).isMultiHost())
return new ResolverExport[0]; // fragment is restricting attachment
ImportPackageSpecification[] newImports = fragment.getBundle().getImportPackages();
BundleSpecification[] newRequires = fragment.getBundle().getRequiredBundles();
ExportPackageDescription[] newExports = fragment.getBundle().getExportPackages();
if (constraintsConflict(newImports, newRequires))
return new ResolverExport[0]; // do not allow fragments with conflicting constraints
if (isResolved() && newExports.length > 0)
fragment.setNewFragmentExports(true);
initFragments();
if (fragments.contains(fragment))
return new ResolverExport[0];
fragments.add(fragment);
fragment.getHost().addMatchingBundle(this);
if (newImports.length > 0) {
ArrayList hostImports = new ArrayList(newImports.length);
for (int i = 0; i < newImports.length; i++)
if (!isImported(newImports[i].getName()))
hostImports.add(new ResolverImport(this, newImports[i]));
fragmentImports.put(fragment.bundleID, hostImports);
}
if (newRequires.length > 0) {
ArrayList hostRequires = new ArrayList(newRequires.length);
for (int i = 0; i < newRequires.length; i++)
if (!isRequired(newRequires[i].getName()))
hostRequires.add(new BundleConstraint(this, newRequires[i]));
fragmentRequires.put(fragment.bundleID, hostRequires);
}
ArrayList hostExports = new ArrayList(newExports.length);
if (newExports.length > 0 && addExports) {
StateObjectFactory factory = resolver.getState().getFactory();
for (int i = 0; i < newExports.length; i++) {
if (!isExported(newExports[i].getName())) {
ExportPackageDescription hostExport = factory.createExportPackageDescription(newExports[i].getName(), newExports[i].getVersion(), newExports[i].getDirectives(), newExports[i].getAttributes(), newExports[i].isRoot(), getBundle());
hostExports.add(new ResolverExport(this, hostExport));
}
}
fragmentExports.put(fragment.bundleID, hostExports);
}
return (ResolverExport[]) hostExports.toArray(new ResolverExport[hostExports.size()]);
}
| ResolverExport[] attachFragment(ResolverBundle fragment, boolean dynamicAttach) {
if (isFragment())
return new ResolverExport[0]; // cannot attach to fragments;
if (!getBundle().attachFragments() || (isResolved() && !getBundle().dynamicFragments()))
return new ResolverExport[0]; // host is restricting attachment
if (fragment.getHost().getMatchingBundles() != null && !((HostSpecification) fragment.getHost().getVersionConstraint()).isMultiHost())
return new ResolverExport[0]; // fragment is restricting attachment
ImportPackageSpecification[] newImports = fragment.getBundle().getImportPackages();
BundleSpecification[] newRequires = fragment.getBundle().getRequiredBundles();
ExportPackageDescription[] newExports = fragment.getBundle().getExportPackages();
// if this is not during initialization then check if constraints conflict
if (dynamicAttach && constraintsConflict(newImports, newRequires))
return new ResolverExport[0]; // do not allow fragments with conflicting constraints
if (isResolved() && newExports.length > 0)
fragment.setNewFragmentExports(true);
initFragments();
if (fragments.contains(fragment))
return new ResolverExport[0];
fragments.add(fragment);
fragment.getHost().addMatchingBundle(this);
if (newImports.length > 0) {
ArrayList hostImports = new ArrayList(newImports.length);
for (int i = 0; i < newImports.length; i++)
if (!isImported(newImports[i].getName()))
hostImports.add(new ResolverImport(this, newImports[i]));
fragmentImports.put(fragment.bundleID, hostImports);
}
if (newRequires.length > 0) {
ArrayList hostRequires = new ArrayList(newRequires.length);
for (int i = 0; i < newRequires.length; i++)
if (!isRequired(newRequires[i].getName()))
hostRequires.add(new BundleConstraint(this, newRequires[i]));
fragmentRequires.put(fragment.bundleID, hostRequires);
}
ArrayList hostExports = new ArrayList(newExports.length);
if (newExports.length > 0 && dynamicAttach) {
StateObjectFactory factory = resolver.getState().getFactory();
for (int i = 0; i < newExports.length; i++) {
if (!isExported(newExports[i].getName())) {
ExportPackageDescription hostExport = factory.createExportPackageDescription(newExports[i].getName(), newExports[i].getVersion(), newExports[i].getDirectives(), newExports[i].getAttributes(), newExports[i].isRoot(), getBundle());
hostExports.add(new ResolverExport(this, hostExport));
}
}
fragmentExports.put(fragment.bundleID, hostExports);
}
return (ResolverExport[]) hostExports.toArray(new ResolverExport[hostExports.size()]);
}
|
diff --git a/bindings/java/src/org/hyperic/sigar/test/TestProcTime.java b/bindings/java/src/org/hyperic/sigar/test/TestProcTime.java
index d0ce5681..c541e62a 100644
--- a/bindings/java/src/org/hyperic/sigar/test/TestProcTime.java
+++ b/bindings/java/src/org/hyperic/sigar/test/TestProcTime.java
@@ -1,59 +1,60 @@
/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.sigar.test;
import java.util.Date;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.ProcCpu;
public class TestProcTime extends SigarTestCase {
public TestProcTime(String name) {
super(name);
}
public void testCreate() throws Exception {
Sigar sigar = getSigar();
try {
sigar.getProcTime(getInvalidPid());
} catch (SigarException e) {
}
ProcCpu procTime = sigar.getProcCpu(sigar.getPid());
assertGtEqZeroTrace("StartTime", procTime.getStartTime());
traceln("StartDate=" + new Date(procTime.getStartTime()));
//XXX
//assertTrue(procTime.getStartTime() < System.currentTimeMillis());
assertGtEqZeroTrace("User", procTime.getUser());
assertGtEqZeroTrace("Sys", procTime.getSys());
assertGtEqZeroTrace("Total", procTime.getTotal());
double value = procTime.getPercent() * 100.0;
traceln("Percent=" + value);
assertTrue(value >= 0.0);
- assertTrue(value <= 100.0);
+ int ncpu = sigar.getCpuList().length;
+ assertTrue(value <= (100.0 * ncpu)); //SIGAR-145 Irix mode
}
}
| true | true | public void testCreate() throws Exception {
Sigar sigar = getSigar();
try {
sigar.getProcTime(getInvalidPid());
} catch (SigarException e) {
}
ProcCpu procTime = sigar.getProcCpu(sigar.getPid());
assertGtEqZeroTrace("StartTime", procTime.getStartTime());
traceln("StartDate=" + new Date(procTime.getStartTime()));
//XXX
//assertTrue(procTime.getStartTime() < System.currentTimeMillis());
assertGtEqZeroTrace("User", procTime.getUser());
assertGtEqZeroTrace("Sys", procTime.getSys());
assertGtEqZeroTrace("Total", procTime.getTotal());
double value = procTime.getPercent() * 100.0;
traceln("Percent=" + value);
assertTrue(value >= 0.0);
assertTrue(value <= 100.0);
}
| public void testCreate() throws Exception {
Sigar sigar = getSigar();
try {
sigar.getProcTime(getInvalidPid());
} catch (SigarException e) {
}
ProcCpu procTime = sigar.getProcCpu(sigar.getPid());
assertGtEqZeroTrace("StartTime", procTime.getStartTime());
traceln("StartDate=" + new Date(procTime.getStartTime()));
//XXX
//assertTrue(procTime.getStartTime() < System.currentTimeMillis());
assertGtEqZeroTrace("User", procTime.getUser());
assertGtEqZeroTrace("Sys", procTime.getSys());
assertGtEqZeroTrace("Total", procTime.getTotal());
double value = procTime.getPercent() * 100.0;
traceln("Percent=" + value);
assertTrue(value >= 0.0);
int ncpu = sigar.getCpuList().length;
assertTrue(value <= (100.0 * ncpu)); //SIGAR-145 Irix mode
}
|
diff --git a/extension/portlets/platformNavigation/src/main/java/org/exoplatform/platform/component/UIAdminToolbarContainer.java b/extension/portlets/platformNavigation/src/main/java/org/exoplatform/platform/component/UIAdminToolbarContainer.java
index da7bf417d4..523a40008e 100644
--- a/extension/portlets/platformNavigation/src/main/java/org/exoplatform/platform/component/UIAdminToolbarContainer.java
+++ b/extension/portlets/platformNavigation/src/main/java/org/exoplatform/platform/component/UIAdminToolbarContainer.java
@@ -1,207 +1,208 @@
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.platform.component;
import java.util.UUID;
import org.exoplatform.portal.application.PortalRequestContext;
import org.exoplatform.portal.config.UserACL;
import org.exoplatform.portal.config.UserPortalConfig;
import org.exoplatform.portal.config.UserPortalConfigService;
import org.exoplatform.portal.config.model.PageNavigation;
import org.exoplatform.portal.config.model.PageNode;
import org.exoplatform.portal.config.model.PortalConfig;
import org.exoplatform.portal.webui.navigation.UINavigationManagement;
import org.exoplatform.portal.webui.navigation.UINavigationNodeSelector;
import org.exoplatform.portal.webui.page.UIPageNodeForm;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.wcm.webui.Utils;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.webui.application.WebuiApplication;
import org.exoplatform.webui.application.WebuiRequestContext;
import org.exoplatform.webui.application.portlet.PortletRequestContext;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.ComponentConfigs;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIApplication;
import org.exoplatform.webui.core.UIPopupWindow;
import org.exoplatform.webui.core.UIPortletApplication;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.Event.Phase;
import org.exoplatform.webui.event.EventListener;
@ComponentConfigs({
@ComponentConfig(
template = "app:/groovy/platformNavigation/portlet/UIAdminToolbarPortlet/UIAdminToolbarContainer.gtmpl",
events = {
@EventConfig(listeners = UIAdminToolbarContainer.ChangeEditingActionListener.class),
@EventConfig(listeners = UIAdminToolbarContainer.EditNavigationActionListener.class)
}
),
@ComponentConfig(type = UIPageNodeForm.class, lifecycle = UIFormLifecycle.class,
template = "system:/groovy/webui/form/UIFormTabPane.gtmpl",
events = {
@EventConfig(listeners = UIPageNodeForm.SaveActionListener.class),
@EventConfig(listeners = UIAdminToolbarContainer.BackActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIPageNodeForm.SwitchPublicationDateActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIPageNodeForm.SwitchVisibleActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIPageNodeForm.ClearPageActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIPageNodeForm.CreatePageActionListener.class, phase = Phase.DECODE)
}
)
})
public class UIAdminToolbarContainer extends UIPortletApplication {
public UIAdminToolbarContainer() throws Exception {
PortalRequestContext context = Util.getPortalRequestContext();
Boolean quickEdit = (Boolean) context.getRequest().getSession().getAttribute(Utils.TURN_ON_QUICK_EDIT);
if (quickEdit == null) {
context.getRequest().getSession().setAttribute(Utils.TURN_ON_QUICK_EDIT, false);
}
UIPopupWindow editNavigation = addChild(UIPopupWindow.class, null, null);
editNavigation.setWindowSize(400, 400);
editNavigation.setId(editNavigation.getId() + "-" + UUID.randomUUID().toString().replaceAll("-", ""));
}
public PageNavigation getSelectedNavigation() throws Exception {
return Utils.getSelectedNavigation();
}
public boolean hasEditPermissionOnPortal() throws Exception {
return Utils.hasEditPermissionOnPortal();
}
public boolean hasEditPermissionOnNavigation() throws Exception {
return Utils.hasEditPermissionOnNavigation();
}
public boolean hasEditPermissionOnPage() throws Exception {
return Utils.hasEditPermissionOnPage();
}
public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception {
// A user could view the toolbar portlet if he/she has edit permission
// either on
// 'active' page, 'active' portal or 'active' navigation
if (hasEditPermissionOnNavigation() || hasEditPermissionOnPage() || hasEditPermissionOnPortal()) {
super.processRender(app, context);
}
}
public static class ChangeEditingActionListener extends EventListener<UIAdminToolbarContainer> {
/*
* (non-Javadoc)
* @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event)
*/
public void execute(Event<UIAdminToolbarContainer> event) throws Exception {
PortalRequestContext context = Util.getPortalRequestContext();
Boolean quickEdit = (Boolean) context.getRequest().getSession().getAttribute(Utils.TURN_ON_QUICK_EDIT);
if (quickEdit == null || !quickEdit) {
context.getRequest().getSession().setAttribute(Utils.TURN_ON_QUICK_EDIT, true);
Utils.updatePortal((PortletRequestContext) event.getRequestContext());
} else {
context.getRequest().getSession().setAttribute(Utils.TURN_ON_QUICK_EDIT, false);
Utils.updatePortal((PortletRequestContext) event.getRequestContext());
}
}
}
static public class EditNavigationActionListener extends EventListener<UIAdminToolbarContainer> {
public void execute(Event<UIAdminToolbarContainer> event) throws Exception {
UIAdminToolbarContainer uicomp = event.getSource();
PageNavigation edittedNavigation = Utils.getSelectedNavigation();
WebuiRequestContext context = event.getRequestContext();
UIApplication uiApplication = context.getUIApplication();
if (edittedNavigation == null) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.Invalid-editPermission", null));
return;
}
UserACL userACL = uicomp.getApplicationComponent(UserACL.class);
if (edittedNavigation.getOwnerType().equals(PortalConfig.PORTAL_TYPE)) {
String portalName = Util.getPortalRequestContext().getPortalOwner();
UserPortalConfigService configService = uicomp.getApplicationComponent(UserPortalConfigService.class);
UserPortalConfig userPortalConfig = configService.getUserPortalConfig(portalName, context.getRemoteUser());
if (userPortalConfig == null) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.portal-not-exist", new String[] { portalName }));
return;
}
if (!userACL.hasEditPermission(userPortalConfig.getPortalConfig())) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.Invalid-editPermission", null));
return;
}
} else if (edittedNavigation.getOwnerType().equals(PortalConfig.GROUP_TYPE)) {
if (!userACL.hasEditPermission(edittedNavigation)) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.Invalid-editPermission", null));
return;
}
}
UIPopupWindow popUp = uicomp.getChild(UIPopupWindow.class);
UINavigationManagement naviManager = popUp.createUIComponent(UINavigationManagement.class, null, null, popUp);
naviManager.setOwner(edittedNavigation.getOwnerId());
naviManager.setOwnerType(edittedNavigation.getOwnerType());
UINavigationNodeSelector selector = naviManager.getChild(UINavigationNodeSelector.class);
selector.setEdittedNavigation(edittedNavigation);
selector.initTreeData();
popUp.setUIComponent(naviManager);
popUp.setShowMask(true);
popUp.setShow(true);
+ popUp.setWindowSize(400, 400);
context.addUIComponentToUpdateByAjax(uicomp);
}
}
static public class BackActionListener extends EventListener<UIPageNodeForm>
{
public void execute(Event<UIPageNodeForm> event) throws Exception
{
UIPageNodeForm uiPageNodeForm = event.getSource();
PageNavigation contextNavigation = uiPageNodeForm.getContextPageNavigation();
UIAdminToolbarContainer uiAdminToolbarContainer = uiPageNodeForm.getAncestorOfType(UIAdminToolbarContainer.class);
UIPopupWindow uiNavigationPopup = uiAdminToolbarContainer.getChild(UIPopupWindow.class);
UINavigationManagement navigationManager = uiPageNodeForm.createUIComponent(UINavigationManagement.class, null, null);
navigationManager.setOwner(contextNavigation.getOwnerId());
navigationManager.setOwnerType(contextNavigation.getOwnerType());
UINavigationNodeSelector selector = navigationManager.getChild(UINavigationNodeSelector.class);
selector.setEdittedNavigation(uiPageNodeForm.getContextPageNavigation());
selector.initTreeData();
if (uiPageNodeForm.getSelectedParent() instanceof PageNode)
{
PageNode selectedParent = (PageNode)uiPageNodeForm.getSelectedParent();
selector.selectPageNodeByUri(selectedParent.getUri());
}
uiNavigationPopup.setUIComponent(navigationManager);
uiNavigationPopup.setWindowSize(400, 400);
event.getRequestContext().addUIComponentToUpdateByAjax(uiNavigationPopup.getParent());
}
}
}
| true | true | public void execute(Event<UIAdminToolbarContainer> event) throws Exception {
UIAdminToolbarContainer uicomp = event.getSource();
PageNavigation edittedNavigation = Utils.getSelectedNavigation();
WebuiRequestContext context = event.getRequestContext();
UIApplication uiApplication = context.getUIApplication();
if (edittedNavigation == null) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.Invalid-editPermission", null));
return;
}
UserACL userACL = uicomp.getApplicationComponent(UserACL.class);
if (edittedNavigation.getOwnerType().equals(PortalConfig.PORTAL_TYPE)) {
String portalName = Util.getPortalRequestContext().getPortalOwner();
UserPortalConfigService configService = uicomp.getApplicationComponent(UserPortalConfigService.class);
UserPortalConfig userPortalConfig = configService.getUserPortalConfig(portalName, context.getRemoteUser());
if (userPortalConfig == null) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.portal-not-exist", new String[] { portalName }));
return;
}
if (!userACL.hasEditPermission(userPortalConfig.getPortalConfig())) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.Invalid-editPermission", null));
return;
}
} else if (edittedNavigation.getOwnerType().equals(PortalConfig.GROUP_TYPE)) {
if (!userACL.hasEditPermission(edittedNavigation)) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.Invalid-editPermission", null));
return;
}
}
UIPopupWindow popUp = uicomp.getChild(UIPopupWindow.class);
UINavigationManagement naviManager = popUp.createUIComponent(UINavigationManagement.class, null, null, popUp);
naviManager.setOwner(edittedNavigation.getOwnerId());
naviManager.setOwnerType(edittedNavigation.getOwnerType());
UINavigationNodeSelector selector = naviManager.getChild(UINavigationNodeSelector.class);
selector.setEdittedNavigation(edittedNavigation);
selector.initTreeData();
popUp.setUIComponent(naviManager);
popUp.setShowMask(true);
popUp.setShow(true);
context.addUIComponentToUpdateByAjax(uicomp);
}
| public void execute(Event<UIAdminToolbarContainer> event) throws Exception {
UIAdminToolbarContainer uicomp = event.getSource();
PageNavigation edittedNavigation = Utils.getSelectedNavigation();
WebuiRequestContext context = event.getRequestContext();
UIApplication uiApplication = context.getUIApplication();
if (edittedNavigation == null) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.Invalid-editPermission", null));
return;
}
UserACL userACL = uicomp.getApplicationComponent(UserACL.class);
if (edittedNavigation.getOwnerType().equals(PortalConfig.PORTAL_TYPE)) {
String portalName = Util.getPortalRequestContext().getPortalOwner();
UserPortalConfigService configService = uicomp.getApplicationComponent(UserPortalConfigService.class);
UserPortalConfig userPortalConfig = configService.getUserPortalConfig(portalName, context.getRemoteUser());
if (userPortalConfig == null) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.portal-not-exist", new String[] { portalName }));
return;
}
if (!userACL.hasEditPermission(userPortalConfig.getPortalConfig())) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.Invalid-editPermission", null));
return;
}
} else if (edittedNavigation.getOwnerType().equals(PortalConfig.GROUP_TYPE)) {
if (!userACL.hasEditPermission(edittedNavigation)) {
uiApplication.addMessage(new ApplicationMessage("UISiteManagement.msg.Invalid-editPermission", null));
return;
}
}
UIPopupWindow popUp = uicomp.getChild(UIPopupWindow.class);
UINavigationManagement naviManager = popUp.createUIComponent(UINavigationManagement.class, null, null, popUp);
naviManager.setOwner(edittedNavigation.getOwnerId());
naviManager.setOwnerType(edittedNavigation.getOwnerType());
UINavigationNodeSelector selector = naviManager.getChild(UINavigationNodeSelector.class);
selector.setEdittedNavigation(edittedNavigation);
selector.initTreeData();
popUp.setUIComponent(naviManager);
popUp.setShowMask(true);
popUp.setShow(true);
popUp.setWindowSize(400, 400);
context.addUIComponentToUpdateByAjax(uicomp);
}
|
diff --git a/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java b/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java
index dd5c8dae..92c3f838 100644
--- a/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java
+++ b/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java
@@ -1,260 +1,260 @@
/**
* 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.mahout.utils.vectors.lucene;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import org.apache.commons.cli2.CommandLine;
import org.apache.commons.cli2.Group;
import org.apache.commons.cli2.Option;
import org.apache.commons.cli2.OptionException;
import org.apache.commons.cli2.builder.ArgumentBuilder;
import org.apache.commons.cli2.builder.DefaultOptionBuilder;
import org.apache.commons.cli2.builder.GroupBuilder;
import org.apache.commons.cli2.commandline.Parser;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.mahout.common.CommandLineUtil;
import org.apache.mahout.math.VectorWritable;
import org.apache.mahout.utils.vectors.TermInfo;
import org.apache.mahout.utils.vectors.io.JWriterTermInfoWriter;
import org.apache.mahout.utils.vectors.io.JWriterVectorWriter;
import org.apache.mahout.utils.vectors.io.SequenceFileVectorWriter;
import org.apache.mahout.utils.vectors.io.VectorWriter;
import org.apache.mahout.vectorizer.TF;
import org.apache.mahout.vectorizer.TFIDF;
import org.apache.mahout.vectorizer.Weight;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Driver {
private static final Logger log = LoggerFactory.getLogger(Driver.class);
private Driver() { }
public static void main(String[] args) throws IOException {
DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
ArgumentBuilder abuilder = new ArgumentBuilder();
GroupBuilder gbuilder = new GroupBuilder();
Option inputOpt = obuilder.withLongName("dir").withRequired(true).withArgument(
abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
.withDescription("The Lucene directory").withShortName("d").create();
Option outputOpt = obuilder.withLongName("output").withRequired(true).withArgument(
abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription("The output file")
.withShortName("o").create();
Option fieldOpt = obuilder.withLongName("field").withRequired(true).withArgument(
abuilder.withName("field").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index").withShortName("f").create();
Option idFieldOpt = obuilder.withLongName("idField").withRequired(false).withArgument(
abuilder.withName("idField").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index containing the index. If null, then the Lucene internal doc "
+ "id is used which is prone to error if the underlying index changes").withShortName("i").create();
Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true).withArgument(
abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()).withDescription(
"The output of the dictionary").withShortName("t").create();
Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument(
abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription(
"The kind of weight to use. Currently TF or TFIDF").withShortName("w").create();
Option delimiterOpt = obuilder.withLongName("delimiter").withRequired(false).withArgument(
abuilder.withName("delimiter").withMinimum(1).withMaximum(1).create()).withDescription(
- "The delimiter for outputing the dictionary").withShortName("l").create();
+ "The delimiter for outputting the dictionary").withShortName("l").create();
Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument(
abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription(
"The norm to use, expressed as either a double or \"INF\" if you want to use the Infinite norm. "
+ "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create();
Option maxOpt = obuilder.withLongName("max").withRequired(false).withArgument(
abuilder.withName("max").withMinimum(1).withMaximum(1).create()).withDescription(
"The maximum number of vectors to output. If not specified, then it will loop over all docs")
.withShortName("m").create();
Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false).withArgument(
abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()).withDescription(
"The VectorWriter to use, either seq "
+ "(SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)")
.withShortName("e").create();
Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument(
abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription(
"The minimum document frequency. Default is 1").withShortName("md").create();
Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument(
abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription(
"The max percentage of docs for the DF. Can be used to remove really high frequency terms."
+ " Expressed as an integer between 0 and 100. Default is 99.").withShortName("x").create();
Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
.create();
Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(idFieldOpt).withOption(
outputOpt).withOption(delimiterOpt).withOption(helpOpt).withOption(fieldOpt).withOption(maxOpt)
.withOption(dictOutOpt).withOption(powerOpt).withOption(outWriterOpt).withOption(maxDFPercentOpt)
.withOption(weightOpt).withOption(minDFOpt).create();
try {
Parser parser = new Parser();
parser.setGroup(group);
CommandLine cmdLine = parser.parse(args);
if (cmdLine.hasOption(helpOpt)) {
CommandLineUtil.printHelp(group);
return;
}
// Springify all this
if (cmdLine.hasOption(inputOpt)) { // Lucene case
File file = new File(cmdLine.getValue(inputOpt).toString());
if (!file.isDirectory()) {
throw new IllegalArgumentException("Lucene directory: " + file.getAbsolutePath()
+ " does not exist or is not a directory");
}
long maxDocs = Long.MAX_VALUE;
if (cmdLine.hasOption(maxOpt)) {
maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString());
}
if (maxDocs < 0) {
throw new IllegalArgumentException("maxDocs must be >= 0");
}
Directory dir = FSDirectory.open(file);
IndexReader reader = IndexReader.open(dir, true);
Weight weight;
if (cmdLine.hasOption(weightOpt)) {
String wString = cmdLine.getValue(weightOpt).toString();
if ("tf".equalsIgnoreCase(wString)) {
weight = new TF();
} else if ("tfidf".equalsIgnoreCase(wString)) {
weight = new TFIDF();
} else {
throw new OptionException(weightOpt);
}
} else {
weight = new TFIDF();
}
String field = cmdLine.getValue(fieldOpt).toString();
int minDf = 1;
if (cmdLine.hasOption(minDFOpt)) {
minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString());
}
int maxDFPercent = 99;
if (cmdLine.hasOption(maxDFPercentOpt)) {
maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString());
}
TermInfo termInfo = new CachedTermInfo(reader, field, minDf, maxDFPercent);
VectorMapper mapper = new TFDFMapper(reader, weight, termInfo);
double norm = LuceneIterable.NO_NORMALIZING;
if (cmdLine.hasOption(powerOpt)) {
String power = cmdLine.getValue(powerOpt).toString();
if ("INF".equals(power)) {
norm = Double.POSITIVE_INFINITY;
} else {
norm = Double.parseDouble(power);
}
}
String idField = null;
if (cmdLine.hasOption(idFieldOpt)) {
idField = cmdLine.getValue(idFieldOpt).toString();
}
LuceneIterable iterable;
if (norm == LuceneIterable.NO_NORMALIZING) {
iterable = new LuceneIterable(reader, idField, field, mapper, LuceneIterable.NO_NORMALIZING);
} else {
iterable = new LuceneIterable(reader, idField, field, mapper, norm);
}
String outFile = cmdLine.getValue(outputOpt).toString();
log.info("Output File: {}", outFile);
VectorWriter vectorWriter;
if (cmdLine.hasOption(outWriterOpt)) {
String outWriter = cmdLine.getValue(outWriterOpt).toString();
if ("file".equals(outWriter)) {
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
vectorWriter = new JWriterVectorWriter(writer);
} else {
vectorWriter = getSeqFileWriter(outFile);
}
} else {
vectorWriter = getSeqFileWriter(outFile);
}
long numDocs = vectorWriter.write(iterable, maxDocs);
vectorWriter.close();
log.info("Wrote: {} vectors", numDocs);
String delimiter = cmdLine.hasOption(delimiterOpt) ? cmdLine.getValue(delimiterOpt).toString() : "\t";
File dictOutFile = new File(cmdLine.getValue(dictOutOpt).toString());
log.info("Dictionary Output file: {}", dictOutFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(dictOutFile), Charset.forName("UTF8")));
JWriterTermInfoWriter tiWriter = new JWriterTermInfoWriter(writer, delimiter, field);
tiWriter.write(termInfo);
tiWriter.close();
writer.close();
}
} catch (OptionException e) {
log.error("Exception", e);
CommandLineUtil.printHelp(group);
}
}
private static VectorWriter getSeqFileWriter(String outFile) throws IOException {
Path path = new Path(outFile);
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
// TODO: Make this parameter driven
SequenceFile.Writer seqWriter = SequenceFile.createWriter(fs, conf, path, LongWritable.class,
VectorWritable.class);
return new SequenceFileVectorWriter(seqWriter);
}
}
| true | true | public static void main(String[] args) throws IOException {
DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
ArgumentBuilder abuilder = new ArgumentBuilder();
GroupBuilder gbuilder = new GroupBuilder();
Option inputOpt = obuilder.withLongName("dir").withRequired(true).withArgument(
abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
.withDescription("The Lucene directory").withShortName("d").create();
Option outputOpt = obuilder.withLongName("output").withRequired(true).withArgument(
abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription("The output file")
.withShortName("o").create();
Option fieldOpt = obuilder.withLongName("field").withRequired(true).withArgument(
abuilder.withName("field").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index").withShortName("f").create();
Option idFieldOpt = obuilder.withLongName("idField").withRequired(false).withArgument(
abuilder.withName("idField").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index containing the index. If null, then the Lucene internal doc "
+ "id is used which is prone to error if the underlying index changes").withShortName("i").create();
Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true).withArgument(
abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()).withDescription(
"The output of the dictionary").withShortName("t").create();
Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument(
abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription(
"The kind of weight to use. Currently TF or TFIDF").withShortName("w").create();
Option delimiterOpt = obuilder.withLongName("delimiter").withRequired(false).withArgument(
abuilder.withName("delimiter").withMinimum(1).withMaximum(1).create()).withDescription(
"The delimiter for outputing the dictionary").withShortName("l").create();
Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument(
abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription(
"The norm to use, expressed as either a double or \"INF\" if you want to use the Infinite norm. "
+ "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create();
Option maxOpt = obuilder.withLongName("max").withRequired(false).withArgument(
abuilder.withName("max").withMinimum(1).withMaximum(1).create()).withDescription(
"The maximum number of vectors to output. If not specified, then it will loop over all docs")
.withShortName("m").create();
Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false).withArgument(
abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()).withDescription(
"The VectorWriter to use, either seq "
+ "(SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)")
.withShortName("e").create();
Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument(
abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription(
"The minimum document frequency. Default is 1").withShortName("md").create();
Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument(
abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription(
"The max percentage of docs for the DF. Can be used to remove really high frequency terms."
+ " Expressed as an integer between 0 and 100. Default is 99.").withShortName("x").create();
Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
.create();
Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(idFieldOpt).withOption(
outputOpt).withOption(delimiterOpt).withOption(helpOpt).withOption(fieldOpt).withOption(maxOpt)
.withOption(dictOutOpt).withOption(powerOpt).withOption(outWriterOpt).withOption(maxDFPercentOpt)
.withOption(weightOpt).withOption(minDFOpt).create();
try {
Parser parser = new Parser();
parser.setGroup(group);
CommandLine cmdLine = parser.parse(args);
if (cmdLine.hasOption(helpOpt)) {
CommandLineUtil.printHelp(group);
return;
}
// Springify all this
if (cmdLine.hasOption(inputOpt)) { // Lucene case
File file = new File(cmdLine.getValue(inputOpt).toString());
if (!file.isDirectory()) {
throw new IllegalArgumentException("Lucene directory: " + file.getAbsolutePath()
+ " does not exist or is not a directory");
}
long maxDocs = Long.MAX_VALUE;
if (cmdLine.hasOption(maxOpt)) {
maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString());
}
if (maxDocs < 0) {
throw new IllegalArgumentException("maxDocs must be >= 0");
}
Directory dir = FSDirectory.open(file);
IndexReader reader = IndexReader.open(dir, true);
Weight weight;
if (cmdLine.hasOption(weightOpt)) {
String wString = cmdLine.getValue(weightOpt).toString();
if ("tf".equalsIgnoreCase(wString)) {
weight = new TF();
} else if ("tfidf".equalsIgnoreCase(wString)) {
weight = new TFIDF();
} else {
throw new OptionException(weightOpt);
}
} else {
weight = new TFIDF();
}
String field = cmdLine.getValue(fieldOpt).toString();
int minDf = 1;
if (cmdLine.hasOption(minDFOpt)) {
minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString());
}
int maxDFPercent = 99;
if (cmdLine.hasOption(maxDFPercentOpt)) {
maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString());
}
TermInfo termInfo = new CachedTermInfo(reader, field, minDf, maxDFPercent);
VectorMapper mapper = new TFDFMapper(reader, weight, termInfo);
double norm = LuceneIterable.NO_NORMALIZING;
if (cmdLine.hasOption(powerOpt)) {
String power = cmdLine.getValue(powerOpt).toString();
if ("INF".equals(power)) {
norm = Double.POSITIVE_INFINITY;
} else {
norm = Double.parseDouble(power);
}
}
String idField = null;
if (cmdLine.hasOption(idFieldOpt)) {
idField = cmdLine.getValue(idFieldOpt).toString();
}
LuceneIterable iterable;
if (norm == LuceneIterable.NO_NORMALIZING) {
iterable = new LuceneIterable(reader, idField, field, mapper, LuceneIterable.NO_NORMALIZING);
} else {
iterable = new LuceneIterable(reader, idField, field, mapper, norm);
}
String outFile = cmdLine.getValue(outputOpt).toString();
log.info("Output File: {}", outFile);
VectorWriter vectorWriter;
if (cmdLine.hasOption(outWriterOpt)) {
String outWriter = cmdLine.getValue(outWriterOpt).toString();
if ("file".equals(outWriter)) {
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
vectorWriter = new JWriterVectorWriter(writer);
} else {
vectorWriter = getSeqFileWriter(outFile);
}
} else {
vectorWriter = getSeqFileWriter(outFile);
}
long numDocs = vectorWriter.write(iterable, maxDocs);
vectorWriter.close();
log.info("Wrote: {} vectors", numDocs);
String delimiter = cmdLine.hasOption(delimiterOpt) ? cmdLine.getValue(delimiterOpt).toString() : "\t";
File dictOutFile = new File(cmdLine.getValue(dictOutOpt).toString());
log.info("Dictionary Output file: {}", dictOutFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(dictOutFile), Charset.forName("UTF8")));
JWriterTermInfoWriter tiWriter = new JWriterTermInfoWriter(writer, delimiter, field);
tiWriter.write(termInfo);
tiWriter.close();
writer.close();
}
} catch (OptionException e) {
log.error("Exception", e);
CommandLineUtil.printHelp(group);
}
}
| public static void main(String[] args) throws IOException {
DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
ArgumentBuilder abuilder = new ArgumentBuilder();
GroupBuilder gbuilder = new GroupBuilder();
Option inputOpt = obuilder.withLongName("dir").withRequired(true).withArgument(
abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
.withDescription("The Lucene directory").withShortName("d").create();
Option outputOpt = obuilder.withLongName("output").withRequired(true).withArgument(
abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription("The output file")
.withShortName("o").create();
Option fieldOpt = obuilder.withLongName("field").withRequired(true).withArgument(
abuilder.withName("field").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index").withShortName("f").create();
Option idFieldOpt = obuilder.withLongName("idField").withRequired(false).withArgument(
abuilder.withName("idField").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index containing the index. If null, then the Lucene internal doc "
+ "id is used which is prone to error if the underlying index changes").withShortName("i").create();
Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true).withArgument(
abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()).withDescription(
"The output of the dictionary").withShortName("t").create();
Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument(
abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription(
"The kind of weight to use. Currently TF or TFIDF").withShortName("w").create();
Option delimiterOpt = obuilder.withLongName("delimiter").withRequired(false).withArgument(
abuilder.withName("delimiter").withMinimum(1).withMaximum(1).create()).withDescription(
"The delimiter for outputting the dictionary").withShortName("l").create();
Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument(
abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription(
"The norm to use, expressed as either a double or \"INF\" if you want to use the Infinite norm. "
+ "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create();
Option maxOpt = obuilder.withLongName("max").withRequired(false).withArgument(
abuilder.withName("max").withMinimum(1).withMaximum(1).create()).withDescription(
"The maximum number of vectors to output. If not specified, then it will loop over all docs")
.withShortName("m").create();
Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false).withArgument(
abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()).withDescription(
"The VectorWriter to use, either seq "
+ "(SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)")
.withShortName("e").create();
Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument(
abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription(
"The minimum document frequency. Default is 1").withShortName("md").create();
Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument(
abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription(
"The max percentage of docs for the DF. Can be used to remove really high frequency terms."
+ " Expressed as an integer between 0 and 100. Default is 99.").withShortName("x").create();
Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
.create();
Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(idFieldOpt).withOption(
outputOpt).withOption(delimiterOpt).withOption(helpOpt).withOption(fieldOpt).withOption(maxOpt)
.withOption(dictOutOpt).withOption(powerOpt).withOption(outWriterOpt).withOption(maxDFPercentOpt)
.withOption(weightOpt).withOption(minDFOpt).create();
try {
Parser parser = new Parser();
parser.setGroup(group);
CommandLine cmdLine = parser.parse(args);
if (cmdLine.hasOption(helpOpt)) {
CommandLineUtil.printHelp(group);
return;
}
// Springify all this
if (cmdLine.hasOption(inputOpt)) { // Lucene case
File file = new File(cmdLine.getValue(inputOpt).toString());
if (!file.isDirectory()) {
throw new IllegalArgumentException("Lucene directory: " + file.getAbsolutePath()
+ " does not exist or is not a directory");
}
long maxDocs = Long.MAX_VALUE;
if (cmdLine.hasOption(maxOpt)) {
maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString());
}
if (maxDocs < 0) {
throw new IllegalArgumentException("maxDocs must be >= 0");
}
Directory dir = FSDirectory.open(file);
IndexReader reader = IndexReader.open(dir, true);
Weight weight;
if (cmdLine.hasOption(weightOpt)) {
String wString = cmdLine.getValue(weightOpt).toString();
if ("tf".equalsIgnoreCase(wString)) {
weight = new TF();
} else if ("tfidf".equalsIgnoreCase(wString)) {
weight = new TFIDF();
} else {
throw new OptionException(weightOpt);
}
} else {
weight = new TFIDF();
}
String field = cmdLine.getValue(fieldOpt).toString();
int minDf = 1;
if (cmdLine.hasOption(minDFOpt)) {
minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString());
}
int maxDFPercent = 99;
if (cmdLine.hasOption(maxDFPercentOpt)) {
maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString());
}
TermInfo termInfo = new CachedTermInfo(reader, field, minDf, maxDFPercent);
VectorMapper mapper = new TFDFMapper(reader, weight, termInfo);
double norm = LuceneIterable.NO_NORMALIZING;
if (cmdLine.hasOption(powerOpt)) {
String power = cmdLine.getValue(powerOpt).toString();
if ("INF".equals(power)) {
norm = Double.POSITIVE_INFINITY;
} else {
norm = Double.parseDouble(power);
}
}
String idField = null;
if (cmdLine.hasOption(idFieldOpt)) {
idField = cmdLine.getValue(idFieldOpt).toString();
}
LuceneIterable iterable;
if (norm == LuceneIterable.NO_NORMALIZING) {
iterable = new LuceneIterable(reader, idField, field, mapper, LuceneIterable.NO_NORMALIZING);
} else {
iterable = new LuceneIterable(reader, idField, field, mapper, norm);
}
String outFile = cmdLine.getValue(outputOpt).toString();
log.info("Output File: {}", outFile);
VectorWriter vectorWriter;
if (cmdLine.hasOption(outWriterOpt)) {
String outWriter = cmdLine.getValue(outWriterOpt).toString();
if ("file".equals(outWriter)) {
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
vectorWriter = new JWriterVectorWriter(writer);
} else {
vectorWriter = getSeqFileWriter(outFile);
}
} else {
vectorWriter = getSeqFileWriter(outFile);
}
long numDocs = vectorWriter.write(iterable, maxDocs);
vectorWriter.close();
log.info("Wrote: {} vectors", numDocs);
String delimiter = cmdLine.hasOption(delimiterOpt) ? cmdLine.getValue(delimiterOpt).toString() : "\t";
File dictOutFile = new File(cmdLine.getValue(dictOutOpt).toString());
log.info("Dictionary Output file: {}", dictOutFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(dictOutFile), Charset.forName("UTF8")));
JWriterTermInfoWriter tiWriter = new JWriterTermInfoWriter(writer, delimiter, field);
tiWriter.write(termInfo);
tiWriter.close();
writer.close();
}
} catch (OptionException e) {
log.error("Exception", e);
CommandLineUtil.printHelp(group);
}
}
|
diff --git a/src/main/java/org/apache/ws/security/message/WSSecEncrypt.java b/src/main/java/org/apache/ws/security/message/WSSecEncrypt.java
index defec9484..ba9ac7667 100644
--- a/src/main/java/org/apache/ws/security/message/WSSecEncrypt.java
+++ b/src/main/java/org/apache/ws/security/message/WSSecEncrypt.java
@@ -1,689 +1,689 @@
/**
* 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.ws.security.message;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSEncryptionPart;
import org.apache.ws.security.WSSConfig;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.CryptoType;
import org.apache.ws.security.message.token.Reference;
import org.apache.ws.security.message.token.SecurityTokenReference;
import org.apache.ws.security.util.Base64;
import org.apache.ws.security.util.WSSecurityUtil;
import org.apache.xml.security.algorithms.JCEMapper;
import org.apache.xml.security.encryption.EncryptedData;
import org.apache.xml.security.encryption.XMLCipher;
import org.apache.xml.security.encryption.XMLEncryptionException;
import org.apache.xml.security.keys.KeyInfo;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
/**
* Encrypts a parts of a message according to WS Specification, X509 profile,
* and adds the encryption data.
*
* @author Davanum Srinivas ([email protected]).
* @author Werner Dittmann ([email protected]).
*/
public class WSSecEncrypt extends WSSecEncryptedKey {
private static org.apache.commons.logging.Log log =
org.apache.commons.logging.LogFactory.getLog(WSSecEncrypt.class);
protected String symEncAlgo = WSConstants.AES_128;
protected byte[] embeddedKey = null;
protected String embeddedKeyName = null;
/**
* Symmetric key used in the EncrytpedKey.
*/
protected SecretKey symmetricKey = null;
/**
* SecurityTokenReference to be inserted into EncryptedData/keyInfo element.
*/
protected SecurityTokenReference securityTokenReference = null;
/**
* Indicates whether to encrypt the symmetric key into an EncryptedKey
* or not.
*/
private boolean encryptSymmKey = true;
/**
* Custom reference value
*/
private String customReferenceValue;
/**
* True if the encKeyId is a direct reference to a key identifier instead of a URI to a key
*/
private boolean encKeyIdDirectId;
public WSSecEncrypt() {
super();
}
public WSSecEncrypt(WSSConfig config) {
super(config);
}
/**
* Sets the key to use during embedded encryption.
*
* @param key to use during encryption. The key must fit the selected
* symmetrical encryption algorithm
*/
public void setKey(byte[] key) {
embeddedKey = key;
}
/**
* Sets the algorithm to encode the symmetric key.
*
* Default is the <code>WSConstants.KEYTRANSPORT_RSA15</code> algorithm.
*
* @param keyEnc specifies the key encoding algorithm.
* @see WSConstants#KEYTRANSPORT_RSA15
* @see WSConstants#KEYTRANSPORT_RSAOEP
*/
public void setKeyEnc(String keyEnc) {
keyEncAlgo = keyEnc;
}
/**
* Set the key name for EMBEDDED_KEYNAME
*
* @param embeddedKeyName
*/
public void setEmbeddedKeyName(String embeddedKeyName) {
this.embeddedKeyName = embeddedKeyName;
}
/**
* Set the name of the symmetric encryption algorithm to use.
*
* This encryption algorithm is used to encrypt the data. If the algorithm
* is not set then AES128 is used. Refer to WSConstants which algorithms are
* supported.
*
* @param algo Is the name of the encryption algorithm
* @see WSConstants#TRIPLE_DES
* @see WSConstants#AES_128
* @see WSConstants#AES_192
* @see WSConstants#AES_256
*/
public void setSymmetricEncAlgorithm(String algo) {
symEncAlgo = algo;
}
/**
* Get the name of symmetric encryption algorithm to use.
*
* The name of the encryption algorithm to encrypt the data, i.e. the SOAP
* Body. Refer to WSConstants which algorithms are supported.
*
* @return the name of the currently selected symmetric encryption algorithm
* @see WSConstants#TRIPLE_DES
* @see WSConstants#AES_128
* @see WSConstants#AES_192
* @see WSConstants#AES_256
*/
public String getSymmetricEncAlgorithm() {
return symEncAlgo;
}
/**
* Initialize a WSSec Encrypt.
*
* The method prepares and initializes a WSSec Encrypt structure after the
* relevant information was set. After preparation of the token references
* can be added and encrypted.
*
* This method does not add any element to the security header. This must be
* done explicitly.
*
* @param doc The SOAP envelope as <code>Document</code>
* @param crypto An instance of the Crypto API to handle keystore and certificates
* @throws WSSecurityException
*/
public void prepare(Document doc, Crypto crypto) throws WSSecurityException {
document = doc;
//
// If no external key (symmetricalKey) was set generate an encryption
// key (session key) for this Encrypt element. This key will be
// encrypted using the public key of the receiver
//
if (ephemeralKey == null) {
if (symmetricKey == null) {
KeyGenerator keyGen = getKeyGenerator();
symmetricKey = keyGen.generateKey();
}
ephemeralKey = symmetricKey.getEncoded();
}
if (symmetricKey == null) {
symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, ephemeralKey);
}
//
// Get the certificate that contains the public key for the public key
// algorithm that will encrypt the generated symmetric (session) key.
//
if (encryptSymmKey) {
X509Certificate remoteCert = useThisCert;
if (remoteCert == null) {
CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
cryptoType.setAlias(user);
X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
if (certs == null || certs.length <= 0) {
throw new WSSecurityException(
WSSecurityException.FAILURE,
"noUserCertsFound",
new Object[] { user, "encryption" }
);
}
remoteCert = certs[0];
}
prepareInternal(ephemeralKey, remoteCert, crypto);
} else {
encryptedEphemeralKey = ephemeralKey;
}
}
/**
* Builds the SOAP envelope with encrypted Body and adds encrypted key.
*
* This is a convenience method and for backward compatibility. The method
* calls the single function methods in order to perform a <i>one shot
* encryption</i>. This method is compatible with the build method of the
* previous version with the exception of the additional WSSecHeader
* parameter.
*
* @param doc the SOAP envelope as <code>Document</code> with plain text Body
* @param crypto an instance of the Crypto API to handle keystore and Certificates
* @param secHeader the security header element to hold the encrypted key element.
* @return the SOAP envelope with encrypted Body as <code>Document</code>
* @throws WSSecurityException
*/
public Document build(Document doc, Crypto crypto, WSSecHeader secHeader)
throws WSSecurityException {
doDebug = log.isDebugEnabled();
if (keyIdentifierType == WSConstants.EMBEDDED_KEYNAME
|| keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) {
encryptSymmKey = false;
document = doc;
//
// Generate a symmetric key from the specified key (password) for this
// algorithm, and set the cipher into encryption mode.
//
if (symmetricKey == null) {
if (embeddedKey == null) {
throw new WSSecurityException(WSSecurityException.FAILURE, "noKeySupplied");
}
symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, embeddedKey);
}
} else {
prepare(doc, crypto);
}
if (envelope == null) {
envelope = document.getDocumentElement();
}
if (parts == null) {
parts = new ArrayList<WSEncryptionPart>(1);
String soapNamespace = WSSecurityUtil.getSOAPNamespace(envelope);
WSEncryptionPart encP =
new WSEncryptionPart(
WSConstants.ELEM_BODY,
soapNamespace,
"Content"
);
parts.add(encP);
}
if (doDebug) {
log.debug("Beginning Encryption...");
}
Element refs = encryptForRef(null, parts);
if (encryptedKeyElement != null) {
addInternalRefElement(refs);
prependToHeader(secHeader);
} else {
addExternalRefElement(refs, secHeader);
}
if (bstToken != null) {
prependBSTElementToHeader(secHeader);
}
log.debug("Encryption complete.");
return doc;
}
/**
* Encrypt one or more parts or elements of the message.
*
* This method takes a vector of <code>WSEncryptionPart</code> object that
* contain information about the elements to encrypt. The method call the
* encryption method, takes the reference information generated during
* encryption and add this to the <code>xenc:Reference</code> element.
* This method can be called after <code>prepare()</code> and can be
* called multiple times to encrypt a number of parts or elements.
*
* The method generates a <code>xenc:Reference</code> element that <i>must</i>
* be added to this token. See <code>addInternalRefElement()</code>.
*
* If the <code>dataRef</code> parameter is <code>null</code> the method
* creates and initializes a new Reference element.
*
* @param dataRef A <code>xenc:Reference</code> element or <code>null</code>
* @param references A list containing WSEncryptionPart objects
* @return Returns the updated <code>xenc:Reference</code> element
* @throws WSSecurityException
*/
public Element encryptForRef(
Element dataRef,
List<WSEncryptionPart> references
) throws WSSecurityException {
KeyInfo keyInfo = createKeyInfo();
List<String> encDataRefs =
doEncryption(
document, getWsConfig(), keyInfo, symmetricKey, symEncAlgo, references, callbackLookup
);
if (dataRef == null) {
dataRef =
document.createElementNS(
WSConstants.ENC_NS,
WSConstants.ENC_PREFIX + ":ReferenceList"
);
//
// If we're not placing the ReferenceList in an EncryptedKey structure,
// then add the ENC namespace
//
if (!encryptSymmKey) {
WSSecurityUtil.setNamespace(
dataRef, WSConstants.ENC_NS, WSConstants.ENC_PREFIX
);
}
}
return createDataRefList(document, dataRef, encDataRefs);
}
/**
* @deprecated Use encryptForRef(dataRef, references) instead
*/
public Element encryptForInternalRef(Element dataRef, List<WSEncryptionPart> references)
throws WSSecurityException {
return encryptForRef(dataRef, references);
}
/**
* @deprecated Use encryptForRef(dataRef, references) instead
*/
public Element encryptForExternalRef(Element dataRef, List<WSEncryptionPart> references)
throws WSSecurityException {
return encryptForRef(dataRef, references);
}
/**
* Adds the internal Reference element to this Encrypt data.
*
* The reference element <i>must</i> be created by the
* <code>encryptForInternalRef()</code> method. The reference element is
* added to the <code>EncryptedKey</code> element of this encrypt block.
*
* @param dataRef The internal <code>enc:Reference</code> element
*/
public void addInternalRefElement(Element dataRef) {
encryptedKeyElement.appendChild(dataRef);
}
/**
* Adds (prepends) the external Reference element to the Security header.
*
* The reference element <i>must</i> be created by the
* <code>encryptForExternalRef() </code> method. The method prepends the
* reference element in the SecurityHeader.
*
* @param dataRef The external <code>enc:Reference</code> element
* @param secHeader The security header.
*/
public void addExternalRefElement(Element dataRef, WSSecHeader secHeader) {
WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), dataRef);
}
/**
* Perform encryption on the SOAP envelope.
* @param doc The document containing the SOAP envelope as document element
* @param config The WSSConfig from which to generate wsu:ID's
* @param keyInfo The KeyInfo object to set in EncryptedData
* @param secretKey The SecretKey object with which to encrypt data
* @param encryptionAlgorithm The encryption algorithm URI to use
* @param references The list of references to encrypt
* @return a List of references to EncryptedData elements
* @throws WSSecurityException
*/
public static List<String> doEncryption(
Document doc,
WSSConfig config,
KeyInfo keyInfo,
SecretKey secretKey,
String encryptionAlgorithm,
List<WSEncryptionPart> references,
CallbackLookup callbackLookup
) throws WSSecurityException {
XMLCipher xmlCipher = null;
try {
xmlCipher = XMLCipher.getInstance(encryptionAlgorithm);
} catch (XMLEncryptionException ex) {
throw new WSSecurityException(
WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, ex
);
}
List<String> encDataRef = new ArrayList<String>();
for (int part = 0; part < references.size(); part++) {
WSEncryptionPart encPart = references.get(part);
//
// Get the data to encrypt.
//
if (callbackLookup == null) {
callbackLookup = new DOMCallbackLookup(doc);
}
List<Element> elementsToEncrypt =
WSSecurityUtil.findElements(encPart, callbackLookup, doc);
if (elementsToEncrypt == null || elementsToEncrypt.size() == 0) {
throw new WSSecurityException(
WSSecurityException.FAILURE,
"noEncElement",
new Object[] {"{" + encPart.getNamespace() + "}" + encPart.getName()}
);
}
String modifier = encPart.getEncModifier();
for (Element elementToEncrypt : elementsToEncrypt) {
String id =
encryptElement(doc, elementToEncrypt, modifier, config, xmlCipher,
secretKey, keyInfo);
encPart.setEncId(id);
encDataRef.add("#" + id);
}
if (part != (references.size() - 1)) {
try {
keyInfo = new KeyInfo((Element) keyInfo.getElement().cloneNode(true), null);
} catch (Exception ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
}
}
}
return encDataRef;
}
/**
* Encrypt an element.
*/
private static String encryptElement(
Document doc,
Element elementToEncrypt,
String modifier,
WSSConfig config,
XMLCipher xmlCipher,
SecretKey secretKey,
KeyInfo keyInfo
) throws WSSecurityException {
- boolean content = modifier.equals("Content") ? true : false;
+ boolean content = "Content".equals(modifier) ? true : false;
//
// Encrypt data, and set necessary attributes in xenc:EncryptedData
//
String xencEncryptedDataId =
config.getIdAllocator().createId("ED-", elementToEncrypt);
try {
String headerId = "";
if (modifier.equals("Header")) {
Element elem =
doc.createElementNS(
WSConstants.WSSE11_NS, "wsse11:" + WSConstants.ENCRYPTED_HEADER
);
WSSecurityUtil.setNamespace(elem, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
String wsuPrefix =
WSSecurityUtil.setNamespace(elem, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
headerId = config.getIdAllocator().createId("EH-", elementToEncrypt);
elem.setAttributeNS(
WSConstants.WSU_NS, wsuPrefix + ":Id", headerId
);
//
// Add the EncryptedHeader node to the element to be encrypted's parent
// (i.e. the SOAP header). Add the element to be encrypted to the Encrypted
// Header node as well
//
Node parent = elementToEncrypt.getParentNode();
elementToEncrypt = (Element)parent.replaceChild(elem, elementToEncrypt);
elem.appendChild(elementToEncrypt);
NamedNodeMap map = elementToEncrypt.getAttributes();
for (int i = 0; i < map.getLength(); i++) {
Attr attr = (Attr)map.item(i);
if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV)
|| attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) {
String soapEnvPrefix =
WSSecurityUtil.setNamespace(
elem, attr.getNamespaceURI(), WSConstants.DEFAULT_SOAP_PREFIX
);
elem.setAttributeNS(
attr.getNamespaceURI(),
soapEnvPrefix + ":" + attr.getLocalName(),
attr.getValue()
);
}
}
}
xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData encData = xmlCipher.getEncryptedData();
encData.setId(xencEncryptedDataId);
encData.setKeyInfo(keyInfo);
xmlCipher.doFinal(doc, elementToEncrypt, content);
return xencEncryptedDataId;
} catch (Exception ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
}
}
/**
* Create a KeyInfo object
*/
private KeyInfo createKeyInfo() throws WSSecurityException {
KeyInfo keyInfo = new KeyInfo(document);
if (keyIdentifierType == WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER) {
SecurityTokenReference secToken = new SecurityTokenReference(document);
secToken.addWSSENamespace();
if (customReferenceValue != null) {
secToken.setKeyIdentifierEncKeySHA1(customReferenceValue);
} else {
byte[] encodedBytes = WSSecurityUtil.generateDigest(encryptedEphemeralKey);
secToken.setKeyIdentifierEncKeySHA1(Base64.encode(encodedBytes));
}
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
keyInfo.addUnknownElement(secToken.getElement());
} else if (keyIdentifierType == WSConstants.EMBEDDED_KEYNAME) {
keyInfo.addKeyName(embeddedKeyName == null ? user : embeddedKeyName);
} else if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customReferenceValue)) {
SecurityTokenReference secToken = new SecurityTokenReference(document);
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
secToken.setKeyIdentifier(WSConstants.WSS_SAML_KI_VALUE_TYPE, encKeyId);
keyInfo.addUnknownElement(secToken.getElement());
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customReferenceValue)) {
SecurityTokenReference secToken = new SecurityTokenReference(document);
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
secToken.setKeyIdentifier(WSConstants.WSS_SAML2_KI_VALUE_TYPE, encKeyId);
keyInfo.addUnknownElement(secToken.getElement());
} else if (securityTokenReference != null) {
Element tmpE = securityTokenReference.getElement();
tmpE.setAttributeNS(
WSConstants.XMLNS_NS, "xmlns:" + tmpE.getPrefix(), tmpE.getNamespaceURI()
);
keyInfo.addUnknownElement(securityTokenReference.getElement());
} else {
SecurityTokenReference secToken = new SecurityTokenReference(document);
secToken.addWSSENamespace();
Reference ref = new Reference(document);
if (encKeyIdDirectId) {
ref.setURI(encKeyId);
} else {
ref.setURI("#" + encKeyId);
}
if (customReferenceValue != null) {
ref.setValueType(customReferenceValue);
}
secToken.setReference(ref);
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
keyInfo.addUnknownElement(secToken.getElement());
}
Element keyInfoElement = keyInfo.getElement();
keyInfoElement.setAttributeNS(
WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS
);
return keyInfo;
}
private KeyGenerator getKeyGenerator() throws WSSecurityException {
try {
//
// Assume AES as default, so initialize it
//
String keyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(symEncAlgo);
KeyGenerator keyGen = KeyGenerator.getInstance(keyAlgorithm);
if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_128)) {
keyGen.init(128);
} else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_192)) {
keyGen.init(192);
} else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_256)) {
keyGen.init(256);
}
return keyGen;
} catch (NoSuchAlgorithmException e) {
throw new WSSecurityException(
WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e
);
}
}
/**
* Create DOM subtree for <code>xenc:EncryptedKey</code>
*
* @param doc the SOAP envelope parent document
* @param referenceList
* @param encDataRefs
* @return an <code>xenc:EncryptedKey</code> element
*/
public static Element createDataRefList(
Document doc,
Element referenceList,
List<String> encDataRefs
) {
for (String dataReferenceUri : encDataRefs) {
Element dataReference =
doc.createElementNS(
WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":DataReference"
);
dataReference.setAttributeNS(null, "URI", dataReferenceUri);
referenceList.appendChild(dataReference);
}
return referenceList;
}
/**
* @return The symmetric key
*/
public SecretKey getSymmetricKey() {
return symmetricKey;
}
/**
* Set the symmetric key to be used for encryption
*
* @param key
*/
public void setSymmetricKey(SecretKey key) {
this.symmetricKey = key;
}
/**
* @return Return the SecurityTokenRefernce
*/
public SecurityTokenReference getSecurityTokenReference() {
return securityTokenReference;
}
/**
* @param reference
*/
public void setSecurityTokenReference(SecurityTokenReference reference) {
securityTokenReference = reference;
}
public boolean isEncryptSymmKey() {
return encryptSymmKey;
}
public void setEncryptSymmKey(boolean encryptSymmKey) {
this.encryptSymmKey = encryptSymmKey;
}
public void setCustomReferenceValue(String customReferenceValue) {
this.customReferenceValue = customReferenceValue;
}
public void setEncKeyIdDirectId(boolean b) {
encKeyIdDirectId = b;
}
}
| true | true | private static String encryptElement(
Document doc,
Element elementToEncrypt,
String modifier,
WSSConfig config,
XMLCipher xmlCipher,
SecretKey secretKey,
KeyInfo keyInfo
) throws WSSecurityException {
boolean content = modifier.equals("Content") ? true : false;
//
// Encrypt data, and set necessary attributes in xenc:EncryptedData
//
String xencEncryptedDataId =
config.getIdAllocator().createId("ED-", elementToEncrypt);
try {
String headerId = "";
if (modifier.equals("Header")) {
Element elem =
doc.createElementNS(
WSConstants.WSSE11_NS, "wsse11:" + WSConstants.ENCRYPTED_HEADER
);
WSSecurityUtil.setNamespace(elem, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
String wsuPrefix =
WSSecurityUtil.setNamespace(elem, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
headerId = config.getIdAllocator().createId("EH-", elementToEncrypt);
elem.setAttributeNS(
WSConstants.WSU_NS, wsuPrefix + ":Id", headerId
);
//
// Add the EncryptedHeader node to the element to be encrypted's parent
// (i.e. the SOAP header). Add the element to be encrypted to the Encrypted
// Header node as well
//
Node parent = elementToEncrypt.getParentNode();
elementToEncrypt = (Element)parent.replaceChild(elem, elementToEncrypt);
elem.appendChild(elementToEncrypt);
NamedNodeMap map = elementToEncrypt.getAttributes();
for (int i = 0; i < map.getLength(); i++) {
Attr attr = (Attr)map.item(i);
if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV)
|| attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) {
String soapEnvPrefix =
WSSecurityUtil.setNamespace(
elem, attr.getNamespaceURI(), WSConstants.DEFAULT_SOAP_PREFIX
);
elem.setAttributeNS(
attr.getNamespaceURI(),
soapEnvPrefix + ":" + attr.getLocalName(),
attr.getValue()
);
}
}
}
xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData encData = xmlCipher.getEncryptedData();
encData.setId(xencEncryptedDataId);
encData.setKeyInfo(keyInfo);
xmlCipher.doFinal(doc, elementToEncrypt, content);
return xencEncryptedDataId;
} catch (Exception ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
}
}
| private static String encryptElement(
Document doc,
Element elementToEncrypt,
String modifier,
WSSConfig config,
XMLCipher xmlCipher,
SecretKey secretKey,
KeyInfo keyInfo
) throws WSSecurityException {
boolean content = "Content".equals(modifier) ? true : false;
//
// Encrypt data, and set necessary attributes in xenc:EncryptedData
//
String xencEncryptedDataId =
config.getIdAllocator().createId("ED-", elementToEncrypt);
try {
String headerId = "";
if (modifier.equals("Header")) {
Element elem =
doc.createElementNS(
WSConstants.WSSE11_NS, "wsse11:" + WSConstants.ENCRYPTED_HEADER
);
WSSecurityUtil.setNamespace(elem, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
String wsuPrefix =
WSSecurityUtil.setNamespace(elem, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
headerId = config.getIdAllocator().createId("EH-", elementToEncrypt);
elem.setAttributeNS(
WSConstants.WSU_NS, wsuPrefix + ":Id", headerId
);
//
// Add the EncryptedHeader node to the element to be encrypted's parent
// (i.e. the SOAP header). Add the element to be encrypted to the Encrypted
// Header node as well
//
Node parent = elementToEncrypt.getParentNode();
elementToEncrypt = (Element)parent.replaceChild(elem, elementToEncrypt);
elem.appendChild(elementToEncrypt);
NamedNodeMap map = elementToEncrypt.getAttributes();
for (int i = 0; i < map.getLength(); i++) {
Attr attr = (Attr)map.item(i);
if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV)
|| attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) {
String soapEnvPrefix =
WSSecurityUtil.setNamespace(
elem, attr.getNamespaceURI(), WSConstants.DEFAULT_SOAP_PREFIX
);
elem.setAttributeNS(
attr.getNamespaceURI(),
soapEnvPrefix + ":" + attr.getLocalName(),
attr.getValue()
);
}
}
}
xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData encData = xmlCipher.getEncryptedData();
encData.setId(xencEncryptedDataId);
encData.setKeyInfo(keyInfo);
xmlCipher.doFinal(doc, elementToEncrypt, content);
return xencEncryptedDataId;
} catch (Exception ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
}
}
|
diff --git a/src/com/android/calendar/LaunchActivity.java b/src/com/android/calendar/LaunchActivity.java
index b1ded98f..d11a4aca 100644
--- a/src/com/android/calendar/LaunchActivity.java
+++ b/src/com/android/calendar/LaunchActivity.java
@@ -1,109 +1,110 @@
/*
* Copyright (C) 2007 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.calendar;
import com.google.android.googlelogin.GoogleLoginServiceConstants;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.Future2;
import android.accounts.Future2Callback;
import android.accounts.OperationCanceledException;
import android.accounts.Account;
import android.accounts.Constants;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Gmail;
import java.io.IOException;
public class LaunchActivity extends Activity {
static final String KEY_DETAIL_VIEW = "DETAIL_VIEW";
private Bundle mExtras;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mExtras = getIntent().getExtras();
// Our UI is not something intended for the user to see. We just
// stick around until we can figure out what to do next based on
// the current state of the system.
- setVisible(false);
+ // TODO: Removed until framework is fixed in b/2008662
+ // setVisible(false);
// Only try looking for an account if this is the first launch.
if (icicle == null) {
// This will request a Gmail account and if none are present, it will
// invoke SetupWizard to login or create one. The result is returned
// via the Future2Callback.
Bundle bundle = new Bundle();
bundle.putCharSequence("optional_message", getText(R.string.calendar_plug));
AccountManager.get(this).getAuthTokenByFeatures(
GoogleLoginServiceConstants.ACCOUNT_TYPE, Gmail.GMAIL_AUTH_SERVICE,
new String[]{GoogleLoginServiceConstants.FEATURE_GOOGLE_OR_DASHER}, this,
bundle, null /* loginOptions */, new Future2Callback() {
public void run(Future2 future) {
try {
Bundle result = future.getResult();
onAccountsLoaded(new Account(
result.getString(GoogleLoginServiceConstants.AUTH_ACCOUNT_KEY),
result.getString(Constants.ACCOUNT_TYPE_KEY)));
} catch (OperationCanceledException e) {
finish();
} catch (IOException e) {
finish();
} catch (AuthenticatorException e) {
finish();
}
}
}, null /* handler */);
}
}
private void onAccountsLoaded(Account account) {
// Get the data for from this intent, if any
Intent myIntent = getIntent();
Uri myData = myIntent.getData();
// Set up the intent for the start activity
Intent intent = new Intent();
if (myData != null) {
intent.setData(myData);
}
String defaultViewKey = CalendarPreferenceActivity.KEY_START_VIEW;
if (mExtras != null) {
intent.putExtras(mExtras);
if (mExtras.getBoolean(KEY_DETAIL_VIEW, false)) {
defaultViewKey = CalendarPreferenceActivity.KEY_DETAILED_VIEW;
}
}
intent.putExtras(myIntent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String startActivity = prefs.getString(defaultViewKey,
CalendarPreferenceActivity.DEFAULT_START_VIEW);
intent.setClassName(this, startActivity);
startActivity(intent);
finish();
}
}
| true | true | protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mExtras = getIntent().getExtras();
// Our UI is not something intended for the user to see. We just
// stick around until we can figure out what to do next based on
// the current state of the system.
setVisible(false);
// Only try looking for an account if this is the first launch.
if (icicle == null) {
// This will request a Gmail account and if none are present, it will
// invoke SetupWizard to login or create one. The result is returned
// via the Future2Callback.
Bundle bundle = new Bundle();
bundle.putCharSequence("optional_message", getText(R.string.calendar_plug));
AccountManager.get(this).getAuthTokenByFeatures(
GoogleLoginServiceConstants.ACCOUNT_TYPE, Gmail.GMAIL_AUTH_SERVICE,
new String[]{GoogleLoginServiceConstants.FEATURE_GOOGLE_OR_DASHER}, this,
bundle, null /* loginOptions */, new Future2Callback() {
public void run(Future2 future) {
try {
Bundle result = future.getResult();
onAccountsLoaded(new Account(
result.getString(GoogleLoginServiceConstants.AUTH_ACCOUNT_KEY),
result.getString(Constants.ACCOUNT_TYPE_KEY)));
} catch (OperationCanceledException e) {
finish();
} catch (IOException e) {
finish();
} catch (AuthenticatorException e) {
finish();
}
}
}, null /* handler */);
}
}
| protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mExtras = getIntent().getExtras();
// Our UI is not something intended for the user to see. We just
// stick around until we can figure out what to do next based on
// the current state of the system.
// TODO: Removed until framework is fixed in b/2008662
// setVisible(false);
// Only try looking for an account if this is the first launch.
if (icicle == null) {
// This will request a Gmail account and if none are present, it will
// invoke SetupWizard to login or create one. The result is returned
// via the Future2Callback.
Bundle bundle = new Bundle();
bundle.putCharSequence("optional_message", getText(R.string.calendar_plug));
AccountManager.get(this).getAuthTokenByFeatures(
GoogleLoginServiceConstants.ACCOUNT_TYPE, Gmail.GMAIL_AUTH_SERVICE,
new String[]{GoogleLoginServiceConstants.FEATURE_GOOGLE_OR_DASHER}, this,
bundle, null /* loginOptions */, new Future2Callback() {
public void run(Future2 future) {
try {
Bundle result = future.getResult();
onAccountsLoaded(new Account(
result.getString(GoogleLoginServiceConstants.AUTH_ACCOUNT_KEY),
result.getString(Constants.ACCOUNT_TYPE_KEY)));
} catch (OperationCanceledException e) {
finish();
} catch (IOException e) {
finish();
} catch (AuthenticatorException e) {
finish();
}
}
}, null /* handler */);
}
}
|
diff --git a/src/jtermios/linux/JTermiosImpl.java b/src/jtermios/linux/JTermiosImpl.java
index a079836..9d6479f 100755
--- a/src/jtermios/linux/JTermiosImpl.java
+++ b/src/jtermios/linux/JTermiosImpl.java
@@ -1,590 +1,590 @@
/*
* Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs
* 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 Kustaa Nyholm or SpareTimeLabs 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 jtermios.linux;
import java.io.File;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import jtermios.FDSet;
import jtermios.JTermios;
import jtermios.Pollfd;
import jtermios.Termios;
import jtermios.TimeVal;
import jtermios.JTermios.JTermiosInterface;
import jtermios.linux.JTermiosImpl.Linux_C_lib.pollfd;
import jtermios.linux.JTermiosImpl.Linux_C_lib.serial_struct;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.NativeLongByReference;
import static jtermios.JTermios.*;
import static jtermios.JTermios.JTermiosLogging.log;
public class JTermiosImpl implements jtermios.JTermios.JTermiosInterface {
private static String DEVICE_DIR_PATH = "/dev/";
static Linux_C_lib m_Clib = (Linux_C_lib) Native.loadLibrary("c", Linux_C_lib.class);
private final static int TIOCGSERIAL = 0x0000541E;
private final static int TIOCSSERIAL = 0x0000541F;
private final static int ASYNC_SPD_MASK = 0x00001030;
private final static int ASYNC_SPD_CUST = 0x00000030;
private final static int[] m_BaudRates = { //
50, 0000001, //
75, 0000002, //
110, 0000003, //
134, 0000004, //
150, 0000005, //
200, 0000006, //
300, 0000007, //
600, 0000010, //
1200, 0000011, //
1800, 0000012, //
2400, 0000013, //
4800, 0000014, //
9600, 0000015, //
19200, 0000016, //
38400, 0000017, //
57600, 0010001, //
115200, 0010002, //
230400, 0010003, //
460800, 0010004, //
500000, 0010005, //
576000, 0010006, //
921600, 0010007, //
1000000, 0010010, //
1152000, 0010011, //
1500000, 0010012, //
2000000, 0010013, //
2500000, 0010014, //
3000000, 0010015, //
3500000, 0010016, //
4000000, 0010017 //
};
public interface Linux_C_lib extends com.sun.jna.Library {
public IntByReference __error();
public int tcdrain(int fd);
public void cfmakeraw(termios termios);
public int fcntl(int fd, int cmd, int[] arg);
public int fcntl(int fd, int cmd, int arg);
public int ioctl(int fd, int cmd, int[] arg);
public int ioctl(int fd, int cmd, serial_struct arg);
public int open(String path, int flags);
public int close(int fd);
public int tcgetattr(int fd, termios termios);
public int tcsetattr(int fd, int cmd, termios termios);
public int cfsetispeed(termios termios, NativeLong i);
public int cfsetospeed(termios termios, NativeLong i);
public NativeLong cfgetispeed(termios termios);
public NativeLong cfgetospeed(termios termios);
public NativeLong write(int fd, ByteBuffer buffer, NativeLong count);
public NativeLong read(int fd, ByteBuffer buffer, NativeLong count);
public int select(int n, int[] read, int[] write, int[] error, TimeVal timeout);
public int poll(pollfd[] fds, int nfds, int timeout);
public int tcflush(int fd, int qs);
public void perror(String msg);
public int tcsendbreak(int fd, int duration);
static public class TimeVal extends Structure {
public NativeLong tv_sec;
public NativeLong tv_usec;
public TimeVal(jtermios.TimeVal timeout) {
tv_sec = new NativeLong(timeout.tv_sec);
tv_usec = new NativeLong(timeout.tv_usec);
}
}
static public class pollfd extends Structure {
public int fd;
public short events;
public short revents;
public pollfd(Pollfd pfd) {
fd = pfd.fd;
events = pfd.events;
revents = pfd.revents;
}
}
public static class serial_struct extends Structure {
public int type;
public int line;
public int port;
public int irq;
public int flags;
public int xmit_fifo_size;
public int custom_divisor;
public int baud_base;
public short close_delay;
public short io_type;
//public char io_type;
//public char reserved_char;
public int hub6;
public short closing_wait;
public short closing_wait2;
public Pointer iomem_base;
public short iomem_reg_shift;
public int port_high;
public NativeLong iomap_base;
};
static public class termios extends Structure {
public int c_iflag;
public int c_oflag;
public int c_cflag;
public int c_lflag;
public byte c_line;
public byte[] c_cc = new byte[32];
public int c_ispeed;
public int c_ospeed;
public termios() {
}
public termios(jtermios.Termios t) {
c_iflag = t.c_iflag;
c_oflag = t.c_oflag;
c_cflag = t.c_cflag;
c_lflag = t.c_lflag;
System.arraycopy(t.c_cc, 0, c_cc, 0, t.c_cc.length);
c_ispeed = t.c_ispeed;
c_ospeed = t.c_ospeed;
}
public void update(jtermios.Termios t) {
t.c_iflag = c_iflag;
t.c_oflag = c_oflag;
t.c_cflag = c_cflag;
t.c_lflag = c_lflag;
System.arraycopy(c_cc, 0, t.c_cc, 0, t.c_cc.length);
t.c_ispeed = c_ispeed;
t.c_ospeed = c_ospeed;
}
}
}
static private class FDSetImpl extends FDSet {
static final int FD_SET_SIZE = 1024;
static final int NFBBITS = 32;
int[] bits = new int[(FD_SET_SIZE + NFBBITS - 1) / NFBBITS];
public String toString() {
return String.format("%08X%08X", bits[0], bits[1]);
}
}
public JTermiosImpl() {
log = log && log(1, "instantiating %s\n", getClass().getCanonicalName());
//linux/serial.h stuff
FIONREAD = 0x541B; // Looked up manually
//fcntl.h stuff
O_RDWR = 0x00000002;
O_NONBLOCK = 0x00000800;
O_NOCTTY = 0x00000100;
O_NDELAY = 0x00000800;
F_GETFL = 0x00000003;
F_SETFL = 0x00000004;
//errno.h stuff
- EAGAIN = 35;
- EACCES = 22;
+ EAGAIN = 11;
+ EACCES = 13;
EEXIST = 17;
EINTR = 4;
EINVAL = 22;
EIO = 5;
EISDIR = 21;
ELOOP = 40;
EMFILE = 24;
ENAMETOOLONG = 36;
ENFILE = 23;
ENOENT = 2;
ENOSR = 63;
ENOSPC = 28;
ENOTDIR = 20;
ENXIO = 6;
EOVERFLOW = 75;
EROFS = 30;
ENOTSUP = 95;
//termios.h stuff
TIOCM_RNG = 0x00000080;
TIOCM_CAR = 0x00000040;
IGNBRK = 0x00000001;
BRKINT = 0x00000002;
PARMRK = 0x00000008;
INLCR = 0x00000040;
IGNCR = 0x00000080;
ICRNL = 0x00000100;
ECHONL = 0x00000040;
IEXTEN = 0x00008000;
CLOCAL = 0x00000800;
OPOST = 0x00000001;
VSTART = 0x00000008;
TCSANOW = 0x00000000;
VSTOP = 0x00000009;
VMIN = 0x00000006;
VTIME = 0x00000005;
VEOF = 0x00000004;
TIOCMGET = 0x00005415;
TIOCM_CTS = 0x00000020;
TIOCM_DSR = 0x00000100;
TIOCM_RI = 0x00000080;
TIOCM_CD = 0x00000040;
TIOCM_DTR = 0x00000002;
TIOCM_RTS = 0x00000004;
ICANON = 0x00000002;
ECHO = 0x00000008;
ECHOE = 0x00000010;
ISIG = 0x00000001;
TIOCMSET = 0x00005418;
IXON = 0x00000400;
IXOFF = 0x00001000;
IXANY = 0x00000800;
CRTSCTS = 0x80000000;
TCSADRAIN = 0x00000001;
INPCK = 0x00000010;
ISTRIP = 0x00000020;
CSIZE = 0x00000030;
TCIFLUSH = 0x00000000;
TCOFLUSH = 0x00000001;
TCIOFLUSH = 0x00000002;
CS5 = 0x00000000;
CS6 = 0x00000010;
CS7 = 0x00000020;
CS8 = 0x00000030;
CSTOPB = 0x00000040;
CREAD = 0x00000080;
PARENB = 0x00000100;
PARODD = 0x00000200;
B0 = 0;
B50 = 1;
B75 = 2;
B110 = 3;
B134 = 4;
B150 = 5;
B200 = 6;
B300 = 7;
B600 = 8;
- B1200 = 8;
+ B1200 = 9;
B1800 = 10;
B2400 = 11;
B4800 = 12;
B9600 = 13;
B19200 = 14;
B38400 = 15;
B57600 = 4097;
B115200 = 4098;
B230400 = 4099;
//poll.h stuff
POLLIN = 0x0001;
POLLPRI = 0x0002;
POLLOUT = 0x0004;
POLLERR = 0x0008;
POLLNVAL = 0x0020;
//select.h stuff
}
public int errno() {
return Native.getLastError();
}
public void cfmakeraw(Termios termios) {
Linux_C_lib.termios t = new Linux_C_lib.termios(termios);
m_Clib.cfmakeraw(t);
t.update(termios);
}
public int fcntl(int fd, int cmd, int[] arg) {
return m_Clib.fcntl(fd, cmd, arg);
}
public int fcntl(int fd, int cmd, int arg) {
return m_Clib.fcntl(fd, cmd, arg);
}
public int tcdrain(int fd) {
return m_Clib.tcdrain(fd);
}
public int cfgetispeed(Termios termios) {
return m_Clib.cfgetispeed(new Linux_C_lib.termios(termios)).intValue();
}
public int cfgetospeed(Termios termios) {
return m_Clib.cfgetospeed(new Linux_C_lib.termios(termios)).intValue();
}
public int cfsetispeed(Termios termios, int speed) {
Linux_C_lib.termios t = new Linux_C_lib.termios(termios);
int ret = m_Clib.cfsetispeed(t, new NativeLong(speed));
t.update(termios);
return ret;
}
public int cfsetospeed(Termios termios, int speed) {
Linux_C_lib.termios t = new Linux_C_lib.termios(termios);
int ret = m_Clib.cfsetospeed(t, new NativeLong(speed));
t.update(termios);
return ret;
}
public int open(String s, int t) {
if (s != null && !s.startsWith("/"))
s = DEVICE_DIR_PATH + s;
return m_Clib.open(s, t);
}
public int read(int fd, byte[] buffer, int len) {
return m_Clib.read(fd, ByteBuffer.wrap(buffer), new NativeLong(len)).intValue();
}
public int write(int fd, byte[] buffer, int len) {
return m_Clib.write(fd, ByteBuffer.wrap(buffer), new NativeLong(len)).intValue();
}
public int close(int fd) {
return m_Clib.close(fd);
}
public int tcflush(int fd, int b) {
return m_Clib.tcflush(fd, b);
}
public int tcgetattr(int fd, Termios termios) {
Linux_C_lib.termios t = new Linux_C_lib.termios();
int ret = m_Clib.tcgetattr(fd, t);
t.update(termios);
return ret;
}
public void perror(String msg) {
m_Clib.perror(msg);
}
public int tcsendbreak(int fd, int duration) {
// If duration is not zero, it sends zero-valued bits for duration*N seconds,
// where N is at least 0.25, and not more than 0.5.
return m_Clib.tcsendbreak(fd, duration / 250);
}
public int tcsetattr(int fd, int cmd, Termios termios) {
return m_Clib.tcsetattr(fd, cmd, new Linux_C_lib.termios(termios));
}
public void FD_CLR(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] &= ~(1 << (fd % FDSetImpl.NFBBITS));
}
public boolean FD_ISSET(int fd, FDSet set) {
if (set == null)
return false;
FDSetImpl p = (FDSetImpl) set;
return (p.bits[fd / FDSetImpl.NFBBITS] & (1 << (fd % FDSetImpl.NFBBITS))) != 0;
}
public void FD_SET(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] |= 1 << (fd % FDSetImpl.NFBBITS);
}
public void FD_ZERO(FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
java.util.Arrays.fill(p.bits, 0);
}
public int select(int nfds, FDSet rfds, FDSet wfds, FDSet efds, TimeVal timeout) {
Linux_C_lib.TimeVal tout = null;
if (timeout != null)
tout = new Linux_C_lib.TimeVal(timeout);
int[] r = rfds != null ? ((FDSetImpl) rfds).bits : null;
int[] w = wfds != null ? ((FDSetImpl) wfds).bits : null;
int[] e = efds != null ? ((FDSetImpl) efds).bits : null;
return m_Clib.select(nfds, r, w, e, tout);
}
public int poll(Pollfd fds[], int nfds, int timeout) {
pollfd[] pfds = new pollfd[fds.length];
for (int i = 0; i < nfds; i++)
pfds[i] = new pollfd(fds[i]);
int ret = m_Clib.poll(pfds, nfds, timeout);
for(int i = 0; i < nfds; i++)
fds[i].revents = pfds[i].revents;
return ret;
}
public FDSet newFDSet() {
return new FDSetImpl();
}
public int ioctl(int fd, int cmd, int[] data) {
return m_Clib.ioctl(fd, cmd, data);
}
// This ioctl is Linux specific, so keep it private for now
private int ioctl(int fd, int cmd, serial_struct data) {
// Do the logging here as this does not go through the JTermios which normally does the logging
log = log && log(5, "> ioctl(%d,%d,%s)\n", fd, cmd, data);
int ret = m_Clib.ioctl(fd, cmd, data);
log = log && log(3, "< tcsetattr(%d,%d,%s) => %d\n", fd, cmd, data, ret);
return ret;
}
public String getPortNamePattern() {
return "^tty.*";
}
public List<String> getPortList() {
File dir = new File(DEVICE_DIR_PATH);
if (!dir.isDirectory()) {
log = log && log(1, "device directory %s does not exist\n", DEVICE_DIR_PATH);
return null;
}
String[] devs = dir.list();
LinkedList<String> list = new LinkedList<String>();
Pattern p = JTermios.getPortNamePattern(this);
if (devs != null) {
for (int i = 0; i < devs.length; i++) {
String s = devs[i];
if (p.matcher(s).matches())
list.add(s);
}
}
return list;
}
public void shutDown() {
}
public int setspeed(int fd, Termios termios, int speed) {
int c = speed;
int r;
for (int i = 0; i < m_BaudRates.length; i += 2) {
if (m_BaudRates[i] == speed) {
// found the baudrate from the table
// in case custom divisor was in use, turn it off first
serial_struct ss = new serial_struct();
// not every driver supports TIOCGSERIAL, so if it fails, just ignore it
if ((r = ioctl(fd, TIOCGSERIAL, ss)) == 0) {
ss.flags &= ~ASYNC_SPD_MASK;
if ((r = ioctl(fd, TIOCSSERIAL, ss)) != 0)
return r;
}
// now set the speed with the constant from the table
c = m_BaudRates[i + 1];
if ((r = JTermios.cfsetispeed(termios, c)) != 0)
return r;
if ((r = JTermios.cfsetospeed(termios, c)) != 0)
return r;
if ((r = JTermios.tcsetattr(fd, TCSANOW, termios)) != 0)
return r;
return 0;
}
}
// baudrate not defined in the table, try custom divisor approach
// configure port to use custom speed instead of 38400
serial_struct ss = new serial_struct();
if ((r = ioctl(fd, TIOCGSERIAL, ss)) != 0)
return r;
ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
ss.custom_divisor = (ss.baud_base + (speed / 2)) / speed;
int closestSpeed = ss.baud_base / ss.custom_divisor;
if (closestSpeed < speed * 98 / 100 || closestSpeed > speed * 102 / 100) {
log = log && log(1, "best available baudrate %d not close enough to requested %d \n", closestSpeed, speed);
return -1;
}
if ((r = ioctl(fd, TIOCSSERIAL, ss)) != 0)
return r;
if ((r = JTermios.cfsetispeed(termios, B38400)) != 0)
return r;
if ((r = JTermios.cfsetospeed(termios, B38400)) != 0)
return r;
if ((r = JTermios.tcsetattr(fd, TCSANOW, termios)) != 0)
return r;
return 0;
}
}
| false | true | public JTermiosImpl() {
log = log && log(1, "instantiating %s\n", getClass().getCanonicalName());
//linux/serial.h stuff
FIONREAD = 0x541B; // Looked up manually
//fcntl.h stuff
O_RDWR = 0x00000002;
O_NONBLOCK = 0x00000800;
O_NOCTTY = 0x00000100;
O_NDELAY = 0x00000800;
F_GETFL = 0x00000003;
F_SETFL = 0x00000004;
//errno.h stuff
EAGAIN = 35;
EACCES = 22;
EEXIST = 17;
EINTR = 4;
EINVAL = 22;
EIO = 5;
EISDIR = 21;
ELOOP = 40;
EMFILE = 24;
ENAMETOOLONG = 36;
ENFILE = 23;
ENOENT = 2;
ENOSR = 63;
ENOSPC = 28;
ENOTDIR = 20;
ENXIO = 6;
EOVERFLOW = 75;
EROFS = 30;
ENOTSUP = 95;
//termios.h stuff
TIOCM_RNG = 0x00000080;
TIOCM_CAR = 0x00000040;
IGNBRK = 0x00000001;
BRKINT = 0x00000002;
PARMRK = 0x00000008;
INLCR = 0x00000040;
IGNCR = 0x00000080;
ICRNL = 0x00000100;
ECHONL = 0x00000040;
IEXTEN = 0x00008000;
CLOCAL = 0x00000800;
OPOST = 0x00000001;
VSTART = 0x00000008;
TCSANOW = 0x00000000;
VSTOP = 0x00000009;
VMIN = 0x00000006;
VTIME = 0x00000005;
VEOF = 0x00000004;
TIOCMGET = 0x00005415;
TIOCM_CTS = 0x00000020;
TIOCM_DSR = 0x00000100;
TIOCM_RI = 0x00000080;
TIOCM_CD = 0x00000040;
TIOCM_DTR = 0x00000002;
TIOCM_RTS = 0x00000004;
ICANON = 0x00000002;
ECHO = 0x00000008;
ECHOE = 0x00000010;
ISIG = 0x00000001;
TIOCMSET = 0x00005418;
IXON = 0x00000400;
IXOFF = 0x00001000;
IXANY = 0x00000800;
CRTSCTS = 0x80000000;
TCSADRAIN = 0x00000001;
INPCK = 0x00000010;
ISTRIP = 0x00000020;
CSIZE = 0x00000030;
TCIFLUSH = 0x00000000;
TCOFLUSH = 0x00000001;
TCIOFLUSH = 0x00000002;
CS5 = 0x00000000;
CS6 = 0x00000010;
CS7 = 0x00000020;
CS8 = 0x00000030;
CSTOPB = 0x00000040;
CREAD = 0x00000080;
PARENB = 0x00000100;
PARODD = 0x00000200;
B0 = 0;
B50 = 1;
B75 = 2;
B110 = 3;
B134 = 4;
B150 = 5;
B200 = 6;
B300 = 7;
B600 = 8;
B1200 = 8;
B1800 = 10;
B2400 = 11;
B4800 = 12;
B9600 = 13;
B19200 = 14;
B38400 = 15;
B57600 = 4097;
B115200 = 4098;
B230400 = 4099;
//poll.h stuff
POLLIN = 0x0001;
POLLPRI = 0x0002;
POLLOUT = 0x0004;
POLLERR = 0x0008;
POLLNVAL = 0x0020;
//select.h stuff
}
| public JTermiosImpl() {
log = log && log(1, "instantiating %s\n", getClass().getCanonicalName());
//linux/serial.h stuff
FIONREAD = 0x541B; // Looked up manually
//fcntl.h stuff
O_RDWR = 0x00000002;
O_NONBLOCK = 0x00000800;
O_NOCTTY = 0x00000100;
O_NDELAY = 0x00000800;
F_GETFL = 0x00000003;
F_SETFL = 0x00000004;
//errno.h stuff
EAGAIN = 11;
EACCES = 13;
EEXIST = 17;
EINTR = 4;
EINVAL = 22;
EIO = 5;
EISDIR = 21;
ELOOP = 40;
EMFILE = 24;
ENAMETOOLONG = 36;
ENFILE = 23;
ENOENT = 2;
ENOSR = 63;
ENOSPC = 28;
ENOTDIR = 20;
ENXIO = 6;
EOVERFLOW = 75;
EROFS = 30;
ENOTSUP = 95;
//termios.h stuff
TIOCM_RNG = 0x00000080;
TIOCM_CAR = 0x00000040;
IGNBRK = 0x00000001;
BRKINT = 0x00000002;
PARMRK = 0x00000008;
INLCR = 0x00000040;
IGNCR = 0x00000080;
ICRNL = 0x00000100;
ECHONL = 0x00000040;
IEXTEN = 0x00008000;
CLOCAL = 0x00000800;
OPOST = 0x00000001;
VSTART = 0x00000008;
TCSANOW = 0x00000000;
VSTOP = 0x00000009;
VMIN = 0x00000006;
VTIME = 0x00000005;
VEOF = 0x00000004;
TIOCMGET = 0x00005415;
TIOCM_CTS = 0x00000020;
TIOCM_DSR = 0x00000100;
TIOCM_RI = 0x00000080;
TIOCM_CD = 0x00000040;
TIOCM_DTR = 0x00000002;
TIOCM_RTS = 0x00000004;
ICANON = 0x00000002;
ECHO = 0x00000008;
ECHOE = 0x00000010;
ISIG = 0x00000001;
TIOCMSET = 0x00005418;
IXON = 0x00000400;
IXOFF = 0x00001000;
IXANY = 0x00000800;
CRTSCTS = 0x80000000;
TCSADRAIN = 0x00000001;
INPCK = 0x00000010;
ISTRIP = 0x00000020;
CSIZE = 0x00000030;
TCIFLUSH = 0x00000000;
TCOFLUSH = 0x00000001;
TCIOFLUSH = 0x00000002;
CS5 = 0x00000000;
CS6 = 0x00000010;
CS7 = 0x00000020;
CS8 = 0x00000030;
CSTOPB = 0x00000040;
CREAD = 0x00000080;
PARENB = 0x00000100;
PARODD = 0x00000200;
B0 = 0;
B50 = 1;
B75 = 2;
B110 = 3;
B134 = 4;
B150 = 5;
B200 = 6;
B300 = 7;
B600 = 8;
B1200 = 9;
B1800 = 10;
B2400 = 11;
B4800 = 12;
B9600 = 13;
B19200 = 14;
B38400 = 15;
B57600 = 4097;
B115200 = 4098;
B230400 = 4099;
//poll.h stuff
POLLIN = 0x0001;
POLLPRI = 0x0002;
POLLOUT = 0x0004;
POLLERR = 0x0008;
POLLNVAL = 0x0020;
//select.h stuff
}
|
diff --git a/src/com/funkymonkeysoftware/adm/checker/CheckerModel.java b/src/com/funkymonkeysoftware/adm/checker/CheckerModel.java
index d379871..3507b08 100644
--- a/src/com/funkymonkeysoftware/adm/checker/CheckerModel.java
+++ b/src/com/funkymonkeysoftware/adm/checker/CheckerModel.java
@@ -1,311 +1,311 @@
package com.funkymonkeysoftware.adm.checker;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Observable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.util.Log;
import com.funkymonkeysoftware.adm.DownloadsDBOpenHelper;
/**
* Model representative of the ADM link checker.
*
* <p>This class holds the internal state of the Link Checker for ADM.
* In good old fashioned MVC style, the Activity (which acts as view and
* controller) communicates with this class to add, check and remove URLS
* within the ADM database. The model can also pass URLS on to the downloader
* by changing their status to pending in the database.</p>
*
* @author James Ravenscroft
*
*/
public class CheckerModel extends Observable{
/**
* Instance of the SQL database that should be used for the checker
*/
private DownloadsDBOpenHelper dbhelper;
/**
* Keep a list of selected URLs i.e. that the user has tapped
*/
private LinkedList<CheckerLink> checkerLinks;
public CheckerModel(Context c){
//set up connection to the SQLite database
dbhelper = new DownloadsDBOpenHelper(c);
//set up the checkerLinks map
checkerLinks = new LinkedList<CheckerLink>();
}
/**
* Add a new URL to the database
*
* This method will add a given URL to the downloads database provided
* that the url is not a duplicate.
*
* @param url
*/
public void addURL(String url) {
SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM downloads WHERE url=?",
new String[]{url});
if(c.moveToFirst()) return;
//otherwise carry out the insert
ContentValues values = new ContentValues();
values.put("url", url);
values.put("status", "unchecked");
db.insert("downloads", null, values);
}
/**
* Select links from the database and keep in the model
*
* @throws MalformedURLException
*/
public void loadLinks() throws MalformedURLException{
SQLiteDatabase db = dbhelper.getReadableDatabase();
//clear the list of links first
checkerLinks = new LinkedList<CheckerLink>();
Cursor c = db.rawQuery("SELECT url,status,filesize" +
" FROM downloads WHERE status IN ('online'," +
"'unchecked','offline')", null);
while(c.moveToNext()){
CheckerLink l = new CheckerLink(c.getString(0),
c.getString(1),
true,
c.getLong(2));
checkerLinks.add(l);
Log.v("linkchecker",String.valueOf(c.getLong(2)));
}
}
public int getLinkCount(){
return checkerLinks.size();
}
/**
* Return a collection of CheckerLink objects represented by this model
*
* @return
*/
public Collection<CheckerLink> getLinks(){
return new LinkedList<CheckerLink>(checkerLinks);
}
/**
* Find urls with offline status and select them
*/
public void selectOffline(){
for(CheckerLink l : checkerLinks) {
if(l.getStatus().equals("offline"))
l.setSelected(true);
else
l.setSelected(false);
}
}
/**-
* Remove urls that have been selected for deletion
*/
public void removeSelected(){
LinkedList<String> removeURLS = new LinkedList<String>();
int i=0;
for( CheckerLink link : getLinks()) {
if(link.isSelected()){
removeURLS.add(link.getURL().toString());
checkerLinks.remove(link);
}
i++;
}
if(removeURLS.size() > 0){
String where = "(";
for(i=0; i < removeURLS.size() - 1; i++){
where += "?,";
}
//add the last questionmark with no comma
where += "? )";
SQLiteDatabase db = dbhelper.getWritableDatabase();
db.delete("downloads", "url IN " + where,
removeURLS.toArray(new String[removeURLS.size()]));
//close the database
db.close();
}
}
/**
* Method used to move selected URLS to the download queue
*/
public void downloadSelected(){
LinkedList<String> downloadURLS = new LinkedList<String>();
int i=0;
for( CheckerLink link : getLinks()) {
if(link.isSelected()){
downloadURLS.add(link.getURL().toString());
- checkerLinks.remove(i);
+ checkerLinks.remove(link);
}
i++;
}
if(downloadURLS.size() > 0){
String where = "(";
for(i=0; i < downloadURLS.size() - 1; i++){
where += "?,";
}
//add the last questionmark with no comma
where += "? )";
SQLiteDatabase db = dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("status", "pending");
db.update("downloads", values, "url IN " + where,
downloadURLS.toArray(new String[downloadURLS.size()]));
//close the database
db.close();
}
}
/**
* Create a new instance of the LinkCheckerTask and runs it
*/
public void checkLinks() {
LinkCheckerTask lc = new LinkCheckerTask();
//run the link checker on the links
lc.execute();
}
/**
* Either select or deselect a known URL
*
* @param url The URL that should exist in the hashmap
* @param selected whether this element is selected or not
*/
public void selectURL(String url, boolean selected){
//look up the link in the list
for(CheckerLink l : checkerLinks){
if(l.getURL().equals(url)){
//update the selected element#
l.setSelected(selected);
return;
}
}
}
/**
* This class runs URLCheckers over all the URLs
*
* @author James Ravenscroft
*
*/
private class LinkCheckerTask extends AsyncTask<Void, Integer, Void> {
protected Void doInBackground(Void... params) {
ILinkChecker chk = new HTTPChecker();
int currentLink = 1;
for(CheckerLink l : checkerLinks){
try{
chk.checkURL(l);
} catch (IOException e) {
//if there was an IO exception, assume it to be offline
l.setStatus("offline");
}
//publish the current link progress
publishProgress(currentLink);
currentLink++;
}
return null;
}
/**
* When an update to the progress is made, update the shiny!
*
*/
protected void onProgressUpdate(Integer... progress){
setChanged();
notifyObservers(progress[0]);
}
/**
* Method executed when all links have been checked.
*
* @param result <p>An array of strings that map directly to
* each of the input URLs</p>
*/
protected void onPostExecute(Void result){
SQLiteDatabase db = dbhelper.getWritableDatabase();
//iterate through all links and update them in the database
for(CheckerLink l : checkerLinks){
ContentValues values = new ContentValues();
values.put("status", l.getStatus());
values.put("filesize", l.getContentLength());
Log.v("linkchecker", values.get("filesize").toString());
db.update("downloads", values, "url=?", new String[]{l.getURL().toString()});
}
//tell the model observers the check is complete
setChanged();
notifyObservers(101);
}
}
}
| true | true | public void downloadSelected(){
LinkedList<String> downloadURLS = new LinkedList<String>();
int i=0;
for( CheckerLink link : getLinks()) {
if(link.isSelected()){
downloadURLS.add(link.getURL().toString());
checkerLinks.remove(i);
}
i++;
}
if(downloadURLS.size() > 0){
String where = "(";
for(i=0; i < downloadURLS.size() - 1; i++){
where += "?,";
}
//add the last questionmark with no comma
where += "? )";
SQLiteDatabase db = dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("status", "pending");
db.update("downloads", values, "url IN " + where,
downloadURLS.toArray(new String[downloadURLS.size()]));
//close the database
db.close();
}
}
| public void downloadSelected(){
LinkedList<String> downloadURLS = new LinkedList<String>();
int i=0;
for( CheckerLink link : getLinks()) {
if(link.isSelected()){
downloadURLS.add(link.getURL().toString());
checkerLinks.remove(link);
}
i++;
}
if(downloadURLS.size() > 0){
String where = "(";
for(i=0; i < downloadURLS.size() - 1; i++){
where += "?,";
}
//add the last questionmark with no comma
where += "? )";
SQLiteDatabase db = dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("status", "pending");
db.update("downloads", values, "url IN " + where,
downloadURLS.toArray(new String[downloadURLS.size()]));
//close the database
db.close();
}
}
|
diff --git a/se/hello-world/src/main/java/org/jboss/weld/environment/se/example/simple/HelloWorld.java b/se/hello-world/src/main/java/org/jboss/weld/environment/se/example/simple/HelloWorld.java
index 79de20a36..523f3530d 100644
--- a/se/hello-world/src/main/java/org/jboss/weld/environment/se/example/simple/HelloWorld.java
+++ b/se/hello-world/src/main/java/org/jboss/weld/environment/se/example/simple/HelloWorld.java
@@ -1,53 +1,55 @@
/**
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.weld.environment.se.example.simple;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import org.jboss.weld.environment.se.events.ContainerInitialized;
import javax.inject.Inject;
/**
* @author Peter Royle
*/
@ApplicationScoped
public class HelloWorld
{
@Inject
CommandLineArgsValidator argsValidator;
public HelloWorld()
{
}
/**
* Prints a hello message using the first name.
* @param firstName The first name.
*/
public void printHello( @Observes ContainerInitialized init )
{
if (!argsValidator.hasErrors())
{
System.out.println( "Hello " + argsValidator.getValidParameters().get( 0 ) );
} else
{
- System.out.println( "Please provide just one argument: your first name" );
+ for (String error : argsValidator.getErrors()) {
+ System.out.println( error );
+ }
}
}
}
| true | true | public void printHello( @Observes ContainerInitialized init )
{
if (!argsValidator.hasErrors())
{
System.out.println( "Hello " + argsValidator.getValidParameters().get( 0 ) );
} else
{
System.out.println( "Please provide just one argument: your first name" );
}
}
| public void printHello( @Observes ContainerInitialized init )
{
if (!argsValidator.hasErrors())
{
System.out.println( "Hello " + argsValidator.getValidParameters().get( 0 ) );
} else
{
for (String error : argsValidator.getErrors()) {
System.out.println( error );
}
}
}
|
diff --git a/src/main/java/de/hypoport/twitterwall/config/TwitterConfiguration.java b/src/main/java/de/hypoport/twitterwall/config/TwitterConfiguration.java
index a78d0ff..4f92dd3 100644
--- a/src/main/java/de/hypoport/twitterwall/config/TwitterConfiguration.java
+++ b/src/main/java/de/hypoport/twitterwall/config/TwitterConfiguration.java
@@ -1,40 +1,39 @@
package de.hypoport.twitterwall.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class TwitterConfiguration {
static Logger logger = LoggerFactory.getLogger(TwitterConfiguration.class);
private String consumerKey;
private String consumerSecret;
public TwitterConfiguration() {
this.consumerKey = System.getProperty("consumerKey", System.getenv("consumerKey"));
this.consumerSecret = System.getProperty("consumerSecret", System.getenv("consumerSecret"));
}
public boolean isFullyConfigured() {
boolean fullyConfigured = consumerKey != null && consumerSecret != null && !consumerKey.isEmpty() && !consumerSecret.isEmpty();
- fullyConfigured = false;
if (!fullyConfigured) {
logger.warn("No configuration for Twitter found.\n" +
"The search service is disabled and will only return mock data!\n" +
"Please provide 'consumerKey' and 'consumerSecret' variables as environment variable OR as system property.");
} else {
logger.info("Found Twitter access tokes (consumerKey and consumerSecret).");
}
return fullyConfigured;
}
public String getConsumerKey() {
return consumerKey;
}
public String getConsumerSecret() {
return consumerSecret;
}
}
| true | true | public boolean isFullyConfigured() {
boolean fullyConfigured = consumerKey != null && consumerSecret != null && !consumerKey.isEmpty() && !consumerSecret.isEmpty();
fullyConfigured = false;
if (!fullyConfigured) {
logger.warn("No configuration for Twitter found.\n" +
"The search service is disabled and will only return mock data!\n" +
"Please provide 'consumerKey' and 'consumerSecret' variables as environment variable OR as system property.");
} else {
logger.info("Found Twitter access tokes (consumerKey and consumerSecret).");
}
return fullyConfigured;
}
| public boolean isFullyConfigured() {
boolean fullyConfigured = consumerKey != null && consumerSecret != null && !consumerKey.isEmpty() && !consumerSecret.isEmpty();
if (!fullyConfigured) {
logger.warn("No configuration for Twitter found.\n" +
"The search service is disabled and will only return mock data!\n" +
"Please provide 'consumerKey' and 'consumerSecret' variables as environment variable OR as system property.");
} else {
logger.info("Found Twitter access tokes (consumerKey and consumerSecret).");
}
return fullyConfigured;
}
|
diff --git a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectGroupAction.java b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectGroupAction.java
index c1d3ec0f7..dabf12c59 100644
--- a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectGroupAction.java
+++ b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/ProjectGroupAction.java
@@ -1,675 +1,675 @@
package org.apache.maven.continuum.web.action;
/*
* 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.
*/
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectDependency;
import org.apache.maven.continuum.model.project.ProjectGroup;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.apache.maven.continuum.web.bean.ProjectGroupUserBean;
import org.apache.maven.continuum.web.exception.AuthorizationRequiredException;
import org.codehaus.plexus.redback.rbac.RBACManager;
import org.codehaus.plexus.redback.rbac.RbacManagerException;
import org.codehaus.plexus.redback.rbac.RbacObjectNotFoundException;
import org.codehaus.plexus.redback.rbac.Role;
import org.codehaus.plexus.redback.role.RoleManager;
import org.codehaus.plexus.redback.role.RoleManagerException;
import org.codehaus.plexus.redback.users.User;
import org.codehaus.plexus.redback.users.UserManager;
import org.codehaus.plexus.util.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* ProjectGroupAction:
*
* @author Jesse McConnell <[email protected]>
* @version $Id$
* @plexus.component role="com.opensymphony.xwork.Action" role-hint="projectGroup"
*/
public class ProjectGroupAction
extends ContinuumConfirmAction
{
private final static Map FILTER_CRITERIA = new HashMap();
static
{
FILTER_CRITERIA.put( "username", "Username contains" );
FILTER_CRITERIA.put( "fullName", "Name contains" );
FILTER_CRITERIA.put( "email", "Email contains" );
}
/**
* @plexus.requirement role-hint="cached"
*/
private UserManager manager;
/**
* @plexus.requirement role-hint="cached"
*/
private RBACManager rbac;
/**
* @plexus.requirement role-hint="default"
*/
private RoleManager roleManager;
private int projectGroupId;
private ProjectGroup projectGroup;
private String name;
private String description;
private Map projects = new HashMap();
private Map projectGroups = new HashMap();
private boolean confirmed;
private boolean projectInCOQueue = false;
private Collection projectList;
private List projectGroupUsers;
private String filterProperty;
private String filterKey;
private boolean ascending = true;
private Collection groupProjects;
private int releaseProjectId;
public String summary()
throws ContinuumException
{
try
{
checkViewProjectGroupAuthorization( getProjectGroupName() );
}
catch ( AuthorizationRequiredException authzE )
{
addActionError( authzE.getMessage() );
return REQUIRES_AUTHORIZATION;
}
projectGroup = getProjectGroup( projectGroupId );
return SUCCESS;
}
public String members()
throws ContinuumException
{
try
{
checkViewProjectGroupAuthorization( getProjectGroupName() );
}
catch ( AuthorizationRequiredException authzE )
{
addActionError( authzE.getMessage() );
return REQUIRES_AUTHORIZATION;
}
projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId );
groupProjects = projectGroup.getProjects();
populateProjectGroupUsers( projectGroup );
return SUCCESS;
}
public Collection getGroupProjects()
throws ContinuumException
{
return groupProjects;
}
public String buildDefinitions()
throws ContinuumException
{
return summary();
}
public String notifiers()
throws ContinuumException
{
return summary();
}
public String remove()
throws ContinuumException
{
try
{
checkRemoveProjectGroupAuthorization( getProjectGroupName() );
}
catch ( AuthorizationRequiredException authzE )
{
addActionError( authzE.getMessage() );
return REQUIRES_AUTHORIZATION;
}
if ( confirmed )
{
getContinuum().removeProjectGroup( projectGroupId );
}
else
{
name = getProjectGroupName();
return CONFIRM;
}
return SUCCESS;
}
public String edit()
throws ContinuumException
{
try
{
checkModifyProjectGroupAuthorization( getProjectGroupName() );
}
catch ( AuthorizationRequiredException authzE )
{
addActionError( authzE.getMessage() );
return REQUIRES_AUTHORIZATION;
}
projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId );
name = projectGroup.getName();
description = projectGroup.getDescription();
projectList = projectGroup.getProjects();
if ( projectList != null )
{
Iterator proj = projectList.iterator();
while ( proj.hasNext() )
{
Project p = (Project) proj.next();
if ( getContinuum().isInCheckoutQueue( p.getId() ) )
{
projectInCOQueue = true;
}
projects.put( p, new Integer( p.getProjectGroup().getId() ) );
}
}
Iterator proj_group = getContinuum().getAllProjectGroupsWithProjects().iterator();
while ( proj_group.hasNext() )
{
ProjectGroup pg = (ProjectGroup) proj_group.next();
projectGroups.put( new Integer( pg.getId() ), pg.getName() );
}
return SUCCESS;
}
public String save()
throws ContinuumException
{
try
{
checkModifyProjectGroupAuthorization( getProjectGroupName() );
}
catch ( AuthorizationRequiredException authzE )
{
addActionError( authzE.getMessage() );
return REQUIRES_AUTHORIZATION;
}
if ( name != null && name.equals( "" ) )
{
addActionError( "projectGroup.error.name.required" );
return INPUT;
}
else if ( name != null && name.trim().equals( "" ) )
{
addActionError( "projectGroup.error.name.cannot.be.spaces" );
return INPUT;
}
projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId );
// need to administer roles since they are based off of this
// todo convert everything like to work off of string keys
if ( !name.equals( projectGroup.getName() ) )
{
try
{
roleManager.updateRole( "project-administrator", projectGroup.getName(), name );
roleManager.updateRole( "project-developer", projectGroup.getName(), name );
roleManager.updateRole( "project-user", projectGroup.getName(), name );
projectGroup.setName( name );
}
catch ( RoleManagerException e )
{
throw new ContinuumException( "unable to rename the project group", e );
}
}
projectGroup.setDescription( description );
getContinuum().updateProjectGroup( projectGroup );
Iterator keys = projects.keySet().iterator();
while ( keys.hasNext() )
{
String key = (String) keys.next();
String[] id = (String[]) projects.get( key );
int projectId = Integer.parseInt( key );
Project project = null;
Iterator i = projectGroup.getProjects().iterator();
while ( i.hasNext() )
{
project = (Project) i.next();
if ( projectId == project.getId() )
{
break;
}
}
- ProjectGroup newProjectGroup = getContinuum().getProjectGroup( new Integer( id[0] ).intValue() );
+ ProjectGroup newProjectGroup = getContinuum().getProjectGroupWithProjects( new Integer( id[0] ).intValue() );
if ( newProjectGroup.getId() != projectGroup.getId() )
{
getLogger().info(
"Moving project " + project.getName() + " to project group " + newProjectGroup.getName() );
project.setProjectGroup( newProjectGroup );
getContinuum().updateProject( project );
}
}
return SUCCESS;
}
public String build()
throws ContinuumException
{
try
{
checkBuildProjectGroupAuthorization( getProjectGroupName() );
}
catch ( AuthorizationRequiredException authzE )
{
addActionError( authzE.getMessage() );
return REQUIRES_AUTHORIZATION;
}
getContinuum().buildProjectGroup( projectGroupId );
return SUCCESS;
}
public String release()
throws ContinuumException
{
try
{
checkBuildProjectGroupAuthorization( getProjectGroupName() );
}
catch ( AuthorizationRequiredException authzE )
{
addActionError( authzE.getMessage() );
return REQUIRES_AUTHORIZATION;
}
//get the parent of the group by finding the parent project
//i.e., the project that doesn't have a parent, or it's parent is not in the group.
Project parent = null;
boolean allBuildsOk = true;
projectList = getContinuum().getProjectsInGroupWithDependencies( projectGroupId );
if ( projectList != null )
{
Iterator proj = projectList.iterator();
while ( proj.hasNext() )
{
Project p = (Project) proj.next();
if ( p.getState() != ContinuumProjectState.OK )
{
allBuildsOk = false;
}
if ( ( p.getParent() == null ) || ( !isParentInProjectGroup( p.getParent(), projectList ) ) )
{
if ( parent == null )
{
parent = p;
}
else
{
//currently, we have no provisions for releasing 2 or more parents
//at the same time, this will be implemented in the future
addActionError( "projectGroup.release.error.severalParentProjects" );
return INPUT;
}
}
}
}
if ( parent == null )
{
addActionError( "projectGroup.release.error.emptyGroup" );
return INPUT;
}
releaseProjectId = parent.getId();
if ( allBuildsOk )
{
return SUCCESS;
}
else
{
addActionError( "projectGroup.release.error.projectNotInSuccess" );
return INPUT;
}
}
private boolean isParentInProjectGroup( ProjectDependency parent, Collection projectsInGroup )
throws ContinuumException
{
boolean result = false;
Iterator projectsIterator = projectsInGroup.iterator();
while ( projectsIterator.hasNext() )
{
Project project = (Project) projectsIterator.next();
if ( parent != null )
{
if ( ( project.getArtifactId().equals( parent.getArtifactId() ) ) &&
( project.getGroupId().equals( parent.getGroupId() ) ) &&
( project.getVersion().equals( parent.getVersion() ) ) )
{
result = true;
}
}
}
return result;
}
private void populateProjectGroupUsers( ProjectGroup group )
{
List users;
if ( StringUtils.isEmpty( filterKey ) )
{
// REVIEW: for caching in the user manager
users = manager.getUsers( ascending );
}
else
{
users = findUsers( filterProperty, filterKey, ascending );
}
projectGroupUsers = new ArrayList();
for ( Iterator i = users.iterator(); i.hasNext(); )
{
ProjectGroupUserBean pgUser = new ProjectGroupUserBean();
User user = (User) i.next();
pgUser.setUser( user );
pgUser.setProjectGroup( group );
try
{
Collection effectiveRoles = rbac.getEffectivelyAssignedRoles( user.getUsername() );
for ( Iterator j = effectiveRoles.iterator(); j.hasNext(); )
{
Role role = (Role) j.next();
if ( role.getName().indexOf( projectGroup.getName() ) > -1 )
{
pgUser.setRoles( effectiveRoles );
projectGroupUsers.add( pgUser );
break;
}
}
}
catch ( RbacObjectNotFoundException e )
{
pgUser.setRoles( Collections.EMPTY_LIST );
}
catch ( RbacManagerException e )
{
pgUser.setRoles( Collections.EMPTY_LIST );
}
}
}
private List findUsers( String searchProperty, String searchKey, boolean orderAscending )
{
List users = null;
if ( "username".equals( searchProperty ) )
{
users = manager.findUsersByUsernameKey( searchKey, orderAscending );
}
else if ( "fullName".equals( getFilterProperty() ) )
{
users = manager.findUsersByFullNameKey( searchKey, orderAscending );
}
else if ( "email".equals( getFilterProperty() ) )
{
users = manager.findUsersByEmailKey( searchKey, orderAscending );
}
else
{
users = Collections.EMPTY_LIST;
}
return users;
}
public int getProjectGroupId()
{
return projectGroupId;
}
public void setProjectGroupId( int projectGroupId )
{
this.projectGroupId = projectGroupId;
}
public ProjectGroup getProjectGroup()
{
return projectGroup;
}
public void setProjectGroup( ProjectGroup projectGroup )
{
this.projectGroup = projectGroup;
}
public boolean isConfirmed()
{
return confirmed;
}
public void setConfirmed( boolean confirmed )
{
this.confirmed = confirmed;
}
public String getDescription()
{
return description;
}
public void setDescription( String description )
{
this.description = description;
}
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
public Map getProjects()
{
return projects;
}
public void setProjects( Map projects )
{
this.projects = projects;
}
public Map getProjectGroups()
{
return projectGroups;
}
public void setProjectGroups( Map projectGroups )
{
this.projectGroups = projectGroups;
}
public boolean isProjectInCOQueue()
{
return projectInCOQueue;
}
public void setProjectInCOQueue( boolean projectInQueue )
{
this.projectInCOQueue = projectInQueue;
}
public Collection getProjectList()
{
return projectList;
}
public List getProjectGroupUsers()
{
return projectGroupUsers;
}
public boolean isAscending()
{
return ascending;
}
public void setAscending( boolean ascending )
{
this.ascending = ascending;
}
public String getFilterKey()
{
return filterKey;
}
public void setFilterKey( String filterKey )
{
this.filterKey = filterKey;
}
public String getFilterProperty()
{
return filterProperty;
}
public void setFilterProperty( String filterProperty )
{
this.filterProperty = filterProperty;
}
public Map getCriteria()
{
return FILTER_CRITERIA;
}
public void setReleaseProjectId( int releaseProjectId )
{
this.releaseProjectId = releaseProjectId;
}
public int getReleaseProjectId()
{
return this.releaseProjectId;
}
public ProjectGroup getProjectGroup( int projectGroupId )
throws ContinuumException
{
if ( projectGroup == null )
{
projectGroup = getContinuum().getProjectGroup( projectGroupId );
}
else
{
if ( projectGroup.getId() != projectGroupId )
{
projectGroup = getContinuum().getProjectGroup( projectGroupId );
}
}
return projectGroup;
}
public String getProjectGroupName()
throws ContinuumException
{
return getProjectGroup( projectGroupId ).getName();
}
}
| true | true | public String save()
throws ContinuumException
{
try
{
checkModifyProjectGroupAuthorization( getProjectGroupName() );
}
catch ( AuthorizationRequiredException authzE )
{
addActionError( authzE.getMessage() );
return REQUIRES_AUTHORIZATION;
}
if ( name != null && name.equals( "" ) )
{
addActionError( "projectGroup.error.name.required" );
return INPUT;
}
else if ( name != null && name.trim().equals( "" ) )
{
addActionError( "projectGroup.error.name.cannot.be.spaces" );
return INPUT;
}
projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId );
// need to administer roles since they are based off of this
// todo convert everything like to work off of string keys
if ( !name.equals( projectGroup.getName() ) )
{
try
{
roleManager.updateRole( "project-administrator", projectGroup.getName(), name );
roleManager.updateRole( "project-developer", projectGroup.getName(), name );
roleManager.updateRole( "project-user", projectGroup.getName(), name );
projectGroup.setName( name );
}
catch ( RoleManagerException e )
{
throw new ContinuumException( "unable to rename the project group", e );
}
}
projectGroup.setDescription( description );
getContinuum().updateProjectGroup( projectGroup );
Iterator keys = projects.keySet().iterator();
while ( keys.hasNext() )
{
String key = (String) keys.next();
String[] id = (String[]) projects.get( key );
int projectId = Integer.parseInt( key );
Project project = null;
Iterator i = projectGroup.getProjects().iterator();
while ( i.hasNext() )
{
project = (Project) i.next();
if ( projectId == project.getId() )
{
break;
}
}
ProjectGroup newProjectGroup = getContinuum().getProjectGroup( new Integer( id[0] ).intValue() );
if ( newProjectGroup.getId() != projectGroup.getId() )
{
getLogger().info(
"Moving project " + project.getName() + " to project group " + newProjectGroup.getName() );
project.setProjectGroup( newProjectGroup );
getContinuum().updateProject( project );
}
}
return SUCCESS;
}
| public String save()
throws ContinuumException
{
try
{
checkModifyProjectGroupAuthorization( getProjectGroupName() );
}
catch ( AuthorizationRequiredException authzE )
{
addActionError( authzE.getMessage() );
return REQUIRES_AUTHORIZATION;
}
if ( name != null && name.equals( "" ) )
{
addActionError( "projectGroup.error.name.required" );
return INPUT;
}
else if ( name != null && name.trim().equals( "" ) )
{
addActionError( "projectGroup.error.name.cannot.be.spaces" );
return INPUT;
}
projectGroup = getContinuum().getProjectGroupWithProjects( projectGroupId );
// need to administer roles since they are based off of this
// todo convert everything like to work off of string keys
if ( !name.equals( projectGroup.getName() ) )
{
try
{
roleManager.updateRole( "project-administrator", projectGroup.getName(), name );
roleManager.updateRole( "project-developer", projectGroup.getName(), name );
roleManager.updateRole( "project-user", projectGroup.getName(), name );
projectGroup.setName( name );
}
catch ( RoleManagerException e )
{
throw new ContinuumException( "unable to rename the project group", e );
}
}
projectGroup.setDescription( description );
getContinuum().updateProjectGroup( projectGroup );
Iterator keys = projects.keySet().iterator();
while ( keys.hasNext() )
{
String key = (String) keys.next();
String[] id = (String[]) projects.get( key );
int projectId = Integer.parseInt( key );
Project project = null;
Iterator i = projectGroup.getProjects().iterator();
while ( i.hasNext() )
{
project = (Project) i.next();
if ( projectId == project.getId() )
{
break;
}
}
ProjectGroup newProjectGroup = getContinuum().getProjectGroupWithProjects( new Integer( id[0] ).intValue() );
if ( newProjectGroup.getId() != projectGroup.getId() )
{
getLogger().info(
"Moving project " + project.getName() + " to project group " + newProjectGroup.getName() );
project.setProjectGroup( newProjectGroup );
getContinuum().updateProject( project );
}
}
return SUCCESS;
}
|
diff --git a/microemulator/microemu-midp/src/main/java/javax/microedition/lcdui/StringComponent.java b/microemulator/microemu-midp/src/main/java/javax/microedition/lcdui/StringComponent.java
index 5ae54ab7..c3621599 100644
--- a/microemulator/microemu-midp/src/main/java/javax/microedition/lcdui/StringComponent.java
+++ b/microemulator/microemu-midp/src/main/java/javax/microedition/lcdui/StringComponent.java
@@ -1,257 +1,260 @@
/*
* MicroEmulator
* Copyright (C) 2001 Bartek Teodorczyk <[email protected]>
*
* It is licensed under the following two licenses as alternatives:
* 1. GNU Lesser General Public License (the "LGPL") version 2.1 or any newer version
* 2. Apache License (the "AL") Version 2.0
*
* You may not use this file except in compliance with at least one of
* the above two licenses.
*
* You may obtain a copy of the LGPL at
* http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
*
* You may obtain a copy of the AL 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 LGPL or the AL for the specific language governing permissions and
* limitations.
*/
package javax.microedition.lcdui;
import org.microemu.device.DeviceFactory;
class StringComponent {
private String text;
private int breaks[] = new int[4];
private boolean invertPaint = false;
private int numOfBreaks;
private int width;
private int widthDecreaser;
public StringComponent() {
this(null);
}
public StringComponent(String text) {
synchronized (this) {
this.width = -1;
this.widthDecreaser = 0;
setText(text);
}
}
public int getCharHeight() {
return Font.getDefaultFont().getHeight();
}
public int getCharPositionX(int num) {
synchronized (this) {
if (numOfBreaks == -1) {
updateBreaks();
}
int i, prevIndex = 0;
Font f = Font.getDefaultFont();
for (i = 0; i < numOfBreaks; i++) {
if (num < breaks[i]) {
break;
}
prevIndex = breaks[i];
}
return f.substringWidth(text, prevIndex, num - prevIndex);
}
}
public int getCharPositionY(int num) {
int y = 0;
synchronized (this) {
if (numOfBreaks == -1) {
updateBreaks();
}
Font f = Font.getDefaultFont();
for (int i = 0; i < numOfBreaks; i++) {
if (num < breaks[i]) {
break;
}
y += f.getHeight();
}
}
return y;
}
public int getHeight() {
int height;
synchronized (this) {
if (numOfBreaks == -1) {
updateBreaks();
}
Font f = Font.getDefaultFont();
if (text == null) {
return 0;
}
if (numOfBreaks == 0) {
return f.getHeight();
}
height = numOfBreaks * f.getHeight();
if (breaks[numOfBreaks - 1] == text.length() - 1
&& text.charAt(text.length() - 1) == '\n') {
} else {
height += f.getHeight();
}
}
return height;
}
public String getText() {
return text;
}
public void invertPaint(boolean state) {
synchronized (this) {
invertPaint = state;
}
}
public int paint(Graphics g) {
if (text == null) {
return 0;
}
int y;
synchronized (this) {
if (numOfBreaks == -1) {
updateBreaks();
}
int i, prevIndex;
Font f = Font.getDefaultFont();
for (i = prevIndex = y = 0; i < numOfBreaks; i++) {
if (invertPaint) {
g.setGrayScale(0);
} else {
g.setGrayScale(255);
}
g.fillRect(0, y, width, f.getHeight());
if (invertPaint) {
g.setGrayScale(255);
} else {
g.setGrayScale(0);
}
g.drawSubstring(text, prevIndex, breaks[i] - prevIndex, 0, y, 0);
prevIndex = breaks[i];
y += f.getHeight();
}
- if (prevIndex != text.length()) {
+ // By adding the OR clasuse (text length comparison) we make sure
+ // that even if the current value of a ChoiceGroup is empty, there will
+ // be some visual clue that the ChoiceGroup is there
+ if (prevIndex != text.length() || text.length() == 0) {
if (invertPaint) {
g.setGrayScale(0);
} else {
g.setGrayScale(255);
}
g.fillRect(0, y, width, f.getHeight());
if (invertPaint) {
g.setGrayScale(255);
} else {
g.setGrayScale(0);
}
g.drawSubstring(text, prevIndex, text.length() - prevIndex, 0, y, 0);
y += f.getHeight();
}
}
return y;
}
public void setText(String text) {
synchronized (this) {
this.text = text;
this.numOfBreaks = -1;
}
}
public void setWidthDecreaser(int widthDecreaser) {
synchronized (this) {
this.widthDecreaser = widthDecreaser;
numOfBreaks = -1;
}
}
private void insertBreak(int pos) {
int i;
for (i = 0; i < numOfBreaks; i++) {
if (pos < breaks[i]) {
break;
}
}
if (numOfBreaks + 1 == breaks.length) {
int newbreaks[] = new int[breaks.length + 4];
System.arraycopy(breaks, 0, newbreaks, 0, numOfBreaks);
breaks = newbreaks;
}
System.arraycopy(breaks, i, breaks, i + 1, numOfBreaks - i);
breaks[i] = pos;
numOfBreaks++;
}
private void updateBreaks() {
if (text == null) {
return;
}
// TODO use Displayable width
width = DeviceFactory.getDevice().getDeviceDisplay().getWidth()
- widthDecreaser;
int prevIndex = 0;
int canBreak = 0;
numOfBreaks = 0;
Font f = Font.getDefaultFont();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ') {
canBreak = i + 1;
}
if (text.charAt(i) == '\n') {
insertBreak(i);
canBreak = 0;
prevIndex = i + 1;
continue;
}
if (f.substringWidth(text, prevIndex, i - prevIndex + 1) > width) {
if (canBreak != 0) {
insertBreak(canBreak);
i = canBreak;
prevIndex = i;
} else {
insertBreak(i);
prevIndex = i + 1;
}
canBreak = 0;
}
}
}
}
| true | true | public int paint(Graphics g) {
if (text == null) {
return 0;
}
int y;
synchronized (this) {
if (numOfBreaks == -1) {
updateBreaks();
}
int i, prevIndex;
Font f = Font.getDefaultFont();
for (i = prevIndex = y = 0; i < numOfBreaks; i++) {
if (invertPaint) {
g.setGrayScale(0);
} else {
g.setGrayScale(255);
}
g.fillRect(0, y, width, f.getHeight());
if (invertPaint) {
g.setGrayScale(255);
} else {
g.setGrayScale(0);
}
g.drawSubstring(text, prevIndex, breaks[i] - prevIndex, 0, y, 0);
prevIndex = breaks[i];
y += f.getHeight();
}
if (prevIndex != text.length()) {
if (invertPaint) {
g.setGrayScale(0);
} else {
g.setGrayScale(255);
}
g.fillRect(0, y, width, f.getHeight());
if (invertPaint) {
g.setGrayScale(255);
} else {
g.setGrayScale(0);
}
g.drawSubstring(text, prevIndex, text.length() - prevIndex, 0, y, 0);
y += f.getHeight();
}
}
return y;
}
| public int paint(Graphics g) {
if (text == null) {
return 0;
}
int y;
synchronized (this) {
if (numOfBreaks == -1) {
updateBreaks();
}
int i, prevIndex;
Font f = Font.getDefaultFont();
for (i = prevIndex = y = 0; i < numOfBreaks; i++) {
if (invertPaint) {
g.setGrayScale(0);
} else {
g.setGrayScale(255);
}
g.fillRect(0, y, width, f.getHeight());
if (invertPaint) {
g.setGrayScale(255);
} else {
g.setGrayScale(0);
}
g.drawSubstring(text, prevIndex, breaks[i] - prevIndex, 0, y, 0);
prevIndex = breaks[i];
y += f.getHeight();
}
// By adding the OR clasuse (text length comparison) we make sure
// that even if the current value of a ChoiceGroup is empty, there will
// be some visual clue that the ChoiceGroup is there
if (prevIndex != text.length() || text.length() == 0) {
if (invertPaint) {
g.setGrayScale(0);
} else {
g.setGrayScale(255);
}
g.fillRect(0, y, width, f.getHeight());
if (invertPaint) {
g.setGrayScale(255);
} else {
g.setGrayScale(0);
}
g.drawSubstring(text, prevIndex, text.length() - prevIndex, 0, y, 0);
y += f.getHeight();
}
}
return y;
}
|
diff --git a/test-modules/functional-tests/src/test/java/org/openlmis/functional/E2EInitiateRnR.java b/test-modules/functional-tests/src/test/java/org/openlmis/functional/E2EInitiateRnR.java
index d671be6547..0653d85d68 100644
--- a/test-modules/functional-tests/src/test/java/org/openlmis/functional/E2EInitiateRnR.java
+++ b/test-modules/functional-tests/src/test/java/org/openlmis/functional/E2EInitiateRnR.java
@@ -1,239 +1,238 @@
/*
* Copyright © 2013 VillageReach. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
*
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.openlmis.functional;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.pageobjects.*;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class E2EInitiateRnR extends TestCaseHelper {
@BeforeMethod(groups = {"smoke"})
public void setUp() throws Exception {
super.setup();
}
@DataProvider(name = "envData")
public Object[][] getEnvData() {
return new Object[][]{};
}
@Test(groups = {"smoke"}, dataProvider = "Data-Provider-Function-Positive")
public void testE2EInitiateRnR(String program, String userSIC, String userMO, String userlmu, String password, String[] credentials) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility();
String geoZone = "Ngorongoro";
String parentgeoZone = "Dodoma";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "FCcode";
String facilityNamePrefix = "FCname";
String date_time = createFacilityPage.enterValuesInFacility(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy);
createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created");
String facility_code = "FCcode" + date_time;
dbWrapper.insertFacilities("F10", "F11");
createRole(homePage);
dbWrapper.insertSupervisoryNode("F10", "N1", "Node 1", "null");
dbWrapper.insertSupervisoryNodeSecond("F11", "N2", "Node 2", "N1");
String passwordUsers = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPageSIC = homePage.navigateToUser();
String userSICEmail = "[email protected]";
String userSICFirstName = "Fatima";
String userSICLastName = "Doe";
String userSICUserName = "storeincharge";
String userIDSIC = userPageSIC.enterAndverifyUserDetails(userSICUserName, userSICEmail, userSICFirstName, userSICLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userSICEmail);
userPageSIC.enterMyFacilityAndMySupervisedFacilityData(userSICFirstName, userSICLastName, "F10", "HIV", "Node 1", "Store-in-charge", false);
String passwordUserslmu = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPagelmu = homePage.navigateToUser();
String userlmuEmail = "[email protected]";
String userlmuFirstName = "Lmu";
String userlmuLastName = "Doe";
String userlmuUserName = "lmu";
userPagelmu.enterAndverifyUserDetails(userlmuUserName, userlmuEmail, userlmuFirstName, userlmuLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUserslmu, userlmuEmail);
userPagelmu.enterMyFacilityAndMySupervisedFacilityData(userlmuFirstName, userlmuLastName, "F10", "HIV", "Node 1", "lmu", true);
UserPage userPageMO = homePage.navigateToUser();
String userMOEmail = "[email protected]";
String userMOFirstName = "Jane";
String userMOLastName = "Doe";
String userMOUserName = "medicalofficer";
userPageMO.enterAndverifyUserDetails(userMOUserName, userMOEmail, userMOFirstName, userMOLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userMOEmail);
userPageMO.enterMyFacilityAndMySupervisedFacilityData(userMOFirstName, userMOLastName, "F11", "HIV", "Node 2", "Medical-Officer", false);
dbWrapper.updateRoleGroupMember(facility_code);
setupProductTestData("P10", "P11", program, "Lvl3 Hospital");
dbWrapper.insertRequisitionGroups("RG1", "RG2", "N1", "N2");
dbWrapper.insertRequisitionGroupMembers("F10", facility_code);
ManageSchedulePage manageSchedulePage = homePage.navigateToSchedule();
manageSchedulePage.createAndVerifySchedule();
manageSchedulePage.editAndVerifySchedule();
PeriodsPage periodsPage = manageSchedulePage.navigatePeriods();
periodsPage.createAndVerifyPeriods();
periodsPage.deleteAndVerifyPeriods();
dbWrapper.insertRequisitionGroupProgramSchedule();
dbWrapper.allocateFacilityToUser(userIDSIC, facility_code);
TemplateConfigPage templateConfigPage = homePage.selectProgramToConfigTemplate(program);
templateConfigPage.configureTemplate();
dbWrapper.insertSupplyLines("N1", "HIV", "FCcode" + date_time);
LoginPage loginPageSecond = homePage.logout(baseUrlGlobal);
HomePage homePageUser = loginPageSecond.loginAs(userSIC, password);
String periodDetails = homePageUser.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePageUser.clickProceed();
initiateRnRPage.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
initiateRnRPage.submitRnR();
initiateRnRPage.verifySubmitRnrErrorMsg();
initiateRnRPage.calculateAndVerifyStockOnHand(10, 10, 10, 1);
initiateRnRPage.submitRnR();
initiateRnRPage.clickOk();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.typeCommentsInCommentsTextArea("Test comment.");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.verifyValueInCommentsTextArea("");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.addComments("Dummy Comments.");
initiateRnRPage.verifyComment("Dummy Comments.", userSICUserName, 1);
initiateRnRPage.enterValuesAndVerifyCalculatedOrderQuantity(10, 10, 101, 51, 153, 142);
initiateRnRPage.verifyPacksToShip(15);
initiateRnRPage.enterAndVerifyRequestedQuantityExplanation(10);
initiateRnRPage.verifyPacksToShip(1);
initiateRnRPage.calculateAndVerifyTotalCost();
initiateRnRPage.saveRnR();
initiateRnRPage.addNonFullSupplyLineItems("99", "Due to unforeseen event", "antibiotic", "P11", "Antibiotics", baseUrlGlobal, dburlGlobal);
initiateRnRPage.calculateAndVerifyTotalCostNonFullSupply();
initiateRnRPage.verifyCostOnFooter();
initiateRnRPage.authorizeRnR();
initiateRnRPage.clickOk();
initiateRnRPage.verifyAuthorizeRnrSuccessMsg();
initiateRnRPage.verifyApproveButtonNotPresent();
ApprovePage approvePage = homePageUser.navigateToApprove();
approvePage.verifyNoRequisitionPendingMessage();
LoginPage loginPagethird = homePageUser.logout(baseUrlGlobal);
HomePage homePageLowerSNUser = loginPagethird.loginAs(userMO, password);
ApprovePage approvePageLowerSNUser = homePageLowerSNUser.navigateToApprove();
approvePageLowerSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageLowerSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageLowerSNUser.verifyApprovedQuantity();
approvePageLowerSNUser.editApproveQuantityAndVerifyTotalCost("290");
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.typeCommentsInCommentsTextArea("Test comment.");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.verifyValueInCommentsTextArea("");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.addComments("This is urgent");
approvePageLowerSNUser.verifyComment("This is urgent", userMO, 2);
approvePageLowerSNUser.clickSaveButton();
approvePageLowerSNUser.clickApproveButton();
approvePageLowerSNUser.clickOk();
approvePageLowerSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPageTopSNUser = homePageLowerSNUser.logout(baseUrlGlobal);
HomePage homePageTopSNUser = loginPageTopSNUser.loginAs(userSIC, password);
ApprovePage approvePageTopSNUser = homePageTopSNUser.navigateToApprove();
String periodTopSNUser = approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageTopSNUser.verifyApprovedQuantityApprovedFromLowerHierarchy("290");
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCost("100");
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPagelmu = homePageTopSNUser.logout(baseUrlGlobal);
HomePage homePagelmu = loginPagelmu.loginAs(userlmu, password);
OrderPage orderPageOrdersPending = homePagelmu.navigateConvertToOrder();
String[] periods = periodTopSNUser.split("-");
String supplyFacilityName = dbWrapper.getSupplyFacilityName("N1", "HIV");
orderPageOrdersPending.verifyOrderListElements(program, "FCcode" + date_time, "FCname" + date_time, periods[0].trim(), periods[1].trim(), supplyFacilityName);
verifyConvertToOrder(orderPageOrdersPending);
- orderPageOrdersPending.convertToOrder();
}
private void verifyConvertToOrder(OrderPage orderPageOrdersPending) {
orderPageOrdersPending.clickConvertToOrderButton();
orderPageOrdersPending.verifyMessageOnOrderScreen("Message 'Please select atleast one Requisition for Converting to Order.' is not displayed");
orderPageOrdersPending.clickCheckBoxConvertToOrder();
orderPageOrdersPending.clickConvertToOrderButton();
orderPageOrdersPending.clickOk();
}
private void createRole(HomePage homePage) throws IOException {
RolesPage rolesPage = homePage.navigateRoleAssignments();
List<String> userRoleListStoreincharge = new ArrayList<String>();
userRoleListStoreincharge.add("Create Requisition");
userRoleListStoreincharge.add("Authorize Requisition");
userRoleListStoreincharge.add("Approve Requisition");
rolesPage.createRole("Store-in-charge", "Store-in-charge", userRoleListStoreincharge, true);
RolesPage rolesPagelmu = homePage.navigateRoleAssignments();
List<String> userRoleListlmu = new ArrayList<String>();
userRoleListlmu.add("Convert To Order Requisition");
rolesPagelmu.createRole("lmu", "lmu", userRoleListlmu, false);
List<String> userRoleListMedicalofficer = new ArrayList<String>();
userRoleListMedicalofficer.add("Approve Requisition");
rolesPage.createRole("Medical-officer", "Medical-officer", userRoleListMedicalofficer, true);
}
@AfterMethod(groups = {"smoke"})
public void tearDown() throws Exception {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
@DataProvider(name = "Data-Provider-Function-Positive")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"HIV", "storeincharge", "medicalofficer", "lmu", "Admin123", new String[]{"Admin123", "Admin123"}}
};
}
}
| true | true | public void testE2EInitiateRnR(String program, String userSIC, String userMO, String userlmu, String password, String[] credentials) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility();
String geoZone = "Ngorongoro";
String parentgeoZone = "Dodoma";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "FCcode";
String facilityNamePrefix = "FCname";
String date_time = createFacilityPage.enterValuesInFacility(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy);
createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created");
String facility_code = "FCcode" + date_time;
dbWrapper.insertFacilities("F10", "F11");
createRole(homePage);
dbWrapper.insertSupervisoryNode("F10", "N1", "Node 1", "null");
dbWrapper.insertSupervisoryNodeSecond("F11", "N2", "Node 2", "N1");
String passwordUsers = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPageSIC = homePage.navigateToUser();
String userSICEmail = "[email protected]";
String userSICFirstName = "Fatima";
String userSICLastName = "Doe";
String userSICUserName = "storeincharge";
String userIDSIC = userPageSIC.enterAndverifyUserDetails(userSICUserName, userSICEmail, userSICFirstName, userSICLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userSICEmail);
userPageSIC.enterMyFacilityAndMySupervisedFacilityData(userSICFirstName, userSICLastName, "F10", "HIV", "Node 1", "Store-in-charge", false);
String passwordUserslmu = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPagelmu = homePage.navigateToUser();
String userlmuEmail = "[email protected]";
String userlmuFirstName = "Lmu";
String userlmuLastName = "Doe";
String userlmuUserName = "lmu";
userPagelmu.enterAndverifyUserDetails(userlmuUserName, userlmuEmail, userlmuFirstName, userlmuLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUserslmu, userlmuEmail);
userPagelmu.enterMyFacilityAndMySupervisedFacilityData(userlmuFirstName, userlmuLastName, "F10", "HIV", "Node 1", "lmu", true);
UserPage userPageMO = homePage.navigateToUser();
String userMOEmail = "[email protected]";
String userMOFirstName = "Jane";
String userMOLastName = "Doe";
String userMOUserName = "medicalofficer";
userPageMO.enterAndverifyUserDetails(userMOUserName, userMOEmail, userMOFirstName, userMOLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userMOEmail);
userPageMO.enterMyFacilityAndMySupervisedFacilityData(userMOFirstName, userMOLastName, "F11", "HIV", "Node 2", "Medical-Officer", false);
dbWrapper.updateRoleGroupMember(facility_code);
setupProductTestData("P10", "P11", program, "Lvl3 Hospital");
dbWrapper.insertRequisitionGroups("RG1", "RG2", "N1", "N2");
dbWrapper.insertRequisitionGroupMembers("F10", facility_code);
ManageSchedulePage manageSchedulePage = homePage.navigateToSchedule();
manageSchedulePage.createAndVerifySchedule();
manageSchedulePage.editAndVerifySchedule();
PeriodsPage periodsPage = manageSchedulePage.navigatePeriods();
periodsPage.createAndVerifyPeriods();
periodsPage.deleteAndVerifyPeriods();
dbWrapper.insertRequisitionGroupProgramSchedule();
dbWrapper.allocateFacilityToUser(userIDSIC, facility_code);
TemplateConfigPage templateConfigPage = homePage.selectProgramToConfigTemplate(program);
templateConfigPage.configureTemplate();
dbWrapper.insertSupplyLines("N1", "HIV", "FCcode" + date_time);
LoginPage loginPageSecond = homePage.logout(baseUrlGlobal);
HomePage homePageUser = loginPageSecond.loginAs(userSIC, password);
String periodDetails = homePageUser.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePageUser.clickProceed();
initiateRnRPage.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
initiateRnRPage.submitRnR();
initiateRnRPage.verifySubmitRnrErrorMsg();
initiateRnRPage.calculateAndVerifyStockOnHand(10, 10, 10, 1);
initiateRnRPage.submitRnR();
initiateRnRPage.clickOk();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.typeCommentsInCommentsTextArea("Test comment.");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.verifyValueInCommentsTextArea("");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.addComments("Dummy Comments.");
initiateRnRPage.verifyComment("Dummy Comments.", userSICUserName, 1);
initiateRnRPage.enterValuesAndVerifyCalculatedOrderQuantity(10, 10, 101, 51, 153, 142);
initiateRnRPage.verifyPacksToShip(15);
initiateRnRPage.enterAndVerifyRequestedQuantityExplanation(10);
initiateRnRPage.verifyPacksToShip(1);
initiateRnRPage.calculateAndVerifyTotalCost();
initiateRnRPage.saveRnR();
initiateRnRPage.addNonFullSupplyLineItems("99", "Due to unforeseen event", "antibiotic", "P11", "Antibiotics", baseUrlGlobal, dburlGlobal);
initiateRnRPage.calculateAndVerifyTotalCostNonFullSupply();
initiateRnRPage.verifyCostOnFooter();
initiateRnRPage.authorizeRnR();
initiateRnRPage.clickOk();
initiateRnRPage.verifyAuthorizeRnrSuccessMsg();
initiateRnRPage.verifyApproveButtonNotPresent();
ApprovePage approvePage = homePageUser.navigateToApprove();
approvePage.verifyNoRequisitionPendingMessage();
LoginPage loginPagethird = homePageUser.logout(baseUrlGlobal);
HomePage homePageLowerSNUser = loginPagethird.loginAs(userMO, password);
ApprovePage approvePageLowerSNUser = homePageLowerSNUser.navigateToApprove();
approvePageLowerSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageLowerSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageLowerSNUser.verifyApprovedQuantity();
approvePageLowerSNUser.editApproveQuantityAndVerifyTotalCost("290");
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.typeCommentsInCommentsTextArea("Test comment.");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.verifyValueInCommentsTextArea("");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.addComments("This is urgent");
approvePageLowerSNUser.verifyComment("This is urgent", userMO, 2);
approvePageLowerSNUser.clickSaveButton();
approvePageLowerSNUser.clickApproveButton();
approvePageLowerSNUser.clickOk();
approvePageLowerSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPageTopSNUser = homePageLowerSNUser.logout(baseUrlGlobal);
HomePage homePageTopSNUser = loginPageTopSNUser.loginAs(userSIC, password);
ApprovePage approvePageTopSNUser = homePageTopSNUser.navigateToApprove();
String periodTopSNUser = approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageTopSNUser.verifyApprovedQuantityApprovedFromLowerHierarchy("290");
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCost("100");
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPagelmu = homePageTopSNUser.logout(baseUrlGlobal);
HomePage homePagelmu = loginPagelmu.loginAs(userlmu, password);
OrderPage orderPageOrdersPending = homePagelmu.navigateConvertToOrder();
String[] periods = periodTopSNUser.split("-");
String supplyFacilityName = dbWrapper.getSupplyFacilityName("N1", "HIV");
orderPageOrdersPending.verifyOrderListElements(program, "FCcode" + date_time, "FCname" + date_time, periods[0].trim(), periods[1].trim(), supplyFacilityName);
verifyConvertToOrder(orderPageOrdersPending);
orderPageOrdersPending.convertToOrder();
}
| public void testE2EInitiateRnR(String program, String userSIC, String userMO, String userlmu, String password, String[] credentials) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility();
String geoZone = "Ngorongoro";
String parentgeoZone = "Dodoma";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "FCcode";
String facilityNamePrefix = "FCname";
String date_time = createFacilityPage.enterValuesInFacility(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy);
createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created");
String facility_code = "FCcode" + date_time;
dbWrapper.insertFacilities("F10", "F11");
createRole(homePage);
dbWrapper.insertSupervisoryNode("F10", "N1", "Node 1", "null");
dbWrapper.insertSupervisoryNodeSecond("F11", "N2", "Node 2", "N1");
String passwordUsers = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPageSIC = homePage.navigateToUser();
String userSICEmail = "[email protected]";
String userSICFirstName = "Fatima";
String userSICLastName = "Doe";
String userSICUserName = "storeincharge";
String userIDSIC = userPageSIC.enterAndverifyUserDetails(userSICUserName, userSICEmail, userSICFirstName, userSICLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userSICEmail);
userPageSIC.enterMyFacilityAndMySupervisedFacilityData(userSICFirstName, userSICLastName, "F10", "HIV", "Node 1", "Store-in-charge", false);
String passwordUserslmu = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPagelmu = homePage.navigateToUser();
String userlmuEmail = "[email protected]";
String userlmuFirstName = "Lmu";
String userlmuLastName = "Doe";
String userlmuUserName = "lmu";
userPagelmu.enterAndverifyUserDetails(userlmuUserName, userlmuEmail, userlmuFirstName, userlmuLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUserslmu, userlmuEmail);
userPagelmu.enterMyFacilityAndMySupervisedFacilityData(userlmuFirstName, userlmuLastName, "F10", "HIV", "Node 1", "lmu", true);
UserPage userPageMO = homePage.navigateToUser();
String userMOEmail = "[email protected]";
String userMOFirstName = "Jane";
String userMOLastName = "Doe";
String userMOUserName = "medicalofficer";
userPageMO.enterAndverifyUserDetails(userMOUserName, userMOEmail, userMOFirstName, userMOLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userMOEmail);
userPageMO.enterMyFacilityAndMySupervisedFacilityData(userMOFirstName, userMOLastName, "F11", "HIV", "Node 2", "Medical-Officer", false);
dbWrapper.updateRoleGroupMember(facility_code);
setupProductTestData("P10", "P11", program, "Lvl3 Hospital");
dbWrapper.insertRequisitionGroups("RG1", "RG2", "N1", "N2");
dbWrapper.insertRequisitionGroupMembers("F10", facility_code);
ManageSchedulePage manageSchedulePage = homePage.navigateToSchedule();
manageSchedulePage.createAndVerifySchedule();
manageSchedulePage.editAndVerifySchedule();
PeriodsPage periodsPage = manageSchedulePage.navigatePeriods();
periodsPage.createAndVerifyPeriods();
periodsPage.deleteAndVerifyPeriods();
dbWrapper.insertRequisitionGroupProgramSchedule();
dbWrapper.allocateFacilityToUser(userIDSIC, facility_code);
TemplateConfigPage templateConfigPage = homePage.selectProgramToConfigTemplate(program);
templateConfigPage.configureTemplate();
dbWrapper.insertSupplyLines("N1", "HIV", "FCcode" + date_time);
LoginPage loginPageSecond = homePage.logout(baseUrlGlobal);
HomePage homePageUser = loginPageSecond.loginAs(userSIC, password);
String periodDetails = homePageUser.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePageUser.clickProceed();
initiateRnRPage.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
initiateRnRPage.submitRnR();
initiateRnRPage.verifySubmitRnrErrorMsg();
initiateRnRPage.calculateAndVerifyStockOnHand(10, 10, 10, 1);
initiateRnRPage.submitRnR();
initiateRnRPage.clickOk();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.typeCommentsInCommentsTextArea("Test comment.");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.verifyValueInCommentsTextArea("");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.addComments("Dummy Comments.");
initiateRnRPage.verifyComment("Dummy Comments.", userSICUserName, 1);
initiateRnRPage.enterValuesAndVerifyCalculatedOrderQuantity(10, 10, 101, 51, 153, 142);
initiateRnRPage.verifyPacksToShip(15);
initiateRnRPage.enterAndVerifyRequestedQuantityExplanation(10);
initiateRnRPage.verifyPacksToShip(1);
initiateRnRPage.calculateAndVerifyTotalCost();
initiateRnRPage.saveRnR();
initiateRnRPage.addNonFullSupplyLineItems("99", "Due to unforeseen event", "antibiotic", "P11", "Antibiotics", baseUrlGlobal, dburlGlobal);
initiateRnRPage.calculateAndVerifyTotalCostNonFullSupply();
initiateRnRPage.verifyCostOnFooter();
initiateRnRPage.authorizeRnR();
initiateRnRPage.clickOk();
initiateRnRPage.verifyAuthorizeRnrSuccessMsg();
initiateRnRPage.verifyApproveButtonNotPresent();
ApprovePage approvePage = homePageUser.navigateToApprove();
approvePage.verifyNoRequisitionPendingMessage();
LoginPage loginPagethird = homePageUser.logout(baseUrlGlobal);
HomePage homePageLowerSNUser = loginPagethird.loginAs(userMO, password);
ApprovePage approvePageLowerSNUser = homePageLowerSNUser.navigateToApprove();
approvePageLowerSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageLowerSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageLowerSNUser.verifyApprovedQuantity();
approvePageLowerSNUser.editApproveQuantityAndVerifyTotalCost("290");
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.typeCommentsInCommentsTextArea("Test comment.");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.verifyValueInCommentsTextArea("");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.addComments("This is urgent");
approvePageLowerSNUser.verifyComment("This is urgent", userMO, 2);
approvePageLowerSNUser.clickSaveButton();
approvePageLowerSNUser.clickApproveButton();
approvePageLowerSNUser.clickOk();
approvePageLowerSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPageTopSNUser = homePageLowerSNUser.logout(baseUrlGlobal);
HomePage homePageTopSNUser = loginPageTopSNUser.loginAs(userSIC, password);
ApprovePage approvePageTopSNUser = homePageTopSNUser.navigateToApprove();
String periodTopSNUser = approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageTopSNUser.verifyApprovedQuantityApprovedFromLowerHierarchy("290");
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCost("100");
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPagelmu = homePageTopSNUser.logout(baseUrlGlobal);
HomePage homePagelmu = loginPagelmu.loginAs(userlmu, password);
OrderPage orderPageOrdersPending = homePagelmu.navigateConvertToOrder();
String[] periods = periodTopSNUser.split("-");
String supplyFacilityName = dbWrapper.getSupplyFacilityName("N1", "HIV");
orderPageOrdersPending.verifyOrderListElements(program, "FCcode" + date_time, "FCname" + date_time, periods[0].trim(), periods[1].trim(), supplyFacilityName);
verifyConvertToOrder(orderPageOrdersPending);
}
|
diff --git a/plugins/org.jboss.tools.jst.web/src/org/jboss/tools/jst/web/model/helpers/InnerModelHelper.java b/plugins/org.jboss.tools.jst.web/src/org/jboss/tools/jst/web/model/helpers/InnerModelHelper.java
index 5f2b6e59..edcb8ec8 100644
--- a/plugins/org.jboss.tools.jst.web/src/org/jboss/tools/jst/web/model/helpers/InnerModelHelper.java
+++ b/plugins/org.jboss.tools.jst.web/src/org/jboss/tools/jst/web/model/helpers/InnerModelHelper.java
@@ -1,134 +1,136 @@
/*******************************************************************************
* Copyright (c) 2007 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.jst.web.model.helpers;
import java.io.IOException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.wst.common.componentcore.ComponentCore;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualFolder;
import org.jboss.tools.common.model.XModel;
import org.jboss.tools.common.model.XModelConstants;
import org.jboss.tools.common.model.XModelObject;
import org.jboss.tools.common.model.project.IModelNature;
import org.jboss.tools.common.model.util.EclipseResourceUtil;
import org.jboss.tools.common.model.util.XModelObjectUtil;
import org.jboss.tools.common.web.WebUtils;
public class InnerModelHelper {
public static XModel createXModel(IProject project) {
IModelNature n = EclipseResourceUtil.getModelNature(project.getProject());
if(n != null) return n.getModel();
XModelObject o = EclipseResourceUtil.createObjectForResource(project.getProject());
if(o == null) return null;
XModel model = o.getModel();
XModelObject webinf = model.getByPath("FileSystems/WEB-INF"); //$NON-NLS-1$
if(webinf != null) return model;
IPath webInfPath = getWebInfPath(project);
if(webInfPath == null) return model;
IFolder webInfFolder = ResourcesPlugin.getWorkspace().getRoot().getFolder(webInfPath);
model.getProperties().setProperty(XModelConstants.WORKSPACE, webInfFolder.getLocation().toString());
model.getProperties().setProperty(XModelConstants.WORKSPACE_OLD, webInfFolder.getLocation().toString());
XModelObject fs = model.getByPath("FileSystems"); //$NON-NLS-1$
webinf = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
webinf.setAttributeValue("name", "WEB-INF"); //$NON-NLS-1$ //$NON-NLS-2$
webinf.setAttributeValue("location", XModelConstants.WORKSPACE_REF); //$NON-NLS-1$
fs.addChild(webinf);
String webInfLocation = XModelObjectUtil.expand(XModelConstants.WORKSPACE_REF, model, null);
String webRootLocation = getWebRootPath(project, webInfLocation);
XModelObject webroot = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
webroot.setAttributeValue("name", "WEB-ROOT"); //$NON-NLS-1$ //$NON-NLS-2$
webroot.setAttributeValue("location", webRootLocation); //$NON-NLS-1$
fs.addChild(webroot);
- XModelObject lib = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
- lib.setAttributeValue("name", "lib"); //$NON-NLS-1$ //$NON-NLS-2$
- lib.setAttributeValue("location", XModelConstants.WORKSPACE_REF + "/lib"); //$NON-NLS-1$ //$NON-NLS-2$
- fs.addChild(lib);
+ if(webInfFolder.getFolder("lib").exists()) {
+ XModelObject lib = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
+ lib.setAttributeValue("name", "lib"); //$NON-NLS-1$ //$NON-NLS-2$
+ lib.setAttributeValue("location", XModelConstants.WORKSPACE_REF + "/lib"); //$NON-NLS-1$ //$NON-NLS-2$
+ fs.addChild(lib);
+ }
return model;
}
//Taken from J2EEUtils and modified
public static IPath getWebInfPath(IProject project) {
IContainer[] cs = WebUtils.getWebRootFolders(project, true);
for (IContainer c: cs) {
if(c.exists()) {
IFolder f = c.getFolder(new Path("WEB-INF")); //$NON-NLS-1$
if(f.exists()) {
return f.getFullPath();
}
}
}
IVirtualComponent component = ComponentCore.createComponent(project);
if(component == null) return null;
IVirtualFolder webInfDir = component.getRootFolder().getFolder(new Path("/WEB-INF")); //$NON-NLS-1$
IPath modulePath = webInfDir.getWorkspaceRelativePath();
return (!webInfDir.exists()) ? null : modulePath;
}
public static IPath getFirstWebContentPath(IProject project) {
IContainer[] cs = WebUtils.getWebRootFolders(project, true);
for (IContainer c: cs) {
if(c.exists()) {
return c.getFullPath();
}
}
return null;
}
static String getWebRootPath(IProject project, String webInfLocation) {
String webRootLocation = XModelConstants.WORKSPACE_REF + "/.."; //$NON-NLS-1$
IPath wrp = getFirstWebContentPath(project);
IPath wip = getWebInfPath(project);
if(wrp == null || wip == null) {
return webRootLocation;
}
IResource wrpc = ResourcesPlugin.getWorkspace().getRoot().findMember(wrp);
IResource wipc = ResourcesPlugin.getWorkspace().getRoot().findMember(wip);
if(wrpc != null && wipc != null && wipc.isLinked()) {
IPath p = wrpc.getLocation();
if(p != null) {
try {
webRootLocation = p.toFile().getCanonicalPath().replace('\\', '/');
} catch (IOException e) {
}
String relative = org.jboss.tools.common.util.FileUtil.getRelativePath(webInfLocation, webRootLocation);
if(relative != null) {
webRootLocation = XModelConstants.WORKSPACE_REF + relative;
}
}
}
return webRootLocation;
}
}
| true | true | public static XModel createXModel(IProject project) {
IModelNature n = EclipseResourceUtil.getModelNature(project.getProject());
if(n != null) return n.getModel();
XModelObject o = EclipseResourceUtil.createObjectForResource(project.getProject());
if(o == null) return null;
XModel model = o.getModel();
XModelObject webinf = model.getByPath("FileSystems/WEB-INF"); //$NON-NLS-1$
if(webinf != null) return model;
IPath webInfPath = getWebInfPath(project);
if(webInfPath == null) return model;
IFolder webInfFolder = ResourcesPlugin.getWorkspace().getRoot().getFolder(webInfPath);
model.getProperties().setProperty(XModelConstants.WORKSPACE, webInfFolder.getLocation().toString());
model.getProperties().setProperty(XModelConstants.WORKSPACE_OLD, webInfFolder.getLocation().toString());
XModelObject fs = model.getByPath("FileSystems"); //$NON-NLS-1$
webinf = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
webinf.setAttributeValue("name", "WEB-INF"); //$NON-NLS-1$ //$NON-NLS-2$
webinf.setAttributeValue("location", XModelConstants.WORKSPACE_REF); //$NON-NLS-1$
fs.addChild(webinf);
String webInfLocation = XModelObjectUtil.expand(XModelConstants.WORKSPACE_REF, model, null);
String webRootLocation = getWebRootPath(project, webInfLocation);
XModelObject webroot = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
webroot.setAttributeValue("name", "WEB-ROOT"); //$NON-NLS-1$ //$NON-NLS-2$
webroot.setAttributeValue("location", webRootLocation); //$NON-NLS-1$
fs.addChild(webroot);
XModelObject lib = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
lib.setAttributeValue("name", "lib"); //$NON-NLS-1$ //$NON-NLS-2$
lib.setAttributeValue("location", XModelConstants.WORKSPACE_REF + "/lib"); //$NON-NLS-1$ //$NON-NLS-2$
fs.addChild(lib);
return model;
}
| public static XModel createXModel(IProject project) {
IModelNature n = EclipseResourceUtil.getModelNature(project.getProject());
if(n != null) return n.getModel();
XModelObject o = EclipseResourceUtil.createObjectForResource(project.getProject());
if(o == null) return null;
XModel model = o.getModel();
XModelObject webinf = model.getByPath("FileSystems/WEB-INF"); //$NON-NLS-1$
if(webinf != null) return model;
IPath webInfPath = getWebInfPath(project);
if(webInfPath == null) return model;
IFolder webInfFolder = ResourcesPlugin.getWorkspace().getRoot().getFolder(webInfPath);
model.getProperties().setProperty(XModelConstants.WORKSPACE, webInfFolder.getLocation().toString());
model.getProperties().setProperty(XModelConstants.WORKSPACE_OLD, webInfFolder.getLocation().toString());
XModelObject fs = model.getByPath("FileSystems"); //$NON-NLS-1$
webinf = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
webinf.setAttributeValue("name", "WEB-INF"); //$NON-NLS-1$ //$NON-NLS-2$
webinf.setAttributeValue("location", XModelConstants.WORKSPACE_REF); //$NON-NLS-1$
fs.addChild(webinf);
String webInfLocation = XModelObjectUtil.expand(XModelConstants.WORKSPACE_REF, model, null);
String webRootLocation = getWebRootPath(project, webInfLocation);
XModelObject webroot = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
webroot.setAttributeValue("name", "WEB-ROOT"); //$NON-NLS-1$ //$NON-NLS-2$
webroot.setAttributeValue("location", webRootLocation); //$NON-NLS-1$
fs.addChild(webroot);
if(webInfFolder.getFolder("lib").exists()) {
XModelObject lib = model.createModelObject("FileSystemFolder", null); //$NON-NLS-1$
lib.setAttributeValue("name", "lib"); //$NON-NLS-1$ //$NON-NLS-2$
lib.setAttributeValue("location", XModelConstants.WORKSPACE_REF + "/lib"); //$NON-NLS-1$ //$NON-NLS-2$
fs.addChild(lib);
}
return model;
}
|
diff --git a/src/ca/ualberta/CMPUT301F13T02/chooseyouradventure/elasticsearch/ESHttpRequest.java b/src/ca/ualberta/CMPUT301F13T02/chooseyouradventure/elasticsearch/ESHttpRequest.java
index c44a6ad..98bf2be 100644
--- a/src/ca/ualberta/CMPUT301F13T02/chooseyouradventure/elasticsearch/ESHttpRequest.java
+++ b/src/ca/ualberta/CMPUT301F13T02/chooseyouradventure/elasticsearch/ESHttpRequest.java
@@ -1,131 +1,129 @@
/*
* Copyright (c) 2013, TeamCMPUT301F13T02
* 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 {organization} 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 ca.ualberta.CMPUT301F13T02.chooseyouradventure.elasticsearch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import android.os.StrictMode;
import ca.ualberta.CMPUT301F13T02.chooseyouradventure.HandlerException;
/**
* Wraps all HTTP requests to the Elastic Search service. This is an abstract
* class that is extended by ESHttp- Get, Post, and Delete.
*/
public abstract class ESHttpRequest extends HttpEntityEnclosingRequestBase {
/**
* Create an Elastic Search request
*
* @param url The URL of the request
*/
public ESHttpRequest(String url) {
super();
try {
setURI(new URI(ESHandler.serviceURL + url));
}
catch (URISyntaxException e) {
e.printStackTrace();
}
setHeader("Accept", "application/json");
/* This allows the implementation of ESHandler to work */
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/**
* Execute a resquest to Elastic Search
* @throws IOException
* @throws HandlerException
* @return A String representation of Elastic Search's response
*/
public String execute() throws IOException, HandlerException {
/* This method with inspiration from https://github.com/rayzhangcl/ESDemo */
HttpResponse response = null;
try {
response = ESHandler.client.execute(this);
}
- catch (ClientProtocolException e) {
- e.printStackTrace();
- }
- catch (IOException e) {
+ catch (Exception e) {
e.printStackTrace();
+ throw new HandlerException("Failure to get response");
}
String status = response.getStatusLine().toString();
System.out.println(status);
if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201)
throw new HandlerException("ESHttpGet " + getURI() + " returned " + status);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
//Build string from response body
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
System.out.println(sb.toString());
//Close connection
try {
entity.consumeContent();
}
catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* Returns the type of request this is
*/
@Override
public abstract String getMethod();
}
| false | true | public String execute() throws IOException, HandlerException {
/* This method with inspiration from https://github.com/rayzhangcl/ESDemo */
HttpResponse response = null;
try {
response = ESHandler.client.execute(this);
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
String status = response.getStatusLine().toString();
System.out.println(status);
if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201)
throw new HandlerException("ESHttpGet " + getURI() + " returned " + status);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
//Build string from response body
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
System.out.println(sb.toString());
//Close connection
try {
entity.consumeContent();
}
catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
| public String execute() throws IOException, HandlerException {
/* This method with inspiration from https://github.com/rayzhangcl/ESDemo */
HttpResponse response = null;
try {
response = ESHandler.client.execute(this);
}
catch (Exception e) {
e.printStackTrace();
throw new HandlerException("Failure to get response");
}
String status = response.getStatusLine().toString();
System.out.println(status);
if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201)
throw new HandlerException("ESHttpGet " + getURI() + " returned " + status);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
//Build string from response body
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
System.out.println(sb.toString());
//Close connection
try {
entity.consumeContent();
}
catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
|
diff --git a/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/AbstractStorableDomainObjectResource.java b/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/AbstractStorableDomainObjectResource.java
index 53b1525dd..6114d0fca 100644
--- a/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/AbstractStorableDomainObjectResource.java
+++ b/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/AbstractStorableDomainObjectResource.java
@@ -1,54 +1,55 @@
package edu.northwestern.bioinformatics.studycalendar.restlets;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.Variant;
import org.restlet.resource.ResourceException;
import java.io.IOException;
/**
* Base class for resources which are backed by a single domain object and
* which support GET and PUT.
*
* @author Rhett Sutphin
*/
public abstract class AbstractStorableDomainObjectResource<D extends DomainObject> extends AbstractDomainObjectResource<D> {
@Override
public void doInit() {
super.doInit();
getAllowedMethods().add(Method.PUT);
}
@Override
@SuppressWarnings({"unchecked"})
public Representation put(Representation entity, Variant variant) throws ResourceException {
if (entity.getMediaType().includes(MediaType.TEXT_XML)) {
validateEntity(entity);
D read;
try {
read = getXmlSerializer().readDocument(entity.getStream());
store(read);
} catch (IOException e) {
log.warn("PUT failed with IOException", e);
throw new ResourceException(e);
}
getResponse().setEntity(createXmlRepresentation(read));
if (getRequestedObject() == null) {
getResponse().setStatus(Status.SUCCESS_CREATED);
} else {
getResponse().setStatus(Status.SUCCESS_OK);
}
return null;
} else {
- throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
+ throw new ResourceException(
+ Status.CLIENT_ERROR_BAD_REQUEST, "Unsupported content type: " + entity.getMediaType());
}
}
public abstract void store(D instance) throws ResourceException;
protected void validateEntity(Representation entity) throws ResourceException {}
}
| true | true | public Representation put(Representation entity, Variant variant) throws ResourceException {
if (entity.getMediaType().includes(MediaType.TEXT_XML)) {
validateEntity(entity);
D read;
try {
read = getXmlSerializer().readDocument(entity.getStream());
store(read);
} catch (IOException e) {
log.warn("PUT failed with IOException", e);
throw new ResourceException(e);
}
getResponse().setEntity(createXmlRepresentation(read));
if (getRequestedObject() == null) {
getResponse().setStatus(Status.SUCCESS_CREATED);
} else {
getResponse().setStatus(Status.SUCCESS_OK);
}
return null;
} else {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
}
}
| public Representation put(Representation entity, Variant variant) throws ResourceException {
if (entity.getMediaType().includes(MediaType.TEXT_XML)) {
validateEntity(entity);
D read;
try {
read = getXmlSerializer().readDocument(entity.getStream());
store(read);
} catch (IOException e) {
log.warn("PUT failed with IOException", e);
throw new ResourceException(e);
}
getResponse().setEntity(createXmlRepresentation(read));
if (getRequestedObject() == null) {
getResponse().setStatus(Status.SUCCESS_CREATED);
} else {
getResponse().setStatus(Status.SUCCESS_OK);
}
return null;
} else {
throw new ResourceException(
Status.CLIENT_ERROR_BAD_REQUEST, "Unsupported content type: " + entity.getMediaType());
}
}
|
diff --git a/addons/impl/src/main/java/org/jboss/forge/addons/AddonProjectConfigurator.java b/addons/impl/src/main/java/org/jboss/forge/addons/AddonProjectConfigurator.java
index 727d7716f..3dc6a2100 100644
--- a/addons/impl/src/main/java/org/jboss/forge/addons/AddonProjectConfigurator.java
+++ b/addons/impl/src/main/java/org/jboss/forge/addons/AddonProjectConfigurator.java
@@ -1,157 +1,157 @@
/*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addons;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import javax.inject.Inject;
import org.jboss.forge.addons.facets.ForgeAddonAPIFacet;
import org.jboss.forge.addons.facets.ForgeAddonFacet;
import org.jboss.forge.addons.facets.ForgeAddonImplFacet;
import org.jboss.forge.addons.facets.ForgeAddonSPIFacet;
import org.jboss.forge.addons.facets.ForgeAddonTestFacet;
import org.jboss.forge.addons.facets.ForgeContainerAPIFacet;
import org.jboss.forge.container.addons.AddonId;
import org.jboss.forge.container.versions.Version;
import org.jboss.forge.dependencies.Dependency;
import org.jboss.forge.dependencies.builder.DependencyBuilder;
import org.jboss.forge.facets.FacetFactory;
import org.jboss.forge.projects.Project;
import org.jboss.forge.projects.ProjectFacet;
import org.jboss.forge.projects.ProjectFactory;
import org.jboss.forge.projects.dependencies.DependencyInstaller;
import org.jboss.forge.projects.facets.MetadataFacet;
import org.jboss.forge.resource.DirectoryResource;
/**
* Creates Forge Addon projects
*
* @author <a href="mailto:[email protected]">George Gastaldi</a>
*
*/
@SuppressWarnings("unchecked")
class AddonProjectConfigurator
{
private Logger log = Logger.getLogger(getClass().getName());
@Inject
private FacetFactory facetFactory;
@Inject
private ProjectFactory projectFactory;
@Inject
private DependencyInstaller dependencyInstaller;
public void setupSimpleAddonProject(Project project, Version forgeVersion, Iterable<AddonId> dependencyAddons)
{
project.install(facetFactory.create(ForgeAddonFacet.class, project));
installSelectedAddons(project, dependencyAddons, false);
}
/**
* Create a Forge Project with the full structure (api,impl,tests,spi and addon)
*/
public void setupAddonProject(Project project, Version forgeVersion, Iterable<AddonId> dependencyAddons)
{
MetadataFacet metadata = project.getFacet(MetadataFacet.class);
String projectName = metadata.getProjectName();
metadata.setProjectName(projectName + "-parent");
DirectoryResource newRoot = project.getProjectRoot().getParent().getChildDirectory(metadata.getProjectName());
// FORGE-877: there's an eclipse (not m2e) limitation that says if a project is located directly in the workspace
- // folder, then the project name must match the project folder name
- if (!newRoot.exists() && !project.getProjectRoot().renameTo(newRoot))
+ // folder, then the imported project's name is always the same as the folder it is contained in.
+ if (newRoot.exists() || !project.getProjectRoot().renameTo(newRoot))
{
log.warning("Could not rename project root");
}
dependencyInstaller.installManaged(project, DependencyBuilder.create(ForgeContainerAPIFacet.FORGE_API_DEPENDENCY)
.setVersion(forgeVersion.getVersionString()));
Project addonProject = createSubmoduleProject(project, "addon", projectName, ForgeAddonFacet.class);
Project apiProject = createSubmoduleProject(project, "api", projectName + "-api", ForgeAddonAPIFacet.class);
Project implProject = createSubmoduleProject(project, "impl", projectName + "-impl", ForgeAddonImplFacet.class);
Project spiProject = createSubmoduleProject(project, "spi", projectName + "-spi", ForgeAddonSPIFacet.class,
ForgeAddonFacet.class);
Project testsProject = createSubmoduleProject(project, "tests", projectName + "-tests",
ForgeAddonTestFacet.class, ForgeAddonFacet.class);
Dependency apiProjectDependency = apiProject.getFacet(MetadataFacet.class).getOutputDependency();
Dependency implProjectDependency = implProject.getFacet(MetadataFacet.class).getOutputDependency();
Dependency spiProjectDependency = DependencyBuilder.create(
spiProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon");
Dependency addonProjectDependency = DependencyBuilder.create(
addonProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon");
dependencyInstaller.installManaged(project, addonProjectDependency);
dependencyInstaller.installManaged(project, apiProjectDependency);
dependencyInstaller.installManaged(project, implProjectDependency);
dependencyInstaller.installManaged(project, spiProjectDependency);
installSelectedAddons(project, dependencyAddons, true);
installSelectedAddons(addonProject, dependencyAddons, false);
installSelectedAddons(testsProject, dependencyAddons, false);
dependencyInstaller.install(addonProject, DependencyBuilder.create(apiProjectDependency));
dependencyInstaller.install(addonProject, DependencyBuilder.create(implProjectDependency)
.setScopeType("runtime"));
dependencyInstaller.install(addonProject, DependencyBuilder.create(spiProjectDependency));
dependencyInstaller.install(implProject, DependencyBuilder.create(apiProjectDependency).setScopeType("provided"));
dependencyInstaller.install(implProject, DependencyBuilder.create(spiProjectDependency).setScopeType("provided"));
dependencyInstaller.install(apiProject, DependencyBuilder.create(spiProjectDependency).setScopeType("provided"));
dependencyInstaller.install(testsProject, addonProjectDependency);
project.getProjectRoot().getChild("src").delete(true);
}
private void installSelectedAddons(final Project project, Iterable<AddonId> addons, boolean managed)
{
for (AddonId addon : addons)
{
String[] mavenCoords = addon.getName().split(":");
DependencyBuilder dependency = DependencyBuilder.create().setGroupId(mavenCoords[0])
.setArtifactId(mavenCoords[1])
.setVersion(addon.getVersion().getVersionString()).setClassifier("forge-addon");
if (managed)
{
dependencyInstaller.installManaged(project, dependency);
}
else
{
dependencyInstaller.install(project, dependency);
}
}
}
private Project createSubmoduleProject(final Project parent, String moduleName, String artifactId,
Class<? extends ProjectFacet>... requiredProjectFacets)
{
DirectoryResource location = parent.getProjectRoot().getOrCreateChildDirectory(moduleName);
Set<Class<? extends ProjectFacet>> facets = new HashSet<Class<? extends ProjectFacet>>();
facets.addAll(Arrays.asList(requiredProjectFacets));
facets.add(ForgeContainerAPIFacet.class);
Project project = projectFactory.createProject(location, facets);
MetadataFacet metadata = project.getFacet(MetadataFacet.class);
metadata.setProjectName(artifactId);
return project;
}
}
| true | true | public void setupAddonProject(Project project, Version forgeVersion, Iterable<AddonId> dependencyAddons)
{
MetadataFacet metadata = project.getFacet(MetadataFacet.class);
String projectName = metadata.getProjectName();
metadata.setProjectName(projectName + "-parent");
DirectoryResource newRoot = project.getProjectRoot().getParent().getChildDirectory(metadata.getProjectName());
// FORGE-877: there's an eclipse (not m2e) limitation that says if a project is located directly in the workspace
// folder, then the project name must match the project folder name
if (!newRoot.exists() && !project.getProjectRoot().renameTo(newRoot))
{
log.warning("Could not rename project root");
}
dependencyInstaller.installManaged(project, DependencyBuilder.create(ForgeContainerAPIFacet.FORGE_API_DEPENDENCY)
.setVersion(forgeVersion.getVersionString()));
Project addonProject = createSubmoduleProject(project, "addon", projectName, ForgeAddonFacet.class);
Project apiProject = createSubmoduleProject(project, "api", projectName + "-api", ForgeAddonAPIFacet.class);
Project implProject = createSubmoduleProject(project, "impl", projectName + "-impl", ForgeAddonImplFacet.class);
Project spiProject = createSubmoduleProject(project, "spi", projectName + "-spi", ForgeAddonSPIFacet.class,
ForgeAddonFacet.class);
Project testsProject = createSubmoduleProject(project, "tests", projectName + "-tests",
ForgeAddonTestFacet.class, ForgeAddonFacet.class);
Dependency apiProjectDependency = apiProject.getFacet(MetadataFacet.class).getOutputDependency();
Dependency implProjectDependency = implProject.getFacet(MetadataFacet.class).getOutputDependency();
Dependency spiProjectDependency = DependencyBuilder.create(
spiProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon");
Dependency addonProjectDependency = DependencyBuilder.create(
addonProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon");
dependencyInstaller.installManaged(project, addonProjectDependency);
dependencyInstaller.installManaged(project, apiProjectDependency);
dependencyInstaller.installManaged(project, implProjectDependency);
dependencyInstaller.installManaged(project, spiProjectDependency);
installSelectedAddons(project, dependencyAddons, true);
installSelectedAddons(addonProject, dependencyAddons, false);
installSelectedAddons(testsProject, dependencyAddons, false);
dependencyInstaller.install(addonProject, DependencyBuilder.create(apiProjectDependency));
dependencyInstaller.install(addonProject, DependencyBuilder.create(implProjectDependency)
.setScopeType("runtime"));
dependencyInstaller.install(addonProject, DependencyBuilder.create(spiProjectDependency));
dependencyInstaller.install(implProject, DependencyBuilder.create(apiProjectDependency).setScopeType("provided"));
dependencyInstaller.install(implProject, DependencyBuilder.create(spiProjectDependency).setScopeType("provided"));
dependencyInstaller.install(apiProject, DependencyBuilder.create(spiProjectDependency).setScopeType("provided"));
dependencyInstaller.install(testsProject, addonProjectDependency);
project.getProjectRoot().getChild("src").delete(true);
}
| public void setupAddonProject(Project project, Version forgeVersion, Iterable<AddonId> dependencyAddons)
{
MetadataFacet metadata = project.getFacet(MetadataFacet.class);
String projectName = metadata.getProjectName();
metadata.setProjectName(projectName + "-parent");
DirectoryResource newRoot = project.getProjectRoot().getParent().getChildDirectory(metadata.getProjectName());
// FORGE-877: there's an eclipse (not m2e) limitation that says if a project is located directly in the workspace
// folder, then the imported project's name is always the same as the folder it is contained in.
if (newRoot.exists() || !project.getProjectRoot().renameTo(newRoot))
{
log.warning("Could not rename project root");
}
dependencyInstaller.installManaged(project, DependencyBuilder.create(ForgeContainerAPIFacet.FORGE_API_DEPENDENCY)
.setVersion(forgeVersion.getVersionString()));
Project addonProject = createSubmoduleProject(project, "addon", projectName, ForgeAddonFacet.class);
Project apiProject = createSubmoduleProject(project, "api", projectName + "-api", ForgeAddonAPIFacet.class);
Project implProject = createSubmoduleProject(project, "impl", projectName + "-impl", ForgeAddonImplFacet.class);
Project spiProject = createSubmoduleProject(project, "spi", projectName + "-spi", ForgeAddonSPIFacet.class,
ForgeAddonFacet.class);
Project testsProject = createSubmoduleProject(project, "tests", projectName + "-tests",
ForgeAddonTestFacet.class, ForgeAddonFacet.class);
Dependency apiProjectDependency = apiProject.getFacet(MetadataFacet.class).getOutputDependency();
Dependency implProjectDependency = implProject.getFacet(MetadataFacet.class).getOutputDependency();
Dependency spiProjectDependency = DependencyBuilder.create(
spiProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon");
Dependency addonProjectDependency = DependencyBuilder.create(
addonProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon");
dependencyInstaller.installManaged(project, addonProjectDependency);
dependencyInstaller.installManaged(project, apiProjectDependency);
dependencyInstaller.installManaged(project, implProjectDependency);
dependencyInstaller.installManaged(project, spiProjectDependency);
installSelectedAddons(project, dependencyAddons, true);
installSelectedAddons(addonProject, dependencyAddons, false);
installSelectedAddons(testsProject, dependencyAddons, false);
dependencyInstaller.install(addonProject, DependencyBuilder.create(apiProjectDependency));
dependencyInstaller.install(addonProject, DependencyBuilder.create(implProjectDependency)
.setScopeType("runtime"));
dependencyInstaller.install(addonProject, DependencyBuilder.create(spiProjectDependency));
dependencyInstaller.install(implProject, DependencyBuilder.create(apiProjectDependency).setScopeType("provided"));
dependencyInstaller.install(implProject, DependencyBuilder.create(spiProjectDependency).setScopeType("provided"));
dependencyInstaller.install(apiProject, DependencyBuilder.create(spiProjectDependency).setScopeType("provided"));
dependencyInstaller.install(testsProject, addonProjectDependency);
project.getProjectRoot().getChild("src").delete(true);
}
|
diff --git a/hale/eu.esdihumboldt.hale.ui.util/src/eu/esdihumboldt/hale/ui/util/viewer/tree/TreePathFilteredTree.java b/hale/eu.esdihumboldt.hale.ui.util/src/eu/esdihumboldt/hale/ui/util/viewer/tree/TreePathFilteredTree.java
index 99f3defb2..69b9e4563 100644
--- a/hale/eu.esdihumboldt.hale.ui.util/src/eu/esdihumboldt/hale/ui/util/viewer/tree/TreePathFilteredTree.java
+++ b/hale/eu.esdihumboldt.hale.ui.util/src/eu/esdihumboldt/hale/ui/util/viewer/tree/TreePathFilteredTree.java
@@ -1,135 +1,135 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2011.
*/
package eu.esdihumboldt.hale.ui.util.viewer.tree;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.viewers.ITreePathContentProvider;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
/**
* Filtered tree that supports a {@link ITreePathContentProvider} and
* a {@link TreePathPatternFilter}
* @author Simon Templer
*/
public class TreePathFilteredTree extends FilteredTree {
/**
* Tree viewer that calls filters with {@link TreePath}s as elements
*/
public static class TreePathTreeViewer extends /*Notifying*/TreeViewer {
/**
* @see TreeViewer#TreeViewer(Composite, int)
*/
public TreePathTreeViewer(Composite parent, int style) {
super(parent, style);
}
/**
* @see StructuredViewer#getFilteredChildren(Object)
*/
@Override
protected Object[] getFilteredChildren(Object parent) {
Object[] elements = getRawChildren(parent);
if (parent != null && !(parent instanceof TreePath)) {
// root element
parent = TreePath.EMPTY;
}
TreePath parentPath = (TreePath) parent;
// create tree paths from elements
List<TreePath> paths = getPathsForElements(parentPath, elements);
List<ViewerFilter> filters = Arrays.asList(getFilters());
if (filters != null) {
for (Iterator<ViewerFilter> iter = filters.iterator(); iter.hasNext();) {
ViewerFilter f = iter.next();
- // call TreePath overload of filter method
+ // call filter with TreePath objects
Object[] filteredResult = f.filter(this, parent, paths.toArray());
paths.clear();
for (Object res : filteredResult) {
paths.add((TreePath) res);
}
}
}
List<Object> result = new ArrayList<Object>();
for (TreePath path : paths) {
result.add(path.getLastSegment());
}
return result.toArray();
}
}
/**
* @see FilteredTree#FilteredTree(Composite, int, PatternFilter, boolean)
*/
public TreePathFilteredTree(Composite parent, int treeStyle,
PatternFilter filter, boolean useNewLook) {
super(parent, treeStyle, filter, useNewLook);
}
/**
* @see FilteredTree#doCreateTreeViewer(Composite, int)
*/
@Override
protected TreeViewer doCreateTreeViewer(Composite parent, int style) {
return new TreePathTreeViewer(parent, style);
}
/**
* Get the tree paths for the given objects with the given parent path.
* @param parentPath the parent path for each object
* @param elements the objects
* @return the list of tree paths
*/
public static List<TreePath> getPathsForElements(TreePath parentPath,
Object[] elements) {
List<TreePath> paths = new ArrayList<TreePath>();
// create tree paths from elements
List<Object> parentSegments = new ArrayList<Object>();
if (parentPath != null) {
for (int i = 0; i < parentPath.getSegmentCount(); i++) {
parentSegments.add(parentPath.getSegment(i));
}
}
for (Object element : elements) {
TreePath path;
if (parentPath == null) {
path = new TreePath(new Object[]{element});
}
else {
parentSegments.add(element);
path = new TreePath(parentSegments.toArray());
parentSegments.remove(parentSegments.size() - 1);
}
paths.add(path);
}
return paths;
}
}
| true | true | protected Object[] getFilteredChildren(Object parent) {
Object[] elements = getRawChildren(parent);
if (parent != null && !(parent instanceof TreePath)) {
// root element
parent = TreePath.EMPTY;
}
TreePath parentPath = (TreePath) parent;
// create tree paths from elements
List<TreePath> paths = getPathsForElements(parentPath, elements);
List<ViewerFilter> filters = Arrays.asList(getFilters());
if (filters != null) {
for (Iterator<ViewerFilter> iter = filters.iterator(); iter.hasNext();) {
ViewerFilter f = iter.next();
// call TreePath overload of filter method
Object[] filteredResult = f.filter(this, parent, paths.toArray());
paths.clear();
for (Object res : filteredResult) {
paths.add((TreePath) res);
}
}
}
List<Object> result = new ArrayList<Object>();
for (TreePath path : paths) {
result.add(path.getLastSegment());
}
return result.toArray();
}
| protected Object[] getFilteredChildren(Object parent) {
Object[] elements = getRawChildren(parent);
if (parent != null && !(parent instanceof TreePath)) {
// root element
parent = TreePath.EMPTY;
}
TreePath parentPath = (TreePath) parent;
// create tree paths from elements
List<TreePath> paths = getPathsForElements(parentPath, elements);
List<ViewerFilter> filters = Arrays.asList(getFilters());
if (filters != null) {
for (Iterator<ViewerFilter> iter = filters.iterator(); iter.hasNext();) {
ViewerFilter f = iter.next();
// call filter with TreePath objects
Object[] filteredResult = f.filter(this, parent, paths.toArray());
paths.clear();
for (Object res : filteredResult) {
paths.add((TreePath) res);
}
}
}
List<Object> result = new ArrayList<Object>();
for (TreePath path : paths) {
result.add(path.getLastSegment());
}
return result.toArray();
}
|
diff --git a/src/de/schildbach/pte/AbstractEfaProvider.java b/src/de/schildbach/pte/AbstractEfaProvider.java
index 3cfeced9..3345364f 100644
--- a/src/de/schildbach/pte/AbstractEfaProvider.java
+++ b/src/de/schildbach/pte/AbstractEfaProvider.java
@@ -1,2055 +1,2058 @@
/*
* Copyright 2010, 2011 the original author or authors.
*
* 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.schildbach.pte;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import de.schildbach.pte.dto.Connection;
import de.schildbach.pte.dto.Departure;
import de.schildbach.pte.dto.Fare;
import de.schildbach.pte.dto.Fare.Type;
import de.schildbach.pte.dto.GetConnectionDetailsResult;
import de.schildbach.pte.dto.Line;
import de.schildbach.pte.dto.LineDestination;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.LocationType;
import de.schildbach.pte.dto.NearbyStationsResult;
import de.schildbach.pte.dto.Point;
import de.schildbach.pte.dto.QueryConnectionsResult;
import de.schildbach.pte.dto.QueryConnectionsResult.Status;
import de.schildbach.pte.dto.QueryDeparturesResult;
import de.schildbach.pte.dto.StationDepartures;
import de.schildbach.pte.dto.Stop;
import de.schildbach.pte.exception.ParserException;
import de.schildbach.pte.exception.SessionExpiredException;
import de.schildbach.pte.util.Color;
import de.schildbach.pte.util.ParserUtils;
import de.schildbach.pte.util.XmlPullUtil;
/**
* @author Andreas Schildbach
*/
public abstract class AbstractEfaProvider implements NetworkProvider
{
private final String apiBase;
private final String additionalQueryParameter;
private final boolean canAcceptPoiID;
private final XmlPullParserFactory parserFactory;
public AbstractEfaProvider()
{
this(null, null);
}
public AbstractEfaProvider(final String apiBase, final String additionalQueryParameter)
{
this(apiBase, additionalQueryParameter, false);
}
public AbstractEfaProvider(final String apiBase, final String additionalQueryParameter, final boolean canAcceptPoiID)
{
try
{
parserFactory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
this.apiBase = apiBase;
this.additionalQueryParameter = additionalQueryParameter;
this.canAcceptPoiID = canAcceptPoiID;
}
protected TimeZone timeZone()
{
return TimeZone.getTimeZone("Europe/Berlin");
}
private final void appendCommonRequestParams(final StringBuilder uri)
{
uri.append("?outputFormat=XML");
uri.append("&coordOutputFormat=WGS84");
if (additionalQueryParameter != null)
uri.append('&').append(additionalQueryParameter);
}
protected List<Location> xmlStopfinderRequest(final Location constraint) throws IOException
{
final StringBuilder uri = new StringBuilder(apiBase);
uri.append("XML_STOPFINDER_REQUEST");
appendCommonRequestParams(uri);
uri.append("&locationServerActive=1");
appendLocation(uri, constraint, "sf");
if (constraint.type == LocationType.ANY)
{
uri.append("&SpEncId=0");
uri.append("&anyObjFilter_sf=126"); // 1=place 2=stop 4=street 8=address 16=crossing 32=poi 64=postcode
uri.append("&reducedAnyPostcodeObjFilter_sf=64&reducedAnyTooManyObjFilter_sf=2");
uri.append("&useHouseNumberList=true®ionID_sf=1");
}
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(uri.toString());
final XmlPullParser pp = parserFactory.newPullParser();
pp.setInput(is, null);
enterItdRequest(pp);
final List<Location> results = new ArrayList<Location>();
XmlPullUtil.enter(pp, "itdStopFinderRequest");
XmlPullUtil.require(pp, "itdOdv");
if (!"sf".equals(pp.getAttributeValue(null, "usage")))
throw new IllegalStateException("cannot find <itdOdv usage=\"sf\" />");
XmlPullUtil.enter(pp, "itdOdv");
XmlPullUtil.require(pp, "itdOdvPlace");
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "itdOdvName");
final String nameState = pp.getAttributeValue(null, "state");
XmlPullUtil.enter(pp, "itdOdvName");
if (XmlPullUtil.test(pp, "itdMessage"))
XmlPullUtil.next(pp);
if ("identified".equals(nameState) || "list".equals(nameState))
{
while (XmlPullUtil.test(pp, "odvNameElem"))
results.add(processOdvNameElem(pp, null));
}
else if ("notidentified".equals(nameState))
{
// do nothing
}
else
{
throw new RuntimeException("unknown nameState '" + nameState + "' on " + uri);
}
XmlPullUtil.exit(pp, "itdOdvName");
XmlPullUtil.exit(pp, "itdOdv");
XmlPullUtil.exit(pp, "itdStopFinderRequest");
return results;
}
catch (final XmlPullParserException x)
{
throw new ParserException(x);
}
finally
{
if (is != null)
is.close();
}
}
protected List<Location> xmlCoordRequest(final int lat, final int lon, final int maxDistance, final int maxStations) throws IOException
{
final StringBuilder uri = new StringBuilder(apiBase);
uri.append("XML_COORD_REQUEST");
appendCommonRequestParams(uri);
uri.append("&coord=").append(String.format(Locale.ENGLISH, "%2.6f:%2.6f:WGS84", latLonToDouble(lon), latLonToDouble(lat)));
uri.append("&coordListOutputFormat=STRING");
uri.append("&max=").append(maxStations != 0 ? maxStations : 50);
uri.append("&inclFilter=1&radius_1=").append(maxDistance != 0 ? maxDistance : 1320);
uri.append("&type_1=STOP");
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(uri.toString());
final XmlPullParser pp = parserFactory.newPullParser();
pp.setInput(is, null);
enterItdRequest(pp);
XmlPullUtil.enter(pp, "itdCoordInfoRequest");
XmlPullUtil.enter(pp, "itdCoordInfo");
XmlPullUtil.enter(pp, "coordInfoRequest");
XmlPullUtil.exit(pp, "coordInfoRequest");
final List<Location> results = new ArrayList<Location>();
if (XmlPullUtil.test(pp, "coordInfoItemList"))
{
XmlPullUtil.enter(pp, "coordInfoItemList");
while (XmlPullUtil.test(pp, "coordInfoItem"))
{
if (!"STOP".equals(pp.getAttributeValue(null, "type")))
throw new RuntimeException("unknown type");
final int id = XmlPullUtil.intAttr(pp, "id");
final String name = normalizeLocationName(XmlPullUtil.attr(pp, "name"));
final String place = normalizeLocationName(XmlPullUtil.attr(pp, "locality"));
XmlPullUtil.enter(pp, "coordInfoItem");
// FIXME this is always only one coordinate
final Point coord = processItdPathCoordinates(pp).get(0);
XmlPullUtil.exit(pp, "coordInfoItem");
results.add(new Location(LocationType.STATION, id, coord.lat, coord.lon, place, name));
}
XmlPullUtil.exit(pp, "coordInfoItemList");
}
return results;
}
catch (final XmlPullParserException x)
{
throw new ParserException(x);
}
finally
{
if (is != null)
is.close();
}
}
public List<Location> autocompleteStations(final CharSequence constraint) throws IOException
{
final StringBuilder uri = new StringBuilder(apiBase);
uri.append("XSLT_TRIP_REQUEST2");
appendCommonRequestParams(uri);
uri.append("&type_origin=any");
uri.append("&name_origin=").append(ParserUtils.urlEncode(constraint.toString(), "ISO-8859-1"));
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(uri.toString());
final XmlPullParser pp = parserFactory.newPullParser();
pp.setInput(is, null);
enterItdRequest(pp);
final List<Location> results = new ArrayList<Location>();
// parse odv name elements
if (!XmlPullUtil.jumpToStartTag(pp, null, "itdOdv") || !"origin".equals(pp.getAttributeValue(null, "usage")))
throw new IllegalStateException("cannot find <itdOdv usage=\"origin\" />");
XmlPullUtil.enter(pp, "itdOdv");
final String place = processItdOdvPlace(pp);
if (!XmlPullUtil.test(pp, "itdOdvName"))
throw new IllegalStateException("cannot find <itdOdvName />");
final String nameState = XmlPullUtil.attr(pp, "state");
XmlPullUtil.enter(pp, "itdOdvName");
if (XmlPullUtil.test(pp, "itdMessage"))
XmlPullUtil.next(pp);
if ("identified".equals(nameState) || "list".equals(nameState))
while (XmlPullUtil.test(pp, "odvNameElem"))
results.add(processOdvNameElem(pp, place));
// parse assigned stops
if (XmlPullUtil.jumpToStartTag(pp, null, "itdOdvAssignedStops"))
{
XmlPullUtil.enter(pp, "itdOdvAssignedStops");
while (XmlPullUtil.test(pp, "itdOdvAssignedStop"))
{
final Location location = processItdOdvAssignedStop(pp);
if (!results.contains(location))
results.add(location);
}
}
return results;
}
catch (final XmlPullParserException x)
{
throw new ParserException(x);
}
finally
{
if (is != null)
is.close();
}
}
private String processItdOdvPlace(final XmlPullParser pp) throws XmlPullParserException, IOException
{
if (!XmlPullUtil.test(pp, "itdOdvPlace"))
throw new IllegalStateException("expecting <itdOdvPlace />");
final String placeState = XmlPullUtil.attr(pp, "state");
XmlPullUtil.enter(pp, "itdOdvPlace");
String place = null;
if ("identified".equals(placeState))
{
if (XmlPullUtil.test(pp, "odvPlaceElem"))
{
XmlPullUtil.enter(pp, "odvPlaceElem");
place = normalizeLocationName(pp.getText());
XmlPullUtil.exit(pp, "odvPlaceElem");
}
}
XmlPullUtil.exit(pp, "itdOdvPlace");
return place;
}
private Location processOdvNameElem(final XmlPullParser pp, final String defaultPlace) throws XmlPullParserException, IOException
{
if (!XmlPullUtil.test(pp, "odvNameElem"))
throw new IllegalStateException("expecting <odvNameElem />");
final String anyType = pp.getAttributeValue(null, "anyType");
final String idStr = pp.getAttributeValue(null, "id");
final String stopIdStr = pp.getAttributeValue(null, "stopID");
final String poiIdStr = pp.getAttributeValue(null, "poiID");
final String streetIdStr = pp.getAttributeValue(null, "streetID");
final String place = !"loc".equals(anyType) ? normalizeLocationName(pp.getAttributeValue(null, "locality")) : null;
final String name = normalizeLocationName(pp.getAttributeValue(null, "objectName"));
int lat = 0, lon = 0;
if ("WGS84".equals(pp.getAttributeValue(null, "mapName")))
{
lat = Integer.parseInt(pp.getAttributeValue(null, "y"));
lon = Integer.parseInt(pp.getAttributeValue(null, "x"));
}
LocationType type;
int id;
if ("stop".equals(anyType))
{
type = LocationType.STATION;
id = Integer.parseInt(idStr);
}
else if ("poi".equals(anyType) || "poiHierarchy".equals(anyType))
{
type = LocationType.POI;
id = Integer.parseInt(idStr);
}
else if ("loc".equals(anyType))
{
type = LocationType.ANY;
id = 0;
}
else if ("postcode".equals(anyType) || "street".equals(anyType) || "crossing".equals(anyType) || "address".equals(anyType)
|| "singlehouse".equals(anyType) || "buildingname".equals(anyType))
{
type = LocationType.ADDRESS;
id = 0;
}
else if (stopIdStr != null)
{
type = LocationType.STATION;
id = Integer.parseInt(stopIdStr);
}
else if (poiIdStr != null)
{
type = LocationType.POI;
id = Integer.parseInt(poiIdStr);
}
else if (stopIdStr == null && idStr == null && (lat != 0 || lon != 0))
{
type = LocationType.ADDRESS;
id = 0;
}
else if (streetIdStr != null)
{
type = LocationType.ADDRESS;
id = Integer.parseInt(streetIdStr);
}
else
{
throw new IllegalArgumentException("unknown type: " + anyType + " " + idStr + " " + stopIdStr);
}
XmlPullUtil.enter(pp, "odvNameElem");
final String longName = normalizeLocationName(pp.getText());
XmlPullUtil.exit(pp, "odvNameElem");
return new Location(type, id, lat, lon, place != null ? place : defaultPlace, name != null ? name : longName);
}
private Location processItdOdvAssignedStop(final XmlPullParser pp) throws XmlPullParserException, IOException
{
final int id = Integer.parseInt(pp.getAttributeValue(null, "stopID"));
int lat = 0, lon = 0;
if ("WGS84".equals(pp.getAttributeValue(null, "mapName")))
{
lat = Integer.parseInt(pp.getAttributeValue(null, "y"));
lon = Integer.parseInt(pp.getAttributeValue(null, "x"));
}
final String place = normalizeLocationName(XmlPullUtil.attr(pp, "place"));
XmlPullUtil.enter(pp, "itdOdvAssignedStop");
final String name = normalizeLocationName(pp.getText());
XmlPullUtil.exit(pp, "itdOdvAssignedStop");
return new Location(LocationType.STATION, id, lat, lon, place, name);
}
protected abstract String nearbyStationUri(int stationId);
public NearbyStationsResult queryNearbyStations(final Location location, final int maxDistance, final int maxStations) throws IOException
{
if (location.hasLocation())
return new NearbyStationsResult(xmlCoordRequest(location.lat, location.lon, maxDistance, maxStations));
if (location.type != LocationType.STATION)
throw new IllegalArgumentException("cannot handle: " + location.type);
if (!location.hasId())
throw new IllegalArgumentException("at least one of stationId or lat/lon must be given");
final String uri = nearbyStationUri(location.id);
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(uri);
final XmlPullParser pp = parserFactory.newPullParser();
pp.setInput(is, null);
enterItdRequest(pp);
if (!XmlPullUtil.jumpToStartTag(pp, null, "itdOdv") || !"dm".equals(pp.getAttributeValue(null, "usage")))
throw new IllegalStateException("cannot find <itdOdv usage=\"dm\" />");
XmlPullUtil.enter(pp, "itdOdv");
final String place = processItdOdvPlace(pp);
XmlPullUtil.require(pp, "itdOdvName");
final String nameState = pp.getAttributeValue(null, "state");
XmlPullUtil.enter(pp, "itdOdvName");
if ("identified".equals(nameState))
{
final Location ownLocation = processOdvNameElem(pp, place);
final Location ownStation = ownLocation.type == LocationType.STATION ? ownLocation : null;
final List<Location> stations = new ArrayList<Location>();
if (XmlPullUtil.jumpToStartTag(pp, null, "itdOdvAssignedStops"))
{
XmlPullUtil.enter(pp, "itdOdvAssignedStops");
while (XmlPullUtil.test(pp, "itdOdvAssignedStop"))
{
final String parsedMapName = pp.getAttributeValue(null, "mapName");
if (parsedMapName != null)
{
final int parsedLocationId = XmlPullUtil.intAttr(pp, "stopID");
// final String parsedLongName = normalizeLocationName(XmlPullUtil.attr(pp,
// "nameWithPlace"));
final String parsedPlace = normalizeLocationName(XmlPullUtil.attr(pp, "place"));
final int parsedLon = XmlPullUtil.intAttr(pp, "x");
final int parsedLat = XmlPullUtil.intAttr(pp, "y");
XmlPullUtil.enter(pp, "itdOdvAssignedStop");
final String parsedName = normalizeLocationName(pp.getText());
XmlPullUtil.exit(pp, "itdOdvAssignedStop");
if (!"WGS84".equals(parsedMapName))
throw new IllegalStateException("unknown mapName: " + parsedMapName);
final Location newStation = new Location(LocationType.STATION, parsedLocationId, parsedLat, parsedLon, parsedPlace,
parsedName);
if (!stations.contains(newStation))
stations.add(newStation);
}
else
{
if (!pp.isEmptyElementTag())
{
XmlPullUtil.enter(pp, "itdOdvAssignedStop");
XmlPullUtil.exit(pp, "itdOdvAssignedStop");
}
else
{
XmlPullUtil.next(pp);
}
}
}
}
if (ownStation != null && !stations.contains(ownStation))
stations.add(ownStation);
if (maxStations == 0 || maxStations >= stations.size())
return new NearbyStationsResult(stations);
else
return new NearbyStationsResult(stations.subList(0, maxStations));
}
else if ("list".equals(nameState))
{
final List<Location> stations = new ArrayList<Location>();
if (XmlPullUtil.test(pp, "itdMessage"))
XmlPullUtil.next(pp);
while (XmlPullUtil.test(pp, "odvNameElem"))
{
final Location newLocation = processOdvNameElem(pp, place);
if (newLocation.type == LocationType.STATION && !stations.contains(newLocation))
stations.add(newLocation);
}
return new NearbyStationsResult(stations);
}
else if ("notidentified".equals(nameState))
{
return new NearbyStationsResult(NearbyStationsResult.Status.INVALID_STATION);
}
else
{
throw new RuntimeException("unknown nameState '" + nameState + "' on " + uri);
}
// XmlPullUtil.exit(pp, "itdOdvName");
}
catch (final XmlPullParserException x)
{
throw new ParserException(x);
}
finally
{
if (is != null)
is.close();
}
}
private static final Pattern P_LINE_IRE = Pattern.compile("IRE\\d+");
private static final Pattern P_LINE_RE = Pattern.compile("RE\\d+");
private static final Pattern P_LINE_RB = Pattern.compile("RB\\d+");
private static final Pattern P_LINE_VB = Pattern.compile("VB\\d+");
private static final Pattern P_LINE_OE = Pattern.compile("OE\\d+");
private static final Pattern P_LINE_R = Pattern.compile("R\\d+(/R\\d+|\\(z\\))?");
private static final Pattern P_LINE_U = Pattern.compile("U\\d+");
private static final Pattern P_LINE_S = Pattern.compile("^(?:%)?(S\\d+)");
private static final Pattern P_LINE_NUMBER = Pattern.compile("\\d+");
private static final Pattern P_LINE_Y = Pattern.compile("\\d+Y");
protected String parseLine(final String mot, final String name, final String longName, final String noTrainName)
{
if (mot == null)
{
if (noTrainName != null)
{
final String str = name != null ? name : "";
if (noTrainName.equals("S-Bahn"))
return 'S' + str;
if (noTrainName.equals("U-Bahn"))
return 'U' + str;
if (noTrainName.equals("Straßenbahn"))
return 'T' + str;
if (noTrainName.equals("Badner Bahn"))
return 'T' + str;
if (noTrainName.equals("Stadtbus"))
return 'B' + str;
if (noTrainName.equals("Citybus"))
return 'B' + str;
if (noTrainName.equals("Regionalbus"))
return 'B' + str;
if (noTrainName.equals("ÖBB-Postbus"))
return 'B' + str;
if (noTrainName.equals("Autobus"))
return 'B' + str;
if (noTrainName.equals("Discobus"))
return 'B' + str;
if (noTrainName.equals("Nachtbus"))
return 'B' + str;
if (noTrainName.equals("Anrufsammeltaxi"))
return 'B' + str;
if (noTrainName.equals("Ersatzverkehr"))
return 'B' + str;
if (noTrainName.equals("Vienna Airport Lines"))
return 'B' + str;
}
throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '"
+ noTrainName + "'");
}
final int t = Integer.parseInt(mot);
if (t == 0)
{
final String[] parts = longName.split(" ", 3);
final String type = parts[0];
final String num = parts.length >= 2 ? parts[1] : null;
final String str = type + (num != null ? num : "");
if (type.equals("EC")) // Eurocity
return 'I' + str;
if (type.equals("EN")) // Euronight
return 'I' + str;
if (type.equals("IC")) // Intercity
return 'I' + str;
if (type.equals("ICE")) // Intercity Express
return 'I' + str;
if (type.equals("X")) // InterConnex
return 'I' + str;
if (type.equals("CNL")) // City Night Line
return 'I' + str;
if (type.equals("THA")) // Thalys
return 'I' + str;
if (type.equals("TGV")) // TGV
return 'I' + str;
if (type.equals("RJ")) // railjet
return 'I' + str;
if (type.equals("OEC")) // ÖBB-EuroCity
return 'I' + str;
if (type.equals("OIC")) // ÖBB-InterCity
return 'I' + str;
if (type.equals("HT")) // First Hull Trains, GB
return 'I' + str;
if (type.equals("MT")) // Müller Touren, Schnee Express
return 'I' + str;
if (type.equals("HKX")) // Hamburg-Koeln-Express
return 'I' + str;
if (type.equals("DNZ")) // Nachtzug Basel-Moskau
return 'I' + str;
if (type.equals("IR")) // Interregio
return 'R' + str;
if (type.equals("IRE")) // Interregio-Express
return 'R' + str;
if (P_LINE_IRE.matcher(type).matches())
return 'R' + str;
if (type.equals("RE")) // Regional-Express
return 'R' + str;
if (type.equals("R-Bahn")) // Regional-Express, VRR
return 'R' + str;
if (type.equals("REX")) // RegionalExpress, Österreich
return 'R' + str;
if ("EZ".equals(type)) // ÖBB ErlebnisBahn
return 'R' + str;
if (P_LINE_RE.matcher(type).matches())
return 'R' + str;
if (type.equals("RB")) // Regionalbahn
return 'R' + str;
if (P_LINE_RB.matcher(type).matches())
return 'R' + str;
if (type.equals("R")) // Regionalzug
return 'R' + str;
if (P_LINE_R.matcher(type).matches())
return 'R' + str;
if (type.equals("Bahn"))
return 'R' + str;
if (type.equals("Regionalbahn"))
return 'R' + str;
if (type.equals("D")) // Schnellzug
return 'R' + str;
if (type.equals("E")) // Eilzug
return 'R' + str;
if (type.equals("S")) // ~Innsbruck
return 'R' + str;
if (type.equals("WFB")) // Westfalenbahn
return 'R' + str;
if ("Westfalenbahn".equals(type)) // Westfalenbahn
return 'R' + name;
if (type.equals("NWB")) // NordWestBahn
return 'R' + str;
if (type.equals("NordWestBahn"))
return 'R' + str;
if (type.equals("ME")) // Metronom
return 'R' + str;
if (type.equals("ERB")) // eurobahn
return 'R' + str;
if (type.equals("CAN")) // cantus
return 'R' + str;
if (type.equals("HEX")) // Veolia Verkehr Sachsen-Anhalt
return 'R' + str;
if (type.equals("EB")) // Erfurter Bahn
return 'R' + str;
if (type.equals("MRB")) // Mittelrheinbahn
return 'R' + str;
if (type.equals("ABR")) // ABELLIO Rail NRW
return 'R' + str;
if (type.equals("NEB")) // Niederbarnimer Eisenbahn
return 'R' + str;
if (type.equals("OE")) // Ostdeutsche Eisenbahn
return 'R' + str;
if (P_LINE_OE.matcher(type).matches())
return 'R' + str;
if (type.equals("MR")) // Märkische Regiobahn
return 'R' + str;
if (type.equals("OLA")) // Ostseeland Verkehr
return 'R' + str;
if (type.equals("UBB")) // Usedomer Bäderbahn
return 'R' + str;
if (type.equals("EVB")) // Elbe-Weser
return 'R' + str;
if (type.equals("PEG")) // Prignitzer Eisenbahngesellschaft
return 'R' + str;
if (type.equals("RTB")) // Rurtalbahn
return 'R' + str;
if (type.equals("STB")) // Süd-Thüringen-Bahn
return 'R' + str;
if (type.equals("HTB")) // Hellertalbahn
return 'R' + str;
if (type.equals("VBG")) // Vogtlandbahn
return 'R' + str;
if (type.equals("VB")) // Vogtlandbahn
return 'R' + str;
if (P_LINE_VB.matcher(type).matches())
return 'R' + str;
if (type.equals("VX")) // Vogtland Express
return 'R' + str;
if (type.equals("CB")) // City-Bahn Chemnitz
return 'R' + str;
if (type.equals("VEC")) // VECTUS Verkehrsgesellschaft
return 'R' + str;
if (type.equals("HzL")) // Hohenzollerische Landesbahn
return 'R' + str;
if (type.equals("OSB")) // Ortenau-S-Bahn
return 'R' + str;
if (type.equals("SBB")) // SBB
return 'R' + str;
if (type.equals("MBB")) // Mecklenburgische Bäderbahn Molli
return 'R' + str;
if (type.equals("OS")) // Regionalbahn
return 'R' + str;
if (type.equals("SP"))
return 'R' + str;
if (type.equals("Dab")) // Daadetalbahn
return 'R' + str;
if (type.equals("FEG")) // Freiberger Eisenbahngesellschaft
return 'R' + str;
if (type.equals("ARR")) // ARRIVA
return 'R' + str;
if (type.equals("HSB")) // Harzer Schmalspurbahn
return 'R' + str;
if (type.equals("SBE")) // Sächsisch-Böhmische Eisenbahngesellschaft
return 'R' + str;
if (type.equals("ALX")) // Arriva-Länderbahn-Express
return 'R' + str;
if (type.equals("EX")) // ALX verwandelt sich
return 'R' + str;
if (type.equals("MEr")) // metronom regional
return 'R' + str;
if (type.equals("AKN")) // AKN Eisenbahn
return 'R' + str;
if (type.equals("ZUG")) // Regionalbahn
return 'R' + str;
if (type.equals("SOE")) // Sächsisch-Oberlausitzer Eisenbahngesellschaft
return 'R' + str;
if (type.equals("VIA")) // VIAS
return 'R' + str;
if (type.equals("BRB")) // Bayerische Regiobahn
return 'R' + str;
if (type.equals("BLB")) // Berchtesgadener Land Bahn
return 'R' + str;
if (type.equals("HLB")) // Hessische Landesbahn
return 'R' + str;
if (type.equals("NOB")) // NordOstseeBahn
return 'R' + str;
if (type.equals("WEG")) // Wieslauftalbahn
return 'R' + str;
if (type.equals("NBE")) // Nordbahn Eisenbahngesellschaft
return 'R' + str;
if (type.equals("VEN")) // Rhenus Veniro
return 'R' + str;
if (type.equals("DPN")) // Nahreisezug
return 'R' + str;
if (type.equals("SHB")) // Schleswig-Holstein-Bahn
return 'R' + str;
if (type.equals("RBG")) // Regental Bahnbetriebs GmbH
return 'R' + str;
if (type.equals("BOB")) // Bayerische Oberlandbahn
return 'R' + str;
if (type.equals("SWE")) // Südwestdeutsche Verkehrs AG
return 'R' + str;
if (type.equals("VE")) // Vetter
return 'R' + str;
if (type.equals("SDG")) // Sächsische Dampfeisenbahngesellschaft
return 'R' + str;
if (type.equals("PRE")) // Pressnitztalbahn
return 'R' + str;
if (type.equals("VEB")) // Vulkan-Eifel-Bahn
return 'R' + str;
if (type.equals("neg")) // Norddeutsche Eisenbahn Gesellschaft
return 'R' + str;
if (type.equals("AVG")) // Felsenland-Express
return 'R' + str;
if (type.equals("ABG")) // Anhaltische Bahngesellschaft
return 'R' + str;
if (type.equals("LGB")) // Lößnitzgrundbahn
return 'R' + str;
if (type.equals("LEO")) // Chiemgauer Lokalbahn
return 'R' + str;
if (type.equals("WTB")) // Weißeritztalbahn
return 'R' + str;
if (type.equals("P")) // Kasbachtalbahn, Wanderbahn im Regental, Rhön-Zügle
return 'R' + str;
if (type.equals("ÖBA")) // Eisenbahn-Betriebsgesellschaft Ochsenhausen
return 'R' + str;
if (type.equals("MBS")) // Montafonerbahn
return 'R' + str;
if (type.equals("EGP")) // EGP - die Städtebahn GmbH
return 'R' + str;
if (type.equals("SBS")) // EGP - die Städtebahn GmbH
return 'R' + str;
if (type.equals("SES")) // EGP - die Städtebahn GmbH
return 'R' + str;
if (type.equals("agi")) // agilis
return 'R' + str;
if (type.equals("ag")) // agilis
return 'R' + str;
if (type.equals("TLX")) // Trilex (Vogtlandbahn)
return 'R' + str;
if (type.equals("BE")) // Grensland-Express, Niederlande
return 'R' + str;
if (type.equals("MEL")) // Museums-Eisenbahn Losheim
return 'R' + str;
if (type.equals("Abellio-Zug")) // Abellio
return 'R' + str;
if ("SWEG-Zug".equals(type)) // Südwestdeutschen Verkehrs-Aktiengesellschaft, evtl. S-Bahn?
return 'R' + str;
if (type.equals("KBS")) // Kursbuchstrecke
return 'R' + str;
if (type.equals("Zug"))
return 'R' + str;
if (type.equals("ÖBB"))
return 'R' + str;
if (type.equals("CAT")) // City Airport Train Wien
return 'R' + str;
if (type.equals("DZ")) // Dampfzug, STV
return 'R' + str;
if (type.equals("CD"))
return 'R' + str;
if (type.equals("PR"))
return 'R' + str;
if (type.equals("KD")) // Koleje Dolnośląskie (Niederschlesische Eisenbahn)
return 'R' + str;
if (type.equals("VIAMO"))
return 'R' + str;
if (type.equals("SE")) // Southeastern, GB
return 'R' + str;
if (type.equals("SW")) // South West Trains, GB
return 'R' + str;
if (type.equals("SN")) // Southern, GB
return 'R' + str;
if (type.equals("NT")) // Northern Rail, GB
return 'R' + str;
if (type.equals("CH")) // Chiltern Railways, GB
return 'R' + str;
if (type.equals("EA")) // National Express East Anglia, GB
return 'R' + str;
if (type.equals("FC")) // First Capital Connect, GB
return 'R' + str;
if (type.equals("GW")) // First Great Western, GB
return 'R' + str;
if (type.equals("XC")) // Cross Country, GB, evtl. auch highspeed?
return 'R' + str;
if (type.equals("HC")) // Heathrow Connect, GB
return 'R' + str;
if (type.equals("HX")) // Heathrow Express, GB
return 'R' + str;
if (type.equals("GX")) // Gatwick Express, GB
return 'R' + str;
if (type.equals("C2C")) // c2c, GB
return 'R' + str;
if (type.equals("LM")) // London Midland, GB
return 'R' + str;
if (type.equals("EM")) // East Midlands Trains, GB
return 'R' + str;
if (type.equals("VT")) // Virgin Trains, GB, evtl. auch highspeed?
return 'R' + str;
if (type.equals("SR")) // ScotRail, GB, evtl. auch long-distance?
return 'R' + str;
if (type.equals("AW")) // Arriva Trains Wales, GB
return 'R' + str;
if (type.equals("WS")) // Wrexham & Shropshire, GB
return 'R' + str;
if (type.equals("TP")) // First TransPennine Express, GB, evtl. auch long-distance?
return 'R' + str;
if (type.equals("GC")) // Grand Central, GB
return 'R' + str;
if (type.equals("IL")) // Island Line, GB
return 'R' + str;
if (type.equals("BR")) // ??, GB
return 'R' + str;
if (type.equals("OO")) // ??, GB
return 'R' + str;
if (type.equals("XX")) // ??, GB
return 'R' + str;
if (type.equals("XZ")) // ??, GB
return 'R' + str;
if (type.equals("DB-Zug")) // VRR
return 'R' + name;
if (type.equals("Regionalexpress")) // VRR
return 'R' + name;
if ("CAPITOL".equals(name)) // San Francisco
return 'R' + name;
if ("Train".equals(noTrainName) || "Train".equals(type)) // San Francisco
return "R" + name;
if ("Regional Train :".equals(longName))
return "R";
if ("Regional Train".equals(noTrainName)) // Melbourne
return "R" + name;
if ("Regional".equals(type)) // Melbourne
return "R" + name;
if (type.equals("ATB")) // Autoschleuse Tauernbahn
return 'R' + name;
if ("Chiemsee-Bahn".equals(type))
return 'R' + name;
if (type.equals("BSB")) // Breisgau-S-Bahn
return 'S' + str;
if (type.equals("RER")) // Réseau Express Régional, Frankreich
return 'S' + str;
if (type.equals("LO")) // London Overground, GB
return 'S' + str;
if ("A".equals(name) || "B".equals(name) || "C".equals(name)) // SES
return 'S' + str;
+ final Matcher m = P_LINE_S.matcher(name);
+ if (m.find())
+ return 'S' + m.group(1);
if (P_LINE_U.matcher(type).matches())
return 'U' + str;
if ("Underground".equals(type)) // London Underground, GB
return 'U' + str;
if ("Millbrae / Richmond".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Richmond / Millbrae".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Fremont / RIchmond".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Richmond / Fremont".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Pittsburg Bay Point / SFO".equals(name)) // San Francisco, BART
return 'U' + name;
if ("SFO / Pittsburg Bay Point".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Dublin Pleasanton / Daly City".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Daly City / Dublin Pleasanton".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Fremont / Daly City".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Daly City / Fremont".equals(name)) // San Francisco, BART
return 'U' + name;
if (type.equals("RT")) // RegioTram
return 'T' + str;
if (type.equals("STR")) // Nordhausen
return 'T' + str;
if ("California Cable Car".equals(name)) // San Francisco
return 'T' + name;
if ("Muni".equals(type)) // San Francisco
return 'T' + name;
if ("Cable".equals(type)) // San Francisco
return 'T' + name;
if ("Muni Rail".equals(noTrainName)) // San Francisco
return 'T' + name;
if ("Cable Car".equals(noTrainName)) // San Francisco
return 'T' + name;
if (type.equals("BUS"))
return 'B' + str;
if ("SEV-Bus".equals(type))
return 'B' + str;
if ("Bex".equals(type)) // Bayern Express
return 'B' + str;
if (type.length() == 0)
return "?";
if (P_LINE_NUMBER.matcher(type).matches())
return "?";
if (P_LINE_Y.matcher(name).matches())
return "?" + name;
throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '"
+ noTrainName + "' type '" + type + "' str '" + str + "'");
}
if (t == 1)
{
final Matcher m = P_LINE_S.matcher(name);
if (m.find())
return 'S' + m.group(1);
else
return 'S' + name;
}
if (t == 2)
return 'U' + name;
if (t == 3 || t == 4)
return 'T' + name;
if (t == 5 || t == 6 || t == 7 || t == 10)
{
if (name.equals("Schienenersatzverkehr"))
return "BSEV";
else
return 'B' + name;
}
if (t == 8)
return 'C' + name;
if (t == 9)
return 'F' + name;
if (t == 11 || t == -1)
return '?' + name;
throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName
+ "'");
}
public QueryDeparturesResult queryDepartures(final int stationId, final int maxDepartures, final boolean equivs) throws IOException
{
final StringBuilder uri = new StringBuilder(apiBase);
uri.append("XSLT_DM_REQUEST");
appendCommonRequestParams(uri);
uri.append("&type_dm=stop&useRealtime=1&mode=direct");
uri.append("&name_dm=").append(stationId);
uri.append("&deleteAssignedStops_dm=").append(equivs ? '0' : '1');
if (maxDepartures > 0)
uri.append("&limit=").append(maxDepartures);
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(uri.toString());
final XmlPullParser pp = parserFactory.newPullParser();
pp.setInput(is, null);
enterItdRequest(pp);
XmlPullUtil.enter(pp, "itdDepartureMonitorRequest");
if (!XmlPullUtil.test(pp, "itdOdv") || !"dm".equals(XmlPullUtil.attr(pp, "usage")))
throw new IllegalStateException("cannot find <itdOdv usage=\"dm\" />");
XmlPullUtil.enter(pp, "itdOdv");
final String place = processItdOdvPlace(pp);
XmlPullUtil.require(pp, "itdOdvName");
final String nameState = pp.getAttributeValue(null, "state");
XmlPullUtil.enter(pp, "itdOdvName");
if ("identified".equals(nameState))
{
final QueryDeparturesResult result = new QueryDeparturesResult();
final Location location = processOdvNameElem(pp, place);
result.stationDepartures.add(new StationDepartures(location, new LinkedList<Departure>(), new LinkedList<LineDestination>()));
XmlPullUtil.exit(pp, "itdOdvName");
if (XmlPullUtil.test(pp, "itdOdvAssignedStops"))
{
XmlPullUtil.enter(pp, "itdOdvAssignedStops");
while (XmlPullUtil.test(pp, "itdOdvAssignedStop"))
{
final Location assignedLocation = processItdOdvAssignedStop(pp);
if (findStationDepartures(result.stationDepartures, assignedLocation.id) == null)
result.stationDepartures.add(new StationDepartures(assignedLocation, new LinkedList<Departure>(),
new LinkedList<LineDestination>()));
}
XmlPullUtil.exit(pp, "itdOdvAssignedStops");
}
XmlPullUtil.exit(pp, "itdOdv");
if (XmlPullUtil.test(pp, "itdDateTime"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdDateRange"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdTripOptions"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdMessage"))
XmlPullUtil.next(pp);
final Calendar plannedDepartureTime = new GregorianCalendar(timeZone());
final Calendar predictedDepartureTime = new GregorianCalendar(timeZone());
XmlPullUtil.require(pp, "itdServingLines");
if (!pp.isEmptyElementTag())
{
XmlPullUtil.enter(pp, "itdServingLines");
while (XmlPullUtil.test(pp, "itdServingLine"))
{
final String assignedStopIdStr = pp.getAttributeValue(null, "assignedStopID");
final int assignedStopId = assignedStopIdStr != null ? Integer.parseInt(assignedStopIdStr) : 0;
final String destination = normalizeLocationName(pp.getAttributeValue(null, "direction"));
final String destinationIdStr = pp.getAttributeValue(null, "destID");
final int destinationId = destinationIdStr.length() > 0 ? Integer.parseInt(destinationIdStr) : 0;
final LineDestination line = new LineDestination(processItdServingLine(pp), destinationId, destination);
StationDepartures assignedStationDepartures;
if (assignedStopId == 0)
assignedStationDepartures = result.stationDepartures.get(0);
else
assignedStationDepartures = findStationDepartures(result.stationDepartures, assignedStopId);
if (assignedStationDepartures == null)
assignedStationDepartures = new StationDepartures(new Location(LocationType.STATION, assignedStopId),
new LinkedList<Departure>(), new LinkedList<LineDestination>());
if (!assignedStationDepartures.lines.contains(line))
assignedStationDepartures.lines.add(line);
}
XmlPullUtil.exit(pp, "itdServingLines");
}
else
{
XmlPullUtil.next(pp);
}
XmlPullUtil.require(pp, "itdDepartureList");
if (!pp.isEmptyElementTag())
{
XmlPullUtil.enter(pp, "itdDepartureList");
while (XmlPullUtil.test(pp, "itdDeparture"))
{
final int assignedStopId = XmlPullUtil.intAttr(pp, "stopID");
StationDepartures assignedStationDepartures = findStationDepartures(result.stationDepartures, assignedStopId);
if (assignedStationDepartures == null)
{
final String mapName = pp.getAttributeValue(null, "mapName");
if (mapName == null || !"WGS84".equals(mapName))
throw new IllegalStateException("unknown mapName: " + mapName);
final int lon = XmlPullUtil.intAttr(pp, "x");
final int lat = XmlPullUtil.intAttr(pp, "y");
// final String name = normalizeLocationName(XmlPullUtil.attr(pp, "nameWO"));
assignedStationDepartures = new StationDepartures(new Location(LocationType.STATION, assignedStopId, lat, lon),
new LinkedList<Departure>(), new LinkedList<LineDestination>());
}
final String position = normalizePlatform(pp.getAttributeValue(null, "platform"), pp.getAttributeValue(null, "platformName"));
XmlPullUtil.enter(pp, "itdDeparture");
XmlPullUtil.require(pp, "itdDateTime");
plannedDepartureTime.clear();
processItdDateTime(pp, plannedDepartureTime);
predictedDepartureTime.clear();
if (XmlPullUtil.test(pp, "itdRTDateTime"))
processItdDateTime(pp, predictedDepartureTime);
if (XmlPullUtil.test(pp, "itdFrequencyInfo"))
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "itdServingLine");
final boolean isRealtime = pp.getAttributeValue(null, "realtime").equals("1");
final String destination = normalizeLocationName(pp.getAttributeValue(null, "direction"));
final int destinationId = Integer.parseInt(pp.getAttributeValue(null, "destID"));
final Line line = processItdServingLine(pp);
if (isRealtime && !predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY))
predictedDepartureTime.setTimeInMillis(plannedDepartureTime.getTimeInMillis());
final Departure departure = new Departure(plannedDepartureTime.getTime(),
predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY) ? predictedDepartureTime.getTime() : null, line, position,
destinationId, destination, null, null);
assignedStationDepartures.departures.add(departure);
XmlPullUtil.exit(pp, "itdDeparture");
}
XmlPullUtil.exit(pp, "itdDepartureList");
}
return result;
}
else if ("notidentified".equals(nameState))
{
return new QueryDeparturesResult(QueryDeparturesResult.Status.INVALID_STATION);
}
else
{
throw new RuntimeException("unknown nameState '" + nameState + "' on " + uri);
}
}
catch (final XmlPullParserException x)
{
throw new ParserException(x);
}
finally
{
if (is != null)
is.close();
}
}
private StationDepartures findStationDepartures(final List<StationDepartures> stationDepartures, final int id)
{
for (final StationDepartures stationDeparture : stationDepartures)
if (stationDeparture.location.id == id)
return stationDeparture;
return null;
}
private Location processItdPointAttributes(final XmlPullParser pp)
{
final int id = Integer.parseInt(pp.getAttributeValue(null, "stopID"));
final String place = normalizeLocationName(pp.getAttributeValue(null, "locality"));
String name = normalizeLocationName(pp.getAttributeValue(null, "nameWO"));
if (name == null)
name = normalizeLocationName(pp.getAttributeValue(null, "name"));
final int lat, lon;
if ("WGS84".equals(pp.getAttributeValue(null, "mapName")))
{
lat = Integer.parseInt(pp.getAttributeValue(null, "y"));
lon = Integer.parseInt(pp.getAttributeValue(null, "x"));
}
else
{
lat = 0;
lon = 0;
}
return new Location(LocationType.STATION, id, lat, lon, place, name);
}
private boolean processItdDateTime(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException
{
XmlPullUtil.enter(pp);
calendar.clear();
final boolean success = processItdDate(pp, calendar);
if (success)
processItdTime(pp, calendar);
XmlPullUtil.exit(pp);
return success;
}
private boolean processItdDate(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException
{
XmlPullUtil.require(pp, "itdDate");
final int year = Integer.parseInt(pp.getAttributeValue(null, "year"));
final int month = Integer.parseInt(pp.getAttributeValue(null, "month")) - 1;
final int day = Integer.parseInt(pp.getAttributeValue(null, "day"));
XmlPullUtil.next(pp);
if (year == 0)
return false;
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
return true;
}
private void processItdTime(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException
{
XmlPullUtil.require(pp, "itdTime");
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(pp.getAttributeValue(null, "hour")));
calendar.set(Calendar.MINUTE, Integer.parseInt(pp.getAttributeValue(null, "minute")));
XmlPullUtil.next(pp);
}
private Line processItdServingLine(final XmlPullParser pp) throws XmlPullParserException, IOException
{
XmlPullUtil.require(pp, "itdServingLine");
final String motType = pp.getAttributeValue(null, "motType");
final String number = pp.getAttributeValue(null, "number");
final String id = pp.getAttributeValue(null, "stateless");
XmlPullUtil.enter(pp, "itdServingLine");
String noTrainName = null;
if (XmlPullUtil.test(pp, "itdNoTrain"))
noTrainName = pp.getAttributeValue(null, "name");
XmlPullUtil.exit(pp, "itdServingLine");
final String label = parseLine(motType, number, number, noTrainName);
return new Line(id, label, lineColors(label));
}
private static final Pattern P_STATION_NAME_WHITESPACE = Pattern.compile("\\s+");
protected String normalizeLocationName(final String name)
{
if (name == null || name.length() == 0)
return null;
return P_STATION_NAME_WHITESPACE.matcher(name).replaceAll(" ");
}
protected static double latLonToDouble(final int value)
{
return (double) value / 1000000;
}
private String xsltTripRequest2Uri(final Location from, final Location via, final Location to, final Date date, final boolean dep,
final String products, final WalkSpeed walkSpeed)
{
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
final DateFormat TIME_FORMAT = new SimpleDateFormat("HHmm");
final StringBuilder uri = new StringBuilder(apiBase);
uri.append("XSLT_TRIP_REQUEST2");
appendCommonRequestParams(uri);
uri.append("&sessionID=0");
uri.append("&requestID=0");
uri.append("&language=de");
appendCommonXsltTripRequest2Params(uri);
appendLocation(uri, from, "origin");
appendLocation(uri, to, "destination");
if (via != null)
appendLocation(uri, via, "via");
uri.append("&itdDate=").append(ParserUtils.urlEncode(DATE_FORMAT.format(date)));
uri.append("&itdTime=").append(ParserUtils.urlEncode(TIME_FORMAT.format(date)));
uri.append("&itdTripDateTimeDepArr=").append(dep ? "dep" : "arr");
uri.append("&ptOptionsActive=1");
uri.append("&changeSpeed=").append(WALKSPEED_MAP.get(walkSpeed));
if (products != null)
{
uri.append("&includedMeans=checkbox");
boolean hasI = false;
for (final char p : products.toCharArray())
{
if (p == 'I' || p == 'R')
{
uri.append("&inclMOT_0=on");
if (p == 'I')
hasI = true;
}
if (p == 'S')
uri.append("&inclMOT_1=on");
if (p == 'U')
uri.append("&inclMOT_2=on");
if (p == 'T')
uri.append("&inclMOT_3=on&inclMOT_4=on");
if (p == 'B')
uri.append("&inclMOT_5=on&inclMOT_6=on&inclMOT_7=on");
if (p == 'P')
uri.append("&inclMOT_10=on");
if (p == 'F')
uri.append("&inclMOT_9=on");
if (p == 'C')
uri.append("&inclMOT_8=on");
uri.append("&inclMOT_11=on"); // TODO always show 'others', for now
}
// workaround for highspeed trains: fails when you want highspeed, but not regional
if (!hasI)
uri.append("&lineRestriction=403"); // means: all but ice
}
uri.append("&locationServerActive=1");
uri.append("&useRealtime=1");
uri.append("&useProxFootSearch=1"); // walk if it makes journeys quicker
return uri.toString();
}
private String commandLink(final String sessionId, final String requestId, final String command)
{
final StringBuilder uri = new StringBuilder(apiBase);
uri.append("XSLT_TRIP_REQUEST2");
uri.append("?sessionID=").append(sessionId);
uri.append("&requestID=").append(requestId);
appendCommonXsltTripRequest2Params(uri);
uri.append("&command=").append(command);
return uri.toString();
}
private static final void appendCommonXsltTripRequest2Params(final StringBuilder uri)
{
uri.append("&coordListOutputFormat=STRING");
uri.append("&calcNumberOfTrips=4");
}
public QueryConnectionsResult queryConnections(final Location from, final Location via, final Location to, final Date date, final boolean dep,
final String products, final WalkSpeed walkSpeed) throws IOException
{
final String uri = xsltTripRequest2Uri(from, via, to, date, dep, products, walkSpeed);
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(uri, null, "HASESSIONID", 3);
return queryConnections(uri, is);
}
catch (final XmlPullParserException x)
{
throw new ParserException(x);
}
finally
{
if (is != null)
is.close();
}
}
public QueryConnectionsResult queryMoreConnections(final String uri) throws IOException
{
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(uri, null, "HASESSIONID", 3);
return queryConnections(uri, is);
}
catch (final XmlPullParserException x)
{
if (x.getMessage().startsWith("expected: START_TAG {null}itdRequest"))
throw new SessionExpiredException();
else
throw new ParserException(x);
}
finally
{
if (is != null)
is.close();
}
}
private QueryConnectionsResult queryConnections(final String uri, final InputStream is) throws XmlPullParserException, IOException
{
final XmlPullParser pp = parserFactory.newPullParser();
pp.setInput(is, null);
final String sessionId = enterItdRequest(pp);
XmlPullUtil.require(pp, "itdTripRequest");
final String requestId = XmlPullUtil.attr(pp, "requestID");
XmlPullUtil.enter(pp, "itdTripRequest");
if (XmlPullUtil.test(pp, "itdMessage"))
{
final int code = XmlPullUtil.intAttr(pp, "code");
if (code == -4000) // no connection
return new QueryConnectionsResult(Status.NO_CONNECTIONS);
XmlPullUtil.next(pp);
}
if (XmlPullUtil.test(pp, "itdPrintConfiguration"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdAddress"))
XmlPullUtil.next(pp);
// parse odv name elements
List<Location> ambiguousFrom = null, ambiguousTo = null, ambiguousVia = null;
Location from = null, via = null, to = null;
while (XmlPullUtil.test(pp, "itdOdv"))
{
final String usage = XmlPullUtil.attr(pp, "usage");
XmlPullUtil.enter(pp, "itdOdv");
final String place = processItdOdvPlace(pp);
if (!XmlPullUtil.test(pp, "itdOdvName"))
throw new IllegalStateException("cannot find <itdOdvName /> inside " + usage);
final String nameState = XmlPullUtil.attr(pp, "state");
XmlPullUtil.enter(pp, "itdOdvName");
if (XmlPullUtil.test(pp, "itdMessage"))
XmlPullUtil.next(pp);
if ("list".equals(nameState))
{
if ("origin".equals(usage))
{
ambiguousFrom = new ArrayList<Location>();
while (XmlPullUtil.test(pp, "odvNameElem"))
ambiguousFrom.add(processOdvNameElem(pp, place));
}
else if ("via".equals(usage))
{
ambiguousVia = new ArrayList<Location>();
while (XmlPullUtil.test(pp, "odvNameElem"))
ambiguousVia.add(processOdvNameElem(pp, place));
}
else if ("destination".equals(usage))
{
ambiguousTo = new ArrayList<Location>();
while (XmlPullUtil.test(pp, "odvNameElem"))
ambiguousTo.add(processOdvNameElem(pp, place));
}
else
{
throw new IllegalStateException("unknown usage: " + usage);
}
}
else if ("identified".equals(nameState))
{
if (!XmlPullUtil.test(pp, "odvNameElem"))
throw new IllegalStateException("cannot find <odvNameElem /> inside " + usage);
if ("origin".equals(usage))
from = processOdvNameElem(pp, place);
else if ("via".equals(usage))
via = processOdvNameElem(pp, place);
else if ("destination".equals(usage))
to = processOdvNameElem(pp, place);
else
throw new IllegalStateException("unknown usage: " + usage);
}
XmlPullUtil.exit(pp, "itdOdvName");
XmlPullUtil.exit(pp, "itdOdv");
}
if (ambiguousFrom != null || ambiguousTo != null || ambiguousVia != null)
return new QueryConnectionsResult(ambiguousFrom, ambiguousVia, ambiguousTo);
XmlPullUtil.enter(pp, "itdTripDateTime");
XmlPullUtil.enter(pp, "itdDateTime");
if (!XmlPullUtil.test(pp, "itdDate"))
throw new IllegalStateException("cannot find <itdDate />");
if (!pp.isEmptyElementTag())
{
XmlPullUtil.enter(pp, "itdDate");
if (!XmlPullUtil.test(pp, "itdMessage"))
throw new IllegalStateException("cannot find <itdMessage />");
final String message = pp.nextText();
if (message.equals("invalid date"))
return new QueryConnectionsResult(Status.INVALID_DATE);
XmlPullUtil.exit(pp, "itdDate");
}
XmlPullUtil.exit(pp, "itdDateTime");
final Calendar time = new GregorianCalendar(timeZone());
final List<Connection> connections = new ArrayList<Connection>();
if (XmlPullUtil.jumpToStartTag(pp, null, "itdRouteList"))
{
XmlPullUtil.enter(pp, "itdRouteList");
while (XmlPullUtil.test(pp, "itdRoute"))
{
final String id = pp.getAttributeValue(null, "routeIndex") + "-" + pp.getAttributeValue(null, "routeTripIndex");
XmlPullUtil.enter(pp, "itdRoute");
while (XmlPullUtil.test(pp, "itdDateTime"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdMapItemList"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "itdPartialRouteList");
final List<Connection.Part> parts = new LinkedList<Connection.Part>();
Location firstDeparture = null;
Date firstDepartureTime = null;
Location lastArrival = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "itdPartialRoute"))
{
XmlPullUtil.enter(pp, "itdPartialRoute");
XmlPullUtil.test(pp, "itdPoint");
if (!"departure".equals(pp.getAttributeValue(null, "usage")))
throw new IllegalStateException();
final Location departure = processItdPointAttributes(pp);
if (firstDeparture == null)
firstDeparture = departure;
final String departurePosition = normalizePlatform(pp.getAttributeValue(null, "platform"),
pp.getAttributeValue(null, "platformName"));
XmlPullUtil.enter(pp, "itdPoint");
if (XmlPullUtil.test(pp, "itdMapItemList"))
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "itdDateTime");
processItdDateTime(pp, time);
final Date departureTime = time.getTime();
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
final Date departureTargetTime;
if (XmlPullUtil.test(pp, "itdDateTimeTarget"))
{
processItdDateTime(pp, time);
departureTargetTime = time.getTime();
}
else
{
departureTargetTime = null;
}
XmlPullUtil.exit(pp, "itdPoint");
XmlPullUtil.test(pp, "itdPoint");
if (!"arrival".equals(pp.getAttributeValue(null, "usage")))
throw new IllegalStateException();
final Location arrival = processItdPointAttributes(pp);
lastArrival = arrival;
final String arrivalPosition = normalizePlatform(pp.getAttributeValue(null, "platform"),
pp.getAttributeValue(null, "platformName"));
XmlPullUtil.enter(pp, "itdPoint");
if (XmlPullUtil.test(pp, "itdMapItemList"))
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "itdDateTime");
processItdDateTime(pp, time);
final Date arrivalTime = time.getTime();
lastArrivalTime = arrivalTime;
final Date arrivalTargetTime;
if (XmlPullUtil.test(pp, "itdDateTimeTarget"))
{
processItdDateTime(pp, time);
arrivalTargetTime = time.getTime();
}
else
{
arrivalTargetTime = null;
}
XmlPullUtil.exit(pp, "itdPoint");
XmlPullUtil.test(pp, "itdMeansOfTransport");
final String productName = pp.getAttributeValue(null, "productName");
if ("Fussweg".equals(productName) || "Taxi".equals(productName))
{
final int min = (int) (arrivalTime.getTime() - departureTime.getTime()) / 1000 / 60;
XmlPullUtil.enter(pp, "itdMeansOfTransport");
XmlPullUtil.exit(pp, "itdMeansOfTransport");
if (XmlPullUtil.test(pp, "itdStopSeq"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdFootPathInfo"))
XmlPullUtil.next(pp);
List<Point> path = null;
if (XmlPullUtil.test(pp, "itdPathCoordinates"))
path = processItdPathCoordinates(pp);
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
if (path != null && lastFootway.path != null)
path.addAll(0, lastFootway.path);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departure, arrival, path));
}
else
{
parts.add(new Connection.Footway(min, departure, arrival, path));
}
}
else if ("gesicherter Anschluss".equals(productName) || "nicht umsteigen".equals(productName)) // type97
{
// ignore
XmlPullUtil.enter(pp, "itdMeansOfTransport");
XmlPullUtil.exit(pp, "itdMeansOfTransport");
}
else
{
final String destinationIdStr = pp.getAttributeValue(null, "destID");
final String destinationName = normalizeLocationName(pp.getAttributeValue(null, "destination"));
final Location destination = destinationIdStr.length() > 0 ? new Location(LocationType.STATION,
Integer.parseInt(destinationIdStr), null, destinationName) : new Location(LocationType.ANY, 0, null, destinationName);
final String lineLabel;
if ("AST".equals(pp.getAttributeValue(null, "symbol")))
lineLabel = "BAST";
else
lineLabel = parseLine(pp.getAttributeValue(null, "motType"), pp.getAttributeValue(null, "shortname"),
pp.getAttributeValue(null, "name"), null);
XmlPullUtil.enter(pp, "itdMeansOfTransport");
XmlPullUtil.require(pp, "motDivaParams");
final String lineId = XmlPullUtil.attr(pp, "network") + ':' + XmlPullUtil.attr(pp, "line") + ':'
+ XmlPullUtil.attr(pp, "supplement") + ':' + XmlPullUtil.attr(pp, "direction") + ':'
+ XmlPullUtil.attr(pp, "project");
XmlPullUtil.exit(pp, "itdMeansOfTransport");
final Line line = new Line(lineId, lineLabel, lineColors(lineLabel));
if (XmlPullUtil.test(pp, "itdRBLControlled"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdInfoTextList"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdFootPathInfo"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "infoLink"))
XmlPullUtil.next(pp);
List<Stop> intermediateStops = null;
if (XmlPullUtil.test(pp, "itdStopSeq"))
{
XmlPullUtil.enter(pp, "itdStopSeq");
intermediateStops = new LinkedList<Stop>();
while (XmlPullUtil.test(pp, "itdPoint"))
{
final Location stopLocation = processItdPointAttributes(pp);
final String stopPosition = normalizePlatform(pp.getAttributeValue(null, "platform"),
pp.getAttributeValue(null, "platformName"));
XmlPullUtil.enter(pp, "itdPoint");
XmlPullUtil.require(pp, "itdDateTime");
final boolean success1 = processItdDateTime(pp, time);
final boolean success2 = XmlPullUtil.test(pp, "itdDateTime") ? processItdDateTime(pp, time) : false;
XmlPullUtil.exit(pp, "itdPoint");
if (success1 || success2)
intermediateStops.add(new Stop(stopLocation, stopPosition, time.getTime()));
}
XmlPullUtil.exit(pp, "itdStopSeq");
// remove first and last, because they are not intermediate
final int size = intermediateStops.size();
if (size >= 2)
{
if (intermediateStops.get(size - 1).location.id != arrival.id)
throw new IllegalStateException();
intermediateStops.remove(size - 1);
if (intermediateStops.get(0).location.id != departure.id)
throw new IllegalStateException();
intermediateStops.remove(0);
}
}
List<Point> path = null;
if (XmlPullUtil.test(pp, "itdPathCoordinates"))
path = processItdPathCoordinates(pp);
parts.add(new Connection.Trip(line, destination, departureTime, departurePosition, departure, arrivalTime, arrivalPosition,
arrival, intermediateStops, path));
}
XmlPullUtil.exit(pp, "itdPartialRoute");
}
XmlPullUtil.exit(pp, "itdPartialRouteList");
final List<Fare> fares = new ArrayList<Fare>(2);
if (XmlPullUtil.test(pp, "itdFare") && !pp.isEmptyElementTag())
{
XmlPullUtil.enter(pp, "itdFare");
if (XmlPullUtil.test(pp, "itdSingleTicket"))
{
final String net = XmlPullUtil.attr(pp, "net");
final Currency currency = parseCurrency(XmlPullUtil.attr(pp, "currency"));
final String fareAdult = XmlPullUtil.attr(pp, "fareAdult");
final String fareChild = XmlPullUtil.attr(pp, "fareChild");
final String unitName = XmlPullUtil.attr(pp, "unitName");
final String unitsAdult = XmlPullUtil.attr(pp, "unitsAdult");
final String unitsChild = XmlPullUtil.attr(pp, "unitsChild");
if (fareAdult != null && fareAdult.length() > 0)
fares.add(new Fare(net, Type.ADULT, currency, Float.parseFloat(fareAdult), unitName, unitsAdult));
if (fareChild != null && fareChild.length() > 0)
fares.add(new Fare(net, Type.CHILD, currency, Float.parseFloat(fareChild), unitName, unitsChild));
if (!pp.isEmptyElementTag())
{
XmlPullUtil.enter(pp, "itdSingleTicket");
if (XmlPullUtil.test(pp, "itdGenericTicketList"))
{
XmlPullUtil.enter(pp, "itdGenericTicketList");
while (XmlPullUtil.test(pp, "itdGenericTicketGroup"))
{
final Fare fare = processItdGenericTicketGroup(pp, net, currency);
if (fare != null)
fares.add(fare);
}
XmlPullUtil.exit(pp, "itdGenericTicketList");
}
XmlPullUtil.exit(pp, "itdSingleTicket");
}
}
XmlPullUtil.exit(pp, "itdFare");
}
connections.add(new Connection(id, uri, firstDepartureTime, lastArrivalTime, firstDeparture, lastArrival, parts,
fares.isEmpty() ? null : fares, null));
XmlPullUtil.exit(pp, "itdRoute");
}
XmlPullUtil.exit(pp, "itdRouteList");
return new QueryConnectionsResult(uri, from, via, to, commandLink(sessionId, requestId, "tripNext"), connections);
}
else
{
return new QueryConnectionsResult(Status.NO_CONNECTIONS);
}
}
private List<Point> processItdPathCoordinates(final XmlPullParser pp) throws XmlPullParserException, IOException
{
final List<Point> path = new LinkedList<Point>();
XmlPullUtil.enter(pp, "itdPathCoordinates");
XmlPullUtil.enter(pp, "coordEllipsoid");
final String ellipsoid = pp.getText();
XmlPullUtil.exit(pp, "coordEllipsoid");
if (!"WGS84".equals(ellipsoid))
throw new IllegalStateException("unknown ellipsoid: " + ellipsoid);
XmlPullUtil.enter(pp, "coordType");
final String type = pp.getText();
XmlPullUtil.exit(pp, "coordType");
if (!"GEO_DECIMAL".equals(type))
throw new IllegalStateException("unknown type: " + type);
XmlPullUtil.enter(pp, "itdCoordinateString");
for (final String coordStr : pp.getText().split(" "))
{
final String[] coordsStr = coordStr.split(",");
path.add(new Point(Integer.parseInt(coordsStr[1]), Integer.parseInt(coordsStr[0])));
}
XmlPullUtil.exit(pp, "itdCoordinateString");
XmlPullUtil.exit(pp, "itdPathCoordinates");
return path;
}
private Fare processItdGenericTicketGroup(final XmlPullParser pp, final String net, final Currency currency) throws XmlPullParserException,
IOException
{
XmlPullUtil.enter(pp, "itdGenericTicketGroup");
Type type = null;
float fare = 0;
while (XmlPullUtil.test(pp, "itdGenericTicket"))
{
XmlPullUtil.enter(pp, "itdGenericTicket");
XmlPullUtil.enter(pp, "ticket");
final String key = pp.getText().trim();
XmlPullUtil.exit(pp, "ticket");
String value = null;
XmlPullUtil.require(pp, "value");
if (!pp.isEmptyElementTag())
{
XmlPullUtil.enter(pp, "value");
value = pp.getText();
if (value != null)
value = value.trim();
XmlPullUtil.exit(pp, "value");
}
if (key.equals("FOR_RIDER"))
{
final String typeStr = value.split(" ")[0].toUpperCase();
if (typeStr.equals("REGULAR"))
type = Type.ADULT;
else
type = Type.valueOf(typeStr);
}
else if (key.equals("PRICE"))
{
fare = Float.parseFloat(value) * (currency.getCurrencyCode().equals("USD") ? 0.01f : 1);
}
XmlPullUtil.exit(pp, "itdGenericTicket");
}
XmlPullUtil.exit(pp, "itdGenericTicketGroup");
if (type != null)
return new Fare(net, type, currency, fare, null, null);
else
return null;
}
private Currency parseCurrency(final String currencyStr)
{
if (currencyStr.equals("US$"))
return Currency.getInstance("USD");
if (currencyStr.equals("Dirham"))
return Currency.getInstance("AED");
return Currency.getInstance(currencyStr);
}
private static final Pattern P_PLATFORM = Pattern.compile("#?(\\d+)", Pattern.CASE_INSENSITIVE);
private static final Pattern P_PLATFORM_NAME = Pattern.compile("(?:Gleis|Gl\\.|Bstg\\.)?\\s*" + //
"(\\d+)\\s*" + //
"(?:([A-Z])\\s*(?:-\\s*([A-Z]))?)?", Pattern.CASE_INSENSITIVE);
private static final String normalizePlatform(final String platform, final String platformName)
{
if (platform != null && platform.length() > 0)
{
final Matcher m = P_PLATFORM.matcher(platform);
if (m.matches())
{
return Integer.toString(Integer.parseInt(m.group(1)));
}
else
{
return platform;
}
}
if (platformName != null && platformName.length() > 0)
{
final Matcher m = P_PLATFORM_NAME.matcher(platformName);
if (m.matches())
{
final String simple = Integer.toString(Integer.parseInt(m.group(1)));
if (m.group(2) != null && m.group(3) != null)
return simple + m.group(2) + "-" + m.group(3);
else if (m.group(2) != null)
return simple + m.group(2);
else
return simple;
}
else
{
return platformName;
}
}
return null;
}
public GetConnectionDetailsResult getConnectionDetails(final String connectionUri) throws IOException
{
throw new UnsupportedOperationException();
}
private void appendLocation(final StringBuilder uri, final Location location, final String paramSuffix)
{
if (canAcceptPoiID && location.type == LocationType.POI && location.hasId())
{
uri.append("&type_").append(paramSuffix).append("=poiID");
uri.append("&name_").append(paramSuffix).append("=").append(location.id);
}
else if ((location.type == LocationType.POI || location.type == LocationType.ADDRESS) && location.hasLocation())
{
uri.append("&type_").append(paramSuffix).append("=coord");
uri.append("&name_").append(paramSuffix).append("=")
.append(String.format(Locale.ENGLISH, "%.6f:%.6f", location.lon / 1E6, location.lat / 1E6)).append(":WGS84");
}
else
{
uri.append("&type_").append(paramSuffix).append("=").append(locationTypeValue(location));
uri.append("&name_").append(paramSuffix).append("=").append(ParserUtils.urlEncode(locationValue(location), "ISO-8859-1"));
}
}
protected static final String locationTypeValue(final Location location)
{
final LocationType type = location.type;
if (type == LocationType.STATION)
return "stop";
if (type == LocationType.ADDRESS)
return "any"; // strange, matches with anyObjFilter
if (type == LocationType.POI)
return "poi";
if (type == LocationType.ANY)
return "any";
throw new IllegalArgumentException(type.toString());
}
protected static final String locationValue(final Location location)
{
if ((location.type == LocationType.STATION || location.type == LocationType.POI) && location.hasId())
return Integer.toString(location.id);
else
return location.name;
}
protected static final Map<WalkSpeed, String> WALKSPEED_MAP = new HashMap<WalkSpeed, String>();
static
{
WALKSPEED_MAP.put(WalkSpeed.SLOW, "slow");
WALKSPEED_MAP.put(WalkSpeed.NORMAL, "normal");
WALKSPEED_MAP.put(WalkSpeed.FAST, "fast");
}
private static final Map<Character, int[]> LINES = new HashMap<Character, int[]>();
static
{
LINES.put('I', new int[] { Color.WHITE, Color.RED, Color.RED });
LINES.put('R', new int[] { Color.GRAY, Color.WHITE });
LINES.put('S', new int[] { Color.parseColor("#006e34"), Color.WHITE });
LINES.put('U', new int[] { Color.parseColor("#003090"), Color.WHITE });
LINES.put('T', new int[] { Color.parseColor("#cc0000"), Color.WHITE });
LINES.put('B', new int[] { Color.parseColor("#993399"), Color.WHITE });
LINES.put('F', new int[] { Color.BLUE, Color.WHITE });
LINES.put('?', new int[] { Color.DKGRAY, Color.WHITE });
}
public int[] lineColors(final String line)
{
if (line.length() == 0)
return null;
return LINES.get(line.charAt(0));
}
private String enterItdRequest(final XmlPullParser pp) throws XmlPullParserException, IOException
{
if (pp.getEventType() == XmlPullParser.START_DOCUMENT)
pp.next();
XmlPullUtil.require(pp, "itdRequest");
final String sessionId = XmlPullUtil.attr(pp, "sessionID");
XmlPullUtil.enter(pp, "itdRequest");
if (XmlPullUtil.test(pp, "clientHeaderLines"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdVersionInfo"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "itdInfoLinkList"))
XmlPullUtil.next(pp);
if (XmlPullUtil.test(pp, "serverMetaInfo"))
XmlPullUtil.next(pp);
return sessionId;
}
}
| true | true | protected String parseLine(final String mot, final String name, final String longName, final String noTrainName)
{
if (mot == null)
{
if (noTrainName != null)
{
final String str = name != null ? name : "";
if (noTrainName.equals("S-Bahn"))
return 'S' + str;
if (noTrainName.equals("U-Bahn"))
return 'U' + str;
if (noTrainName.equals("Straßenbahn"))
return 'T' + str;
if (noTrainName.equals("Badner Bahn"))
return 'T' + str;
if (noTrainName.equals("Stadtbus"))
return 'B' + str;
if (noTrainName.equals("Citybus"))
return 'B' + str;
if (noTrainName.equals("Regionalbus"))
return 'B' + str;
if (noTrainName.equals("ÖBB-Postbus"))
return 'B' + str;
if (noTrainName.equals("Autobus"))
return 'B' + str;
if (noTrainName.equals("Discobus"))
return 'B' + str;
if (noTrainName.equals("Nachtbus"))
return 'B' + str;
if (noTrainName.equals("Anrufsammeltaxi"))
return 'B' + str;
if (noTrainName.equals("Ersatzverkehr"))
return 'B' + str;
if (noTrainName.equals("Vienna Airport Lines"))
return 'B' + str;
}
throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '"
+ noTrainName + "'");
}
final int t = Integer.parseInt(mot);
if (t == 0)
{
final String[] parts = longName.split(" ", 3);
final String type = parts[0];
final String num = parts.length >= 2 ? parts[1] : null;
final String str = type + (num != null ? num : "");
if (type.equals("EC")) // Eurocity
return 'I' + str;
if (type.equals("EN")) // Euronight
return 'I' + str;
if (type.equals("IC")) // Intercity
return 'I' + str;
if (type.equals("ICE")) // Intercity Express
return 'I' + str;
if (type.equals("X")) // InterConnex
return 'I' + str;
if (type.equals("CNL")) // City Night Line
return 'I' + str;
if (type.equals("THA")) // Thalys
return 'I' + str;
if (type.equals("TGV")) // TGV
return 'I' + str;
if (type.equals("RJ")) // railjet
return 'I' + str;
if (type.equals("OEC")) // ÖBB-EuroCity
return 'I' + str;
if (type.equals("OIC")) // ÖBB-InterCity
return 'I' + str;
if (type.equals("HT")) // First Hull Trains, GB
return 'I' + str;
if (type.equals("MT")) // Müller Touren, Schnee Express
return 'I' + str;
if (type.equals("HKX")) // Hamburg-Koeln-Express
return 'I' + str;
if (type.equals("DNZ")) // Nachtzug Basel-Moskau
return 'I' + str;
if (type.equals("IR")) // Interregio
return 'R' + str;
if (type.equals("IRE")) // Interregio-Express
return 'R' + str;
if (P_LINE_IRE.matcher(type).matches())
return 'R' + str;
if (type.equals("RE")) // Regional-Express
return 'R' + str;
if (type.equals("R-Bahn")) // Regional-Express, VRR
return 'R' + str;
if (type.equals("REX")) // RegionalExpress, Österreich
return 'R' + str;
if ("EZ".equals(type)) // ÖBB ErlebnisBahn
return 'R' + str;
if (P_LINE_RE.matcher(type).matches())
return 'R' + str;
if (type.equals("RB")) // Regionalbahn
return 'R' + str;
if (P_LINE_RB.matcher(type).matches())
return 'R' + str;
if (type.equals("R")) // Regionalzug
return 'R' + str;
if (P_LINE_R.matcher(type).matches())
return 'R' + str;
if (type.equals("Bahn"))
return 'R' + str;
if (type.equals("Regionalbahn"))
return 'R' + str;
if (type.equals("D")) // Schnellzug
return 'R' + str;
if (type.equals("E")) // Eilzug
return 'R' + str;
if (type.equals("S")) // ~Innsbruck
return 'R' + str;
if (type.equals("WFB")) // Westfalenbahn
return 'R' + str;
if ("Westfalenbahn".equals(type)) // Westfalenbahn
return 'R' + name;
if (type.equals("NWB")) // NordWestBahn
return 'R' + str;
if (type.equals("NordWestBahn"))
return 'R' + str;
if (type.equals("ME")) // Metronom
return 'R' + str;
if (type.equals("ERB")) // eurobahn
return 'R' + str;
if (type.equals("CAN")) // cantus
return 'R' + str;
if (type.equals("HEX")) // Veolia Verkehr Sachsen-Anhalt
return 'R' + str;
if (type.equals("EB")) // Erfurter Bahn
return 'R' + str;
if (type.equals("MRB")) // Mittelrheinbahn
return 'R' + str;
if (type.equals("ABR")) // ABELLIO Rail NRW
return 'R' + str;
if (type.equals("NEB")) // Niederbarnimer Eisenbahn
return 'R' + str;
if (type.equals("OE")) // Ostdeutsche Eisenbahn
return 'R' + str;
if (P_LINE_OE.matcher(type).matches())
return 'R' + str;
if (type.equals("MR")) // Märkische Regiobahn
return 'R' + str;
if (type.equals("OLA")) // Ostseeland Verkehr
return 'R' + str;
if (type.equals("UBB")) // Usedomer Bäderbahn
return 'R' + str;
if (type.equals("EVB")) // Elbe-Weser
return 'R' + str;
if (type.equals("PEG")) // Prignitzer Eisenbahngesellschaft
return 'R' + str;
if (type.equals("RTB")) // Rurtalbahn
return 'R' + str;
if (type.equals("STB")) // Süd-Thüringen-Bahn
return 'R' + str;
if (type.equals("HTB")) // Hellertalbahn
return 'R' + str;
if (type.equals("VBG")) // Vogtlandbahn
return 'R' + str;
if (type.equals("VB")) // Vogtlandbahn
return 'R' + str;
if (P_LINE_VB.matcher(type).matches())
return 'R' + str;
if (type.equals("VX")) // Vogtland Express
return 'R' + str;
if (type.equals("CB")) // City-Bahn Chemnitz
return 'R' + str;
if (type.equals("VEC")) // VECTUS Verkehrsgesellschaft
return 'R' + str;
if (type.equals("HzL")) // Hohenzollerische Landesbahn
return 'R' + str;
if (type.equals("OSB")) // Ortenau-S-Bahn
return 'R' + str;
if (type.equals("SBB")) // SBB
return 'R' + str;
if (type.equals("MBB")) // Mecklenburgische Bäderbahn Molli
return 'R' + str;
if (type.equals("OS")) // Regionalbahn
return 'R' + str;
if (type.equals("SP"))
return 'R' + str;
if (type.equals("Dab")) // Daadetalbahn
return 'R' + str;
if (type.equals("FEG")) // Freiberger Eisenbahngesellschaft
return 'R' + str;
if (type.equals("ARR")) // ARRIVA
return 'R' + str;
if (type.equals("HSB")) // Harzer Schmalspurbahn
return 'R' + str;
if (type.equals("SBE")) // Sächsisch-Böhmische Eisenbahngesellschaft
return 'R' + str;
if (type.equals("ALX")) // Arriva-Länderbahn-Express
return 'R' + str;
if (type.equals("EX")) // ALX verwandelt sich
return 'R' + str;
if (type.equals("MEr")) // metronom regional
return 'R' + str;
if (type.equals("AKN")) // AKN Eisenbahn
return 'R' + str;
if (type.equals("ZUG")) // Regionalbahn
return 'R' + str;
if (type.equals("SOE")) // Sächsisch-Oberlausitzer Eisenbahngesellschaft
return 'R' + str;
if (type.equals("VIA")) // VIAS
return 'R' + str;
if (type.equals("BRB")) // Bayerische Regiobahn
return 'R' + str;
if (type.equals("BLB")) // Berchtesgadener Land Bahn
return 'R' + str;
if (type.equals("HLB")) // Hessische Landesbahn
return 'R' + str;
if (type.equals("NOB")) // NordOstseeBahn
return 'R' + str;
if (type.equals("WEG")) // Wieslauftalbahn
return 'R' + str;
if (type.equals("NBE")) // Nordbahn Eisenbahngesellschaft
return 'R' + str;
if (type.equals("VEN")) // Rhenus Veniro
return 'R' + str;
if (type.equals("DPN")) // Nahreisezug
return 'R' + str;
if (type.equals("SHB")) // Schleswig-Holstein-Bahn
return 'R' + str;
if (type.equals("RBG")) // Regental Bahnbetriebs GmbH
return 'R' + str;
if (type.equals("BOB")) // Bayerische Oberlandbahn
return 'R' + str;
if (type.equals("SWE")) // Südwestdeutsche Verkehrs AG
return 'R' + str;
if (type.equals("VE")) // Vetter
return 'R' + str;
if (type.equals("SDG")) // Sächsische Dampfeisenbahngesellschaft
return 'R' + str;
if (type.equals("PRE")) // Pressnitztalbahn
return 'R' + str;
if (type.equals("VEB")) // Vulkan-Eifel-Bahn
return 'R' + str;
if (type.equals("neg")) // Norddeutsche Eisenbahn Gesellschaft
return 'R' + str;
if (type.equals("AVG")) // Felsenland-Express
return 'R' + str;
if (type.equals("ABG")) // Anhaltische Bahngesellschaft
return 'R' + str;
if (type.equals("LGB")) // Lößnitzgrundbahn
return 'R' + str;
if (type.equals("LEO")) // Chiemgauer Lokalbahn
return 'R' + str;
if (type.equals("WTB")) // Weißeritztalbahn
return 'R' + str;
if (type.equals("P")) // Kasbachtalbahn, Wanderbahn im Regental, Rhön-Zügle
return 'R' + str;
if (type.equals("ÖBA")) // Eisenbahn-Betriebsgesellschaft Ochsenhausen
return 'R' + str;
if (type.equals("MBS")) // Montafonerbahn
return 'R' + str;
if (type.equals("EGP")) // EGP - die Städtebahn GmbH
return 'R' + str;
if (type.equals("SBS")) // EGP - die Städtebahn GmbH
return 'R' + str;
if (type.equals("SES")) // EGP - die Städtebahn GmbH
return 'R' + str;
if (type.equals("agi")) // agilis
return 'R' + str;
if (type.equals("ag")) // agilis
return 'R' + str;
if (type.equals("TLX")) // Trilex (Vogtlandbahn)
return 'R' + str;
if (type.equals("BE")) // Grensland-Express, Niederlande
return 'R' + str;
if (type.equals("MEL")) // Museums-Eisenbahn Losheim
return 'R' + str;
if (type.equals("Abellio-Zug")) // Abellio
return 'R' + str;
if ("SWEG-Zug".equals(type)) // Südwestdeutschen Verkehrs-Aktiengesellschaft, evtl. S-Bahn?
return 'R' + str;
if (type.equals("KBS")) // Kursbuchstrecke
return 'R' + str;
if (type.equals("Zug"))
return 'R' + str;
if (type.equals("ÖBB"))
return 'R' + str;
if (type.equals("CAT")) // City Airport Train Wien
return 'R' + str;
if (type.equals("DZ")) // Dampfzug, STV
return 'R' + str;
if (type.equals("CD"))
return 'R' + str;
if (type.equals("PR"))
return 'R' + str;
if (type.equals("KD")) // Koleje Dolnośląskie (Niederschlesische Eisenbahn)
return 'R' + str;
if (type.equals("VIAMO"))
return 'R' + str;
if (type.equals("SE")) // Southeastern, GB
return 'R' + str;
if (type.equals("SW")) // South West Trains, GB
return 'R' + str;
if (type.equals("SN")) // Southern, GB
return 'R' + str;
if (type.equals("NT")) // Northern Rail, GB
return 'R' + str;
if (type.equals("CH")) // Chiltern Railways, GB
return 'R' + str;
if (type.equals("EA")) // National Express East Anglia, GB
return 'R' + str;
if (type.equals("FC")) // First Capital Connect, GB
return 'R' + str;
if (type.equals("GW")) // First Great Western, GB
return 'R' + str;
if (type.equals("XC")) // Cross Country, GB, evtl. auch highspeed?
return 'R' + str;
if (type.equals("HC")) // Heathrow Connect, GB
return 'R' + str;
if (type.equals("HX")) // Heathrow Express, GB
return 'R' + str;
if (type.equals("GX")) // Gatwick Express, GB
return 'R' + str;
if (type.equals("C2C")) // c2c, GB
return 'R' + str;
if (type.equals("LM")) // London Midland, GB
return 'R' + str;
if (type.equals("EM")) // East Midlands Trains, GB
return 'R' + str;
if (type.equals("VT")) // Virgin Trains, GB, evtl. auch highspeed?
return 'R' + str;
if (type.equals("SR")) // ScotRail, GB, evtl. auch long-distance?
return 'R' + str;
if (type.equals("AW")) // Arriva Trains Wales, GB
return 'R' + str;
if (type.equals("WS")) // Wrexham & Shropshire, GB
return 'R' + str;
if (type.equals("TP")) // First TransPennine Express, GB, evtl. auch long-distance?
return 'R' + str;
if (type.equals("GC")) // Grand Central, GB
return 'R' + str;
if (type.equals("IL")) // Island Line, GB
return 'R' + str;
if (type.equals("BR")) // ??, GB
return 'R' + str;
if (type.equals("OO")) // ??, GB
return 'R' + str;
if (type.equals("XX")) // ??, GB
return 'R' + str;
if (type.equals("XZ")) // ??, GB
return 'R' + str;
if (type.equals("DB-Zug")) // VRR
return 'R' + name;
if (type.equals("Regionalexpress")) // VRR
return 'R' + name;
if ("CAPITOL".equals(name)) // San Francisco
return 'R' + name;
if ("Train".equals(noTrainName) || "Train".equals(type)) // San Francisco
return "R" + name;
if ("Regional Train :".equals(longName))
return "R";
if ("Regional Train".equals(noTrainName)) // Melbourne
return "R" + name;
if ("Regional".equals(type)) // Melbourne
return "R" + name;
if (type.equals("ATB")) // Autoschleuse Tauernbahn
return 'R' + name;
if ("Chiemsee-Bahn".equals(type))
return 'R' + name;
if (type.equals("BSB")) // Breisgau-S-Bahn
return 'S' + str;
if (type.equals("RER")) // Réseau Express Régional, Frankreich
return 'S' + str;
if (type.equals("LO")) // London Overground, GB
return 'S' + str;
if ("A".equals(name) || "B".equals(name) || "C".equals(name)) // SES
return 'S' + str;
if (P_LINE_U.matcher(type).matches())
return 'U' + str;
if ("Underground".equals(type)) // London Underground, GB
return 'U' + str;
if ("Millbrae / Richmond".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Richmond / Millbrae".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Fremont / RIchmond".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Richmond / Fremont".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Pittsburg Bay Point / SFO".equals(name)) // San Francisco, BART
return 'U' + name;
if ("SFO / Pittsburg Bay Point".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Dublin Pleasanton / Daly City".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Daly City / Dublin Pleasanton".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Fremont / Daly City".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Daly City / Fremont".equals(name)) // San Francisco, BART
return 'U' + name;
if (type.equals("RT")) // RegioTram
return 'T' + str;
if (type.equals("STR")) // Nordhausen
return 'T' + str;
if ("California Cable Car".equals(name)) // San Francisco
return 'T' + name;
if ("Muni".equals(type)) // San Francisco
return 'T' + name;
if ("Cable".equals(type)) // San Francisco
return 'T' + name;
if ("Muni Rail".equals(noTrainName)) // San Francisco
return 'T' + name;
if ("Cable Car".equals(noTrainName)) // San Francisco
return 'T' + name;
if (type.equals("BUS"))
return 'B' + str;
if ("SEV-Bus".equals(type))
return 'B' + str;
if ("Bex".equals(type)) // Bayern Express
return 'B' + str;
if (type.length() == 0)
return "?";
if (P_LINE_NUMBER.matcher(type).matches())
return "?";
if (P_LINE_Y.matcher(name).matches())
return "?" + name;
throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '"
+ noTrainName + "' type '" + type + "' str '" + str + "'");
}
if (t == 1)
{
final Matcher m = P_LINE_S.matcher(name);
if (m.find())
return 'S' + m.group(1);
else
return 'S' + name;
}
if (t == 2)
return 'U' + name;
if (t == 3 || t == 4)
return 'T' + name;
if (t == 5 || t == 6 || t == 7 || t == 10)
{
if (name.equals("Schienenersatzverkehr"))
return "BSEV";
else
return 'B' + name;
}
if (t == 8)
return 'C' + name;
if (t == 9)
return 'F' + name;
if (t == 11 || t == -1)
return '?' + name;
throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName
+ "'");
}
| protected String parseLine(final String mot, final String name, final String longName, final String noTrainName)
{
if (mot == null)
{
if (noTrainName != null)
{
final String str = name != null ? name : "";
if (noTrainName.equals("S-Bahn"))
return 'S' + str;
if (noTrainName.equals("U-Bahn"))
return 'U' + str;
if (noTrainName.equals("Straßenbahn"))
return 'T' + str;
if (noTrainName.equals("Badner Bahn"))
return 'T' + str;
if (noTrainName.equals("Stadtbus"))
return 'B' + str;
if (noTrainName.equals("Citybus"))
return 'B' + str;
if (noTrainName.equals("Regionalbus"))
return 'B' + str;
if (noTrainName.equals("ÖBB-Postbus"))
return 'B' + str;
if (noTrainName.equals("Autobus"))
return 'B' + str;
if (noTrainName.equals("Discobus"))
return 'B' + str;
if (noTrainName.equals("Nachtbus"))
return 'B' + str;
if (noTrainName.equals("Anrufsammeltaxi"))
return 'B' + str;
if (noTrainName.equals("Ersatzverkehr"))
return 'B' + str;
if (noTrainName.equals("Vienna Airport Lines"))
return 'B' + str;
}
throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '"
+ noTrainName + "'");
}
final int t = Integer.parseInt(mot);
if (t == 0)
{
final String[] parts = longName.split(" ", 3);
final String type = parts[0];
final String num = parts.length >= 2 ? parts[1] : null;
final String str = type + (num != null ? num : "");
if (type.equals("EC")) // Eurocity
return 'I' + str;
if (type.equals("EN")) // Euronight
return 'I' + str;
if (type.equals("IC")) // Intercity
return 'I' + str;
if (type.equals("ICE")) // Intercity Express
return 'I' + str;
if (type.equals("X")) // InterConnex
return 'I' + str;
if (type.equals("CNL")) // City Night Line
return 'I' + str;
if (type.equals("THA")) // Thalys
return 'I' + str;
if (type.equals("TGV")) // TGV
return 'I' + str;
if (type.equals("RJ")) // railjet
return 'I' + str;
if (type.equals("OEC")) // ÖBB-EuroCity
return 'I' + str;
if (type.equals("OIC")) // ÖBB-InterCity
return 'I' + str;
if (type.equals("HT")) // First Hull Trains, GB
return 'I' + str;
if (type.equals("MT")) // Müller Touren, Schnee Express
return 'I' + str;
if (type.equals("HKX")) // Hamburg-Koeln-Express
return 'I' + str;
if (type.equals("DNZ")) // Nachtzug Basel-Moskau
return 'I' + str;
if (type.equals("IR")) // Interregio
return 'R' + str;
if (type.equals("IRE")) // Interregio-Express
return 'R' + str;
if (P_LINE_IRE.matcher(type).matches())
return 'R' + str;
if (type.equals("RE")) // Regional-Express
return 'R' + str;
if (type.equals("R-Bahn")) // Regional-Express, VRR
return 'R' + str;
if (type.equals("REX")) // RegionalExpress, Österreich
return 'R' + str;
if ("EZ".equals(type)) // ÖBB ErlebnisBahn
return 'R' + str;
if (P_LINE_RE.matcher(type).matches())
return 'R' + str;
if (type.equals("RB")) // Regionalbahn
return 'R' + str;
if (P_LINE_RB.matcher(type).matches())
return 'R' + str;
if (type.equals("R")) // Regionalzug
return 'R' + str;
if (P_LINE_R.matcher(type).matches())
return 'R' + str;
if (type.equals("Bahn"))
return 'R' + str;
if (type.equals("Regionalbahn"))
return 'R' + str;
if (type.equals("D")) // Schnellzug
return 'R' + str;
if (type.equals("E")) // Eilzug
return 'R' + str;
if (type.equals("S")) // ~Innsbruck
return 'R' + str;
if (type.equals("WFB")) // Westfalenbahn
return 'R' + str;
if ("Westfalenbahn".equals(type)) // Westfalenbahn
return 'R' + name;
if (type.equals("NWB")) // NordWestBahn
return 'R' + str;
if (type.equals("NordWestBahn"))
return 'R' + str;
if (type.equals("ME")) // Metronom
return 'R' + str;
if (type.equals("ERB")) // eurobahn
return 'R' + str;
if (type.equals("CAN")) // cantus
return 'R' + str;
if (type.equals("HEX")) // Veolia Verkehr Sachsen-Anhalt
return 'R' + str;
if (type.equals("EB")) // Erfurter Bahn
return 'R' + str;
if (type.equals("MRB")) // Mittelrheinbahn
return 'R' + str;
if (type.equals("ABR")) // ABELLIO Rail NRW
return 'R' + str;
if (type.equals("NEB")) // Niederbarnimer Eisenbahn
return 'R' + str;
if (type.equals("OE")) // Ostdeutsche Eisenbahn
return 'R' + str;
if (P_LINE_OE.matcher(type).matches())
return 'R' + str;
if (type.equals("MR")) // Märkische Regiobahn
return 'R' + str;
if (type.equals("OLA")) // Ostseeland Verkehr
return 'R' + str;
if (type.equals("UBB")) // Usedomer Bäderbahn
return 'R' + str;
if (type.equals("EVB")) // Elbe-Weser
return 'R' + str;
if (type.equals("PEG")) // Prignitzer Eisenbahngesellschaft
return 'R' + str;
if (type.equals("RTB")) // Rurtalbahn
return 'R' + str;
if (type.equals("STB")) // Süd-Thüringen-Bahn
return 'R' + str;
if (type.equals("HTB")) // Hellertalbahn
return 'R' + str;
if (type.equals("VBG")) // Vogtlandbahn
return 'R' + str;
if (type.equals("VB")) // Vogtlandbahn
return 'R' + str;
if (P_LINE_VB.matcher(type).matches())
return 'R' + str;
if (type.equals("VX")) // Vogtland Express
return 'R' + str;
if (type.equals("CB")) // City-Bahn Chemnitz
return 'R' + str;
if (type.equals("VEC")) // VECTUS Verkehrsgesellschaft
return 'R' + str;
if (type.equals("HzL")) // Hohenzollerische Landesbahn
return 'R' + str;
if (type.equals("OSB")) // Ortenau-S-Bahn
return 'R' + str;
if (type.equals("SBB")) // SBB
return 'R' + str;
if (type.equals("MBB")) // Mecklenburgische Bäderbahn Molli
return 'R' + str;
if (type.equals("OS")) // Regionalbahn
return 'R' + str;
if (type.equals("SP"))
return 'R' + str;
if (type.equals("Dab")) // Daadetalbahn
return 'R' + str;
if (type.equals("FEG")) // Freiberger Eisenbahngesellschaft
return 'R' + str;
if (type.equals("ARR")) // ARRIVA
return 'R' + str;
if (type.equals("HSB")) // Harzer Schmalspurbahn
return 'R' + str;
if (type.equals("SBE")) // Sächsisch-Böhmische Eisenbahngesellschaft
return 'R' + str;
if (type.equals("ALX")) // Arriva-Länderbahn-Express
return 'R' + str;
if (type.equals("EX")) // ALX verwandelt sich
return 'R' + str;
if (type.equals("MEr")) // metronom regional
return 'R' + str;
if (type.equals("AKN")) // AKN Eisenbahn
return 'R' + str;
if (type.equals("ZUG")) // Regionalbahn
return 'R' + str;
if (type.equals("SOE")) // Sächsisch-Oberlausitzer Eisenbahngesellschaft
return 'R' + str;
if (type.equals("VIA")) // VIAS
return 'R' + str;
if (type.equals("BRB")) // Bayerische Regiobahn
return 'R' + str;
if (type.equals("BLB")) // Berchtesgadener Land Bahn
return 'R' + str;
if (type.equals("HLB")) // Hessische Landesbahn
return 'R' + str;
if (type.equals("NOB")) // NordOstseeBahn
return 'R' + str;
if (type.equals("WEG")) // Wieslauftalbahn
return 'R' + str;
if (type.equals("NBE")) // Nordbahn Eisenbahngesellschaft
return 'R' + str;
if (type.equals("VEN")) // Rhenus Veniro
return 'R' + str;
if (type.equals("DPN")) // Nahreisezug
return 'R' + str;
if (type.equals("SHB")) // Schleswig-Holstein-Bahn
return 'R' + str;
if (type.equals("RBG")) // Regental Bahnbetriebs GmbH
return 'R' + str;
if (type.equals("BOB")) // Bayerische Oberlandbahn
return 'R' + str;
if (type.equals("SWE")) // Südwestdeutsche Verkehrs AG
return 'R' + str;
if (type.equals("VE")) // Vetter
return 'R' + str;
if (type.equals("SDG")) // Sächsische Dampfeisenbahngesellschaft
return 'R' + str;
if (type.equals("PRE")) // Pressnitztalbahn
return 'R' + str;
if (type.equals("VEB")) // Vulkan-Eifel-Bahn
return 'R' + str;
if (type.equals("neg")) // Norddeutsche Eisenbahn Gesellschaft
return 'R' + str;
if (type.equals("AVG")) // Felsenland-Express
return 'R' + str;
if (type.equals("ABG")) // Anhaltische Bahngesellschaft
return 'R' + str;
if (type.equals("LGB")) // Lößnitzgrundbahn
return 'R' + str;
if (type.equals("LEO")) // Chiemgauer Lokalbahn
return 'R' + str;
if (type.equals("WTB")) // Weißeritztalbahn
return 'R' + str;
if (type.equals("P")) // Kasbachtalbahn, Wanderbahn im Regental, Rhön-Zügle
return 'R' + str;
if (type.equals("ÖBA")) // Eisenbahn-Betriebsgesellschaft Ochsenhausen
return 'R' + str;
if (type.equals("MBS")) // Montafonerbahn
return 'R' + str;
if (type.equals("EGP")) // EGP - die Städtebahn GmbH
return 'R' + str;
if (type.equals("SBS")) // EGP - die Städtebahn GmbH
return 'R' + str;
if (type.equals("SES")) // EGP - die Städtebahn GmbH
return 'R' + str;
if (type.equals("agi")) // agilis
return 'R' + str;
if (type.equals("ag")) // agilis
return 'R' + str;
if (type.equals("TLX")) // Trilex (Vogtlandbahn)
return 'R' + str;
if (type.equals("BE")) // Grensland-Express, Niederlande
return 'R' + str;
if (type.equals("MEL")) // Museums-Eisenbahn Losheim
return 'R' + str;
if (type.equals("Abellio-Zug")) // Abellio
return 'R' + str;
if ("SWEG-Zug".equals(type)) // Südwestdeutschen Verkehrs-Aktiengesellschaft, evtl. S-Bahn?
return 'R' + str;
if (type.equals("KBS")) // Kursbuchstrecke
return 'R' + str;
if (type.equals("Zug"))
return 'R' + str;
if (type.equals("ÖBB"))
return 'R' + str;
if (type.equals("CAT")) // City Airport Train Wien
return 'R' + str;
if (type.equals("DZ")) // Dampfzug, STV
return 'R' + str;
if (type.equals("CD"))
return 'R' + str;
if (type.equals("PR"))
return 'R' + str;
if (type.equals("KD")) // Koleje Dolnośląskie (Niederschlesische Eisenbahn)
return 'R' + str;
if (type.equals("VIAMO"))
return 'R' + str;
if (type.equals("SE")) // Southeastern, GB
return 'R' + str;
if (type.equals("SW")) // South West Trains, GB
return 'R' + str;
if (type.equals("SN")) // Southern, GB
return 'R' + str;
if (type.equals("NT")) // Northern Rail, GB
return 'R' + str;
if (type.equals("CH")) // Chiltern Railways, GB
return 'R' + str;
if (type.equals("EA")) // National Express East Anglia, GB
return 'R' + str;
if (type.equals("FC")) // First Capital Connect, GB
return 'R' + str;
if (type.equals("GW")) // First Great Western, GB
return 'R' + str;
if (type.equals("XC")) // Cross Country, GB, evtl. auch highspeed?
return 'R' + str;
if (type.equals("HC")) // Heathrow Connect, GB
return 'R' + str;
if (type.equals("HX")) // Heathrow Express, GB
return 'R' + str;
if (type.equals("GX")) // Gatwick Express, GB
return 'R' + str;
if (type.equals("C2C")) // c2c, GB
return 'R' + str;
if (type.equals("LM")) // London Midland, GB
return 'R' + str;
if (type.equals("EM")) // East Midlands Trains, GB
return 'R' + str;
if (type.equals("VT")) // Virgin Trains, GB, evtl. auch highspeed?
return 'R' + str;
if (type.equals("SR")) // ScotRail, GB, evtl. auch long-distance?
return 'R' + str;
if (type.equals("AW")) // Arriva Trains Wales, GB
return 'R' + str;
if (type.equals("WS")) // Wrexham & Shropshire, GB
return 'R' + str;
if (type.equals("TP")) // First TransPennine Express, GB, evtl. auch long-distance?
return 'R' + str;
if (type.equals("GC")) // Grand Central, GB
return 'R' + str;
if (type.equals("IL")) // Island Line, GB
return 'R' + str;
if (type.equals("BR")) // ??, GB
return 'R' + str;
if (type.equals("OO")) // ??, GB
return 'R' + str;
if (type.equals("XX")) // ??, GB
return 'R' + str;
if (type.equals("XZ")) // ??, GB
return 'R' + str;
if (type.equals("DB-Zug")) // VRR
return 'R' + name;
if (type.equals("Regionalexpress")) // VRR
return 'R' + name;
if ("CAPITOL".equals(name)) // San Francisco
return 'R' + name;
if ("Train".equals(noTrainName) || "Train".equals(type)) // San Francisco
return "R" + name;
if ("Regional Train :".equals(longName))
return "R";
if ("Regional Train".equals(noTrainName)) // Melbourne
return "R" + name;
if ("Regional".equals(type)) // Melbourne
return "R" + name;
if (type.equals("ATB")) // Autoschleuse Tauernbahn
return 'R' + name;
if ("Chiemsee-Bahn".equals(type))
return 'R' + name;
if (type.equals("BSB")) // Breisgau-S-Bahn
return 'S' + str;
if (type.equals("RER")) // Réseau Express Régional, Frankreich
return 'S' + str;
if (type.equals("LO")) // London Overground, GB
return 'S' + str;
if ("A".equals(name) || "B".equals(name) || "C".equals(name)) // SES
return 'S' + str;
final Matcher m = P_LINE_S.matcher(name);
if (m.find())
return 'S' + m.group(1);
if (P_LINE_U.matcher(type).matches())
return 'U' + str;
if ("Underground".equals(type)) // London Underground, GB
return 'U' + str;
if ("Millbrae / Richmond".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Richmond / Millbrae".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Fremont / RIchmond".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Richmond / Fremont".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Pittsburg Bay Point / SFO".equals(name)) // San Francisco, BART
return 'U' + name;
if ("SFO / Pittsburg Bay Point".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Dublin Pleasanton / Daly City".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Daly City / Dublin Pleasanton".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Fremont / Daly City".equals(name)) // San Francisco, BART
return 'U' + name;
if ("Daly City / Fremont".equals(name)) // San Francisco, BART
return 'U' + name;
if (type.equals("RT")) // RegioTram
return 'T' + str;
if (type.equals("STR")) // Nordhausen
return 'T' + str;
if ("California Cable Car".equals(name)) // San Francisco
return 'T' + name;
if ("Muni".equals(type)) // San Francisco
return 'T' + name;
if ("Cable".equals(type)) // San Francisco
return 'T' + name;
if ("Muni Rail".equals(noTrainName)) // San Francisco
return 'T' + name;
if ("Cable Car".equals(noTrainName)) // San Francisco
return 'T' + name;
if (type.equals("BUS"))
return 'B' + str;
if ("SEV-Bus".equals(type))
return 'B' + str;
if ("Bex".equals(type)) // Bayern Express
return 'B' + str;
if (type.length() == 0)
return "?";
if (P_LINE_NUMBER.matcher(type).matches())
return "?";
if (P_LINE_Y.matcher(name).matches())
return "?" + name;
throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '"
+ noTrainName + "' type '" + type + "' str '" + str + "'");
}
if (t == 1)
{
final Matcher m = P_LINE_S.matcher(name);
if (m.find())
return 'S' + m.group(1);
else
return 'S' + name;
}
if (t == 2)
return 'U' + name;
if (t == 3 || t == 4)
return 'T' + name;
if (t == 5 || t == 6 || t == 7 || t == 10)
{
if (name.equals("Schienenersatzverkehr"))
return "BSEV";
else
return 'B' + name;
}
if (t == 8)
return 'C' + name;
if (t == 9)
return 'F' + name;
if (t == 11 || t == -1)
return '?' + name;
throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName
+ "'");
}
|
diff --git a/cli/src/test/java/com/predic8/membrane/examples/DistributionExtractingTestcase.java b/cli/src/test/java/com/predic8/membrane/examples/DistributionExtractingTestcase.java
index abc0c2a4..1bc3785b 100644
--- a/cli/src/test/java/com/predic8/membrane/examples/DistributionExtractingTestcase.java
+++ b/cli/src/test/java/com/predic8/membrane/examples/DistributionExtractingTestcase.java
@@ -1,161 +1,161 @@
/* Copyright 2012 predic8 GmbH, www.predic8.com
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.predic8.membrane.examples;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
/**
* Extracts the .zip distribution built by Maven.
*/
public class DistributionExtractingTestcase {
private File targetDir, unzipDir, membraneHome;
@Before
public void init() throws IOException, InterruptedException {
targetDir = new File("target").getCanonicalFile();
if (!targetDir.exists())
throw new RuntimeException("membraneHome " + targetDir.getName() + " does not exist.");
File zip = null;
{
File[] files = targetDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
- return name.startsWith("membrane-esb") && name.endsWith(".zip");
+ return name.startsWith("membrane-service-proxy") && name.endsWith(".zip");
}
});
if (files.length > 1)
- throw new RuntimeException("found more than one membrane-esb*.zip");
+ throw new RuntimeException("found more than one service-proxy*.zip");
if (files.length == 1)
zip = files[0];
}
if (zip == null)
throw new RuntimeException("TODO: calling 'ant dist-router' automatically is not implemented.");
unzipDir = new File(targetDir, "examples-automatic");
if (unzipDir.exists()) {
recursiveDelete(unzipDir);
Thread.sleep(1000);
}
if (!unzipDir.mkdir())
throw new RuntimeException("Could not mkdir " + unzipDir.getAbsolutePath());
System.out.println("unzipping router distribution...");
unzip(zip, unzipDir);
membraneHome = unzipDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
- return name.startsWith("membrane-esb");
+ return name.startsWith("membrane-service-proxy");
}
})[0];
replaceLog4JConfig();
System.out.println("running test...");
}
private void replaceLog4JConfig() throws IOException {
File log4jproperties = new File(membraneHome, "conf" + File.separator + "log4j.properties");
if (!log4jproperties.exists())
throw new RuntimeException("log4j.properties does not exits.");
FileUtils.writeStringToFile(
log4jproperties,
"log4j.appender.stdout=org.apache.log4j.ConsoleAppender\r\n" +
"log4j.appender.stdout.Target=System.out\r\n" +
"log4j.appender.stdout.layout=org.apache.log4j.PatternLayout\r\n" +
"log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n\r\n" +
"\r\n" +
"log4j.rootLogger=warn\r\n" +
"\r\n" +
"log4j.logger.com.predic8=debug, stdout");
}
public File getExampleDir(String name) {
File exampleDir = new File(membraneHome, "examples" + File.separator + name);
if (!exampleDir.exists())
throw new RuntimeException("Example dir " + exampleDir.getAbsolutePath() + " does not exist.");
return exampleDir;
}
public File getMembraneHome() {
return membraneHome;
}
@After
public void done() {
System.out.println("cleaning up...");
recursiveDelete(unzipDir);
System.out.println("done.");
}
private void recursiveDelete(File file) {
if (file.isDirectory())
for (File child : file.listFiles())
recursiveDelete(child);
if (!file.delete())
throw new RuntimeException("could not delete " + file.getAbsolutePath());
}
public static final void unzip(File zip, File target) throws IOException {
ZipFile zipFile = new ZipFile(zip);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory()) {
// Assume directories are stored parents first then children.
// This is not robust, just for demonstration purposes.
new File(target, entry.getName()).mkdir();
} else {
FileOutputStream fos = new FileOutputStream(new File(target, entry.getName()));
try {
copyInputStream(zipFile.getInputStream(entry),
new BufferedOutputStream(fos));
} finally {
fos.close();
}
}
}
zipFile.close();
}
public static final void copyInputStream(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) >= 0)
out.write(buffer, 0, len);
in.close();
out.close();
}
}
| false | true | public void init() throws IOException, InterruptedException {
targetDir = new File("target").getCanonicalFile();
if (!targetDir.exists())
throw new RuntimeException("membraneHome " + targetDir.getName() + " does not exist.");
File zip = null;
{
File[] files = targetDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("membrane-esb") && name.endsWith(".zip");
}
});
if (files.length > 1)
throw new RuntimeException("found more than one membrane-esb*.zip");
if (files.length == 1)
zip = files[0];
}
if (zip == null)
throw new RuntimeException("TODO: calling 'ant dist-router' automatically is not implemented.");
unzipDir = new File(targetDir, "examples-automatic");
if (unzipDir.exists()) {
recursiveDelete(unzipDir);
Thread.sleep(1000);
}
if (!unzipDir.mkdir())
throw new RuntimeException("Could not mkdir " + unzipDir.getAbsolutePath());
System.out.println("unzipping router distribution...");
unzip(zip, unzipDir);
membraneHome = unzipDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("membrane-esb");
}
})[0];
replaceLog4JConfig();
System.out.println("running test...");
}
| public void init() throws IOException, InterruptedException {
targetDir = new File("target").getCanonicalFile();
if (!targetDir.exists())
throw new RuntimeException("membraneHome " + targetDir.getName() + " does not exist.");
File zip = null;
{
File[] files = targetDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("membrane-service-proxy") && name.endsWith(".zip");
}
});
if (files.length > 1)
throw new RuntimeException("found more than one service-proxy*.zip");
if (files.length == 1)
zip = files[0];
}
if (zip == null)
throw new RuntimeException("TODO: calling 'ant dist-router' automatically is not implemented.");
unzipDir = new File(targetDir, "examples-automatic");
if (unzipDir.exists()) {
recursiveDelete(unzipDir);
Thread.sleep(1000);
}
if (!unzipDir.mkdir())
throw new RuntimeException("Could not mkdir " + unzipDir.getAbsolutePath());
System.out.println("unzipping router distribution...");
unzip(zip, unzipDir);
membraneHome = unzipDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("membrane-service-proxy");
}
})[0];
replaceLog4JConfig();
System.out.println("running test...");
}
|
diff --git a/maven-core-it-verifier/src/main/java/org/apache/maven/it/Verifier.java b/maven-core-it-verifier/src/main/java/org/apache/maven/it/Verifier.java
index 1d4d57ca8..122bd4981 100644
--- a/maven-core-it-verifier/src/main/java/org/apache/maven/it/Verifier.java
+++ b/maven-core-it-verifier/src/main/java/org/apache/maven/it/Verifier.java
@@ -1,160 +1,167 @@
package org.apache.maven.it;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
/**
* @author <a href="mailto:[email protected]">Jason van Zyl</a>
* @version $Id$
*/
public class Verifier
{
private String basedir;
private String mavenRepoLocal;
public Verifier( String basedir )
{
this.basedir = basedir;
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public void verify()
throws VerificationException
{
Properties mavenProperties = new Properties();
try
{
mavenProperties.load( new FileInputStream( new File( System.getProperty( "user.home" ), "build.properties" ) ) );
}
catch ( IOException e )
{
throw new VerificationException( "Can't find the build.properties file! Verification can't proceed!" );
}
mavenRepoLocal = mavenProperties.getProperty( "maven.repo.local" );
try
{
BufferedReader reader = new BufferedReader( new FileReader( new File( basedir, "expected-results.txt" ) ) );
String line = "";
while ( ( line = reader.readLine() ) != null )
{
verifyExpectedResult( line );
}
}
catch ( Exception e )
{
throw new VerificationException( e );
}
System.out.println( "-----------------------------------------------------------------------------------> OK" );
}
private void verifyExpectedResult( String line )
throws VerificationException
{
line = replace( line, "${maven.repo.local}", mavenRepoLocal );
if ( line.indexOf( "!/" ) > 0 )
{
String urlString = "jar:file:" + line;
try
{
URL url = new URL( urlString );
InputStream is = url.openStream();
if ( is == null )
{
throw new VerificationException( "Expected JAR resource was not found: " + line );
}
}
catch ( Exception e )
{
throw new VerificationException( "Expected JAR resource was not found: " + line );
}
}
else
{
File expectedFile;
if ( line.startsWith( "/" ) )
{
expectedFile = new File( line );
}
else
{
- expectedFile = new File( basedir, line );
+ if ( line.indexOf( ":" ) > 0 ) //windows
+ {
+ expectedFile = new File( line );
+ }
+ else
+ {
+ expectedFile = new File( basedir, line );
+ }
}
if ( !expectedFile.exists() )
{
throw new VerificationException( "Expected file was not found: " + expectedFile.getPath() );
}
}
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public static String replaceOnce( String text, String repl, String with )
{
return replace( text, repl, with, 1 );
}
public static String replace( String text, String repl, String with )
{
return replace( text, repl, with, -1 );
}
public static String replace( String text, String repl, String with, int max )
{
if ( text == null || repl == null || with == null || repl.length() == 0 )
{
return text;
}
StringBuffer buf = new StringBuffer( text.length() );
int start = 0, end = 0;
while ( ( end = text.indexOf( repl, start ) ) != -1 )
{
buf.append( text.substring( start, end ) ).append( with );
start = end + repl.length();
if ( --max == 0 )
{
break;
}
}
buf.append( text.substring( start ) );
return buf.toString();
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public static void main( String args[] )
throws VerificationException
{
Verifier verifier = new Verifier( args[0] );
verifier.verify();
}
}
| true | true | private void verifyExpectedResult( String line )
throws VerificationException
{
line = replace( line, "${maven.repo.local}", mavenRepoLocal );
if ( line.indexOf( "!/" ) > 0 )
{
String urlString = "jar:file:" + line;
try
{
URL url = new URL( urlString );
InputStream is = url.openStream();
if ( is == null )
{
throw new VerificationException( "Expected JAR resource was not found: " + line );
}
}
catch ( Exception e )
{
throw new VerificationException( "Expected JAR resource was not found: " + line );
}
}
else
{
File expectedFile;
if ( line.startsWith( "/" ) )
{
expectedFile = new File( line );
}
else
{
expectedFile = new File( basedir, line );
}
if ( !expectedFile.exists() )
{
throw new VerificationException( "Expected file was not found: " + expectedFile.getPath() );
}
}
}
| private void verifyExpectedResult( String line )
throws VerificationException
{
line = replace( line, "${maven.repo.local}", mavenRepoLocal );
if ( line.indexOf( "!/" ) > 0 )
{
String urlString = "jar:file:" + line;
try
{
URL url = new URL( urlString );
InputStream is = url.openStream();
if ( is == null )
{
throw new VerificationException( "Expected JAR resource was not found: " + line );
}
}
catch ( Exception e )
{
throw new VerificationException( "Expected JAR resource was not found: " + line );
}
}
else
{
File expectedFile;
if ( line.startsWith( "/" ) )
{
expectedFile = new File( line );
}
else
{
if ( line.indexOf( ":" ) > 0 ) //windows
{
expectedFile = new File( line );
}
else
{
expectedFile = new File( basedir, line );
}
}
if ( !expectedFile.exists() )
{
throw new VerificationException( "Expected file was not found: " + expectedFile.getPath() );
}
}
}
|
diff --git a/src/main/java/com/greplin/zookeeper/RobustZooKeeper.java b/src/main/java/com/greplin/zookeeper/RobustZooKeeper.java
index c785091..dc9326d 100644
--- a/src/main/java/com/greplin/zookeeper/RobustZooKeeper.java
+++ b/src/main/java/com/greplin/zookeeper/RobustZooKeeper.java
@@ -1,212 +1,212 @@
/*
* Copyright 2010 The Greplin Zookeeper Utility 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.greplin.zookeeper;
import com.google.common.base.Preconditions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* The org.apache.zookeeper.ZooKeeper client won't automatically reconnect, and is a bit low-level for many uses
* (e.g., no built-in locks)
* <p/>
* This handles the reconnection logic, and implements some common idioms that are useful to have available.
*/
public class RobustZooKeeper {
private static final Log log = LogFactory.getLog(RobustZooKeeper.class);
protected static final String LOCK_NODE_PREFIX = "/_greplin_robustZK_"; // prefixes all node names
protected static final String LOCK_NAME = "lock-";
protected static final List<ACL> DEFAULT_ACL = ZooDefs.Ids.OPEN_ACL_UNSAFE;
private volatile ZooKeeper client;
private final String ensembleAddress;
private final Lock reconnectLock;
private final AtomicBoolean shutdown;
private final AtomicInteger reconnectCount;
private class ConnectionWatcher implements Watcher {
@Override
public void process(WatchedEvent event) {
// eventually, we should probably force a 'reconnect' on seeing an unexpected disconnect, but for now don't care
}
}
public RobustZooKeeper(String ensembleAddresses) throws IOException {
this.reconnectCount = new AtomicInteger(-1); // start at -1 so that the initial connection doesn't count
this.shutdown = new AtomicBoolean(false);
this.reconnectLock = new ReentrantLock();
this.ensembleAddress = ensembleAddresses;
this.client = null;
}
private static boolean isAlive(ZooKeeper zk) {
return zk != null && zk.getState().isAlive();
}
/**
* Get the number of times the underlying zookeeper connection has had to be reconnected.
* Useful for monitoring/etc
* @return The number of reconnections that have successfully completed.
*/
public int getReconnectionCount() {
return reconnectCount.get();
}
public void shutdown() throws InterruptedException {
boolean alreadyShutdown = this.shutdown.getAndSet(true);
if (!alreadyShutdown) {
if (this.client != null) {
this.client.close();
this.client = null;
}
}
}
// returns an 'alive' client - with no lock in the common case
public ZooKeeper getClient() throws IOException {
Preconditions.checkState(!shutdown.get());
ZooKeeper res = client;
if (!isAlive(res)) {
reconnectLock.lock();
try {
res = client;
if (!isAlive(res)) {
res = new ZooKeeper(ensembleAddress, Integer.MAX_VALUE, new ConnectionWatcher());
reconnectCount.incrementAndGet();
client = res;
}
} finally {
reconnectLock.unlock();
}
}
// not actually guaranteed to be true - the connection could have died between when I last checked and now
assert isAlive(res);
return res;
}
private static String getLockParent(String lockName) {
return LOCK_NODE_PREFIX + lockName;
}
private static String getLockNode(String lockName) {
return getLockParent(lockName) + "/" + LOCK_NAME;
}
/**
* Execute the given Runnable once we obtain the zookeeper lock with the given name.
* Automatically release the lock once the Runnable completes.
* <p/>
* We use the 'lock' recipe from the ZooKeeper documentation to help prevent stampedes:
* 1. Call create( ) with a pathname of "_locknode_/lock-" and the sequence and ephemeral flags set.
* 2. Call getChildren() on the lock node without setting the watch flag (this is important to avoid the herd effect).
* 3. If the pathname created in step 1 has the lowest sequence number suffix, the client
* has the lock and the client exits the protocol.
* 4. The client calls exists( ) with the watch flag set on the path in the lock directory with the next
* lowest sequence number.
* 5. if exists( ) returns false, go to step 2. Otherwise, wait for a notification for the pathname from the
* previous step before going to step 2.
*
* @param lockName The name of the lock you want to obtain in Zookeeper before running the action
* @param action The action to execute, while holding the lock.
* @throws java.io.IOException
* @throws InterruptedException
* @throws org.apache.zookeeper.KeeperException
*
*/
public void withLock(final String lockName, final Runnable action)
throws IOException, InterruptedException, KeeperException {
Preconditions.checkArgument(!lockName.contains("/"));
try {
getClient().create(getLockParent(lockName), new byte[0], DEFAULT_ACL, CreateMode.PERSISTENT);
} catch (KeeperException.NodeExistsException e) {
// ignore - the prior 'create' is only needed for the first locker
}
String myNodeFullyQualified = getClient().create(getLockNode(lockName), new byte[0], DEFAULT_ACL,
CreateMode.EPHEMERAL_SEQUENTIAL);
final String[] nodePathname = myNodeFullyQualified.split("/");
final String relativePath = nodePathname[nodePathname.length - 1];
lockRecipeStepTwo(myNodeFullyQualified, relativePath, lockName, action);
}
private void lockRecipeStepTwo(final String fullPath, final String relativePath,
final String lockName, final Runnable action)
throws IOException, InterruptedException, KeeperException {
// step 2
final List<String> children = getClient().getChildren(getLockParent(lockName), false);
assert children.size() > 0;
Collections.sort(children);
// step 3
if (relativePath.equals(children.get(0))) {
try {
action.run();
} finally {
try {
getClient().delete(fullPath, -1);
} catch (KeeperException.NoNodeException e) {
log.warn("After I finished running an action with lock " + lockName + " the actions lock node ("
+ fullPath + ") no longer exists. This should only happen if you manually deleted "
+ fullPath + " or there was an underlying network failure, and we had to reconnect");
}
}
return;
}
// step 4
int indexOfNodeBefore = children.indexOf(relativePath) - 1;
final String nodeBeforeMine = children.get(indexOfNodeBefore);
Stat exists = getClient().exists(getLockParent(lockName) + "/" + nodeBeforeMine, new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
lockRecipeStepTwo(fullPath, relativePath, lockName, action);
} catch (Exception e) {
- log.error("Unable to execute action with lock " + lockName, e);
+ log.warn("Unable to execute action with lock " + lockName, e);
}
}
});
// step 5
if (exists == null) {
lockRecipeStepTwo(fullPath, relativePath, lockName, action);
}
}
}
| true | true | private void lockRecipeStepTwo(final String fullPath, final String relativePath,
final String lockName, final Runnable action)
throws IOException, InterruptedException, KeeperException {
// step 2
final List<String> children = getClient().getChildren(getLockParent(lockName), false);
assert children.size() > 0;
Collections.sort(children);
// step 3
if (relativePath.equals(children.get(0))) {
try {
action.run();
} finally {
try {
getClient().delete(fullPath, -1);
} catch (KeeperException.NoNodeException e) {
log.warn("After I finished running an action with lock " + lockName + " the actions lock node ("
+ fullPath + ") no longer exists. This should only happen if you manually deleted "
+ fullPath + " or there was an underlying network failure, and we had to reconnect");
}
}
return;
}
// step 4
int indexOfNodeBefore = children.indexOf(relativePath) - 1;
final String nodeBeforeMine = children.get(indexOfNodeBefore);
Stat exists = getClient().exists(getLockParent(lockName) + "/" + nodeBeforeMine, new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
lockRecipeStepTwo(fullPath, relativePath, lockName, action);
} catch (Exception e) {
log.error("Unable to execute action with lock " + lockName, e);
}
}
});
// step 5
if (exists == null) {
lockRecipeStepTwo(fullPath, relativePath, lockName, action);
}
}
| private void lockRecipeStepTwo(final String fullPath, final String relativePath,
final String lockName, final Runnable action)
throws IOException, InterruptedException, KeeperException {
// step 2
final List<String> children = getClient().getChildren(getLockParent(lockName), false);
assert children.size() > 0;
Collections.sort(children);
// step 3
if (relativePath.equals(children.get(0))) {
try {
action.run();
} finally {
try {
getClient().delete(fullPath, -1);
} catch (KeeperException.NoNodeException e) {
log.warn("After I finished running an action with lock " + lockName + " the actions lock node ("
+ fullPath + ") no longer exists. This should only happen if you manually deleted "
+ fullPath + " or there was an underlying network failure, and we had to reconnect");
}
}
return;
}
// step 4
int indexOfNodeBefore = children.indexOf(relativePath) - 1;
final String nodeBeforeMine = children.get(indexOfNodeBefore);
Stat exists = getClient().exists(getLockParent(lockName) + "/" + nodeBeforeMine, new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
lockRecipeStepTwo(fullPath, relativePath, lockName, action);
} catch (Exception e) {
log.warn("Unable to execute action with lock " + lockName, e);
}
}
});
// step 5
if (exists == null) {
lockRecipeStepTwo(fullPath, relativePath, lockName, action);
}
}
|
diff --git a/src/main/java/de/ailis/xadrian/dialogs/SunsDialog.java b/src/main/java/de/ailis/xadrian/dialogs/SunsDialog.java
index fa0badc..bfa7f4b 100644
--- a/src/main/java/de/ailis/xadrian/dialogs/SunsDialog.java
+++ b/src/main/java/de/ailis/xadrian/dialogs/SunsDialog.java
@@ -1,132 +1,132 @@
/*
* $Id$
* Copyright (C) 2009 Klaus Reimer <[email protected]>
* See LICENSE.TXT for licensing information
*/
package de.ailis.xadrian.dialogs;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import de.ailis.xadrian.resources.Images;
import de.ailis.xadrian.support.I18N;
import de.ailis.xadrian.support.ModalDialog;
/**
* Dialog for selecting the suns in percent.
*
* @author Klaus Reimer ([email protected])
* @version $Revision$
*/
public class SunsDialog extends ModalDialog
{
/** Serial version UID */
private static final long serialVersionUID = 5592052723685985901L;
/** The singleton instance of this dialog */
private final static SunsDialog instance = new SunsDialog();
/** The suns combo box */
private JComboBox sunsComboBox;
/**
* Constructor
*/
private SunsDialog()
{
super(Result.OK, Result.CANCEL);
}
/**
* Creates the UI
*/
@Override
protected void createUI()
{
- setTitle(I18N.getTitle("dialog.setSuns"));
+ setTitle(I18N.getTitle("dialog.changeSuns"));
setIconImages(Images.LOGOS);
// Create the content controls
final JLabel sunsLabel = new JLabel(I18N
- .getString("dialog.setSuns.suns"));
+ .getString("dialog.changeSuns.suns"));
this.sunsComboBox = new JComboBox(new String[] { "0 %", "100 %",
"150 %", "300 %", "400 %" });
sunsLabel.setLabelFor(this.sunsComboBox);
// Create the content panel
final JPanel contentPanel = new JPanel();
contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS));
contentPanel.add(sunsLabel);
contentPanel.add(Box.createRigidArea(new Dimension(10, 0)));
contentPanel.add(this.sunsComboBox);
// Add the panels to the dialog
add(contentPanel, BorderLayout.CENTER);
}
/**
* Returns the singleton instance
*
* @return The singleton instance
*/
public static SunsDialog getInstance()
{
return instance;
}
/**
* @see de.ailis.xadrian.support.ModalDialog#open()
*/
@Override
public Result open()
{
this.sunsComboBox.requestFocus();
final Result result = super.open();
return result;
}
/**
* Sets the suns.
*
* @param suns
* The yield to set
*/
public void setSuns(final int suns)
{
this.sunsComboBox.setSelectedItem(suns + " %");
}
/**
* Returns the suns.
*
* @return The suns
*/
public int getSuns()
{
final String value = (String) this.sunsComboBox.getSelectedItem();
return Integer.parseInt(value.substring(0, value.length() - 2));
}
}
| false | true | protected void createUI()
{
setTitle(I18N.getTitle("dialog.setSuns"));
setIconImages(Images.LOGOS);
// Create the content controls
final JLabel sunsLabel = new JLabel(I18N
.getString("dialog.setSuns.suns"));
this.sunsComboBox = new JComboBox(new String[] { "0 %", "100 %",
"150 %", "300 %", "400 %" });
sunsLabel.setLabelFor(this.sunsComboBox);
// Create the content panel
final JPanel contentPanel = new JPanel();
contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS));
contentPanel.add(sunsLabel);
contentPanel.add(Box.createRigidArea(new Dimension(10, 0)));
contentPanel.add(this.sunsComboBox);
// Add the panels to the dialog
add(contentPanel, BorderLayout.CENTER);
}
| protected void createUI()
{
setTitle(I18N.getTitle("dialog.changeSuns"));
setIconImages(Images.LOGOS);
// Create the content controls
final JLabel sunsLabel = new JLabel(I18N
.getString("dialog.changeSuns.suns"));
this.sunsComboBox = new JComboBox(new String[] { "0 %", "100 %",
"150 %", "300 %", "400 %" });
sunsLabel.setLabelFor(this.sunsComboBox);
// Create the content panel
final JPanel contentPanel = new JPanel();
contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS));
contentPanel.add(sunsLabel);
contentPanel.add(Box.createRigidArea(new Dimension(10, 0)));
contentPanel.add(this.sunsComboBox);
// Add the panels to the dialog
add(contentPanel, BorderLayout.CENTER);
}
|
diff --git a/src/edu/uc/cs/distsys/idetect/DetectMain.java b/src/edu/uc/cs/distsys/idetect/DetectMain.java
index 6c676df..49a8d4d 100644
--- a/src/edu/uc/cs/distsys/idetect/DetectMain.java
+++ b/src/edu/uc/cs/distsys/idetect/DetectMain.java
@@ -1,198 +1,203 @@
package edu.uc.cs.distsys.idetect;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import edu.uc.cs.distsys.LogHelper;
import edu.uc.cs.distsys.Node;
import edu.uc.cs.distsys.comms.MessageListener;
import edu.uc.cs.distsys.comms.NotifyThread;
import edu.uc.cs.distsys.ilead.ElectionTracker;
import edu.uc.cs.distsys.ilead.LeaderChangeListener;
import edu.uc.cs.distsys.ilead.LeaderMain;
import edu.uc.cs.distsys.ui.NodeStatusViewThread;
public class DetectMain implements MessageListener<Heartbeat>, LeaderChangeListener {
private static final long HB_INIT_DELAY = 0;
private static final long FAIL_DETECT_PERIOD = 5;
public static final long HB_PERIOD = 1;
private final ScheduledExecutorService scheduledExecutor;
private Lock heartbeatLock;
private HashMap<Integer, Node> nodes;
private List<Node> failedNodes;
private Thread detectorThread;
private LogHelper logger;
private NodeStatusViewThread statusViewThread;
private ElectionTracker tracker;
private Node myNode;
public DetectMain(int nodeId, List<Integer> peers) {
this.logger = new LogHelper(nodeId, System.out, System.err, null);
this.nodes = new HashMap<Integer, Node>();
this.failedNodes = new LinkedList<Node>();
this.heartbeatLock = new ReentrantLock();
this.scheduledExecutor = new ScheduledThreadPoolExecutor(1); //TODO
this.myNode = new Node(nodeId);
this.statusViewThread = new NodeStatusViewThread(this.myNode.getId());
new Thread(statusViewThread).start();
for (int peer : peers) {
this.nodes.put(peer, new Node(peer));
}
}
public void start() throws UnknownHostException {
HeartbeatThread hbThread = new HeartbeatThread(this.myNode.getId(), failedNodes, heartbeatLock, logger);
this.detectorThread = Executors.defaultThreadFactory().newThread(
new NotifyThread<Heartbeat>(this.myNode.getId(), hbThread.getCommsWrapper(), this, logger));
this.detectorThread.start();
this.scheduledExecutor.scheduleAtFixedRate(hbThread, HB_INIT_DELAY, HB_PERIOD, TimeUnit.SECONDS);
this.scheduledExecutor.scheduleAtFixedRate(
new FailureDetectionThread(nodes, failedNodes, heartbeatLock),
HB_INIT_DELAY, FAIL_DETECT_PERIOD, TimeUnit.SECONDS);
List<LeaderChangeListener> listeners = new LinkedList<LeaderChangeListener>();
listeners.add(this);
listeners.add(hbThread);
this.tracker = new LeaderMain(this.myNode.getId(), listeners, logger);
this.tracker.start();
this.tracker.startNewElection();
}
public void stop() {
this.logger.log("Detector shutting down");
this.scheduledExecutor.shutdownNow();
this.detectorThread.interrupt();
}
@Override
public void notifyMessage(Heartbeat status) {
try {
this.heartbeatLock.lock();
if (!nodes.containsKey(status.getNodeId())) {
logger.log("Discovered new node - " + status.getNodeId());
Node n = new Node(status);
this.nodes.put(status.getNodeId(), n);
this.statusViewThread.addMonitoredNode(n);
} else {
logger.debug("Received heartbeat from node " + status.getNodeId());
if (this.nodes.get(status.getNodeId()).updateStatus(status)) {
// Go through all reported failed nodes and update local state if necessary
for (Node failNode : status.getFailedNodes()) {
this.verifyFailedNode(failNode);
}
} else {
logger.error("Warning - Received out-of-order heartbeat from node " + status.getNodeId());
}
}
this.statusViewThread.updateUI();
} finally {
this.heartbeatLock.unlock();
}
}
@Override
public void onNewLeader(int leaderId) {
this.logger.log("New Leader: " + leaderId);
if (this.myNode.getId() == leaderId) {
// update our UI to say we're the current user
this.statusViewThread.setUIMessage("Currently The Leader");
} else {
this.statusViewThread.setUIMessage(null);
}
// update who we believe the leader is
this.myNode.setLeaderId(leaderId);
// start telling all the other nodes who we believe the leader should be
for(Node n: this.nodes.values()) {
n.setLeaderId(leaderId);
}
}
public int getLeaderId() {
return this.myNode.getLeaderId();
}
public int getGroupId() {
return this.myNode.getGroupId();
}
public int getId() {
return this.myNode.getId();
}
/***
* @return Number of known group members including self
*/
public int getNumGroupNodes() {
return this.nodes.size() + 1;
}
private void verifyFailedNode(Node node) {
if (node.getId() == this.myNode.getId())
return;
try {
this.heartbeatLock.lock();
if (!nodes.containsKey(node.getId())) {
logger.log("Discovered new node (offline) - " + node.getId());
this.nodes.put(node.getId(), Node.createFailedNode(node.getId(), node.getSeqHighWaterMark()));
} else {
Node localNode = nodes.get(node.getId());
if (! localNode.isOffline() && localNode.getSeqHighWaterMark() <= node.getSeqHighWaterMark()) {
//update our node
localNode.markFailed(node.getSeqHighWaterMark());
} else if (! localNode.isOffline()) {
//discard out-of-date info
//DEBUG
logger.debug("Reported failed node is actually online (id=" +
node.getId() + ")");
}
}
this.statusViewThread.updateUI();
} finally {
this.heartbeatLock.unlock();
}
}
public static void main(String[] args) {
int node = 0;
if (args.length < 1) {
//System.err.println("Usage: " + args[0] + "<port#> [peer#1] ... [peer#N]");
// DEBUGGING
//port = new Random(System.currentTimeMillis()).nextInt(1000) + 1024;
node = new Random(System.currentTimeMillis()).nextInt(1000);
+ } else {
+ if (args.length >= 1) {
+ // first arg is node id
+ node = Integer.parseInt(args[0]);
+ }
}
List<Integer> peers = new LinkedList<Integer>();
for (int i = 1; i < args.length; i++) {
peers.add(Integer.parseInt(args[i]));
}
try {
final DetectMain detector = new DetectMain(node, peers);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
detector.stop();
}
});
detector.start();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true | true | public static void main(String[] args) {
int node = 0;
if (args.length < 1) {
//System.err.println("Usage: " + args[0] + "<port#> [peer#1] ... [peer#N]");
// DEBUGGING
//port = new Random(System.currentTimeMillis()).nextInt(1000) + 1024;
node = new Random(System.currentTimeMillis()).nextInt(1000);
}
List<Integer> peers = new LinkedList<Integer>();
for (int i = 1; i < args.length; i++) {
peers.add(Integer.parseInt(args[i]));
}
try {
final DetectMain detector = new DetectMain(node, peers);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
detector.stop();
}
});
detector.start();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public static void main(String[] args) {
int node = 0;
if (args.length < 1) {
//System.err.println("Usage: " + args[0] + "<port#> [peer#1] ... [peer#N]");
// DEBUGGING
//port = new Random(System.currentTimeMillis()).nextInt(1000) + 1024;
node = new Random(System.currentTimeMillis()).nextInt(1000);
} else {
if (args.length >= 1) {
// first arg is node id
node = Integer.parseInt(args[0]);
}
}
List<Integer> peers = new LinkedList<Integer>();
for (int i = 1; i < args.length; i++) {
peers.add(Integer.parseInt(args[i]));
}
try {
final DetectMain detector = new DetectMain(node, peers);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
detector.stop();
}
});
detector.start();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/plugins/gwiki-pagetemplates/src/main/java/de/micromata/genome/gwiki/pagetemplates_1_0/macro/PtSectionMacroBean.java b/plugins/gwiki-pagetemplates/src/main/java/de/micromata/genome/gwiki/pagetemplates_1_0/macro/PtSectionMacroBean.java
index 58c293d4..aa8c5be2 100644
--- a/plugins/gwiki-pagetemplates/src/main/java/de/micromata/genome/gwiki/pagetemplates_1_0/macro/PtSectionMacroBean.java
+++ b/plugins/gwiki-pagetemplates/src/main/java/de/micromata/genome/gwiki/pagetemplates_1_0/macro/PtSectionMacroBean.java
@@ -1,289 +1,289 @@
////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2010 Micromata GmbH
//
// 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 de.micromata.genome.gwiki.pagetemplates_1_0.macro;
import static de.micromata.genome.util.xml.xmlbuilder.Xml.attrs;
import static de.micromata.genome.util.xml.xmlbuilder.Xml.text;
import static de.micromata.genome.util.xml.xmlbuilder.html.Html.a;
import static de.micromata.genome.util.xml.xmlbuilder.html.Html.table;
import static de.micromata.genome.util.xml.xmlbuilder.html.Html.td;
import static de.micromata.genome.util.xml.xmlbuilder.html.Html.tr;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import de.micromata.genome.gwiki.model.GWikiElementInfo;
import de.micromata.genome.gwiki.model.GWikiLog;
import de.micromata.genome.gwiki.page.GWikiContext;
import de.micromata.genome.gwiki.page.impl.wiki.GWikiBodyEvalMacro;
import de.micromata.genome.gwiki.page.impl.wiki.GWikiMacroBean;
import de.micromata.genome.gwiki.page.impl.wiki.MacroAttributes;
import de.micromata.genome.gwiki.page.impl.wiki.fragment.GWikiFragment;
import de.micromata.genome.gwiki.page.impl.wiki.fragment.GWikiFragmentLink;
import de.micromata.genome.gwiki.pagetemplates_1_0.editor.PtWikiRawTextEditor;
import de.micromata.genome.util.xml.xmlbuilder.XmlElement;
/**
* Defines an editable section.
*
* @author Roger Rene Kommer ([email protected])
* @author Christian Claus ([email protected])
*/
public class PtSectionMacroBean extends GWikiMacroBean implements GWikiBodyEvalMacro
{
private static final long serialVersionUID = -3101167204944678243L;
/**
* Name of the section
*/
private String name;
/**
* type of the editor.
*/
private String editor;
/**
* optional hint, displays in a html-paragraph before the editor appears
*/
private String hint;
/**
* optional field for images to limit the width of an uploaded image
*/
private String maxWidth;
/**
* optional field for attachments or images to limit the physical size
*/
private String maxFileSize;
/**
* optional field, that allows to render wiki elements in the {@link PtWikiRawTextEditor}
*/
private boolean allowWikiSyntax = false;
/*
* (non-Javadoc)
*
* @see de.micromata.genome.gwiki.page.impl.wiki.GWikiMacroBean#renderImpl(de.micromata.genome.gwiki.page.GWikiContext,
* de.micromata.genome.gwiki.page.impl.wiki.MacroAttributes)
*/
@Override
public boolean renderImpl(final GWikiContext ctx, MacroAttributes attrs)
{
- GWikiElementInfo ei = ctx.getCurrentElement().getElementInfo();
+ GWikiElementInfo ei = ctx.getWikiWeb().findElementInfo("edit/pagetemplates/PageSectionEditor");
if (ctx.getCurrentElement() != null) {
if (ei != null) {
ctx.getWikiWeb().getI18nProvider().addTranslationElement(ctx, "edit/pagetemplates/i18n/PtI18N");
final String edit = ctx.getWikiWeb().getI18nProvider().translate(ctx, "gwiki.pt.common.edit");
String image = "<img src='/inc/gwiki/img/icons/linedpaperpencil32.png' style='position:absolute; right: 0; margin-right:-20px' border=0/>";
boolean allowed = ctx.getWikiWeb().getAuthorization().isAllowToView(ctx, ei);
if (ctx.getWikiWeb().getAuthorization().isAllowToEdit(ctx, ctx.getCurrentElement().getElementInfo()) == true && allowed) {
ctx.append("<div style=\"position:relative; padding: 1px\" onmouseover=\"this.style.border = '1px dashed'; this.style.padding = '0px'\" onmouseout=\"this.style.border = '0px'; this.style.padding='1px'\">");
try {
String id = ei.getId();
String url = getUrl(ctx, id, ctx.getCurrentElement().getElementInfo().getId());
ctx.append("<a id=\"" + URLEncoder.encode(name, "UTF-8") + "\" title=\"" + edit + "\" href=\"" + url + "\">" + image + "</a>");
renderFancyBox(ctx, name);
} catch (UnsupportedEncodingException ex) {
GWikiLog.warn("Error rendering section edit link");
}
}
// render simple div if no edit rights
else {
ctx.append("<div>");
}
}
}
if (attrs.getChildFragment() != null) {
if ("attachment".equals(editor) || "link".equals(editor)) {
List<GWikiFragment> childs = attrs.getChildFragment().getChilds();
XmlElement ta = table(attrs("border", "0", "cellspacing", "0", "cellpadding", "2"));
int i = 0;
for (GWikiFragment child : childs) {
if (child instanceof GWikiFragmentLink) {
GWikiFragmentLink attachment = (GWikiFragmentLink) child;
String target = GWikiFragmentLink.isGlobalUrl(attachment.getTarget()) ? attachment.getTarget() : ctx.localUrl(attachment
.getTargetPageId());
String title = (attachment.getTitle() != null) ? attachment.getTitle() : "";
XmlElement targetLink = a(attrs("href", target), text(title));
ta.nest(//
tr(//
td(attrs("width", "180px"), targetLink)) //
);
try {
renderFancyBox(ctx, name + i);
} catch (UnsupportedEncodingException ex) {
GWikiLog.warn("", ex);
}
i++;
}
}
if (ta.getChilds().size() > 0) {
ctx.append(ta.toString());
}
} else {
attrs.getChildFragment().render(ctx);
}
}
if (ei != null) {
ctx.append("</div>");
}
return true;
}
/**
* @param ctx
* @param id
* @return
* @throws UnsupportedEncodingException
*/
private String getUrl(final GWikiContext ctx, String id, String parentElem) throws UnsupportedEncodingException
{
String url = ctx.localUrl("/" + id)
+ "?pageId="
+ URLEncoder.encode(parentElem, "UTF-8")
+ "§ionName="
+ URLEncoder.encode(name, "UTF-8")
+ (editor == null ? "" : ("&editor=" + URLEncoder.encode(editor, "UTF-8")))
+ (hint == null ? "" : ("&hint=" + URLEncoder.encode(hint, "UTF-8")))
+ (allowWikiSyntax ? ("&allowWikiSyntax=" + URLEncoder.encode(allowWikiSyntax + "", "UTF-8")) : "")
+ (maxWidth == null ? "" : ("&maxWidth=" + URLEncoder.encode(maxWidth, "UTF-8")))
+ (maxFileSize == null ? "" : ("&maxFileSize=" + URLEncoder.encode(maxFileSize, "UTF-8")));
return url;
}
/**
* @param ctx
* @throws UnsupportedEncodingException
*/
private void renderFancyBox(final GWikiContext ctx, String id) throws UnsupportedEncodingException
{
int width = 1100;
int height = 650;
if ("link".equals(editor)) {
width = 700;
height = 600;
} else if ("image".equals(editor)) {
width = 700;
} else if ("attachment".equals(editor)) {
width = 700;
height = 400;
}
ctx.append("\n<script type=\"text/javascript\">\njQuery(document).ready(function() {\n"
+ "$(\"#"
+ URLEncoder.encode(id, "UTF-8")
+ "\").fancybox({\n"
+ "width: "
+ width
+ ",\n"
+ "height: "
+ height
+ ",\n"
+ "type: 'iframe'\n"
+ "});\n"
+ "});\n"
+ "</script>\n");
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEditor()
{
return editor;
}
public void setEditor(String editor)
{
this.editor = editor;
}
public void setHint(String hint)
{
this.hint = hint;
}
public String getHint()
{
return hint;
}
public void setAllowWikiSyntax(boolean allowWikiSyntax)
{
this.allowWikiSyntax = allowWikiSyntax;
}
public boolean isAllowWikiSyntax()
{
return allowWikiSyntax;
}
public void setMaxWidth(String maxWidth)
{
this.maxWidth = maxWidth;
}
public String getMaxWidth()
{
return maxWidth;
}
public void setMaxFileSize(String maxFileSize)
{
this.maxFileSize = maxFileSize;
}
public String getMaxFileSize()
{
return maxFileSize;
}
}
| true | true | public boolean renderImpl(final GWikiContext ctx, MacroAttributes attrs)
{
GWikiElementInfo ei = ctx.getCurrentElement().getElementInfo();
if (ctx.getCurrentElement() != null) {
if (ei != null) {
ctx.getWikiWeb().getI18nProvider().addTranslationElement(ctx, "edit/pagetemplates/i18n/PtI18N");
final String edit = ctx.getWikiWeb().getI18nProvider().translate(ctx, "gwiki.pt.common.edit");
String image = "<img src='/inc/gwiki/img/icons/linedpaperpencil32.png' style='position:absolute; right: 0; margin-right:-20px' border=0/>";
boolean allowed = ctx.getWikiWeb().getAuthorization().isAllowToView(ctx, ei);
if (ctx.getWikiWeb().getAuthorization().isAllowToEdit(ctx, ctx.getCurrentElement().getElementInfo()) == true && allowed) {
ctx.append("<div style=\"position:relative; padding: 1px\" onmouseover=\"this.style.border = '1px dashed'; this.style.padding = '0px'\" onmouseout=\"this.style.border = '0px'; this.style.padding='1px'\">");
try {
String id = ei.getId();
String url = getUrl(ctx, id, ctx.getCurrentElement().getElementInfo().getId());
ctx.append("<a id=\"" + URLEncoder.encode(name, "UTF-8") + "\" title=\"" + edit + "\" href=\"" + url + "\">" + image + "</a>");
renderFancyBox(ctx, name);
} catch (UnsupportedEncodingException ex) {
GWikiLog.warn("Error rendering section edit link");
}
}
// render simple div if no edit rights
else {
ctx.append("<div>");
}
}
}
if (attrs.getChildFragment() != null) {
if ("attachment".equals(editor) || "link".equals(editor)) {
List<GWikiFragment> childs = attrs.getChildFragment().getChilds();
XmlElement ta = table(attrs("border", "0", "cellspacing", "0", "cellpadding", "2"));
int i = 0;
for (GWikiFragment child : childs) {
if (child instanceof GWikiFragmentLink) {
GWikiFragmentLink attachment = (GWikiFragmentLink) child;
String target = GWikiFragmentLink.isGlobalUrl(attachment.getTarget()) ? attachment.getTarget() : ctx.localUrl(attachment
.getTargetPageId());
String title = (attachment.getTitle() != null) ? attachment.getTitle() : "";
XmlElement targetLink = a(attrs("href", target), text(title));
ta.nest(//
tr(//
td(attrs("width", "180px"), targetLink)) //
);
try {
renderFancyBox(ctx, name + i);
} catch (UnsupportedEncodingException ex) {
GWikiLog.warn("", ex);
}
i++;
}
}
if (ta.getChilds().size() > 0) {
ctx.append(ta.toString());
}
} else {
attrs.getChildFragment().render(ctx);
}
}
if (ei != null) {
ctx.append("</div>");
}
return true;
}
| public boolean renderImpl(final GWikiContext ctx, MacroAttributes attrs)
{
GWikiElementInfo ei = ctx.getWikiWeb().findElementInfo("edit/pagetemplates/PageSectionEditor");
if (ctx.getCurrentElement() != null) {
if (ei != null) {
ctx.getWikiWeb().getI18nProvider().addTranslationElement(ctx, "edit/pagetemplates/i18n/PtI18N");
final String edit = ctx.getWikiWeb().getI18nProvider().translate(ctx, "gwiki.pt.common.edit");
String image = "<img src='/inc/gwiki/img/icons/linedpaperpencil32.png' style='position:absolute; right: 0; margin-right:-20px' border=0/>";
boolean allowed = ctx.getWikiWeb().getAuthorization().isAllowToView(ctx, ei);
if (ctx.getWikiWeb().getAuthorization().isAllowToEdit(ctx, ctx.getCurrentElement().getElementInfo()) == true && allowed) {
ctx.append("<div style=\"position:relative; padding: 1px\" onmouseover=\"this.style.border = '1px dashed'; this.style.padding = '0px'\" onmouseout=\"this.style.border = '0px'; this.style.padding='1px'\">");
try {
String id = ei.getId();
String url = getUrl(ctx, id, ctx.getCurrentElement().getElementInfo().getId());
ctx.append("<a id=\"" + URLEncoder.encode(name, "UTF-8") + "\" title=\"" + edit + "\" href=\"" + url + "\">" + image + "</a>");
renderFancyBox(ctx, name);
} catch (UnsupportedEncodingException ex) {
GWikiLog.warn("Error rendering section edit link");
}
}
// render simple div if no edit rights
else {
ctx.append("<div>");
}
}
}
if (attrs.getChildFragment() != null) {
if ("attachment".equals(editor) || "link".equals(editor)) {
List<GWikiFragment> childs = attrs.getChildFragment().getChilds();
XmlElement ta = table(attrs("border", "0", "cellspacing", "0", "cellpadding", "2"));
int i = 0;
for (GWikiFragment child : childs) {
if (child instanceof GWikiFragmentLink) {
GWikiFragmentLink attachment = (GWikiFragmentLink) child;
String target = GWikiFragmentLink.isGlobalUrl(attachment.getTarget()) ? attachment.getTarget() : ctx.localUrl(attachment
.getTargetPageId());
String title = (attachment.getTitle() != null) ? attachment.getTitle() : "";
XmlElement targetLink = a(attrs("href", target), text(title));
ta.nest(//
tr(//
td(attrs("width", "180px"), targetLink)) //
);
try {
renderFancyBox(ctx, name + i);
} catch (UnsupportedEncodingException ex) {
GWikiLog.warn("", ex);
}
i++;
}
}
if (ta.getChilds().size() > 0) {
ctx.append(ta.toString());
}
} else {
attrs.getChildFragment().render(ctx);
}
}
if (ei != null) {
ctx.append("</div>");
}
return true;
}
|
diff --git a/src/main/java/grisu/gricli/command/KillJobCommand.java b/src/main/java/grisu/gricli/command/KillJobCommand.java
index 888116b..fbcf8fa 100644
--- a/src/main/java/grisu/gricli/command/KillJobCommand.java
+++ b/src/main/java/grisu/gricli/command/KillJobCommand.java
@@ -1,150 +1,149 @@
package grisu.gricli.command;
import grisu.control.ServiceInterface;
import grisu.gricli.Gricli;
import grisu.gricli.GricliRuntimeException;
import grisu.gricli.completors.JobnameCompletor;
import grisu.gricli.environment.GricliEnvironment;
import grisu.jcommons.view.cli.CliHelpers;
import grisu.model.dto.DtoStringList;
import grisu.model.status.ActionStatusEvent;
import grisu.model.status.StatusObject;
import java.util.Arrays;
public class KillJobCommand implements GricliCommand, StatusObject.Listener {
private final String[] jobnames;
private final boolean clean;
private boolean deprecated = false;
private final boolean async;
// @SyntaxDescription(command = { "kill", "jobs" })
// @AutoComplete(completors = { JobnameCompletor.class })
public KillJobCommand() {
this.deprecated = true;
this.jobnames = null;
this.async = false;
this.clean = false;
}
public KillJobCommand(boolean clean, String... jobs) {
if ((jobs != null) && (jobs.length > 0)
&& jobs[jobs.length - 1].equals("&")) {
this.jobnames = Arrays.copyOfRange(jobs, 0, jobs.length - 1);
this.async = true;
} else {
this.jobnames = jobs;
this.async = false;
}
this.clean = clean;
}
@SyntaxDescription(command = { "kill", "job" }, arguments = { "jobnames" })
@AutoComplete(completors = { JobnameCompletor.class })
public KillJobCommand(String... jobnames) {
this(false, jobnames);
}
public GricliEnvironment execute(GricliEnvironment env)
throws GricliRuntimeException {
String cmd = "kill";
if (clean) {
cmd = "clean";
}
if (deprecated) {
env.printMessage("\""
+ cmd
+ " jobs\" command is depreacted. Please use \""
+ cmd
+ " job [arg]\" instead. For more information on usage please type"
+
" \"help "
+ cmd + "\" job");
return env;
}
if ((jobnames == null) || (jobnames.length == 0)) {
env.printError("Can't execute " + cmd
+ " command. Please provide at least one jobname.");
return env;
}
final ServiceInterface si = env.getServiceInterface();
String handle = si.killJobs(DtoStringList.fromStringArray(jobnames),
clean);
final StatusObject so = new StatusObject(si, handle);
final int no = so.getStatus().getTotalElements() / 2;
String jobsString = "jobs";
if (no == 1) {
jobsString = "job";
} else if (no == 0) {
env.printMessage("No jobname matched provided argument(s). Nothing to do...");
return env;
}
if (async) {
if (clean) {
env.addTaskToMonitor("Cleaning of " + no + " " + jobsString, so);
env.printMessage("Cleaning of " + no + " " + jobsString
+ " kicked off. Running in background...");
} else {
env.addTaskToMonitor("Killing of " + no + " " + jobsString, so);
env.printMessage("Killing of " + no + " " + jobsString
+ " kicked off. Running in background...");
}
} else {
if (clean) {
env.printMessage("Cleaning " + no + " " + jobsString + "...");
} else {
env.printMessage("Killing " + no + " " + jobsString + "...");
}
try {
so.addListener(this);
so.waitForActionToFinish(2, false);
so.removeListener(this);
CliHelpers.setProgress(no, no);
} catch (final Exception e) {
throw new GricliRuntimeException(e.getLocalizedMessage());
}
if (so.getStatus().isFailed()) {
env.printError("Killing of job(s) failed: "
+ so.getStatus().getErrorCause());
}
- CliHelpers.writeToTerminal("");
if (clean) {
Gricli.completionCache.refreshJobnames();
- env.printMessage("Job(s) cleaned... ");
+ env.printMessage("Job(s) cleaned...");
} else {
- env.printMessage("Job(s) killed... ");
+ env.printMessage("Job(s) killed...");
}
}
return env;
}
public void statusMessage(ActionStatusEvent event) {
final int current = event.getActionStatus().getCurrentElements() / 2;
final int total = event.getActionStatus().getTotalElements() / 2;
CliHelpers.setProgress(current, total);
}
}
| false | true | public GricliEnvironment execute(GricliEnvironment env)
throws GricliRuntimeException {
String cmd = "kill";
if (clean) {
cmd = "clean";
}
if (deprecated) {
env.printMessage("\""
+ cmd
+ " jobs\" command is depreacted. Please use \""
+ cmd
+ " job [arg]\" instead. For more information on usage please type"
+
" \"help "
+ cmd + "\" job");
return env;
}
if ((jobnames == null) || (jobnames.length == 0)) {
env.printError("Can't execute " + cmd
+ " command. Please provide at least one jobname.");
return env;
}
final ServiceInterface si = env.getServiceInterface();
String handle = si.killJobs(DtoStringList.fromStringArray(jobnames),
clean);
final StatusObject so = new StatusObject(si, handle);
final int no = so.getStatus().getTotalElements() / 2;
String jobsString = "jobs";
if (no == 1) {
jobsString = "job";
} else if (no == 0) {
env.printMessage("No jobname matched provided argument(s). Nothing to do...");
return env;
}
if (async) {
if (clean) {
env.addTaskToMonitor("Cleaning of " + no + " " + jobsString, so);
env.printMessage("Cleaning of " + no + " " + jobsString
+ " kicked off. Running in background...");
} else {
env.addTaskToMonitor("Killing of " + no + " " + jobsString, so);
env.printMessage("Killing of " + no + " " + jobsString
+ " kicked off. Running in background...");
}
} else {
if (clean) {
env.printMessage("Cleaning " + no + " " + jobsString + "...");
} else {
env.printMessage("Killing " + no + " " + jobsString + "...");
}
try {
so.addListener(this);
so.waitForActionToFinish(2, false);
so.removeListener(this);
CliHelpers.setProgress(no, no);
} catch (final Exception e) {
throw new GricliRuntimeException(e.getLocalizedMessage());
}
if (so.getStatus().isFailed()) {
env.printError("Killing of job(s) failed: "
+ so.getStatus().getErrorCause());
}
CliHelpers.writeToTerminal("");
if (clean) {
Gricli.completionCache.refreshJobnames();
env.printMessage("Job(s) cleaned... ");
} else {
env.printMessage("Job(s) killed... ");
}
}
return env;
}
| public GricliEnvironment execute(GricliEnvironment env)
throws GricliRuntimeException {
String cmd = "kill";
if (clean) {
cmd = "clean";
}
if (deprecated) {
env.printMessage("\""
+ cmd
+ " jobs\" command is depreacted. Please use \""
+ cmd
+ " job [arg]\" instead. For more information on usage please type"
+
" \"help "
+ cmd + "\" job");
return env;
}
if ((jobnames == null) || (jobnames.length == 0)) {
env.printError("Can't execute " + cmd
+ " command. Please provide at least one jobname.");
return env;
}
final ServiceInterface si = env.getServiceInterface();
String handle = si.killJobs(DtoStringList.fromStringArray(jobnames),
clean);
final StatusObject so = new StatusObject(si, handle);
final int no = so.getStatus().getTotalElements() / 2;
String jobsString = "jobs";
if (no == 1) {
jobsString = "job";
} else if (no == 0) {
env.printMessage("No jobname matched provided argument(s). Nothing to do...");
return env;
}
if (async) {
if (clean) {
env.addTaskToMonitor("Cleaning of " + no + " " + jobsString, so);
env.printMessage("Cleaning of " + no + " " + jobsString
+ " kicked off. Running in background...");
} else {
env.addTaskToMonitor("Killing of " + no + " " + jobsString, so);
env.printMessage("Killing of " + no + " " + jobsString
+ " kicked off. Running in background...");
}
} else {
if (clean) {
env.printMessage("Cleaning " + no + " " + jobsString + "...");
} else {
env.printMessage("Killing " + no + " " + jobsString + "...");
}
try {
so.addListener(this);
so.waitForActionToFinish(2, false);
so.removeListener(this);
CliHelpers.setProgress(no, no);
} catch (final Exception e) {
throw new GricliRuntimeException(e.getLocalizedMessage());
}
if (so.getStatus().isFailed()) {
env.printError("Killing of job(s) failed: "
+ so.getStatus().getErrorCause());
}
if (clean) {
Gricli.completionCache.refreshJobnames();
env.printMessage("Job(s) cleaned...");
} else {
env.printMessage("Job(s) killed...");
}
}
return env;
}
|
diff --git a/DeliveryPerformance/src/com/sff/report_performance/ReportParameterTableHeaderListener.java b/DeliveryPerformance/src/com/sff/report_performance/ReportParameterTableHeaderListener.java
index 57a6f0e..7d75960 100644
--- a/DeliveryPerformance/src/com/sff/report_performance/ReportParameterTableHeaderListener.java
+++ b/DeliveryPerformance/src/com/sff/report_performance/ReportParameterTableHeaderListener.java
@@ -1,31 +1,32 @@
package com.sff.report_performance;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JTable;
import com.sff.report_performance.GUI.Active;
public class ReportParameterTableHeaderListener implements ItemListener{
private GUI gui;
private JTable selectionTable;
public ReportParameterTableHeaderListener(GUI gui, JTable selectionTable){
this.gui = gui;
this.selectionTable = selectionTable;
}
public void itemStateChanged(ItemEvent e){
MyTableModel model = Active.getActiveDisplayModel();
if(e.getStateChange() == ItemEvent.SELECTED && model != null){
JTable display = Active.getActiveDisplayTable();
if(model.getRowData().isEmpty()){
((CheckBoxHeader) display.getColumnModel().getColumn(0).getHeaderRenderer()).setSelected(true);
}
else model.removeRowInterval(0, model.getRowData().size() - 1, selectionTable);
gui.synchDisplayHeaders(Active.getActiveDisplayTable());
+ gui.synchronizeHeader();
}
}
}
| true | true | public void itemStateChanged(ItemEvent e){
MyTableModel model = Active.getActiveDisplayModel();
if(e.getStateChange() == ItemEvent.SELECTED && model != null){
JTable display = Active.getActiveDisplayTable();
if(model.getRowData().isEmpty()){
((CheckBoxHeader) display.getColumnModel().getColumn(0).getHeaderRenderer()).setSelected(true);
}
else model.removeRowInterval(0, model.getRowData().size() - 1, selectionTable);
gui.synchDisplayHeaders(Active.getActiveDisplayTable());
}
}
| public void itemStateChanged(ItemEvent e){
MyTableModel model = Active.getActiveDisplayModel();
if(e.getStateChange() == ItemEvent.SELECTED && model != null){
JTable display = Active.getActiveDisplayTable();
if(model.getRowData().isEmpty()){
((CheckBoxHeader) display.getColumnModel().getColumn(0).getHeaderRenderer()).setSelected(true);
}
else model.removeRowInterval(0, model.getRowData().size() - 1, selectionTable);
gui.synchDisplayHeaders(Active.getActiveDisplayTable());
gui.synchronizeHeader();
}
}
|
diff --git a/src/com/axelby/podax/PodcastDetailActivity.java b/src/com/axelby/podax/PodcastDetailActivity.java
index 2f6dacf..6ab6935 100644
--- a/src/com/axelby/podax/PodcastDetailActivity.java
+++ b/src/com/axelby/podax/PodcastDetailActivity.java
@@ -1,283 +1,285 @@
package com.axelby.podax;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class PodcastDetailActivity extends Activity {
Cursor _cursor;
PodcastCursor _podcast;
long _podcastId;
Handler _handler = new Handler();
TextView _titleView;
TextView _subscriptionTitleView;
WebView _descriptionView;
Button _queueButton;
TextView _queuePosition;
ImageButton _restartButton;
ImageButton _rewindButton;
ImageButton _playButton;
ImageButton _forwardButton;
ImageButton _skipToEndButton;
SeekBar _seekbar;
boolean _seekbar_dragging;
TextView _position;
TextView _duration;
class PodcastObserver extends ContentObserver {
public PodcastObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
_cursor.close();
Uri uri = ContentUris.withAppendedId(PodcastProvider.URI, _podcastId);
_cursor = getContentResolver().query(uri, _projection, null, null, null);
_podcast = new PodcastCursor(PodcastDetailActivity.this, _cursor);
updateQueueViews();
updatePlayerControls(false);
}
}
String[] _projection = new String[] {
PodcastProvider.COLUMN_ID,
PodcastProvider.COLUMN_TITLE,
PodcastProvider.COLUMN_SUBSCRIPTION_TITLE,
PodcastProvider.COLUMN_DESCRIPTION,
PodcastProvider.COLUMN_DURATION,
PodcastProvider.COLUMN_LAST_POSITION,
PodcastProvider.COLUMN_QUEUE_POSITION,
PodcastProvider.COLUMN_MEDIA_URL,
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
if (intent.hasExtra(Constants.EXTRA_PODCAST_ID)) {
int podcastId = intent.getIntExtra(Constants.EXTRA_PODCAST_ID, -1);
if (podcastId == -1) {
finish();
return;
}
Uri uri = ContentUris.withAppendedId(PodcastProvider.URI, podcastId);
_cursor = getContentResolver().query(uri, _projection, null, null, null);
} else {
Uri uri = Uri.withAppendedPath(PodcastProvider.URI, "active");
_cursor = managedQuery(uri, _projection, null, null, null);
// if the queue is empty, don't show this
if (_cursor.isAfterLast()) {
finish();
startActivity(new Intent(this, QueueActivity.class));
return;
}
}
_podcast = new PodcastCursor(this, _cursor);
_podcastId = _podcast.getId();
_observer = new PodcastObserver(_handler);
_podcast.registerContentObserver(_observer);
setTitle(_podcast.getTitle());
setContentView(R.layout.podcast_detail);
_subscriptionTitleView = (TextView)findViewById(R.id.subscription_title);
_subscriptionTitleView.setText(_podcast.getSubscriptionTitle());
_descriptionView = (WebView)findViewById(R.id.description);
String html = "<html><head><style type=\"text/css\">" +
"a { color: #E59F39 }" +
"</style></head>" +
"<body style=\"background:black;color:white\">" + _podcast.getDescription() + "</body></html>";
_descriptionView.loadData(html, "text/html", "utf-8");
_descriptionView.setBackgroundColor(Color.BLACK);
_queuePosition = (TextView)findViewById(R.id.queue_position);
_queueButton = (Button)findViewById(R.id.queue_btn);
updateQueueViews();
_queueButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (_podcast.getQueuePosition() == null)
_podcast.addToQueue();
else
_podcast.removeFromQueue();
}
});
_restartButton = (ImageButton)findViewById(R.id.restart_btn);
_restartButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.restart(PodcastDetailActivity.this);
}
});
_rewindButton = (ImageButton)findViewById(R.id.rewind_btn);
_rewindButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.skipBack(PodcastDetailActivity.this);
}
});
_playButton = (ImageButton)findViewById(R.id.play_btn);
_playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Long activeId = null;
String[] projection = new String[] { PodcastProvider.COLUMN_ID };
Cursor c = getContentResolver().query(PodcastProvider.ACTIVE_PODCAST_URI, projection, null, null, null);
try {
if (c.moveToNext())
activeId = c.getLong(0);
if (Helper.isPlaying(PodcastDetailActivity.this) &&
activeId != null && activeId.equals(_podcast.getId()))
PlayerService.pause(PodcastDetailActivity.this);
else
PlayerService.play(PodcastDetailActivity.this, _podcast);
} finally {
c.close();
}
}
});
_forwardButton = (ImageButton)findViewById(R.id.forward_btn);
_forwardButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.skipForward(PodcastDetailActivity.this);
}
});
_skipToEndButton = (ImageButton)findViewById(R.id.skiptoend_btn);
_skipToEndButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.skipToEnd(PodcastDetailActivity.this);
+ finish();
+ startActivity(new Intent(PodcastDetailActivity.this, PodcastDetailActivity.class));
}
});
_seekbar = (SeekBar)findViewById(R.id.seekbar);
_seekbar.setMax(_podcast.getDuration());
_seekbar.setProgress(_podcast.getLastPosition());
_seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
_position.setText(Helper.getTimeString(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
_seekbar_dragging = true;
}
public void onStopTrackingTouch(SeekBar seekBar) {
_seekbar_dragging = false;
PlayerService.skipTo(PodcastDetailActivity.this, seekBar.getProgress() / 1000);
}
});
_seekbar_dragging = false;
_position = (TextView)findViewById(R.id.position);
_position.setText(Helper.getTimeString(_podcast.getLastPosition()));
_duration = (TextView)findViewById(R.id.duration);
_duration.setText("-" + Helper.getTimeString(_podcast.getDuration() - _podcast.getLastPosition()));
updatePlayerControls(true);
}
@Override
protected void onPause() {
super.onPause();
_podcast.unregisterContentObserver(_observer);
_cursor.close();
}
@Override
protected void onResume() {
super.onResume();
Uri uri = ContentUris.withAppendedId(PodcastProvider.URI, _podcastId);
_cursor = getContentResolver().query(uri, _projection, null, null, null);
_podcast = new PodcastCursor(this, _cursor);
_podcast.registerContentObserver(_observer);
}
boolean _controlsEnabled = true;
private PodcastObserver _observer;
private void updatePlayerControls(boolean force) {
String[] projection = new String[] {
PodcastProvider.COLUMN_ID,
PodcastProvider.COLUMN_LAST_POSITION,
PodcastProvider.COLUMN_DURATION,
};
Cursor c = getContentResolver().query(PodcastProvider.ACTIVE_PODCAST_URI, projection, null, null, null);
try {
PodcastCursor p = new PodcastCursor(this, c);
if (!p.isNull() && p.getId().equals(_podcast.getId())) {
if (!_seekbar_dragging) {
_position.setText(Helper.getTimeString(p.getLastPosition()));
_duration.setText("-" + Helper.getTimeString(p.getDuration() - p.getLastPosition()));
_seekbar.setProgress(p.getLastPosition());
}
int playResource = Helper.isPlaying(this) ? R.drawable.ic_media_pause
: R.drawable.ic_media_play;
_playButton.setImageResource(playResource);
if (!force && _controlsEnabled == true)
return;
_restartButton.setEnabled(true);
_rewindButton.setEnabled(true);
_forwardButton.setEnabled(true);
_skipToEndButton.setEnabled(true);
_seekbar.setEnabled(true);
_controlsEnabled = true;
} else {
if (!force && !_controlsEnabled)
return;
_playButton.setImageResource(R.drawable.ic_media_play);
_restartButton.setEnabled(false);
_rewindButton.setEnabled(false);
_forwardButton.setEnabled(false);
_skipToEndButton.setEnabled(false);
_seekbar.setEnabled(false);
_controlsEnabled = false;
}
} finally {
c.close();
}
}
private void updateQueueViews() {
if (_podcast.getQueuePosition() == null) {
_queueButton.setText(R.string.add_to_queue);
_queuePosition.setText("");
} else {
_queueButton.setText(R.string.remove_from_queue);
_queuePosition.setText("#"
+ String.valueOf(_podcast.getQueuePosition() + 1)
+ " in queue");
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
if (intent.hasExtra(Constants.EXTRA_PODCAST_ID)) {
int podcastId = intent.getIntExtra(Constants.EXTRA_PODCAST_ID, -1);
if (podcastId == -1) {
finish();
return;
}
Uri uri = ContentUris.withAppendedId(PodcastProvider.URI, podcastId);
_cursor = getContentResolver().query(uri, _projection, null, null, null);
} else {
Uri uri = Uri.withAppendedPath(PodcastProvider.URI, "active");
_cursor = managedQuery(uri, _projection, null, null, null);
// if the queue is empty, don't show this
if (_cursor.isAfterLast()) {
finish();
startActivity(new Intent(this, QueueActivity.class));
return;
}
}
_podcast = new PodcastCursor(this, _cursor);
_podcastId = _podcast.getId();
_observer = new PodcastObserver(_handler);
_podcast.registerContentObserver(_observer);
setTitle(_podcast.getTitle());
setContentView(R.layout.podcast_detail);
_subscriptionTitleView = (TextView)findViewById(R.id.subscription_title);
_subscriptionTitleView.setText(_podcast.getSubscriptionTitle());
_descriptionView = (WebView)findViewById(R.id.description);
String html = "<html><head><style type=\"text/css\">" +
"a { color: #E59F39 }" +
"</style></head>" +
"<body style=\"background:black;color:white\">" + _podcast.getDescription() + "</body></html>";
_descriptionView.loadData(html, "text/html", "utf-8");
_descriptionView.setBackgroundColor(Color.BLACK);
_queuePosition = (TextView)findViewById(R.id.queue_position);
_queueButton = (Button)findViewById(R.id.queue_btn);
updateQueueViews();
_queueButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (_podcast.getQueuePosition() == null)
_podcast.addToQueue();
else
_podcast.removeFromQueue();
}
});
_restartButton = (ImageButton)findViewById(R.id.restart_btn);
_restartButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.restart(PodcastDetailActivity.this);
}
});
_rewindButton = (ImageButton)findViewById(R.id.rewind_btn);
_rewindButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.skipBack(PodcastDetailActivity.this);
}
});
_playButton = (ImageButton)findViewById(R.id.play_btn);
_playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Long activeId = null;
String[] projection = new String[] { PodcastProvider.COLUMN_ID };
Cursor c = getContentResolver().query(PodcastProvider.ACTIVE_PODCAST_URI, projection, null, null, null);
try {
if (c.moveToNext())
activeId = c.getLong(0);
if (Helper.isPlaying(PodcastDetailActivity.this) &&
activeId != null && activeId.equals(_podcast.getId()))
PlayerService.pause(PodcastDetailActivity.this);
else
PlayerService.play(PodcastDetailActivity.this, _podcast);
} finally {
c.close();
}
}
});
_forwardButton = (ImageButton)findViewById(R.id.forward_btn);
_forwardButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.skipForward(PodcastDetailActivity.this);
}
});
_skipToEndButton = (ImageButton)findViewById(R.id.skiptoend_btn);
_skipToEndButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.skipToEnd(PodcastDetailActivity.this);
}
});
_seekbar = (SeekBar)findViewById(R.id.seekbar);
_seekbar.setMax(_podcast.getDuration());
_seekbar.setProgress(_podcast.getLastPosition());
_seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
_position.setText(Helper.getTimeString(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
_seekbar_dragging = true;
}
public void onStopTrackingTouch(SeekBar seekBar) {
_seekbar_dragging = false;
PlayerService.skipTo(PodcastDetailActivity.this, seekBar.getProgress() / 1000);
}
});
_seekbar_dragging = false;
_position = (TextView)findViewById(R.id.position);
_position.setText(Helper.getTimeString(_podcast.getLastPosition()));
_duration = (TextView)findViewById(R.id.duration);
_duration.setText("-" + Helper.getTimeString(_podcast.getDuration() - _podcast.getLastPosition()));
updatePlayerControls(true);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
if (intent.hasExtra(Constants.EXTRA_PODCAST_ID)) {
int podcastId = intent.getIntExtra(Constants.EXTRA_PODCAST_ID, -1);
if (podcastId == -1) {
finish();
return;
}
Uri uri = ContentUris.withAppendedId(PodcastProvider.URI, podcastId);
_cursor = getContentResolver().query(uri, _projection, null, null, null);
} else {
Uri uri = Uri.withAppendedPath(PodcastProvider.URI, "active");
_cursor = managedQuery(uri, _projection, null, null, null);
// if the queue is empty, don't show this
if (_cursor.isAfterLast()) {
finish();
startActivity(new Intent(this, QueueActivity.class));
return;
}
}
_podcast = new PodcastCursor(this, _cursor);
_podcastId = _podcast.getId();
_observer = new PodcastObserver(_handler);
_podcast.registerContentObserver(_observer);
setTitle(_podcast.getTitle());
setContentView(R.layout.podcast_detail);
_subscriptionTitleView = (TextView)findViewById(R.id.subscription_title);
_subscriptionTitleView.setText(_podcast.getSubscriptionTitle());
_descriptionView = (WebView)findViewById(R.id.description);
String html = "<html><head><style type=\"text/css\">" +
"a { color: #E59F39 }" +
"</style></head>" +
"<body style=\"background:black;color:white\">" + _podcast.getDescription() + "</body></html>";
_descriptionView.loadData(html, "text/html", "utf-8");
_descriptionView.setBackgroundColor(Color.BLACK);
_queuePosition = (TextView)findViewById(R.id.queue_position);
_queueButton = (Button)findViewById(R.id.queue_btn);
updateQueueViews();
_queueButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (_podcast.getQueuePosition() == null)
_podcast.addToQueue();
else
_podcast.removeFromQueue();
}
});
_restartButton = (ImageButton)findViewById(R.id.restart_btn);
_restartButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.restart(PodcastDetailActivity.this);
}
});
_rewindButton = (ImageButton)findViewById(R.id.rewind_btn);
_rewindButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.skipBack(PodcastDetailActivity.this);
}
});
_playButton = (ImageButton)findViewById(R.id.play_btn);
_playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Long activeId = null;
String[] projection = new String[] { PodcastProvider.COLUMN_ID };
Cursor c = getContentResolver().query(PodcastProvider.ACTIVE_PODCAST_URI, projection, null, null, null);
try {
if (c.moveToNext())
activeId = c.getLong(0);
if (Helper.isPlaying(PodcastDetailActivity.this) &&
activeId != null && activeId.equals(_podcast.getId()))
PlayerService.pause(PodcastDetailActivity.this);
else
PlayerService.play(PodcastDetailActivity.this, _podcast);
} finally {
c.close();
}
}
});
_forwardButton = (ImageButton)findViewById(R.id.forward_btn);
_forwardButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.skipForward(PodcastDetailActivity.this);
}
});
_skipToEndButton = (ImageButton)findViewById(R.id.skiptoend_btn);
_skipToEndButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PlayerService.skipToEnd(PodcastDetailActivity.this);
finish();
startActivity(new Intent(PodcastDetailActivity.this, PodcastDetailActivity.class));
}
});
_seekbar = (SeekBar)findViewById(R.id.seekbar);
_seekbar.setMax(_podcast.getDuration());
_seekbar.setProgress(_podcast.getLastPosition());
_seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
_position.setText(Helper.getTimeString(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
_seekbar_dragging = true;
}
public void onStopTrackingTouch(SeekBar seekBar) {
_seekbar_dragging = false;
PlayerService.skipTo(PodcastDetailActivity.this, seekBar.getProgress() / 1000);
}
});
_seekbar_dragging = false;
_position = (TextView)findViewById(R.id.position);
_position.setText(Helper.getTimeString(_podcast.getLastPosition()));
_duration = (TextView)findViewById(R.id.duration);
_duration.setText("-" + Helper.getTimeString(_podcast.getDuration() - _podcast.getLastPosition()));
updatePlayerControls(true);
}
|
diff --git a/weechat-android/src/com/ubergeek42/WeechatAndroid/WeechatPreferencesActivity.java b/weechat-android/src/com/ubergeek42/WeechatAndroid/WeechatPreferencesActivity.java
index 6c24ff7..ba1481a 100644
--- a/weechat-android/src/com/ubergeek42/WeechatAndroid/WeechatPreferencesActivity.java
+++ b/weechat-android/src/com/ubergeek42/WeechatAndroid/WeechatPreferencesActivity.java
@@ -1,163 +1,163 @@
/*******************************************************************************
* Copyright 2012 Keith Johnson
*
* 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.ubergeek42.WeechatAndroid;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
public class WeechatPreferencesActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
private SharedPreferences sharedPreferences;
private EditTextPreference hostPref;
private EditTextPreference portPref;
private EditTextPreference textSizePref;
private EditTextPreference timestampformatPref;
private EditTextPreference passPref;
private EditTextPreference stunnelCert;
private EditTextPreference stunnelPass;
private EditTextPreference sshHostPref;
private EditTextPreference sshPortPref;
private EditTextPreference sshPassPref;
private EditTextPreference sshUserPref;
private ListPreference prefixPref;
private ListPreference connectionTypePref;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
sharedPreferences = getPreferenceScreen().getSharedPreferences();
hostPref = (EditTextPreference) getPreferenceScreen().findPreference("host");
portPref = (EditTextPreference) getPreferenceScreen().findPreference("port");
passPref = (EditTextPreference) getPreferenceScreen().findPreference("password");
textSizePref = (EditTextPreference) getPreferenceScreen().findPreference("text_size");
timestampformatPref = (EditTextPreference) getPreferenceScreen().findPreference(
"timestamp_format");
stunnelCert = (EditTextPreference) getPreferenceScreen().findPreference("stunnel_cert");
stunnelPass = (EditTextPreference) getPreferenceScreen().findPreference("stunnel_pass");
sshHostPref = (EditTextPreference) getPreferenceScreen().findPreference("ssh_host");
sshUserPref = (EditTextPreference) getPreferenceScreen().findPreference("ssh_user");
sshPortPref = (EditTextPreference) getPreferenceScreen().findPreference("ssh_port");
sshPassPref = (EditTextPreference) getPreferenceScreen().findPreference("ssh_pass");
prefixPref = (ListPreference) getPreferenceScreen().findPreference("prefix_align");
connectionTypePref = (ListPreference) getPreferenceScreen().findPreference(
"connection_type");
setTitle(R.string.preferences);
}
@Override
protected void onPause() {
super.onPause();
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
protected void onResume() {
super.onResume();
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
hostPref.setSummary(sharedPreferences.getString("host", ""));
portPref.setSummary(sharedPreferences.getString("port", "8001"));
textSizePref.setSummary(sharedPreferences.getString("text_size", "10"));
timestampformatPref.setSummary(sharedPreferences.getString("timestamp_format", "HH:mm:ss"));
stunnelCert.setSummary(sharedPreferences.getString("stunnel_cert", "Not Set"));
sshHostPref.setSummary(sharedPreferences.getString("ssh_host", ""));
sshUserPref.setSummary(sharedPreferences.getString("ssh_user", ""));
sshPortPref.setSummary(sharedPreferences.getString("ssh_port", "22"));
prefixPref.setSummary(prefixPref.getEntry());
connectionTypePref.setSummary(connectionTypePref.getEntry());
String tmp;
tmp = sharedPreferences.getString("password", null);
if (tmp == null || tmp.equals("")) {
passPref.setSummary("None Set");
} else {
passPref.setSummary("******");
}
tmp = sharedPreferences.getString("stunnel_pass", null);
if (tmp == null || tmp.equals("")) {
stunnelPass.setSummary("None Set");
} else {
stunnelPass.setSummary("******");
}
tmp = sharedPreferences.getString("ssh_pass", null);
if (tmp == null || tmp.equals("")) {
sshPassPref.setSummary("None Set");
} else {
sshPassPref.setSummary("******");
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("host")) {
hostPref.setSummary(sharedPreferences.getString(key, ""));
} else if (key.equals("port")) {
portPref.setSummary(sharedPreferences.getString("port", "8001"));
} else if (key.equals("password")) {
String tmp = sharedPreferences.getString("password", null);
if (tmp == null || tmp.equals("")) {
passPref.setSummary("None Set");
} else {
passPref.setSummary("******");
}
} else if (key.equals("text_size")) {
textSizePref.setSummary(sharedPreferences.getString("text_size", "10"));
} else if (key.equals("timestamp_format")) {
timestampformatPref.setSummary(sharedPreferences.getString("timestamp_format",
"HH:mm:ss"));
} else if (key.equals("stunnel_cert")) {
stunnelCert.setSummary(sharedPreferences.getString("stunnel_cert",
"/sdcard/weechat/client.p12"));
} else if (key.equals("stunnel_pass")) {
String tmp = sharedPreferences.getString("stunnel_pass", null);
if (tmp == null || tmp.equals("")) {
stunnelPass.setSummary("None Set");
} else {
stunnelPass.setSummary("******");
}
} else if (key.equals("ssh_host")) {
sshHostPref.setSummary(sharedPreferences.getString(key, ""));
} else if (key.equals("ssh_user")) {
sshUserPref.setSummary(sharedPreferences.getString(key, ""));
- } else if (key.equals("port")) {
+ } else if (key.equals("ssh_port")) {
sshPortPref.setSummary(sharedPreferences.getString(key, "22"));
} else if (key.equals("ssh_pass")) {
String tmp = sharedPreferences.getString("ssh_pass", null);
if (tmp == null || tmp.equals("")) {
sshPassPref.setSummary("None Set");
} else {
sshPassPref.setSummary("******");
}
} else if (key.equals("prefix_align")) {
prefixPref.setSummary(prefixPref.getEntry());
} else if (key.equals("connection_type")) {
connectionTypePref.setSummary(connectionTypePref.getEntry());
}
}
}
| true | true | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("host")) {
hostPref.setSummary(sharedPreferences.getString(key, ""));
} else if (key.equals("port")) {
portPref.setSummary(sharedPreferences.getString("port", "8001"));
} else if (key.equals("password")) {
String tmp = sharedPreferences.getString("password", null);
if (tmp == null || tmp.equals("")) {
passPref.setSummary("None Set");
} else {
passPref.setSummary("******");
}
} else if (key.equals("text_size")) {
textSizePref.setSummary(sharedPreferences.getString("text_size", "10"));
} else if (key.equals("timestamp_format")) {
timestampformatPref.setSummary(sharedPreferences.getString("timestamp_format",
"HH:mm:ss"));
} else if (key.equals("stunnel_cert")) {
stunnelCert.setSummary(sharedPreferences.getString("stunnel_cert",
"/sdcard/weechat/client.p12"));
} else if (key.equals("stunnel_pass")) {
String tmp = sharedPreferences.getString("stunnel_pass", null);
if (tmp == null || tmp.equals("")) {
stunnelPass.setSummary("None Set");
} else {
stunnelPass.setSummary("******");
}
} else if (key.equals("ssh_host")) {
sshHostPref.setSummary(sharedPreferences.getString(key, ""));
} else if (key.equals("ssh_user")) {
sshUserPref.setSummary(sharedPreferences.getString(key, ""));
} else if (key.equals("port")) {
sshPortPref.setSummary(sharedPreferences.getString(key, "22"));
} else if (key.equals("ssh_pass")) {
String tmp = sharedPreferences.getString("ssh_pass", null);
if (tmp == null || tmp.equals("")) {
sshPassPref.setSummary("None Set");
} else {
sshPassPref.setSummary("******");
}
} else if (key.equals("prefix_align")) {
prefixPref.setSummary(prefixPref.getEntry());
} else if (key.equals("connection_type")) {
connectionTypePref.setSummary(connectionTypePref.getEntry());
}
}
| public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("host")) {
hostPref.setSummary(sharedPreferences.getString(key, ""));
} else if (key.equals("port")) {
portPref.setSummary(sharedPreferences.getString("port", "8001"));
} else if (key.equals("password")) {
String tmp = sharedPreferences.getString("password", null);
if (tmp == null || tmp.equals("")) {
passPref.setSummary("None Set");
} else {
passPref.setSummary("******");
}
} else if (key.equals("text_size")) {
textSizePref.setSummary(sharedPreferences.getString("text_size", "10"));
} else if (key.equals("timestamp_format")) {
timestampformatPref.setSummary(sharedPreferences.getString("timestamp_format",
"HH:mm:ss"));
} else if (key.equals("stunnel_cert")) {
stunnelCert.setSummary(sharedPreferences.getString("stunnel_cert",
"/sdcard/weechat/client.p12"));
} else if (key.equals("stunnel_pass")) {
String tmp = sharedPreferences.getString("stunnel_pass", null);
if (tmp == null || tmp.equals("")) {
stunnelPass.setSummary("None Set");
} else {
stunnelPass.setSummary("******");
}
} else if (key.equals("ssh_host")) {
sshHostPref.setSummary(sharedPreferences.getString(key, ""));
} else if (key.equals("ssh_user")) {
sshUserPref.setSummary(sharedPreferences.getString(key, ""));
} else if (key.equals("ssh_port")) {
sshPortPref.setSummary(sharedPreferences.getString(key, "22"));
} else if (key.equals("ssh_pass")) {
String tmp = sharedPreferences.getString("ssh_pass", null);
if (tmp == null || tmp.equals("")) {
sshPassPref.setSummary("None Set");
} else {
sshPassPref.setSummary("******");
}
} else if (key.equals("prefix_align")) {
prefixPref.setSummary(prefixPref.getEntry());
} else if (key.equals("connection_type")) {
connectionTypePref.setSummary(connectionTypePref.getEntry());
}
}
|
diff --git a/src/main/java/org/signaut/common/hazelcast/HazelcastFactory.java b/src/main/java/org/signaut/common/hazelcast/HazelcastFactory.java
index e2791ff..e129a1c 100644
--- a/src/main/java/org/signaut/common/hazelcast/HazelcastFactory.java
+++ b/src/main/java/org/signaut/common/hazelcast/HazelcastFactory.java
@@ -1,47 +1,47 @@
package org.signaut.common.hazelcast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.hazelcast.config.XmlConfigBuilder;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
public class HazelcastFactory {
/**
* Loads a file relative to the current location - if this fails it will
* load a resource from the class-loader of <code>loadingClass</code>
*
* @param filename
* @param loadingClass
* @return a new HazelcastInstance based on the configuration in
* <code>filename</code>
* @throws IllegalStateException
* if no file is found
*/
public HazelcastInstance loadHazelcastInstance(String filename, Class<?> loadingClass) {
// Load file from current location
final File file = new File("./" + filename);
final XmlConfigBuilder configBuilder;
if (file.exists()) {
try {
configBuilder = new XmlConfigBuilder(new FileInputStream(file));
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Failed to load file " + filename, e);
}
return Hazelcast.newHazelcastInstance(configBuilder.build());
} else {
// If this fails, load from classpath
final InputStream resource = loadingClass.getResourceAsStream(filename);
if (resource != null) {
configBuilder = new XmlConfigBuilder(resource);
return Hazelcast.newHazelcastInstance(configBuilder.build());
}
}
// Bail out if all else fails
- throw new IllegalStateException("Failed to load hazelcast configuration from " + file);
+ throw new IllegalStateException("Failed to load hazelcast configuration from " + filename);
}
}
| true | true | public HazelcastInstance loadHazelcastInstance(String filename, Class<?> loadingClass) {
// Load file from current location
final File file = new File("./" + filename);
final XmlConfigBuilder configBuilder;
if (file.exists()) {
try {
configBuilder = new XmlConfigBuilder(new FileInputStream(file));
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Failed to load file " + filename, e);
}
return Hazelcast.newHazelcastInstance(configBuilder.build());
} else {
// If this fails, load from classpath
final InputStream resource = loadingClass.getResourceAsStream(filename);
if (resource != null) {
configBuilder = new XmlConfigBuilder(resource);
return Hazelcast.newHazelcastInstance(configBuilder.build());
}
}
// Bail out if all else fails
throw new IllegalStateException("Failed to load hazelcast configuration from " + file);
}
| public HazelcastInstance loadHazelcastInstance(String filename, Class<?> loadingClass) {
// Load file from current location
final File file = new File("./" + filename);
final XmlConfigBuilder configBuilder;
if (file.exists()) {
try {
configBuilder = new XmlConfigBuilder(new FileInputStream(file));
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Failed to load file " + filename, e);
}
return Hazelcast.newHazelcastInstance(configBuilder.build());
} else {
// If this fails, load from classpath
final InputStream resource = loadingClass.getResourceAsStream(filename);
if (resource != null) {
configBuilder = new XmlConfigBuilder(resource);
return Hazelcast.newHazelcastInstance(configBuilder.build());
}
}
// Bail out if all else fails
throw new IllegalStateException("Failed to load hazelcast configuration from " + filename);
}
|
diff --git a/src/main/java/com/brightcove/johnny/http/NullableValueQueryParser.java b/src/main/java/com/brightcove/johnny/http/NullableValueQueryParser.java
index 7736cdf..ea35671 100644
--- a/src/main/java/com/brightcove/johnny/http/NullableValueQueryParser.java
+++ b/src/main/java/com/brightcove/johnny/http/NullableValueQueryParser.java
@@ -1,66 +1,68 @@
package com.brightcove.johnny.http;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.brightcove.johnny.coll.MapEntry;
/**
* A query parser that allows keys that are missing values (e.g. the second
* <code>a</code> in <code>?a=5&a&b=7</code>) and uses a null value
* to represent them.
*/
public class NullableValueQueryParser implements QueryParser {
private static final List<Map.Entry<String,String>> EMPTY_LIST =
Collections.unmodifiableList(new ArrayList<Map.Entry<String,String>>(0));
/** Pattern that finds ampersands. */
public static final Pattern AMPERSAND = Pattern.compile("&");
/**
* Pattern that finds ampersands or semicolons. The W3C recommends
* allowing both, although this is very rare in the wild.
*/
public static final Pattern AMPERSAND_OR_SEMICOLON = Pattern.compile("[&;]");
private final Pattern pairSep;
private final Pattern kSep = Pattern.compile("=");
/**
* Default parser, using ampersand (<code>&</code>) to delimit
* key-value pairs from each other.
*/
public NullableValueQueryParser() {
this(AMPERSAND);
}
/**
* Split key-value pairs from each other based on arbitrary pattern.
*/
public NullableValueQueryParser(Pattern pairSep) {
if (pairSep == null) {
throw new NullPointerException("pair separator pattern must not be null");
}
this.pairSep = pairSep;
}
public Iterable<Map.Entry<String, String>> parseAs(String queryRaw) {
if (queryRaw == null) {
return EMPTY_LIST;
}
LinkedList<Map.Entry<String, String>> ret = new LinkedList<Map.Entry<String, String>>();
String[] pairs = pairSep.split(queryRaw);
for (String pair : pairs) {
if (pair.isEmpty()) {
continue;
}
String[] kv = kSep.split(pair, 2);
- ret.addLast(new MapEntry<String, String>(kv[0], kv.length == 1 ? null : kv[1]));
+ String k = Codecs.percentDecode(kv[0]);
+ String v = kv.length == 1 ? null : Codecs.percentDecode(kv[1]);
+ ret.addLast(new MapEntry<String, String>(k, v));
}
return Collections.unmodifiableList(ret);
}
}
| true | true | public Iterable<Map.Entry<String, String>> parseAs(String queryRaw) {
if (queryRaw == null) {
return EMPTY_LIST;
}
LinkedList<Map.Entry<String, String>> ret = new LinkedList<Map.Entry<String, String>>();
String[] pairs = pairSep.split(queryRaw);
for (String pair : pairs) {
if (pair.isEmpty()) {
continue;
}
String[] kv = kSep.split(pair, 2);
ret.addLast(new MapEntry<String, String>(kv[0], kv.length == 1 ? null : kv[1]));
}
return Collections.unmodifiableList(ret);
}
| public Iterable<Map.Entry<String, String>> parseAs(String queryRaw) {
if (queryRaw == null) {
return EMPTY_LIST;
}
LinkedList<Map.Entry<String, String>> ret = new LinkedList<Map.Entry<String, String>>();
String[] pairs = pairSep.split(queryRaw);
for (String pair : pairs) {
if (pair.isEmpty()) {
continue;
}
String[] kv = kSep.split(pair, 2);
String k = Codecs.percentDecode(kv[0]);
String v = kv.length == 1 ? null : Codecs.percentDecode(kv[1]);
ret.addLast(new MapEntry<String, String>(k, v));
}
return Collections.unmodifiableList(ret);
}
|
diff --git a/luaj-vm/src/addon/java/lua/addon/luacompat/CoroutinesLib.java b/luaj-vm/src/addon/java/lua/addon/luacompat/CoroutinesLib.java
index 9017c2b..be2f6ef 100644
--- a/luaj-vm/src/addon/java/lua/addon/luacompat/CoroutinesLib.java
+++ b/luaj-vm/src/addon/java/lua/addon/luacompat/CoroutinesLib.java
@@ -1,98 +1,101 @@
package lua.addon.luacompat;
import lua.GlobalState;
import lua.VM;
import lua.io.Closure;
import lua.value.LFunction;
import lua.value.LTable;
import lua.value.LThread;
public class CoroutinesLib extends LFunction {
public static void install() {
LTable lib = new LTable(0,6);
lib.put("create", new CoroutinesLib(1));
lib.put("resume", new CoroutinesLib(2));
lib.put("running", new CoroutinesLib(3));
lib.put("status", new CoroutinesLib(4));
lib.put("wrap", new CoroutinesLib(5));
lib.put("yield", new CoroutinesLib(6));
GlobalState.getGlobalsTable().put("coroutine",lib);
}
private final int id;
private final LThread thread;
public CoroutinesLib() {
this.id = 0;
this.thread = null;
}
private CoroutinesLib( int id ) {
this.id = id;
this.thread = null;
}
private CoroutinesLib( int id, LThread thread ) {
this.id = id;
this.thread = thread;
}
public boolean luaStackCall( VM vm ) {
switch ( id ) {
case 0: { // load lib
install();
vm.pushnil();
break;
}
case 1: { // create
Closure c = (Closure) vm.topointer(2);
vm.pushlvalue( new LThread(c) );
break;
}
case 2: {// resume
LThread t = (LThread) vm.topointer(2);
t.resumeFrom( vm, vm.gettop()-2 );
return false;
}
case 3: { // running
LThread r = LThread.getRunning();
if ( r != null ) {
vm.pushlvalue( r );
} else {
vm.pushnil();
}
break;
}
case 4: { // status
vm.pushstring( ((LThread) vm.topointer(2)).getStatus() );
break;
}
case 5: { // wrap
Closure c = (Closure) vm.topointer(2);
vm.pushlvalue( new CoroutinesLib(7,new LThread(c)) );
break;
}
case 6: { // yield
LThread r = LThread.getRunning();
if ( r == null )
vm.error("main thread can't yield");
else {
return r.yield();
}
}
case 7: { // wrapped resume
LThread t = this.thread;
t.resumeFrom( vm, vm.gettop()-1 );
- vm.remove(1);
+ if ( vm.toboolean(1) )
+ vm.remove(1);
+ else
+ vm.error( vm.tostring(2), 0 );
return false;
}
}
vm.insert(1);
vm.settop(1);
return false;
}
}
| true | true | public boolean luaStackCall( VM vm ) {
switch ( id ) {
case 0: { // load lib
install();
vm.pushnil();
break;
}
case 1: { // create
Closure c = (Closure) vm.topointer(2);
vm.pushlvalue( new LThread(c) );
break;
}
case 2: {// resume
LThread t = (LThread) vm.topointer(2);
t.resumeFrom( vm, vm.gettop()-2 );
return false;
}
case 3: { // running
LThread r = LThread.getRunning();
if ( r != null ) {
vm.pushlvalue( r );
} else {
vm.pushnil();
}
break;
}
case 4: { // status
vm.pushstring( ((LThread) vm.topointer(2)).getStatus() );
break;
}
case 5: { // wrap
Closure c = (Closure) vm.topointer(2);
vm.pushlvalue( new CoroutinesLib(7,new LThread(c)) );
break;
}
case 6: { // yield
LThread r = LThread.getRunning();
if ( r == null )
vm.error("main thread can't yield");
else {
return r.yield();
}
}
case 7: { // wrapped resume
LThread t = this.thread;
t.resumeFrom( vm, vm.gettop()-1 );
vm.remove(1);
return false;
}
}
vm.insert(1);
vm.settop(1);
return false;
}
| public boolean luaStackCall( VM vm ) {
switch ( id ) {
case 0: { // load lib
install();
vm.pushnil();
break;
}
case 1: { // create
Closure c = (Closure) vm.topointer(2);
vm.pushlvalue( new LThread(c) );
break;
}
case 2: {// resume
LThread t = (LThread) vm.topointer(2);
t.resumeFrom( vm, vm.gettop()-2 );
return false;
}
case 3: { // running
LThread r = LThread.getRunning();
if ( r != null ) {
vm.pushlvalue( r );
} else {
vm.pushnil();
}
break;
}
case 4: { // status
vm.pushstring( ((LThread) vm.topointer(2)).getStatus() );
break;
}
case 5: { // wrap
Closure c = (Closure) vm.topointer(2);
vm.pushlvalue( new CoroutinesLib(7,new LThread(c)) );
break;
}
case 6: { // yield
LThread r = LThread.getRunning();
if ( r == null )
vm.error("main thread can't yield");
else {
return r.yield();
}
}
case 7: { // wrapped resume
LThread t = this.thread;
t.resumeFrom( vm, vm.gettop()-1 );
if ( vm.toboolean(1) )
vm.remove(1);
else
vm.error( vm.tostring(2), 0 );
return false;
}
}
vm.insert(1);
vm.settop(1);
return false;
}
|
diff --git a/components/dotnet-artifact/src/test/java/org/apache/maven/dotnet/artifact/impl/ArtifactInstallerImplTest.java b/components/dotnet-artifact/src/test/java/org/apache/maven/dotnet/artifact/impl/ArtifactInstallerImplTest.java
index d3183b86..ab0e4fca 100644
--- a/components/dotnet-artifact/src/test/java/org/apache/maven/dotnet/artifact/impl/ArtifactInstallerImplTest.java
+++ b/components/dotnet-artifact/src/test/java/org/apache/maven/dotnet/artifact/impl/ArtifactInstallerImplTest.java
@@ -1,70 +1,72 @@
/*
* 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.maven.dotnet.artifact.impl;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
public class ArtifactInstallerImplTest
extends TestCase
{
public void testInstallArtifactAndDependenciesIntoPrivateApplicationBase()
{
+ /*
File testRepo = new File( System.getProperty( "basedir" ), "target/test-repo/repository" );
ArtifactInstallerImpl artifactInstaller = new ArtifactInstallerImpl();
artifactInstaller.init( null, new ArrayList<ArtifactRepository>(), testRepo );
ArtifactFactory stub = new ArtifactFactoryTestStub();
artifactInstaller.initTest( stub, new DummyLogger() );
Artifact artifact = stub.createArtifact( "NPanday.Model", "NPanday.Model.Pom", "1.0", "compile", "library" );
artifact.setFile( new File( System.getProperty( "basedir" ),
"target/test-repo/uac/gac_msil/NPanday.Model.Pom/1.0__NPanday.Model/NPanday.Model.Pom.dll" ) );
Dependency dependency = new Dependency();
dependency.setGroupId( "NPanday" );
dependency.setArtifactId( "NPanday.Test" );
dependency.setVersion( "1.0" );
dependency.setType( "library" );
List<Dependency> dependencies = new ArrayList<Dependency>();
dependencies.add( dependency );
try
{
artifactInstaller.installArtifactAndDependenciesIntoPrivateApplicationBase( testRepo, artifact,
dependencies );
}
catch ( java.io.IOException e )
{
fail(e.getMessage());
}
assertTrue( "Could not find main artifact", new File(
"target/test-repo/pab/gac_msil/NPanday.Model.Pom/1.0__NPanday.Model/NPanday.Model.Pom.dll" ).exists() );
assertTrue( "Could not find dependent artifact", new File(
"target/test-repo/pab/gac_msil/NPanday.Model.Pom/1.0__NPanday.Model/NPanday.Test.dll" ).exists() );
+ */
}
}
| false | true | public void testInstallArtifactAndDependenciesIntoPrivateApplicationBase()
{
File testRepo = new File( System.getProperty( "basedir" ), "target/test-repo/repository" );
ArtifactInstallerImpl artifactInstaller = new ArtifactInstallerImpl();
artifactInstaller.init( null, new ArrayList<ArtifactRepository>(), testRepo );
ArtifactFactory stub = new ArtifactFactoryTestStub();
artifactInstaller.initTest( stub, new DummyLogger() );
Artifact artifact = stub.createArtifact( "NPanday.Model", "NPanday.Model.Pom", "1.0", "compile", "library" );
artifact.setFile( new File( System.getProperty( "basedir" ),
"target/test-repo/uac/gac_msil/NPanday.Model.Pom/1.0__NPanday.Model/NPanday.Model.Pom.dll" ) );
Dependency dependency = new Dependency();
dependency.setGroupId( "NPanday" );
dependency.setArtifactId( "NPanday.Test" );
dependency.setVersion( "1.0" );
dependency.setType( "library" );
List<Dependency> dependencies = new ArrayList<Dependency>();
dependencies.add( dependency );
try
{
artifactInstaller.installArtifactAndDependenciesIntoPrivateApplicationBase( testRepo, artifact,
dependencies );
}
catch ( java.io.IOException e )
{
fail(e.getMessage());
}
assertTrue( "Could not find main artifact", new File(
"target/test-repo/pab/gac_msil/NPanday.Model.Pom/1.0__NPanday.Model/NPanday.Model.Pom.dll" ).exists() );
assertTrue( "Could not find dependent artifact", new File(
"target/test-repo/pab/gac_msil/NPanday.Model.Pom/1.0__NPanday.Model/NPanday.Test.dll" ).exists() );
}
| public void testInstallArtifactAndDependenciesIntoPrivateApplicationBase()
{
/*
File testRepo = new File( System.getProperty( "basedir" ), "target/test-repo/repository" );
ArtifactInstallerImpl artifactInstaller = new ArtifactInstallerImpl();
artifactInstaller.init( null, new ArrayList<ArtifactRepository>(), testRepo );
ArtifactFactory stub = new ArtifactFactoryTestStub();
artifactInstaller.initTest( stub, new DummyLogger() );
Artifact artifact = stub.createArtifact( "NPanday.Model", "NPanday.Model.Pom", "1.0", "compile", "library" );
artifact.setFile( new File( System.getProperty( "basedir" ),
"target/test-repo/uac/gac_msil/NPanday.Model.Pom/1.0__NPanday.Model/NPanday.Model.Pom.dll" ) );
Dependency dependency = new Dependency();
dependency.setGroupId( "NPanday" );
dependency.setArtifactId( "NPanday.Test" );
dependency.setVersion( "1.0" );
dependency.setType( "library" );
List<Dependency> dependencies = new ArrayList<Dependency>();
dependencies.add( dependency );
try
{
artifactInstaller.installArtifactAndDependenciesIntoPrivateApplicationBase( testRepo, artifact,
dependencies );
}
catch ( java.io.IOException e )
{
fail(e.getMessage());
}
assertTrue( "Could not find main artifact", new File(
"target/test-repo/pab/gac_msil/NPanday.Model.Pom/1.0__NPanday.Model/NPanday.Model.Pom.dll" ).exists() );
assertTrue( "Could not find dependent artifact", new File(
"target/test-repo/pab/gac_msil/NPanday.Model.Pom/1.0__NPanday.Model/NPanday.Test.dll" ).exists() );
*/
}
|
diff --git a/src/test/cli/cloudify/cloud/hp/HpCloudService.java b/src/test/cli/cloudify/cloud/hp/HpCloudService.java
index 4743d8f8..167486ad 100644
--- a/src/test/cli/cloudify/cloud/hp/HpCloudService.java
+++ b/src/test/cli/cloudify/cloud/hp/HpCloudService.java
@@ -1,99 +1,100 @@
package test.cli.cloudify.cloud.hp;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import test.cli.cloudify.cloud.AbstractCloudService;
import framework.tools.SGTestHelper;
import framework.utils.AssertUtils;
import framework.utils.IOUtils;
import framework.utils.ScriptUtils;
public class HpCloudService extends AbstractCloudService {
private String tenant = "24912589714038";
private String cloudName = "openstack";
private String user = "98173213380893";
private String apiKey = "C5nobOW90bhnCmE5AQaLaJ0Ubd8UISPxGih";
private String pemFileName = "sgtest-hp";
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
public String getCloudName() {
return cloudName;
}
public void setCloudName(String cloudName) {
this.cloudName = cloudName;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getPemFileName() {
return pemFileName;
}
public void setPemFileName(String pemFileName) {
this.pemFileName = pemFileName;
}
@Override
public void injectAuthenticationDetails() throws IOException {
String cloudTestPath = (SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/" + cloudName).replace('\\', '/');
String sshKeyPemName = pemFileName + ".pem";
// cloud plugin should include recipe that includes secret key
File cloudPluginDir = new File(ScriptUtils.getBuildPath() , "tools/cli/plugins/esc/" + cloudName + "/");
File originalCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.groovy");
File backupCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.backup");
// first make a backup of the original file
FileUtils.copyFile(originalCloudDslFile, backupCloudDslFile);
Map<String, String> propsToReplace = new HashMap<String,String>();
propsToReplace.put("ENTER_USER", user);
propsToReplace.put("ENTER_API_KEY", apiKey);
propsToReplace.put("cloudify_agent_", this.machinePrefix + "cloudify_agent");
propsToReplace.put("cloudify_manager", this.machinePrefix + "cloudify_manager");
propsToReplace.put("ENTER_KEY_FILE", pemFileName + ".pem");
propsToReplace.put("ENTER_TENANT", tenant);
propsToReplace.put("hp-cloud-demo", "sgtest");
propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + numberOfManagementMachines);
+ propsToReplace.put("\"openstack.wireLog\": \"false\"", "\"openstack.wireLog\": \"true\"");
IOUtils.replaceTextInFile(originalCloudDslFile.getAbsolutePath(), propsToReplace);
// upload dir needs to contain the sshKeyPem
File targetPem = new File(ScriptUtils.getBuildPath(), "tools/cli/plugins/esc/" + cloudName + "/upload/" + sshKeyPemName);
FileUtils.copyFile(new File(cloudTestPath, sshKeyPemName), targetPem);
AssertUtils.assertTrue("File not found", targetPem.isFile());
}
}
| true | true | public void injectAuthenticationDetails() throws IOException {
String cloudTestPath = (SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/" + cloudName).replace('\\', '/');
String sshKeyPemName = pemFileName + ".pem";
// cloud plugin should include recipe that includes secret key
File cloudPluginDir = new File(ScriptUtils.getBuildPath() , "tools/cli/plugins/esc/" + cloudName + "/");
File originalCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.groovy");
File backupCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.backup");
// first make a backup of the original file
FileUtils.copyFile(originalCloudDslFile, backupCloudDslFile);
Map<String, String> propsToReplace = new HashMap<String,String>();
propsToReplace.put("ENTER_USER", user);
propsToReplace.put("ENTER_API_KEY", apiKey);
propsToReplace.put("cloudify_agent_", this.machinePrefix + "cloudify_agent");
propsToReplace.put("cloudify_manager", this.machinePrefix + "cloudify_manager");
propsToReplace.put("ENTER_KEY_FILE", pemFileName + ".pem");
propsToReplace.put("ENTER_TENANT", tenant);
propsToReplace.put("hp-cloud-demo", "sgtest");
propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + numberOfManagementMachines);
IOUtils.replaceTextInFile(originalCloudDslFile.getAbsolutePath(), propsToReplace);
// upload dir needs to contain the sshKeyPem
File targetPem = new File(ScriptUtils.getBuildPath(), "tools/cli/plugins/esc/" + cloudName + "/upload/" + sshKeyPemName);
FileUtils.copyFile(new File(cloudTestPath, sshKeyPemName), targetPem);
AssertUtils.assertTrue("File not found", targetPem.isFile());
}
| public void injectAuthenticationDetails() throws IOException {
String cloudTestPath = (SGTestHelper.getSGTestRootDir() + "/apps/cloudify/cloud/" + cloudName).replace('\\', '/');
String sshKeyPemName = pemFileName + ".pem";
// cloud plugin should include recipe that includes secret key
File cloudPluginDir = new File(ScriptUtils.getBuildPath() , "tools/cli/plugins/esc/" + cloudName + "/");
File originalCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.groovy");
File backupCloudDslFile = new File(cloudPluginDir, cloudName + "-cloud.backup");
// first make a backup of the original file
FileUtils.copyFile(originalCloudDslFile, backupCloudDslFile);
Map<String, String> propsToReplace = new HashMap<String,String>();
propsToReplace.put("ENTER_USER", user);
propsToReplace.put("ENTER_API_KEY", apiKey);
propsToReplace.put("cloudify_agent_", this.machinePrefix + "cloudify_agent");
propsToReplace.put("cloudify_manager", this.machinePrefix + "cloudify_manager");
propsToReplace.put("ENTER_KEY_FILE", pemFileName + ".pem");
propsToReplace.put("ENTER_TENANT", tenant);
propsToReplace.put("hp-cloud-demo", "sgtest");
propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + numberOfManagementMachines);
propsToReplace.put("\"openstack.wireLog\": \"false\"", "\"openstack.wireLog\": \"true\"");
IOUtils.replaceTextInFile(originalCloudDslFile.getAbsolutePath(), propsToReplace);
// upload dir needs to contain the sshKeyPem
File targetPem = new File(ScriptUtils.getBuildPath(), "tools/cli/plugins/esc/" + cloudName + "/upload/" + sshKeyPemName);
FileUtils.copyFile(new File(cloudTestPath, sshKeyPemName), targetPem);
AssertUtils.assertTrue("File not found", targetPem.isFile());
}
|
diff --git a/src/biz/bokhorst/xprivacy/XWifiManager.java b/src/biz/bokhorst/xprivacy/XWifiManager.java
index d16b1873..53b15bea 100644
--- a/src/biz/bokhorst/xprivacy/XWifiManager.java
+++ b/src/biz/bokhorst/xprivacy/XWifiManager.java
@@ -1,110 +1,112 @@
package biz.bokhorst.xprivacy;
import java.lang.reflect.Field;
import java.util.ArrayList;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import de.robv.android.xposed.XC_MethodHook.MethodHookParam;
import static de.robv.android.xposed.XposedHelpers.findField;
public class XWifiManager extends XHook {
public XWifiManager(String methodName, String restrictionName, String[] permissions) {
super(methodName, restrictionName, permissions, null);
}
// public List<WifiConfiguration> getConfiguredNetworks()
// public WifiInfo getConnectionInfo()
// public DhcpInfo getDhcpInfo()
// public List<ScanResult> getScanResults()
// public WifiConfiguration getWifiApConfiguration()
// frameworks/base/wifi/java/android/net/wifi/WifiManager.java
@Override
protected void before(MethodHookParam param) throws Throwable {
if (param.method.getName().equals("getConfiguredNetworks")) {
if (isRestricted(param))
param.setResult(new ArrayList<WifiConfiguration>());
} else if (param.method.getName().equals("getScanResults")) {
if (isRestricted(param))
param.setResult(new ArrayList<ScanResult>());
} else if (param.method.getName().equals("getWifiApConfiguration")) {
if (isRestricted(param))
param.setResult(null);
}
}
@Override
protected void after(MethodHookParam param) throws Throwable {
if (param.method.getName().equals("getConnectionInfo")) {
// frameworks/base/wifi/java/android/net/wifi/WifiInfo.java
WifiInfo wInfo = (WifiInfo) param.getResult();
if (wInfo != null)
if (isRestricted(param))
if (getRestrictionName().equals(PrivacyManager.cInternet)) {
// Supplicant state
try {
Field fieldState = findField(WifiInfo.class, "mSupplicantState");
fieldState.set(wInfo, SupplicantState.DISCONNECTED);
} catch (Throwable ex) {
Util.bug(this, ex);
}
} else {
// BSSID
try {
Field fieldBSSID = findField(WifiInfo.class, "mBSSID");
fieldBSSID.set(wInfo, PrivacyManager.getDefacedProp("MAC"));
} catch (Throwable ex) {
Util.bug(this, ex);
}
// IP address
try {
Field fieldIp = findField(WifiInfo.class, "mIpAddress");
fieldIp.set(wInfo, PrivacyManager.getDefacedProp("InetAddress"));
} catch (Throwable ex) {
Util.bug(this, ex);
}
// MAC address
try {
Field fieldMAC = findField(WifiInfo.class, "mMacAddress");
fieldMAC.set(wInfo, PrivacyManager.getDefacedProp("MAC"));
} catch (Throwable ex) {
Util.bug(this, ex);
}
// SSID
try {
Field fieldSSID = findField(WifiInfo.class, "mSSID");
fieldSSID.set(wInfo, PrivacyManager.getDefacedProp("SSID"));
} catch (Throwable ex) {
try {
Field fieldWifiSsid = findField(WifiInfo.class, "mWifiSsid");
Object mWifiSsid = fieldWifiSsid.get(wInfo);
- Field octets = findField(mWifiSsid.getClass(), "octets");
- octets.set(mWifiSsid, PrivacyManager.getDefacedProp("WifiSsid.octets"));
+ if (mWifiSsid != null) {
+ Field octets = findField(mWifiSsid.getClass(), "octets");
+ octets.set(mWifiSsid, PrivacyManager.getDefacedProp("WifiSsid.octets"));
+ }
} catch (Throwable exex) {
Util.bug(this, exex);
}
}
}
} else if (param.method.getName().equals("getDhcpInfo")) {
// frameworks/base/core/java/android/net/DhcpInfo.java
DhcpInfo dInfo = (DhcpInfo) param.getResult();
if (dInfo != null)
if (isRestricted(param)) {
dInfo.ipAddress = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.gateway = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.dns1 = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.dns2 = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.serverAddress = (Integer) PrivacyManager.getDefacedProp("IPInt");
}
}
}
}
| true | true | protected void after(MethodHookParam param) throws Throwable {
if (param.method.getName().equals("getConnectionInfo")) {
// frameworks/base/wifi/java/android/net/wifi/WifiInfo.java
WifiInfo wInfo = (WifiInfo) param.getResult();
if (wInfo != null)
if (isRestricted(param))
if (getRestrictionName().equals(PrivacyManager.cInternet)) {
// Supplicant state
try {
Field fieldState = findField(WifiInfo.class, "mSupplicantState");
fieldState.set(wInfo, SupplicantState.DISCONNECTED);
} catch (Throwable ex) {
Util.bug(this, ex);
}
} else {
// BSSID
try {
Field fieldBSSID = findField(WifiInfo.class, "mBSSID");
fieldBSSID.set(wInfo, PrivacyManager.getDefacedProp("MAC"));
} catch (Throwable ex) {
Util.bug(this, ex);
}
// IP address
try {
Field fieldIp = findField(WifiInfo.class, "mIpAddress");
fieldIp.set(wInfo, PrivacyManager.getDefacedProp("InetAddress"));
} catch (Throwable ex) {
Util.bug(this, ex);
}
// MAC address
try {
Field fieldMAC = findField(WifiInfo.class, "mMacAddress");
fieldMAC.set(wInfo, PrivacyManager.getDefacedProp("MAC"));
} catch (Throwable ex) {
Util.bug(this, ex);
}
// SSID
try {
Field fieldSSID = findField(WifiInfo.class, "mSSID");
fieldSSID.set(wInfo, PrivacyManager.getDefacedProp("SSID"));
} catch (Throwable ex) {
try {
Field fieldWifiSsid = findField(WifiInfo.class, "mWifiSsid");
Object mWifiSsid = fieldWifiSsid.get(wInfo);
Field octets = findField(mWifiSsid.getClass(), "octets");
octets.set(mWifiSsid, PrivacyManager.getDefacedProp("WifiSsid.octets"));
} catch (Throwable exex) {
Util.bug(this, exex);
}
}
}
} else if (param.method.getName().equals("getDhcpInfo")) {
// frameworks/base/core/java/android/net/DhcpInfo.java
DhcpInfo dInfo = (DhcpInfo) param.getResult();
if (dInfo != null)
if (isRestricted(param)) {
dInfo.ipAddress = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.gateway = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.dns1 = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.dns2 = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.serverAddress = (Integer) PrivacyManager.getDefacedProp("IPInt");
}
}
}
| protected void after(MethodHookParam param) throws Throwable {
if (param.method.getName().equals("getConnectionInfo")) {
// frameworks/base/wifi/java/android/net/wifi/WifiInfo.java
WifiInfo wInfo = (WifiInfo) param.getResult();
if (wInfo != null)
if (isRestricted(param))
if (getRestrictionName().equals(PrivacyManager.cInternet)) {
// Supplicant state
try {
Field fieldState = findField(WifiInfo.class, "mSupplicantState");
fieldState.set(wInfo, SupplicantState.DISCONNECTED);
} catch (Throwable ex) {
Util.bug(this, ex);
}
} else {
// BSSID
try {
Field fieldBSSID = findField(WifiInfo.class, "mBSSID");
fieldBSSID.set(wInfo, PrivacyManager.getDefacedProp("MAC"));
} catch (Throwable ex) {
Util.bug(this, ex);
}
// IP address
try {
Field fieldIp = findField(WifiInfo.class, "mIpAddress");
fieldIp.set(wInfo, PrivacyManager.getDefacedProp("InetAddress"));
} catch (Throwable ex) {
Util.bug(this, ex);
}
// MAC address
try {
Field fieldMAC = findField(WifiInfo.class, "mMacAddress");
fieldMAC.set(wInfo, PrivacyManager.getDefacedProp("MAC"));
} catch (Throwable ex) {
Util.bug(this, ex);
}
// SSID
try {
Field fieldSSID = findField(WifiInfo.class, "mSSID");
fieldSSID.set(wInfo, PrivacyManager.getDefacedProp("SSID"));
} catch (Throwable ex) {
try {
Field fieldWifiSsid = findField(WifiInfo.class, "mWifiSsid");
Object mWifiSsid = fieldWifiSsid.get(wInfo);
if (mWifiSsid != null) {
Field octets = findField(mWifiSsid.getClass(), "octets");
octets.set(mWifiSsid, PrivacyManager.getDefacedProp("WifiSsid.octets"));
}
} catch (Throwable exex) {
Util.bug(this, exex);
}
}
}
} else if (param.method.getName().equals("getDhcpInfo")) {
// frameworks/base/core/java/android/net/DhcpInfo.java
DhcpInfo dInfo = (DhcpInfo) param.getResult();
if (dInfo != null)
if (isRestricted(param)) {
dInfo.ipAddress = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.gateway = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.dns1 = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.dns2 = (Integer) PrivacyManager.getDefacedProp("IPInt");
dInfo.serverAddress = (Integer) PrivacyManager.getDefacedProp("IPInt");
}
}
}
|
diff --git a/src/btwmods/io/Settings.java b/src/btwmods/io/Settings.java
index 0d64075..0b39271 100644
--- a/src/btwmods/io/Settings.java
+++ b/src/btwmods/io/Settings.java
@@ -1,91 +1,91 @@
package btwmods.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class Settings {
public static Settings readSettings(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
Map settings = new LinkedHashMap<String, String>();
String section = "";
String line;
int equalsIndex;
while ((line = reader.readLine()) != null) {
// Trim leading whitespace.
line = line.replaceAll("^[ \t]+", "");
if (!line.startsWith("#")) {
if (line.startsWith("[") && line.trim().endsWith("]")) {
section = line.trim();
}
else if ((equalsIndex = line.indexOf('=')) >= 0) {
- settings.put(line.substring(0, equalsIndex).toLowerCase(), line.substring(equalsIndex + 1));
+ settings.put(section + line.substring(0, equalsIndex).toLowerCase(), line.substring(equalsIndex + 1));
}
}
}
reader.close();
return new Settings(settings);
}
public final Map<String, String> settings;
public Settings() {
this(new HashMap<String, String>());
}
public Settings(Map<String, String> settings) {
this.settings = Collections.unmodifiableMap(settings);
}
public boolean isBoolean(String key) {
if (settings.containsKey(key)) {
String setting = settings.get(key).trim().toLowerCase();
return setting.equalsIgnoreCase("yes") || setting.equalsIgnoreCase("true")|| setting.equalsIgnoreCase("1") || setting.equalsIgnoreCase("on")
|| setting.equalsIgnoreCase("no") || setting.equalsIgnoreCase("false") || setting.equalsIgnoreCase("0") || setting.equalsIgnoreCase("off");
}
return false;
}
public boolean getBoolean(String key) {
if (!isBoolean(key)) throw new IllegalArgumentException("setting is not a valid boolean. check with isBoolean() first");
String setting = settings.get(key).trim().toLowerCase();
return setting.equalsIgnoreCase("yes") || setting.equalsIgnoreCase("true") || setting.equalsIgnoreCase("1") || setting.equalsIgnoreCase("on");
}
public boolean isInt(String key) {
try { return settings.containsKey(key) && Integer.valueOf(settings.get(key)) != null; }
catch (NumberFormatException e) { return false; }
}
public int getInt(String key) {
if (!isInt(key)) throw new IllegalArgumentException("setting is not a valid Integer. check with isInt() first");
return Integer.parseInt(settings.get(key));
}
public boolean isLong(String key) {
try { return settings.containsKey(key) && Long.valueOf(settings.get(key)) != null; }
catch (NumberFormatException e) { return false; }
}
public long getLong(String key) {
if (!isLong(key)) throw new IllegalArgumentException("setting is not a valid Long. check with isLong() first");
return Long.parseLong(settings.get(key));
}
public boolean hasKey(String key) {
return settings.containsKey(key);
}
public String get(String key) {
return settings.get(key);
}
}
| true | true | public static Settings readSettings(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
Map settings = new LinkedHashMap<String, String>();
String section = "";
String line;
int equalsIndex;
while ((line = reader.readLine()) != null) {
// Trim leading whitespace.
line = line.replaceAll("^[ \t]+", "");
if (!line.startsWith("#")) {
if (line.startsWith("[") && line.trim().endsWith("]")) {
section = line.trim();
}
else if ((equalsIndex = line.indexOf('=')) >= 0) {
settings.put(line.substring(0, equalsIndex).toLowerCase(), line.substring(equalsIndex + 1));
}
}
}
reader.close();
return new Settings(settings);
}
| public static Settings readSettings(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
Map settings = new LinkedHashMap<String, String>();
String section = "";
String line;
int equalsIndex;
while ((line = reader.readLine()) != null) {
// Trim leading whitespace.
line = line.replaceAll("^[ \t]+", "");
if (!line.startsWith("#")) {
if (line.startsWith("[") && line.trim().endsWith("]")) {
section = line.trim();
}
else if ((equalsIndex = line.indexOf('=')) >= 0) {
settings.put(section + line.substring(0, equalsIndex).toLowerCase(), line.substring(equalsIndex + 1));
}
}
}
reader.close();
return new Settings(settings);
}
|
diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java
index a6b9ada80..2ad46dfb2 100644
--- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java
+++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java
@@ -1,447 +1,450 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.provisional.p2.ui.operations;
import java.io.IOException;
import java.net.URI;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.internal.p2.ui.*;
import org.eclipse.equinox.internal.p2.ui.model.IIUElement;
import org.eclipse.equinox.internal.provisional.configurator.Configurator;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus;
import org.eclipse.equinox.internal.provisional.p2.director.*;
import org.eclipse.equinox.internal.provisional.p2.engine.*;
import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.repository.IRepository;
import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent;
import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner;
import org.eclipse.osgi.util.NLS;
/**
* Utility methods for clients using the provisioning UI
*
* @since 3.4
*/
public class ProvisioningUtil {
public static void addMetadataRepository(URI location, boolean notify) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
manager.addRepository(location);
if (notify) {
IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus();
if (bus != null) {
bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_METADATA, RepositoryEvent.ADDED));
}
}
}
public static String getMetadataRepositoryProperty(URI location, String key) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
return manager.getRepositoryProperty(location, key);
}
public static void setMetadataRepositoryProperty(URI location, String key, String value) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
manager.setRepositoryProperty(location, key, value);
}
public static boolean getMetadataRepositoryEnablement(URI location) {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
return false;
return manager.isEnabled(location);
}
public static boolean getArtifactRepositoryEnablement(URI location) {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null)
return false;
return manager.isEnabled(location);
}
public static IMetadataRepository loadMetadataRepository(URI location, IProgressMonitor monitor) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
IMetadataRepository repo = manager.loadRepository(location, monitor);
// If there is no user nickname assigned to this repo but there is a provider name, then set the nickname.
// This will keep the name in the manager even when the repo is not loaded
String name = getMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME);
if (name == null) {
name = getMetadataRepositoryProperty(location, IRepository.PROP_NAME);
if (name != null)
setMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
}
return repo;
}
public static IStatus validateMetadataRepositoryLocation(URI location, IProgressMonitor monitor) {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
return manager.validateRepositoryLocation(location, monitor);
}
public static void removeMetadataRepository(URI location) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
manager.removeRepository(location);
IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus();
if (bus != null) {
bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_METADATA, RepositoryEvent.REMOVED));
}
}
public static void addArtifactRepository(URI location, boolean notify) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
manager.addRepository(location);
if (notify) {
IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus();
if (bus != null) {
bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_ARTIFACT, RepositoryEvent.ADDED));
}
}
}
public static String getArtifactRepositoryProperty(URI location, String key) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
return manager.getRepositoryProperty(location, key);
}
public static void setArtifactRepositoryProperty(URI location, String key, String value) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
manager.setRepositoryProperty(location, key, value);
}
public static IArtifactRepository loadArtifactRepository(URI location, IProgressMonitor monitor) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
IArtifactRepository repo = manager.loadRepository(location, monitor);
if (repo == null) {
throw new ProvisionException(NLS.bind(ProvUIMessages.ProvisioningUtil_LoadRepositoryFailure, location));
}
// If there is no user nickname assigned to this repo but there is a provider name, then set the nickname.
// This will keep the name in the manager even when the repo is not loaded
String name = getArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME);
if (name == null) {
name = getArtifactRepositoryProperty(location, IRepository.PROP_NAME);
if (name != null)
setArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
}
return repo;
}
public static void removeArtifactRepository(URI location) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
manager.removeRepository(location);
IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus();
if (bus != null) {
bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_ARTIFACT, RepositoryEvent.REMOVED));
}
}
public static IProfile addProfile(String profileId, Map properties, IProgressMonitor monitor) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.addProfile(profileId, properties);
}
public static void removeProfile(String profileId, IProgressMonitor monitor) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
profileRegistry.removeProfile(profileId);
}
public static IProfile[] getProfiles() throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.getProfiles();
}
public static long[] getProfileTimestamps(String id) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.listProfileTimestamps(id);
}
public static IProfile getProfile(String id) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.getProfile(id);
}
public static IProfile getProfile(String id, long timestamp) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.getProfile(id, timestamp);
}
public static URI[] getMetadataRepositories(int flags) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
return manager.getKnownRepositories(flags);
}
public static void refreshMetadataRepositories(URI[] urls, IProgressMonitor monitor) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
SubMonitor mon = SubMonitor.convert(monitor, urls.length * 100);
for (int i = 0; i < urls.length; i++) {
try {
manager.refreshRepository(urls[i], mon.newChild(100));
} catch (ProvisionException e) {
//ignore problematic repositories when refreshing
}
}
}
public static URI[] getArtifactRepositories(int flags) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
return manager.getKnownRepositories(flags);
}
public static void refreshArtifactRepositories(URI[] urls, IProgressMonitor monitor) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
SubMonitor mon = SubMonitor.convert(monitor, urls.length * 100);
for (int i = 0; i < urls.length; i++) {
manager.refreshRepository(urls[i], mon.newChild(100));
}
}
/*
* Get the plan for the specified install operation
*/
public static ProvisioningPlan getProvisioningPlan(ProfileChangeRequest request, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
try {
return getPlanner().getProvisioningPlan(request, context, monitor);
} catch (OperationCanceledException e) {
return null;
}
}
/*
* Get a plan for reverting to a specified profile snapshot
*/
public static ProvisioningPlan getRevertPlan(IProfile currentProfile, IProfile snapshot, IProgressMonitor monitor) throws ProvisionException {
Assert.isNotNull(currentProfile);
Assert.isNotNull(snapshot);
return getPlanner().getDiffPlan(currentProfile, snapshot, monitor);
}
/*
* Get sizing info for the specified plan
*/
public static long getSize(ProvisioningPlan plan, String profileId, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
// If there is nothing to size, return 0
if (plan == null)
return IIUElement.SIZE_NOTAPPLICABLE;
if (plan.getOperands().length == 0)
return 0;
long installPlanSize = 0;
SubMonitor mon = SubMonitor.convert(monitor, 300);
if (plan.getInstallerPlan() != null) {
SizingPhaseSet set = new SizingPhaseSet();
IStatus status = getEngine().perform(getProfile(profileId), set, plan.getInstallerPlan().getOperands(), context, mon.newChild(100));
if (status.isOK())
installPlanSize = set.getSizing().getDiskSize();
} else {
mon.worked(100);
}
SizingPhaseSet set = new SizingPhaseSet();
IStatus status = getEngine().perform(getProfile(profileId), set, plan.getOperands(), context, mon.newChild(200));
if (status.isOK())
return installPlanSize + set.getSizing().getDiskSize();
return IIUElement.SIZE_UNAVAILABLE;
}
/**
* Perform the specified provisioning plan.
*
* @param plan the plan to perform
* @param phaseSet the phase set to use
* @param profile the profile to be changed. This parameter is now ignored.
* @param context the provisioning context to be used
* @param monitor the progress monitor
* @return a status indicating the success of the plan
* @throws ProvisionException
*
* @deprecated clients should use {@linkplain #performProvisioningPlan(ProvisioningPlan, PhaseSet, ProvisioningContext, IProgressMonitor)}
* because the profile argument is now ignored.
*/
public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, IProfile profile, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
// ignore the profile, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=272355
return performProvisioningPlan(plan, phaseSet, context, monitor);
}
public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
PhaseSet set;
if (phaseSet == null)
set = new DefaultPhaseSet();
else
set = phaseSet;
// 300 ticks for download, 100 to install handlers, 100 to install the rest
SubMonitor mon = SubMonitor.convert(monitor, 500);
int ticksUsed = 0;
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=272355
// The exact profile instance used in the profile change request and passed to the engine must be used for all
// of these operations, otherwise we can get profile out of synch errors.
IProfile profile = plan.getProfileChangeRequest().getProfile();
if (plan.getInstallerPlan() != null) {
if (set instanceof DefaultPhaseSet) {
// If the phase set calls for download and install, then we want to download everything atomically before
// applying the install plan. This way, we can be sure to install the install handler only if we know
// we will be able to get everything else.
List allOperands = new ArrayList();
allOperands.addAll(Arrays.asList(plan.getOperands()));
allOperands.addAll(Arrays.asList(plan.getInstallerPlan().getOperands()));
PhaseSet download = new DownloadPhaseSet();
IStatus downloadStatus = getEngine().perform(profile, download, (Operand[]) allOperands.toArray(new Operand[allOperands.size()]), context, mon.newChild(300));
if (!downloadStatus.isOK()) {
mon.done();
return downloadStatus;
}
ticksUsed = 300;
}
// we pre-downloaded if necessary. Now perform the plan against the original phase set.
IStatus installerPlanStatus = getEngine().perform(profile, set, plan.getInstallerPlan().getOperands(), context, mon.newChild(100));
if (!installerPlanStatus.isOK()) {
mon.done();
return installerPlanStatus;
}
ticksUsed += 100;
// Apply the configuration
Configurator configChanger = (Configurator) ServiceHelper.getService(ProvUIActivator.getContext(), Configurator.class.getName());
try {
+ // TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=274876
ProvisioningOperationRunner.suppressRestart(true);
configChanger.applyConfiguration();
+ // We just applied the configuration so restart is no longer required.
+ ProvisioningOperationRunner.clearRestartRequests();
} catch (IOException e) {
mon.done();
return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_InstallPlanConfigurationError, e);
} finally {
ProvisioningOperationRunner.suppressRestart(false);
}
}
return getEngine().perform(profile, set, plan.getOperands(), context, mon.newChild(500 - ticksUsed));
}
private static IEngine getEngine() throws ProvisionException {
IEngine engine = (IEngine) ServiceHelper.getService(ProvUIActivator.getContext(), IEngine.SERVICE_NAME);
if (engine == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoEngineFound);
}
return engine;
}
public static IPlanner getPlanner() throws ProvisionException {
IPlanner planner = (IPlanner) ServiceHelper.getService(ProvUIActivator.getContext(), IPlanner.class.getName());
if (planner == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoPlannerFound);
}
return planner;
}
public static IDirector getDirector() throws ProvisionException {
IDirector director = (IDirector) ServiceHelper.getService(ProvUIActivator.getContext(), IDirector.class.getName());
if (director == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoDirectorFound);
}
return director;
}
public static void setColocatedRepositoryEnablement(URI location, boolean enabled) {
IMetadataRepositoryManager metaManager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (metaManager != null)
metaManager.setEnabled(location, enabled);
IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (artifactManager != null)
artifactManager.setEnabled(location, enabled);
}
public static boolean isCategory(IInstallableUnit iu) {
String isCategory = iu.getProperty(IInstallableUnit.PROP_TYPE_CATEGORY);
return isCategory != null && Boolean.valueOf(isCategory).booleanValue();
}
/**
* Perform the provisioning plan using a default context that contacts all repositories.
* @param plan the plan to perform
* @param phaseSet the phase set to use
* @param profile the profile to be changed
* @param monitor the progress monitor
* @return a status indicating the success of the plan
* @throws ProvisionException
*
* @deprecated clients should use {@linkplain #performProvisioningPlan(ProvisioningPlan, PhaseSet, IProfile, ProvisioningContext, IProgressMonitor)}
* to explicitly establish a provisioning context. Otherwise all repositories will be contacted
*/
public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, IProfile profile, IProgressMonitor monitor) throws ProvisionException {
PhaseSet set;
if (phaseSet == null)
set = new DefaultPhaseSet();
else
set = phaseSet;
return getEngine().perform(profile, set, plan.getOperands(), new ProvisioningContext(), monitor);
}
}
| false | true | public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
PhaseSet set;
if (phaseSet == null)
set = new DefaultPhaseSet();
else
set = phaseSet;
// 300 ticks for download, 100 to install handlers, 100 to install the rest
SubMonitor mon = SubMonitor.convert(monitor, 500);
int ticksUsed = 0;
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=272355
// The exact profile instance used in the profile change request and passed to the engine must be used for all
// of these operations, otherwise we can get profile out of synch errors.
IProfile profile = plan.getProfileChangeRequest().getProfile();
if (plan.getInstallerPlan() != null) {
if (set instanceof DefaultPhaseSet) {
// If the phase set calls for download and install, then we want to download everything atomically before
// applying the install plan. This way, we can be sure to install the install handler only if we know
// we will be able to get everything else.
List allOperands = new ArrayList();
allOperands.addAll(Arrays.asList(plan.getOperands()));
allOperands.addAll(Arrays.asList(plan.getInstallerPlan().getOperands()));
PhaseSet download = new DownloadPhaseSet();
IStatus downloadStatus = getEngine().perform(profile, download, (Operand[]) allOperands.toArray(new Operand[allOperands.size()]), context, mon.newChild(300));
if (!downloadStatus.isOK()) {
mon.done();
return downloadStatus;
}
ticksUsed = 300;
}
// we pre-downloaded if necessary. Now perform the plan against the original phase set.
IStatus installerPlanStatus = getEngine().perform(profile, set, plan.getInstallerPlan().getOperands(), context, mon.newChild(100));
if (!installerPlanStatus.isOK()) {
mon.done();
return installerPlanStatus;
}
ticksUsed += 100;
// Apply the configuration
Configurator configChanger = (Configurator) ServiceHelper.getService(ProvUIActivator.getContext(), Configurator.class.getName());
try {
ProvisioningOperationRunner.suppressRestart(true);
configChanger.applyConfiguration();
} catch (IOException e) {
mon.done();
return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_InstallPlanConfigurationError, e);
} finally {
ProvisioningOperationRunner.suppressRestart(false);
}
}
return getEngine().perform(profile, set, plan.getOperands(), context, mon.newChild(500 - ticksUsed));
}
| public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
PhaseSet set;
if (phaseSet == null)
set = new DefaultPhaseSet();
else
set = phaseSet;
// 300 ticks for download, 100 to install handlers, 100 to install the rest
SubMonitor mon = SubMonitor.convert(monitor, 500);
int ticksUsed = 0;
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=272355
// The exact profile instance used in the profile change request and passed to the engine must be used for all
// of these operations, otherwise we can get profile out of synch errors.
IProfile profile = plan.getProfileChangeRequest().getProfile();
if (plan.getInstallerPlan() != null) {
if (set instanceof DefaultPhaseSet) {
// If the phase set calls for download and install, then we want to download everything atomically before
// applying the install plan. This way, we can be sure to install the install handler only if we know
// we will be able to get everything else.
List allOperands = new ArrayList();
allOperands.addAll(Arrays.asList(plan.getOperands()));
allOperands.addAll(Arrays.asList(plan.getInstallerPlan().getOperands()));
PhaseSet download = new DownloadPhaseSet();
IStatus downloadStatus = getEngine().perform(profile, download, (Operand[]) allOperands.toArray(new Operand[allOperands.size()]), context, mon.newChild(300));
if (!downloadStatus.isOK()) {
mon.done();
return downloadStatus;
}
ticksUsed = 300;
}
// we pre-downloaded if necessary. Now perform the plan against the original phase set.
IStatus installerPlanStatus = getEngine().perform(profile, set, plan.getInstallerPlan().getOperands(), context, mon.newChild(100));
if (!installerPlanStatus.isOK()) {
mon.done();
return installerPlanStatus;
}
ticksUsed += 100;
// Apply the configuration
Configurator configChanger = (Configurator) ServiceHelper.getService(ProvUIActivator.getContext(), Configurator.class.getName());
try {
// TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=274876
ProvisioningOperationRunner.suppressRestart(true);
configChanger.applyConfiguration();
// We just applied the configuration so restart is no longer required.
ProvisioningOperationRunner.clearRestartRequests();
} catch (IOException e) {
mon.done();
return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_InstallPlanConfigurationError, e);
} finally {
ProvisioningOperationRunner.suppressRestart(false);
}
}
return getEngine().perform(profile, set, plan.getOperands(), context, mon.newChild(500 - ticksUsed));
}
|
diff --git a/sql12/plugins/editextras/src/net/sourceforge/squirrel_sql/plugins/editextras/searchandreplace/SearchAndReplaceKernel.java b/sql12/plugins/editextras/src/net/sourceforge/squirrel_sql/plugins/editextras/searchandreplace/SearchAndReplaceKernel.java
index 5e30bfdd0..6c14b7468 100644
--- a/sql12/plugins/editextras/src/net/sourceforge/squirrel_sql/plugins/editextras/searchandreplace/SearchAndReplaceKernel.java
+++ b/sql12/plugins/editextras/src/net/sourceforge/squirrel_sql/plugins/editextras/searchandreplace/SearchAndReplaceKernel.java
@@ -1,173 +1,177 @@
package net.sourceforge.squirrel_sql.plugins.editextras.searchandreplace;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.squirrel_sql.client.session.ISQLPanelAPI;
public class SearchAndReplaceKernel
{
private ISQLPanelAPI _textArea;
private int _nextFindStart = 0;
private FindConfig _lastFindConfig;
public SearchAndReplaceKernel(ISQLPanelAPI textArea)
{
_textArea = textArea;
}
void reset()
{
_nextFindStart = 0;
}
boolean performFind(FindConfig findConfig)
{
_lastFindConfig = findConfig;
_textArea.setSQLScriptSelectionStart(0);
_textArea.setSQLScriptSelectionEnd(0);
String script = _textArea.getEntireSQLScript();
Pattern pat = Pattern.compile(getRegExp());
Matcher mat = pat.matcher(script);
if(mat.find(_nextFindStart))
{
int selStart = mat.start();
if(Character.isWhitespace(script.charAt(selStart)))
{
++selStart;
}
_textArea.setSQLScriptSelectionStart(selStart);
_textArea.setSQLScriptSelectionEnd(selStart + findConfig.toSearch.length());
_nextFindStart = mat.start() + 1;
return true;
}
else
{
_nextFindStart = 0;
return false;
}
}
private String getRegExp()
{
StringBuffer ret = new StringBuffer();
if(_lastFindConfig.wholeWord)
{
ret.append("(\\s|\\A)");
}
for (int i = 0; i < _lastFindConfig.toSearch.length(); i++)
{
if('.' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\.)");
}
else if('^' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\^)");
}
else if('?' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\?)");
}
else if('$' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\$)");
}
// else if('\\' == _lastFindConfig.toSearch.charAt(i) && i+1 < _lastFindConfig.toSearch.length() && 'n' == _lastFindConfig.toSearch.charAt(i+1))
// {
// ret.append("(\\n)");
// ++i;
// }
else if('(' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\()");
}
+ else if('*' == _lastFindConfig.toSearch.charAt(i))
+ {
+ ret.append("(\\*)");
+ }
else if(')' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\))");
}
else if('\\' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\\\)");
}
else if(!_lastFindConfig.matchCase)
{
char lc = Character.toLowerCase(_lastFindConfig.toSearch.charAt(i));
char uc = Character.toUpperCase(_lastFindConfig.toSearch.charAt(i));
ret.append('(').append(lc).append('|').append(uc).append(')');
}
else
{
ret.append(_lastFindConfig.toSearch.charAt(i));
}
}
if(_lastFindConfig.wholeWord)
{
ret.append("(\\s|\\z)");
}
return ret.toString();
}
void repeatLastFind()
{
if(null != _lastFindConfig)
{
performFind(_lastFindConfig);
}
}
void beginFromStart()
{
_nextFindStart = 0;
}
void findSelected()
{
beginFromStart();
String toSearch = _textArea.getSelectedSQLScript();
if(null == toSearch || "".equals(toSearch))
{
return;
}
FindConfig fc = new FindConfig(toSearch, false, false);
performFind(fc);
}
String getSelectedText()
{
return _textArea.getSelectedSQLScript();
}
void replaceSelectionBy(String toReplaceBy)
{
_nextFindStart = _textArea.getSQLScriptSelectionStart() + toReplaceBy.length();
_textArea.replaceSelectedSQLScript(toReplaceBy, true);
if(_nextFindStart >= _textArea.getEntireSQLScript().length())
{
_nextFindStart = 0;
}
}
int getNextFindStart()
{
return _nextFindStart;
}
FindConfig getLastFindConfig()
{
return _lastFindConfig;
}
}
| true | true | private String getRegExp()
{
StringBuffer ret = new StringBuffer();
if(_lastFindConfig.wholeWord)
{
ret.append("(\\s|\\A)");
}
for (int i = 0; i < _lastFindConfig.toSearch.length(); i++)
{
if('.' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\.)");
}
else if('^' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\^)");
}
else if('?' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\?)");
}
else if('$' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\$)");
}
// else if('\\' == _lastFindConfig.toSearch.charAt(i) && i+1 < _lastFindConfig.toSearch.length() && 'n' == _lastFindConfig.toSearch.charAt(i+1))
// {
// ret.append("(\\n)");
// ++i;
// }
else if('(' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\()");
}
else if(')' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\))");
}
else if('\\' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\\\)");
}
else if(!_lastFindConfig.matchCase)
{
char lc = Character.toLowerCase(_lastFindConfig.toSearch.charAt(i));
char uc = Character.toUpperCase(_lastFindConfig.toSearch.charAt(i));
ret.append('(').append(lc).append('|').append(uc).append(')');
}
else
{
ret.append(_lastFindConfig.toSearch.charAt(i));
}
}
if(_lastFindConfig.wholeWord)
{
ret.append("(\\s|\\z)");
}
return ret.toString();
}
| private String getRegExp()
{
StringBuffer ret = new StringBuffer();
if(_lastFindConfig.wholeWord)
{
ret.append("(\\s|\\A)");
}
for (int i = 0; i < _lastFindConfig.toSearch.length(); i++)
{
if('.' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\.)");
}
else if('^' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\^)");
}
else if('?' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\?)");
}
else if('$' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\$)");
}
// else if('\\' == _lastFindConfig.toSearch.charAt(i) && i+1 < _lastFindConfig.toSearch.length() && 'n' == _lastFindConfig.toSearch.charAt(i+1))
// {
// ret.append("(\\n)");
// ++i;
// }
else if('(' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\()");
}
else if('*' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\*)");
}
else if(')' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\))");
}
else if('\\' == _lastFindConfig.toSearch.charAt(i))
{
ret.append("(\\\\)");
}
else if(!_lastFindConfig.matchCase)
{
char lc = Character.toLowerCase(_lastFindConfig.toSearch.charAt(i));
char uc = Character.toUpperCase(_lastFindConfig.toSearch.charAt(i));
ret.append('(').append(lc).append('|').append(uc).append(')');
}
else
{
ret.append(_lastFindConfig.toSearch.charAt(i));
}
}
if(_lastFindConfig.wholeWord)
{
ret.append("(\\s|\\z)");
}
return ret.toString();
}
|
diff --git a/GW01/src/at/jku/ce/ue/source/entities/Database.java b/GW01/src/at/jku/ce/ue/source/entities/Database.java
index a2bf5eb..19fbf65 100644
--- a/GW01/src/at/jku/ce/ue/source/entities/Database.java
+++ b/GW01/src/at/jku/ce/ue/source/entities/Database.java
@@ -1,223 +1,223 @@
/**
*
*/
package at.jku.ce.ue.source.entities;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;
import at.jku.ce.ue.source.businessLogic.BOMServiceUtil;
import at.jku.ce.ue.source.businessLogic.impl.BOMServiceUtilImpl;
/**
* @author Schnitzi
*
*/
public class Database {
private static Logger log = Logger.getLogger("Database");
private static final int PRODUCER_COUNT = 15;
private Map<String, Producer> producers;
private static Database database;
private Map<String, Part> partsOnPlattform;
public Database() {
this.producers = new HashMap<String, Producer>();
fillWithData();
}
public static Database getInstance() {
if (database == null) {
database = new Database();
}
return database;
}
private void fillWithData() {
createProducers();
producePartsForProducer();
}
private void createProducers() {
for (int i = 0; i < PRODUCER_COUNT; i++) {
Producer prod = new Producer("GW01Producer" + i, "GW01Producer" + i);
this.producers.put("GW01Producer"+i, prod);
}
}
private void producePartsForProducer() {
LinkedList<Part> parts = new LinkedList<Part>();
BOMServiceUtil bomService = new BOMServiceUtilImpl();
partsOnPlattform = new HashMap<String, Part>();
// List of all parts
List<String> productList = bomService.getAllPartsOfBOM();
log.severe("PART COUNT: " + productList.size());
int count = 0;
// Iterator through all parts and put every part and a list of it's
// subparts in the map
for (String partName : productList) {
Random rand = new Random();
Part part = null;
for (Part partInList : partsOnPlattform.values()) {
if (partInList.getName().equals(partName)) {
part = partInList;
}
}
if (part == null) {
int prodId = rand.nextInt(PRODUCER_COUNT);
part = new Part(count, partName, producers.get(prodId));
count += 1;
- producers.get(prodId).getParts().add(part);
+ producers.get("GW01Producer"+prodId).getParts().add(part);
}
// Get all subParts of actual looked part
List<String> subPartList = bomService
.getAllDirectSubpartsOfPart(partName);
// Iterate through all subParts of 'part'
for (String subPartName : subPartList) {
Part subPart = null;
// Check if 'subPartName' already exists as Part in this
// database
for (Part partInList : partsOnPlattform.values()) {
if (partInList.getName().equals(subPartName)) {
subPart = partInList;
}
}
if (subPart == null) {
int prodId = rand.nextInt(PRODUCER_COUNT);
subPart = new Part(count, subPartName,
producers.get(prodId));
count += 1;
- producers.get(prodId).getParts().add(part);
+ producers.get("GW01Producer"+prodId).getParts().add(part);
}
// Add 'subPart' as subpart of 'part'
if (part != null && subPart != null) {
part.getSubParts().add(subPart);
}
}
if (part != null)
partsOnPlattform.put(part.getIdString(), part);
}
printAllParts(partsOnPlattform);
}
private void printAllParts(Map<String, Part> allPartsWithSubParts) {
for (Part part : allPartsWithSubParts.values()) {
String outPut = "Part: No: " + part.getId() + part.getName();
// System.out.println("Part: " + part.getName());
if (part.getSubParts().size() > 0) {
for (Part subPart : part.getSubParts()) {
// System.out.println("\t+" + subPart.getName());
outPut += "\n\t+ No: " + subPart.getId()
+ subPart.getName();
}
} else {
// System.out.println("\t No more subParts");
outPut += "\n\t No more subParts";
}
System.out.println(outPut);
}
}
/**
* @param producerID
* @return
*/
public Producer getProducer(int producerID) {
return producers.get(producerID);
}
public Part getPart(String partID) {
return partsOnPlattform.get(partID);
}
public int registerProducer(String producerName, String password, String adress) {
int prodId = producerName.hashCode();
Producer producer = new Producer("GW01Producer"+prodId, producerName);
if (!producers.containsKey(prodId))
producers.put("GW01Producer"+prodId, producer);
else
log.info("Producer was not able to be registered!");
return prodId;
}
public Producer getProducer(String prodId) {
return null;
}
/**
* @return the producers
*/
public Map<String, Producer> getProducers() {
return producers;
}
/**
* @param producers the producers to set
*/
public void setProducers(Map<String, Producer> producers) {
this.producers = producers;
}
public void addProducer(String name) {
}
/**
* @return the partsOnPlattform
*/
public Map<String, Part> getPartsOnPlattform() {
return partsOnPlattform;
}
/**
* @param partsOnPlattform the partsOnPlattform to set
*/
public void setPartsOnPlattform(Map<String, Part> partsOnPlattform) {
this.partsOnPlattform = partsOnPlattform;
}
}
| false | true | private void producePartsForProducer() {
LinkedList<Part> parts = new LinkedList<Part>();
BOMServiceUtil bomService = new BOMServiceUtilImpl();
partsOnPlattform = new HashMap<String, Part>();
// List of all parts
List<String> productList = bomService.getAllPartsOfBOM();
log.severe("PART COUNT: " + productList.size());
int count = 0;
// Iterator through all parts and put every part and a list of it's
// subparts in the map
for (String partName : productList) {
Random rand = new Random();
Part part = null;
for (Part partInList : partsOnPlattform.values()) {
if (partInList.getName().equals(partName)) {
part = partInList;
}
}
if (part == null) {
int prodId = rand.nextInt(PRODUCER_COUNT);
part = new Part(count, partName, producers.get(prodId));
count += 1;
producers.get(prodId).getParts().add(part);
}
// Get all subParts of actual looked part
List<String> subPartList = bomService
.getAllDirectSubpartsOfPart(partName);
// Iterate through all subParts of 'part'
for (String subPartName : subPartList) {
Part subPart = null;
// Check if 'subPartName' already exists as Part in this
// database
for (Part partInList : partsOnPlattform.values()) {
if (partInList.getName().equals(subPartName)) {
subPart = partInList;
}
}
if (subPart == null) {
int prodId = rand.nextInt(PRODUCER_COUNT);
subPart = new Part(count, subPartName,
producers.get(prodId));
count += 1;
producers.get(prodId).getParts().add(part);
}
// Add 'subPart' as subpart of 'part'
if (part != null && subPart != null) {
part.getSubParts().add(subPart);
}
}
if (part != null)
partsOnPlattform.put(part.getIdString(), part);
}
printAllParts(partsOnPlattform);
}
| private void producePartsForProducer() {
LinkedList<Part> parts = new LinkedList<Part>();
BOMServiceUtil bomService = new BOMServiceUtilImpl();
partsOnPlattform = new HashMap<String, Part>();
// List of all parts
List<String> productList = bomService.getAllPartsOfBOM();
log.severe("PART COUNT: " + productList.size());
int count = 0;
// Iterator through all parts and put every part and a list of it's
// subparts in the map
for (String partName : productList) {
Random rand = new Random();
Part part = null;
for (Part partInList : partsOnPlattform.values()) {
if (partInList.getName().equals(partName)) {
part = partInList;
}
}
if (part == null) {
int prodId = rand.nextInt(PRODUCER_COUNT);
part = new Part(count, partName, producers.get(prodId));
count += 1;
producers.get("GW01Producer"+prodId).getParts().add(part);
}
// Get all subParts of actual looked part
List<String> subPartList = bomService
.getAllDirectSubpartsOfPart(partName);
// Iterate through all subParts of 'part'
for (String subPartName : subPartList) {
Part subPart = null;
// Check if 'subPartName' already exists as Part in this
// database
for (Part partInList : partsOnPlattform.values()) {
if (partInList.getName().equals(subPartName)) {
subPart = partInList;
}
}
if (subPart == null) {
int prodId = rand.nextInt(PRODUCER_COUNT);
subPart = new Part(count, subPartName,
producers.get(prodId));
count += 1;
producers.get("GW01Producer"+prodId).getParts().add(part);
}
// Add 'subPart' as subpart of 'part'
if (part != null && subPart != null) {
part.getSubParts().add(subPart);
}
}
if (part != null)
partsOnPlattform.put(part.getIdString(), part);
}
printAllParts(partsOnPlattform);
}
|
diff --git a/src/org/mythtv/service/guide/ProgramGuideDownloadService.java b/src/org/mythtv/service/guide/ProgramGuideDownloadService.java
index e6c066ef..90d23bc5 100644
--- a/src/org/mythtv/service/guide/ProgramGuideDownloadService.java
+++ b/src/org/mythtv/service/guide/ProgramGuideDownloadService.java
@@ -1,193 +1,193 @@
/**
* This file is part of MythTV Android Frontend
*
* MythTV Android Frontend 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.
*
* MythTV Android Frontend 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 MythTV Android Frontend. If not, see <http://www.gnu.org/licenses/>.
*
* This software can be found at <https://github.com/MythTV-Clients/MythTV-Android-Frontend/>
*/
package org.mythtv.service.guide;
import java.io.File;
import java.io.IOException;
import org.joda.time.DateTime;
import org.mythtv.R;
import org.mythtv.service.MythtvService;
import org.mythtv.service.util.DateUtils;
import org.mythtv.services.api.ETagInfo;
import org.mythtv.services.api.guide.ProgramGuideWrapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
/**
* @author Daniel Frey
*
*/
public class ProgramGuideDownloadService extends MythtvService {
private static final String TAG = ProgramGuideDownloadService.class.getSimpleName();
private static final Integer MAX_HOURS = 288;
public static final String ACTION_DOWNLOAD = "org.mythtv.background.programGuideDownload.ACTION_DOWNLOAD";
public static final String ACTION_PROGRESS = "org.mythtv.background.programGuideDownload.ACTION_PROGRESS";
public static final String ACTION_COMPLETE = "org.mythtv.background.programGuideDownload.ACTION_COMPLETE";
public static final String EXTRA_PROGRESS = "PROGRESS";
public static final String EXTRA_PROGRESS_DATE = "PROGRESS_DATE";
public static final String EXTRA_PROGRESS_ERROR = "PROGRESS_ERROR";
public static final String EXTRA_COMPLETE = "COMPLETE";
public static final String EXTRA_COMPLETE_DOWNLOADED = "COMPLETE_DOWNLOADED";
private NotificationManager mNotificationManager;
private int notificationId;
public ProgramGuideDownloadService() {
super( "ProgamGuideDownloadService" );
}
/* (non-Javadoc)
* @see android.app.IntentService#onHandleIntent(android.content.Intent)
*/
@Override
protected void onHandleIntent( Intent intent ) {
Log.d( TAG, "onHandleIntent : enter" );
super.onHandleIntent( intent );
mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
if ( intent.getAction().equals( ACTION_DOWNLOAD ) ) {
Log.i( TAG, "onHandleIntent : DOWNLOAD action selected" );
download();
}
Log.d( TAG, "onHandleIntent : exit" );
}
// internal helpers
private void download() {
// Log.v( TAG, "download : enter" );
boolean newDataDownloaded = false;
sendNotification();
DateTime start = new DateTime();
start = start.withTime( 0, 0, 0, 001 );
File programGuideCache = mFileHelper.getProgramGuideDataDirectory();
- if( programGuideCache.exists() ) {
+ if( null != programGuideCache && programGuideCache.exists() ) {
for( int currentHour = 0; currentHour < MAX_HOURS; currentHour++ ) {
String sStart = fileDateTimeFormatter.print( start );
String filename = sStart + FILENAME_EXT;
File file = new File( programGuideCache, filename );
if( !file.exists() ) {
DateTime end = new DateTime( start );
end = end.withTime( start.getHourOfDay(), 59, 59, 999 );
Log.i( TAG, "download : starting download for " + DateUtils.dateTimeFormatter.print( start ) + ", end time=" + DateUtils.dateTimeFormatter.print( end ) );
ETagInfo etag = ETagInfo.createEmptyETag();
ResponseEntity<ProgramGuideWrapper> responseEntity = mMainApplication.getMythServicesApi().guideOperations().getProgramGuide( start, end, 1, -1, false, etag );
if( null != responseEntity ) {
if( responseEntity.getStatusCode().equals( HttpStatus.OK ) ) {
Intent progressIntent = new Intent( ACTION_PROGRESS );
try {
ProgramGuideWrapper programGuide = responseEntity.getBody();
mObjectMapper.writeValue( file, programGuide.getProgramGuide() );
newDataDownloaded = true;
progressIntent.putExtra( EXTRA_PROGRESS, "Completed downloading file for " + sStart );
progressIntent.putExtra( EXTRA_PROGRESS_DATE, DateUtils.dateTimeFormatter.print( start ) );
} catch( JsonGenerationException e ) {
Log.e( TAG, "download : JsonGenerationException - error downloading file for " + sStart, e );
progressIntent.putExtra( EXTRA_PROGRESS_ERROR, "error downloading file for " + sStart + ": " + e.getLocalizedMessage() );
} catch( JsonMappingException e ) {
Log.e( TAG, "download : JsonMappingException - error downloading file for " + sStart, e );
progressIntent.putExtra( EXTRA_PROGRESS_ERROR, "error downloading file for " + sStart + ": " + e.getLocalizedMessage() );
} catch( IOException e ) {
Log.e( TAG, "download : IOException - error downloading file for " + sStart, e );
progressIntent.putExtra( EXTRA_PROGRESS_ERROR, "IOException - error downloading file for " + sStart + ": " + e.getLocalizedMessage() );
}
sendBroadcast( progressIntent );
}
}
}
start = start.plusHours( 1 );
}
}
completed();
Intent completeIntent = new Intent( ACTION_COMPLETE );
completeIntent.putExtra( EXTRA_COMPLETE, "Program Guide Download Service Finished" );
completeIntent.putExtra( EXTRA_COMPLETE_DOWNLOADED, newDataDownloaded );
sendBroadcast( completeIntent );
// Log.v( TAG, "download : exit" );
}
// internal helpers
@SuppressWarnings( "deprecation" )
private void sendNotification() {
long when = System.currentTimeMillis();
notificationId = (int) when;
Notification mNotification = new Notification( android.R.drawable.stat_notify_sync, getResources().getString( R.string.notification_sync_program_guide ), when );
Intent notificationIntent = new Intent();
PendingIntent mContentIntent = PendingIntent.getActivity( this, 0, notificationIntent, 0 );
mNotification.setLatestEventInfo( this, getResources().getString( R.string.app_name ), getResources().getString( R.string.notification_sync_program_guide ), mContentIntent );
mNotification.flags = Notification.FLAG_ONGOING_EVENT;
mNotificationManager.notify( notificationId, mNotification );
}
public void completed() {
mNotificationManager.cancel( notificationId );
}
}
| true | true | private void download() {
// Log.v( TAG, "download : enter" );
boolean newDataDownloaded = false;
sendNotification();
DateTime start = new DateTime();
start = start.withTime( 0, 0, 0, 001 );
File programGuideCache = mFileHelper.getProgramGuideDataDirectory();
if( programGuideCache.exists() ) {
for( int currentHour = 0; currentHour < MAX_HOURS; currentHour++ ) {
String sStart = fileDateTimeFormatter.print( start );
String filename = sStart + FILENAME_EXT;
File file = new File( programGuideCache, filename );
if( !file.exists() ) {
DateTime end = new DateTime( start );
end = end.withTime( start.getHourOfDay(), 59, 59, 999 );
Log.i( TAG, "download : starting download for " + DateUtils.dateTimeFormatter.print( start ) + ", end time=" + DateUtils.dateTimeFormatter.print( end ) );
ETagInfo etag = ETagInfo.createEmptyETag();
ResponseEntity<ProgramGuideWrapper> responseEntity = mMainApplication.getMythServicesApi().guideOperations().getProgramGuide( start, end, 1, -1, false, etag );
if( null != responseEntity ) {
if( responseEntity.getStatusCode().equals( HttpStatus.OK ) ) {
Intent progressIntent = new Intent( ACTION_PROGRESS );
try {
ProgramGuideWrapper programGuide = responseEntity.getBody();
mObjectMapper.writeValue( file, programGuide.getProgramGuide() );
newDataDownloaded = true;
progressIntent.putExtra( EXTRA_PROGRESS, "Completed downloading file for " + sStart );
progressIntent.putExtra( EXTRA_PROGRESS_DATE, DateUtils.dateTimeFormatter.print( start ) );
} catch( JsonGenerationException e ) {
Log.e( TAG, "download : JsonGenerationException - error downloading file for " + sStart, e );
progressIntent.putExtra( EXTRA_PROGRESS_ERROR, "error downloading file for " + sStart + ": " + e.getLocalizedMessage() );
} catch( JsonMappingException e ) {
Log.e( TAG, "download : JsonMappingException - error downloading file for " + sStart, e );
progressIntent.putExtra( EXTRA_PROGRESS_ERROR, "error downloading file for " + sStart + ": " + e.getLocalizedMessage() );
} catch( IOException e ) {
Log.e( TAG, "download : IOException - error downloading file for " + sStart, e );
progressIntent.putExtra( EXTRA_PROGRESS_ERROR, "IOException - error downloading file for " + sStart + ": " + e.getLocalizedMessage() );
}
sendBroadcast( progressIntent );
}
}
}
start = start.plusHours( 1 );
}
}
completed();
Intent completeIntent = new Intent( ACTION_COMPLETE );
completeIntent.putExtra( EXTRA_COMPLETE, "Program Guide Download Service Finished" );
completeIntent.putExtra( EXTRA_COMPLETE_DOWNLOADED, newDataDownloaded );
sendBroadcast( completeIntent );
// Log.v( TAG, "download : exit" );
}
| private void download() {
// Log.v( TAG, "download : enter" );
boolean newDataDownloaded = false;
sendNotification();
DateTime start = new DateTime();
start = start.withTime( 0, 0, 0, 001 );
File programGuideCache = mFileHelper.getProgramGuideDataDirectory();
if( null != programGuideCache && programGuideCache.exists() ) {
for( int currentHour = 0; currentHour < MAX_HOURS; currentHour++ ) {
String sStart = fileDateTimeFormatter.print( start );
String filename = sStart + FILENAME_EXT;
File file = new File( programGuideCache, filename );
if( !file.exists() ) {
DateTime end = new DateTime( start );
end = end.withTime( start.getHourOfDay(), 59, 59, 999 );
Log.i( TAG, "download : starting download for " + DateUtils.dateTimeFormatter.print( start ) + ", end time=" + DateUtils.dateTimeFormatter.print( end ) );
ETagInfo etag = ETagInfo.createEmptyETag();
ResponseEntity<ProgramGuideWrapper> responseEntity = mMainApplication.getMythServicesApi().guideOperations().getProgramGuide( start, end, 1, -1, false, etag );
if( null != responseEntity ) {
if( responseEntity.getStatusCode().equals( HttpStatus.OK ) ) {
Intent progressIntent = new Intent( ACTION_PROGRESS );
try {
ProgramGuideWrapper programGuide = responseEntity.getBody();
mObjectMapper.writeValue( file, programGuide.getProgramGuide() );
newDataDownloaded = true;
progressIntent.putExtra( EXTRA_PROGRESS, "Completed downloading file for " + sStart );
progressIntent.putExtra( EXTRA_PROGRESS_DATE, DateUtils.dateTimeFormatter.print( start ) );
} catch( JsonGenerationException e ) {
Log.e( TAG, "download : JsonGenerationException - error downloading file for " + sStart, e );
progressIntent.putExtra( EXTRA_PROGRESS_ERROR, "error downloading file for " + sStart + ": " + e.getLocalizedMessage() );
} catch( JsonMappingException e ) {
Log.e( TAG, "download : JsonMappingException - error downloading file for " + sStart, e );
progressIntent.putExtra( EXTRA_PROGRESS_ERROR, "error downloading file for " + sStart + ": " + e.getLocalizedMessage() );
} catch( IOException e ) {
Log.e( TAG, "download : IOException - error downloading file for " + sStart, e );
progressIntent.putExtra( EXTRA_PROGRESS_ERROR, "IOException - error downloading file for " + sStart + ": " + e.getLocalizedMessage() );
}
sendBroadcast( progressIntent );
}
}
}
start = start.plusHours( 1 );
}
}
completed();
Intent completeIntent = new Intent( ACTION_COMPLETE );
completeIntent.putExtra( EXTRA_COMPLETE, "Program Guide Download Service Finished" );
completeIntent.putExtra( EXTRA_COMPLETE_DOWNLOADED, newDataDownloaded );
sendBroadcast( completeIntent );
// Log.v( TAG, "download : exit" );
}
|
diff --git a/spf4j-core/src/main/java/org/spf4j/stackmonitor/FastStackCollector.java b/spf4j-core/src/main/java/org/spf4j/stackmonitor/FastStackCollector.java
index 4340dd27bd..03c5c66678 100644
--- a/spf4j-core/src/main/java/org/spf4j/stackmonitor/FastStackCollector.java
+++ b/spf4j-core/src/main/java/org/spf4j/stackmonitor/FastStackCollector.java
@@ -1,94 +1,89 @@
/*
* Copyright (c) 2001, Zoltan Farkas All Rights Reserved.
*
* 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 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.spf4j.stackmonitor;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* This is a high performance sampling collector.
* The goal is for the sampling overhead to be minimal.
* This is better than the SimpleStackCollector in 2 ways:
* 1) No HashMap is created during sampling. Resulting in less garbage generated by sampling.
* 2) Stack trace for the sampling Thread is not created at all, saving some time and creating less garbage.
*
* in java 1.7 the reflective invocations can probably be further optimized using:
* http://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandle.html
* http://stackoverflow.com/questions/14146570/
* calling-a-getter-in-java-though-reflection-whats-the-fastest-way-to-repeatedly
* @author zoly
*/
public final class FastStackCollector extends AbstractStackCollector {
private static final java.lang.reflect.Method GET_THREADS;
private static final java.lang.reflect.Method DUMP_THREADS;
static {
try {
GET_THREADS = Thread.class.getDeclaredMethod("getThreads");
DUMP_THREADS = Thread.class.getDeclaredMethod("dumpThreads", Thread[].class);
} catch (SecurityException ex) {
throw new RuntimeException(ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
}
AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Object run() {
GET_THREADS.setAccessible(true);
DUMP_THREADS.setAccessible(true);
return null; // nothing to return
}
});
}
@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings("EXS_EXCEPTION_SOFTENING_NO_CHECKED")
public void sample(final Thread ignore) {
try {
Thread[] threads = (Thread[]) GET_THREADS.invoke(null);
final int nrThreads = threads.length;
- int currThreadPos = -1;
for (int i = 0; i < nrThreads; i++) {
if (ignore == threads[i]) { // not interested in the sampler's stack trace
threads[i] = null;
- currThreadPos = i;
break;
}
}
StackTraceElement[][] stackDump = (StackTraceElement[][]) DUMP_THREADS.invoke(null, (Object) threads);
- for (int i = 0; i < nrThreads; i++) {
- if (i != currThreadPos) {
- StackTraceElement[] stackTrace = stackDump[i];
- if (stackTrace.length > 0) {
+ for (StackTraceElement[] stackTrace : stackDump) {
+ if (stackTrace != null && stackTrace.length > 0) {
addSample(stackTrace);
- }
}
}
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
}
| false | true | public void sample(final Thread ignore) {
try {
Thread[] threads = (Thread[]) GET_THREADS.invoke(null);
final int nrThreads = threads.length;
int currThreadPos = -1;
for (int i = 0; i < nrThreads; i++) {
if (ignore == threads[i]) { // not interested in the sampler's stack trace
threads[i] = null;
currThreadPos = i;
break;
}
}
StackTraceElement[][] stackDump = (StackTraceElement[][]) DUMP_THREADS.invoke(null, (Object) threads);
for (int i = 0; i < nrThreads; i++) {
if (i != currThreadPos) {
StackTraceElement[] stackTrace = stackDump[i];
if (stackTrace.length > 0) {
addSample(stackTrace);
}
}
}
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
| public void sample(final Thread ignore) {
try {
Thread[] threads = (Thread[]) GET_THREADS.invoke(null);
final int nrThreads = threads.length;
for (int i = 0; i < nrThreads; i++) {
if (ignore == threads[i]) { // not interested in the sampler's stack trace
threads[i] = null;
break;
}
}
StackTraceElement[][] stackDump = (StackTraceElement[][]) DUMP_THREADS.invoke(null, (Object) threads);
for (StackTraceElement[] stackTrace : stackDump) {
if (stackTrace != null && stackTrace.length > 0) {
addSample(stackTrace);
}
}
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
|
diff --git a/se/sics/mspsim/cli/MiscCommands.java b/se/sics/mspsim/cli/MiscCommands.java
index 6caf6e9..203cae3 100644
--- a/se/sics/mspsim/cli/MiscCommands.java
+++ b/se/sics/mspsim/cli/MiscCommands.java
@@ -1,433 +1,433 @@
/**
* Copyright (c) 2007, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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.
*
* This file is part of MSPSim.
*
* $Id$
*
* -----------------------------------------------------------------
*
* MiscCommands
*
* Author : Joakim Eriksson
* Created : 9 mar 2008
* Updated : $Date$
* $Revision$
*/
package se.sics.mspsim.cli;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.regex.Pattern;
import se.sics.mspsim.chip.RFListener;
import se.sics.mspsim.chip.RFSource;
import se.sics.mspsim.core.Chip;
import se.sics.mspsim.core.MSP430;
import se.sics.mspsim.core.MSP430Constants;
import se.sics.mspsim.core.TimeEvent;
import se.sics.mspsim.util.ActiveComponent;
import se.sics.mspsim.util.ArgumentManager;
import se.sics.mspsim.util.ComponentRegistry;
import se.sics.mspsim.util.PluginRepository;
import se.sics.mspsim.util.ServiceComponent;
import se.sics.mspsim.util.Utils;
/**
* @author joakim
*
*/
public class MiscCommands implements CommandBundle {
private Hashtable <String, FileTarget> fileTargets = new Hashtable<String, FileTarget>();
public void setupCommands(final ComponentRegistry registry, CommandHandler handler) {
handler.registerCommand("grep", new BasicLineCommand("print lines matching the specified pattern", "[-i] [-v] <regexp>") {
private PrintStream out;
private Pattern pattern;
private boolean isInverted = false;
public int executeCommand(CommandContext context) {
int index = 0;
int flags = 0;
while (index + 1 < context.getArgumentCount()) {
if ("-i".equals(context.getArgument(index))) {
flags |= Pattern.CASE_INSENSITIVE;
} else if ("-v".equals(context.getArgument(index))) {
isInverted = true;
} else {
context.err.println("unknown option: " + context.getArgument(index));
return 1;
}
index++;
}
out = context.out;
pattern = Pattern.compile(context.getArgument(index), flags);
return 0;
}
public void lineRead(String line) {
boolean isMatch = pattern.matcher(line).find();
if(isMatch ^ isInverted) {
out.println(line);
}
}
});
handler.registerCommand("timestamp", new BasicLineCommand("print lines with timestamp prefixed", "") {
private PrintStream out;
private MSP430 cpu;
long startTime;
public int executeCommand(CommandContext context) {
cpu = (MSP430) registry.getComponent(MSP430.class);
if (cpu == null) {
context.err.println("could not access the CPU.");
return 1;
}
out = context.out;
startTime = System.currentTimeMillis() - (long)cpu.getTimeMillis();
return 0;
}
public void lineRead(String line) {
out.println(Long.toString(startTime + (long)cpu.getTimeMillis()) + ' ' + line);
}
});
handler.registerCommand("speed", new BasicCommand("set the speed factor for the CPU", "[factor]") {
public int executeCommand(CommandContext context) {
MSP430 cpu = (MSP430) registry.getComponent(MSP430.class);
if (cpu == null) {
context.err.println("could not access the CPU.");
return 1;
} else if (context.getArgumentCount() == 0) {
long rate = cpu.getSleepRate();
double d = rate / 25000.0;
context.out.println("Speed factor is set to " + (((int)(d * 100 + 0.5)) / 100.0));
} else {
double d = context.getArgumentAsDouble(0);
if (d > 0.0) {
long rate = (long) (25000 * d);
cpu.setSleepRate(rate);
} else {
context.err.println("Speed factor must be larger than zero.");
return 1;
}
}
return 0;
}
});
handler.registerCommand("echo", new BasicCommand("echo arguments", "") {
public int executeCommand(CommandContext context) {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = context.getArgumentCount(); i < n; i++) {
if (i > 0) sb.append(' ');
sb.append(context.getArgument(i));
}
context.out.println(sb.toString());
return 0;
}
});
handler.registerCommand("source", new BasicCommand("run script", "[-v] <filename>") {
public int executeCommand(CommandContext context) {
boolean verbose = false;
if (context.getArgumentCount() > 1) {
verbose = "-v".equals(context.getArgument(0));
}
File fp = new File(context.getArgument(context.getArgumentCount() - 1));
if (!fp.canRead()) {
context.err.println("could not find the script file '" + context.getArgument(0) + "'.");
return 1;
}
try {
FileInputStream infs = new FileInputStream(fp);
BufferedReader input = new BufferedReader(new InputStreamReader(infs));
try {
String line;
while ((line = input.readLine()) != null) {
if (verbose) context.out.println(line);
context.executeCommand(line);
}
} finally {
input.close();
}
} catch (IOException e) {
e.printStackTrace(context.err);
return 1;
}
return 0;
}
});
handler.registerCommand("repeat", new BasicAsyncCommand("repeat the specified command line", "[-t delay] [-c count] <command line>") {
private MSP430 cpu;
private int period = 1;
private int count = 0;
private int maxCount = -1;
private String commandLine;
private boolean isRunning = true;
public int executeCommand(final CommandContext context) {
int index = 0;
do {
String a = context.getArgument(index);
if (a.startsWith("-")) {
if (a.equals("-t")) {
period = context.getArgumentAsInt(index + 1);
index += 2;
} else if (a.equals("-c")) {
maxCount = context.getArgumentAsInt(index + 1);
index += 2;
} else {
context.err.println("illegal option: " + a);
return 1;
}
} else {
break;
}
} while (true);
if (index + 1 < context.getArgumentCount()) {
context.err.println("too many arguments");
return 1;
}
commandLine = context.getArgument(index);
cpu = (MSP430) registry.getComponent(MSP430.class);
if (cpu == null) {
context.err.println("could not access the CPU.");
return 1;
}
cpu.scheduleTimeEventMillis(new TimeEvent(0) {
@Override
public void execute(long t) {
if (isRunning) {
count++;
context.executeCommand(commandLine);
if ((maxCount <= 0) || (count < maxCount)) {
cpu.scheduleTimeEventMillis(this, period * 1000d);
} else {
stopCommand(context);
}
}
}
}, period * 1000d);
return 0;
}
public void stopCommand(CommandContext context) {
isRunning = false;
context.err.println("[repeat exit: " + commandLine + ']');
context.exit(0);
}
});
handler.registerCommand("exec", new ExecCommand());
handler.registerCommand("trig", new BasicLineCommand("trigg command when input match regexp", "<command>") {
String command = null;
CommandContext context;
public int executeCommand(CommandContext context) {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = context.getArgumentCount(); i < n; i++) {
if (i > 0) sb.append(' ');
sb.append(context.getArgument(i));
}
command = sb.toString();
this.context = context;
return 0;
}
public void lineRead(String line) {
context.executeCommand(command);
}
});
handler.registerCommand("install", new BasicCommand("install and start a plugin", "ClassName [Name]") {
@Override
public int executeCommand(CommandContext context) {
String className = context.getArgument(0);
String name = className;
if (context.getArgumentCount() > 1) {
name = context.getArgument(1);
}
if (registry.getComponent(name) != null) {
context.err.println("Another component with name " + name + " is already installed");
return 1;
}
Class pluginClass = null;
PluginRepository plugins = (PluginRepository) registry.getComponent("pluginRepository");
try {
try {
pluginClass = plugins != null ? plugins.loadClass(className) :
Class.forName(className);
} catch (ClassNotFoundException e) {
String newClassName = "se.sics.mspsim.plugin." + className;
pluginClass = plugins != null ? plugins.loadClass(newClassName) :
Class.forName(newClassName);
}
Object component = pluginClass.newInstance();
registry.registerComponent(name, component);
return 0;
} catch (Exception e1) {
e1.printStackTrace(context.err);
}
// TODO Auto-generated method stub
return 1;
}
});
- handler.registerCommand("service", new BasicCommand("handle service plugins", "[class name|service name] [start|stop|install]") {
+ handler.registerCommand("service", new BasicCommand("handle service plugins", "[class name|service name] [start|stop]") {
@Override
public int executeCommand(CommandContext context) {
if (context.getArgumentCount() == 0) {
ServiceComponent[] sc = (ServiceComponent[]) registry.getAllComponents(ServiceComponent.class);
for (int i = 0; i < sc.length; i++) {
context.out.printf(" %-20s %s\n",sc[i].getName(),sc[i].getStatus());
}
} else if (context.getArgumentCount() == 1){
String name = context.getArgument(0);
ServiceComponent sc = getServiceForName(registry, name);
if (sc != null) {
context.out.printf(" %-20s %s\n",sc.getName(),sc.getStatus());
} else {
context.out.println("can not find service" + name);
}
} else {
String name = context.getArgument(0);
String operation = context.getArgument(1);
if ("start".equals(operation)) {
ServiceComponent sc = getServiceForName(registry, name);
if (sc != null) {
sc.start();
context.out.println("service " + sc.getName() + " started");
} else {
context.out.println("can not find service" + name);
}
} else if ("stop".equals(operation)) {
ServiceComponent sc = getServiceForName(registry, name);
if (sc != null) {
- sc.start();
- context.out.println("service " + sc.getName() + " started");
+ sc.stop();
+ context.out.println("service " + sc.getName() + " stopped");
} else {
context.out.println("can not find service" + name);
}
}
}
return 0;
}
});
handler.registerCommand("rflistener", new BasicLineCommand("an rflisteer", "[input|output] <rf-chip>") {
CommandContext context;
RFListener listener;
final MSP430 cpu = (MSP430) registry.getComponent(MSP430.class);
public int executeCommand(CommandContext ctx) {
this.context = ctx;
String inout = context.getArgument(0);
Chip chip = cpu.getChip(context.getArgument(1));
if ("output".equals(inout)) {
if (chip instanceof RFSource) {
((RFSource)chip).setRFListener(new RFListener(){
public void receivedByte(byte data) {
context.out.println("" + Utils.hex8(data));
}
});
}
} else if ("input".equals(inout)){
listener = (RFListener) chip;
} else {
context.err.println("Error: illegal type: " + inout);
}
return 0;
}
public void lineRead(String line) {
if (listener != null) {
byte[] data = Utils.hexconv(line);
context.out.println("Should send bytes to radio: " + line);
for (int i = 0; i < data.length; i++) {
//context.out.println("Byte " + i + " = " + ((int) data[i] & 0xff));
listener.receivedByte(data[i]);
}
}
}
});
handler.registerCommand("sysinfo", new BasicCommand("show info about the MSPSim system", "[-registry]") {
public int executeCommand(CommandContext context) {
ArgumentManager config = (ArgumentManager) registry.getComponent("config");
context.out.println("--------- System info ----------\n");
context.out.println("MSPSim version: " + MSP430Constants.VERSION);
context.out.println("Java version : " + System.getProperty("java.version") + " " +
System.getProperty("java.vendor"));
context.out.println("Firmware : " + config.getProperty("firmwareFile"));
context.out.println("AutoloadScript: " + config.getProperty("autoloadScript"));
context.out.println();
if (context.getOption("registry")) {
context.out.println("--------- Registry info --------\n");
registry.printRegistry(context.out);
}
return 0;
}
});
handler.registerCommand("quit", new BasicCommand("exit MSPSim", "") {
public int executeCommand(CommandContext context) {
/* TODO: flush all files, etc.... */
System.exit(0);
return 0;
}
});
handler.registerCommand("exit", new BasicCommand("exit MSPSim", "") {
public int executeCommand(CommandContext context) {
System.exit(0);
return 0;
}
});
}
private static ServiceComponent getServiceForName(ComponentRegistry registry, String name) {
Object o = registry.getComponent(name);
if (o instanceof ServiceComponent) {
return (ServiceComponent) o;
}
return null;
}
}
| false | true | public void setupCommands(final ComponentRegistry registry, CommandHandler handler) {
handler.registerCommand("grep", new BasicLineCommand("print lines matching the specified pattern", "[-i] [-v] <regexp>") {
private PrintStream out;
private Pattern pattern;
private boolean isInverted = false;
public int executeCommand(CommandContext context) {
int index = 0;
int flags = 0;
while (index + 1 < context.getArgumentCount()) {
if ("-i".equals(context.getArgument(index))) {
flags |= Pattern.CASE_INSENSITIVE;
} else if ("-v".equals(context.getArgument(index))) {
isInverted = true;
} else {
context.err.println("unknown option: " + context.getArgument(index));
return 1;
}
index++;
}
out = context.out;
pattern = Pattern.compile(context.getArgument(index), flags);
return 0;
}
public void lineRead(String line) {
boolean isMatch = pattern.matcher(line).find();
if(isMatch ^ isInverted) {
out.println(line);
}
}
});
handler.registerCommand("timestamp", new BasicLineCommand("print lines with timestamp prefixed", "") {
private PrintStream out;
private MSP430 cpu;
long startTime;
public int executeCommand(CommandContext context) {
cpu = (MSP430) registry.getComponent(MSP430.class);
if (cpu == null) {
context.err.println("could not access the CPU.");
return 1;
}
out = context.out;
startTime = System.currentTimeMillis() - (long)cpu.getTimeMillis();
return 0;
}
public void lineRead(String line) {
out.println(Long.toString(startTime + (long)cpu.getTimeMillis()) + ' ' + line);
}
});
handler.registerCommand("speed", new BasicCommand("set the speed factor for the CPU", "[factor]") {
public int executeCommand(CommandContext context) {
MSP430 cpu = (MSP430) registry.getComponent(MSP430.class);
if (cpu == null) {
context.err.println("could not access the CPU.");
return 1;
} else if (context.getArgumentCount() == 0) {
long rate = cpu.getSleepRate();
double d = rate / 25000.0;
context.out.println("Speed factor is set to " + (((int)(d * 100 + 0.5)) / 100.0));
} else {
double d = context.getArgumentAsDouble(0);
if (d > 0.0) {
long rate = (long) (25000 * d);
cpu.setSleepRate(rate);
} else {
context.err.println("Speed factor must be larger than zero.");
return 1;
}
}
return 0;
}
});
handler.registerCommand("echo", new BasicCommand("echo arguments", "") {
public int executeCommand(CommandContext context) {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = context.getArgumentCount(); i < n; i++) {
if (i > 0) sb.append(' ');
sb.append(context.getArgument(i));
}
context.out.println(sb.toString());
return 0;
}
});
handler.registerCommand("source", new BasicCommand("run script", "[-v] <filename>") {
public int executeCommand(CommandContext context) {
boolean verbose = false;
if (context.getArgumentCount() > 1) {
verbose = "-v".equals(context.getArgument(0));
}
File fp = new File(context.getArgument(context.getArgumentCount() - 1));
if (!fp.canRead()) {
context.err.println("could not find the script file '" + context.getArgument(0) + "'.");
return 1;
}
try {
FileInputStream infs = new FileInputStream(fp);
BufferedReader input = new BufferedReader(new InputStreamReader(infs));
try {
String line;
while ((line = input.readLine()) != null) {
if (verbose) context.out.println(line);
context.executeCommand(line);
}
} finally {
input.close();
}
} catch (IOException e) {
e.printStackTrace(context.err);
return 1;
}
return 0;
}
});
handler.registerCommand("repeat", new BasicAsyncCommand("repeat the specified command line", "[-t delay] [-c count] <command line>") {
private MSP430 cpu;
private int period = 1;
private int count = 0;
private int maxCount = -1;
private String commandLine;
private boolean isRunning = true;
public int executeCommand(final CommandContext context) {
int index = 0;
do {
String a = context.getArgument(index);
if (a.startsWith("-")) {
if (a.equals("-t")) {
period = context.getArgumentAsInt(index + 1);
index += 2;
} else if (a.equals("-c")) {
maxCount = context.getArgumentAsInt(index + 1);
index += 2;
} else {
context.err.println("illegal option: " + a);
return 1;
}
} else {
break;
}
} while (true);
if (index + 1 < context.getArgumentCount()) {
context.err.println("too many arguments");
return 1;
}
commandLine = context.getArgument(index);
cpu = (MSP430) registry.getComponent(MSP430.class);
if (cpu == null) {
context.err.println("could not access the CPU.");
return 1;
}
cpu.scheduleTimeEventMillis(new TimeEvent(0) {
@Override
public void execute(long t) {
if (isRunning) {
count++;
context.executeCommand(commandLine);
if ((maxCount <= 0) || (count < maxCount)) {
cpu.scheduleTimeEventMillis(this, period * 1000d);
} else {
stopCommand(context);
}
}
}
}, period * 1000d);
return 0;
}
public void stopCommand(CommandContext context) {
isRunning = false;
context.err.println("[repeat exit: " + commandLine + ']');
context.exit(0);
}
});
handler.registerCommand("exec", new ExecCommand());
handler.registerCommand("trig", new BasicLineCommand("trigg command when input match regexp", "<command>") {
String command = null;
CommandContext context;
public int executeCommand(CommandContext context) {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = context.getArgumentCount(); i < n; i++) {
if (i > 0) sb.append(' ');
sb.append(context.getArgument(i));
}
command = sb.toString();
this.context = context;
return 0;
}
public void lineRead(String line) {
context.executeCommand(command);
}
});
handler.registerCommand("install", new BasicCommand("install and start a plugin", "ClassName [Name]") {
@Override
public int executeCommand(CommandContext context) {
String className = context.getArgument(0);
String name = className;
if (context.getArgumentCount() > 1) {
name = context.getArgument(1);
}
if (registry.getComponent(name) != null) {
context.err.println("Another component with name " + name + " is already installed");
return 1;
}
Class pluginClass = null;
PluginRepository plugins = (PluginRepository) registry.getComponent("pluginRepository");
try {
try {
pluginClass = plugins != null ? plugins.loadClass(className) :
Class.forName(className);
} catch (ClassNotFoundException e) {
String newClassName = "se.sics.mspsim.plugin." + className;
pluginClass = plugins != null ? plugins.loadClass(newClassName) :
Class.forName(newClassName);
}
Object component = pluginClass.newInstance();
registry.registerComponent(name, component);
return 0;
} catch (Exception e1) {
e1.printStackTrace(context.err);
}
// TODO Auto-generated method stub
return 1;
}
});
handler.registerCommand("service", new BasicCommand("handle service plugins", "[class name|service name] [start|stop|install]") {
@Override
public int executeCommand(CommandContext context) {
if (context.getArgumentCount() == 0) {
ServiceComponent[] sc = (ServiceComponent[]) registry.getAllComponents(ServiceComponent.class);
for (int i = 0; i < sc.length; i++) {
context.out.printf(" %-20s %s\n",sc[i].getName(),sc[i].getStatus());
}
} else if (context.getArgumentCount() == 1){
String name = context.getArgument(0);
ServiceComponent sc = getServiceForName(registry, name);
if (sc != null) {
context.out.printf(" %-20s %s\n",sc.getName(),sc.getStatus());
} else {
context.out.println("can not find service" + name);
}
} else {
String name = context.getArgument(0);
String operation = context.getArgument(1);
if ("start".equals(operation)) {
ServiceComponent sc = getServiceForName(registry, name);
if (sc != null) {
sc.start();
context.out.println("service " + sc.getName() + " started");
} else {
context.out.println("can not find service" + name);
}
} else if ("stop".equals(operation)) {
ServiceComponent sc = getServiceForName(registry, name);
if (sc != null) {
sc.start();
context.out.println("service " + sc.getName() + " started");
} else {
context.out.println("can not find service" + name);
}
}
}
return 0;
}
});
handler.registerCommand("rflistener", new BasicLineCommand("an rflisteer", "[input|output] <rf-chip>") {
CommandContext context;
RFListener listener;
final MSP430 cpu = (MSP430) registry.getComponent(MSP430.class);
public int executeCommand(CommandContext ctx) {
this.context = ctx;
String inout = context.getArgument(0);
Chip chip = cpu.getChip(context.getArgument(1));
if ("output".equals(inout)) {
if (chip instanceof RFSource) {
((RFSource)chip).setRFListener(new RFListener(){
public void receivedByte(byte data) {
context.out.println("" + Utils.hex8(data));
}
});
}
} else if ("input".equals(inout)){
listener = (RFListener) chip;
} else {
context.err.println("Error: illegal type: " + inout);
}
return 0;
}
public void lineRead(String line) {
if (listener != null) {
byte[] data = Utils.hexconv(line);
context.out.println("Should send bytes to radio: " + line);
for (int i = 0; i < data.length; i++) {
//context.out.println("Byte " + i + " = " + ((int) data[i] & 0xff));
listener.receivedByte(data[i]);
}
}
}
});
handler.registerCommand("sysinfo", new BasicCommand("show info about the MSPSim system", "[-registry]") {
public int executeCommand(CommandContext context) {
ArgumentManager config = (ArgumentManager) registry.getComponent("config");
context.out.println("--------- System info ----------\n");
context.out.println("MSPSim version: " + MSP430Constants.VERSION);
context.out.println("Java version : " + System.getProperty("java.version") + " " +
System.getProperty("java.vendor"));
context.out.println("Firmware : " + config.getProperty("firmwareFile"));
context.out.println("AutoloadScript: " + config.getProperty("autoloadScript"));
context.out.println();
if (context.getOption("registry")) {
context.out.println("--------- Registry info --------\n");
registry.printRegistry(context.out);
}
return 0;
}
});
handler.registerCommand("quit", new BasicCommand("exit MSPSim", "") {
public int executeCommand(CommandContext context) {
/* TODO: flush all files, etc.... */
System.exit(0);
return 0;
}
});
handler.registerCommand("exit", new BasicCommand("exit MSPSim", "") {
public int executeCommand(CommandContext context) {
System.exit(0);
return 0;
}
});
}
| public void setupCommands(final ComponentRegistry registry, CommandHandler handler) {
handler.registerCommand("grep", new BasicLineCommand("print lines matching the specified pattern", "[-i] [-v] <regexp>") {
private PrintStream out;
private Pattern pattern;
private boolean isInverted = false;
public int executeCommand(CommandContext context) {
int index = 0;
int flags = 0;
while (index + 1 < context.getArgumentCount()) {
if ("-i".equals(context.getArgument(index))) {
flags |= Pattern.CASE_INSENSITIVE;
} else if ("-v".equals(context.getArgument(index))) {
isInverted = true;
} else {
context.err.println("unknown option: " + context.getArgument(index));
return 1;
}
index++;
}
out = context.out;
pattern = Pattern.compile(context.getArgument(index), flags);
return 0;
}
public void lineRead(String line) {
boolean isMatch = pattern.matcher(line).find();
if(isMatch ^ isInverted) {
out.println(line);
}
}
});
handler.registerCommand("timestamp", new BasicLineCommand("print lines with timestamp prefixed", "") {
private PrintStream out;
private MSP430 cpu;
long startTime;
public int executeCommand(CommandContext context) {
cpu = (MSP430) registry.getComponent(MSP430.class);
if (cpu == null) {
context.err.println("could not access the CPU.");
return 1;
}
out = context.out;
startTime = System.currentTimeMillis() - (long)cpu.getTimeMillis();
return 0;
}
public void lineRead(String line) {
out.println(Long.toString(startTime + (long)cpu.getTimeMillis()) + ' ' + line);
}
});
handler.registerCommand("speed", new BasicCommand("set the speed factor for the CPU", "[factor]") {
public int executeCommand(CommandContext context) {
MSP430 cpu = (MSP430) registry.getComponent(MSP430.class);
if (cpu == null) {
context.err.println("could not access the CPU.");
return 1;
} else if (context.getArgumentCount() == 0) {
long rate = cpu.getSleepRate();
double d = rate / 25000.0;
context.out.println("Speed factor is set to " + (((int)(d * 100 + 0.5)) / 100.0));
} else {
double d = context.getArgumentAsDouble(0);
if (d > 0.0) {
long rate = (long) (25000 * d);
cpu.setSleepRate(rate);
} else {
context.err.println("Speed factor must be larger than zero.");
return 1;
}
}
return 0;
}
});
handler.registerCommand("echo", new BasicCommand("echo arguments", "") {
public int executeCommand(CommandContext context) {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = context.getArgumentCount(); i < n; i++) {
if (i > 0) sb.append(' ');
sb.append(context.getArgument(i));
}
context.out.println(sb.toString());
return 0;
}
});
handler.registerCommand("source", new BasicCommand("run script", "[-v] <filename>") {
public int executeCommand(CommandContext context) {
boolean verbose = false;
if (context.getArgumentCount() > 1) {
verbose = "-v".equals(context.getArgument(0));
}
File fp = new File(context.getArgument(context.getArgumentCount() - 1));
if (!fp.canRead()) {
context.err.println("could not find the script file '" + context.getArgument(0) + "'.");
return 1;
}
try {
FileInputStream infs = new FileInputStream(fp);
BufferedReader input = new BufferedReader(new InputStreamReader(infs));
try {
String line;
while ((line = input.readLine()) != null) {
if (verbose) context.out.println(line);
context.executeCommand(line);
}
} finally {
input.close();
}
} catch (IOException e) {
e.printStackTrace(context.err);
return 1;
}
return 0;
}
});
handler.registerCommand("repeat", new BasicAsyncCommand("repeat the specified command line", "[-t delay] [-c count] <command line>") {
private MSP430 cpu;
private int period = 1;
private int count = 0;
private int maxCount = -1;
private String commandLine;
private boolean isRunning = true;
public int executeCommand(final CommandContext context) {
int index = 0;
do {
String a = context.getArgument(index);
if (a.startsWith("-")) {
if (a.equals("-t")) {
period = context.getArgumentAsInt(index + 1);
index += 2;
} else if (a.equals("-c")) {
maxCount = context.getArgumentAsInt(index + 1);
index += 2;
} else {
context.err.println("illegal option: " + a);
return 1;
}
} else {
break;
}
} while (true);
if (index + 1 < context.getArgumentCount()) {
context.err.println("too many arguments");
return 1;
}
commandLine = context.getArgument(index);
cpu = (MSP430) registry.getComponent(MSP430.class);
if (cpu == null) {
context.err.println("could not access the CPU.");
return 1;
}
cpu.scheduleTimeEventMillis(new TimeEvent(0) {
@Override
public void execute(long t) {
if (isRunning) {
count++;
context.executeCommand(commandLine);
if ((maxCount <= 0) || (count < maxCount)) {
cpu.scheduleTimeEventMillis(this, period * 1000d);
} else {
stopCommand(context);
}
}
}
}, period * 1000d);
return 0;
}
public void stopCommand(CommandContext context) {
isRunning = false;
context.err.println("[repeat exit: " + commandLine + ']');
context.exit(0);
}
});
handler.registerCommand("exec", new ExecCommand());
handler.registerCommand("trig", new BasicLineCommand("trigg command when input match regexp", "<command>") {
String command = null;
CommandContext context;
public int executeCommand(CommandContext context) {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = context.getArgumentCount(); i < n; i++) {
if (i > 0) sb.append(' ');
sb.append(context.getArgument(i));
}
command = sb.toString();
this.context = context;
return 0;
}
public void lineRead(String line) {
context.executeCommand(command);
}
});
handler.registerCommand("install", new BasicCommand("install and start a plugin", "ClassName [Name]") {
@Override
public int executeCommand(CommandContext context) {
String className = context.getArgument(0);
String name = className;
if (context.getArgumentCount() > 1) {
name = context.getArgument(1);
}
if (registry.getComponent(name) != null) {
context.err.println("Another component with name " + name + " is already installed");
return 1;
}
Class pluginClass = null;
PluginRepository plugins = (PluginRepository) registry.getComponent("pluginRepository");
try {
try {
pluginClass = plugins != null ? plugins.loadClass(className) :
Class.forName(className);
} catch (ClassNotFoundException e) {
String newClassName = "se.sics.mspsim.plugin." + className;
pluginClass = plugins != null ? plugins.loadClass(newClassName) :
Class.forName(newClassName);
}
Object component = pluginClass.newInstance();
registry.registerComponent(name, component);
return 0;
} catch (Exception e1) {
e1.printStackTrace(context.err);
}
// TODO Auto-generated method stub
return 1;
}
});
handler.registerCommand("service", new BasicCommand("handle service plugins", "[class name|service name] [start|stop]") {
@Override
public int executeCommand(CommandContext context) {
if (context.getArgumentCount() == 0) {
ServiceComponent[] sc = (ServiceComponent[]) registry.getAllComponents(ServiceComponent.class);
for (int i = 0; i < sc.length; i++) {
context.out.printf(" %-20s %s\n",sc[i].getName(),sc[i].getStatus());
}
} else if (context.getArgumentCount() == 1){
String name = context.getArgument(0);
ServiceComponent sc = getServiceForName(registry, name);
if (sc != null) {
context.out.printf(" %-20s %s\n",sc.getName(),sc.getStatus());
} else {
context.out.println("can not find service" + name);
}
} else {
String name = context.getArgument(0);
String operation = context.getArgument(1);
if ("start".equals(operation)) {
ServiceComponent sc = getServiceForName(registry, name);
if (sc != null) {
sc.start();
context.out.println("service " + sc.getName() + " started");
} else {
context.out.println("can not find service" + name);
}
} else if ("stop".equals(operation)) {
ServiceComponent sc = getServiceForName(registry, name);
if (sc != null) {
sc.stop();
context.out.println("service " + sc.getName() + " stopped");
} else {
context.out.println("can not find service" + name);
}
}
}
return 0;
}
});
handler.registerCommand("rflistener", new BasicLineCommand("an rflisteer", "[input|output] <rf-chip>") {
CommandContext context;
RFListener listener;
final MSP430 cpu = (MSP430) registry.getComponent(MSP430.class);
public int executeCommand(CommandContext ctx) {
this.context = ctx;
String inout = context.getArgument(0);
Chip chip = cpu.getChip(context.getArgument(1));
if ("output".equals(inout)) {
if (chip instanceof RFSource) {
((RFSource)chip).setRFListener(new RFListener(){
public void receivedByte(byte data) {
context.out.println("" + Utils.hex8(data));
}
});
}
} else if ("input".equals(inout)){
listener = (RFListener) chip;
} else {
context.err.println("Error: illegal type: " + inout);
}
return 0;
}
public void lineRead(String line) {
if (listener != null) {
byte[] data = Utils.hexconv(line);
context.out.println("Should send bytes to radio: " + line);
for (int i = 0; i < data.length; i++) {
//context.out.println("Byte " + i + " = " + ((int) data[i] & 0xff));
listener.receivedByte(data[i]);
}
}
}
});
handler.registerCommand("sysinfo", new BasicCommand("show info about the MSPSim system", "[-registry]") {
public int executeCommand(CommandContext context) {
ArgumentManager config = (ArgumentManager) registry.getComponent("config");
context.out.println("--------- System info ----------\n");
context.out.println("MSPSim version: " + MSP430Constants.VERSION);
context.out.println("Java version : " + System.getProperty("java.version") + " " +
System.getProperty("java.vendor"));
context.out.println("Firmware : " + config.getProperty("firmwareFile"));
context.out.println("AutoloadScript: " + config.getProperty("autoloadScript"));
context.out.println();
if (context.getOption("registry")) {
context.out.println("--------- Registry info --------\n");
registry.printRegistry(context.out);
}
return 0;
}
});
handler.registerCommand("quit", new BasicCommand("exit MSPSim", "") {
public int executeCommand(CommandContext context) {
/* TODO: flush all files, etc.... */
System.exit(0);
return 0;
}
});
handler.registerCommand("exit", new BasicCommand("exit MSPSim", "") {
public int executeCommand(CommandContext context) {
System.exit(0);
return 0;
}
});
}
|
diff --git a/src/net/dkebnh/bukkit/FlatlandsBuilder/FlatlandsBuilder.java b/src/net/dkebnh/bukkit/FlatlandsBuilder/FlatlandsBuilder.java
index 83ad06a..a02e284 100644
--- a/src/net/dkebnh/bukkit/FlatlandsBuilder/FlatlandsBuilder.java
+++ b/src/net/dkebnh/bukkit/FlatlandsBuilder/FlatlandsBuilder.java
@@ -1,98 +1,98 @@
package net.dkebnh.bukkit.FlatlandsBuilder;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.java.JavaPlugin;
public class FlatlandsBuilder extends JavaPlugin {
protected FLBLogger log;
private File confFile;
public YamlConfiguration conf;
int height = 64;
String genMode = "grid2";
String block1 = "wool:15";
String block2 = "wool:7";
String block3 = "wool:8";
List<String> blacklist = Arrays.asList("lava","water","tnt","bedrock");
String worldname = "flatlands";
public void onEnable(){
File dFolder = getDataFolder();
if(!dFolder.exists()) dFolder.mkdirs();
confFile = new File(dFolder, "config.yml");
this.getServer().getWorldContainer();
if (confFile.exists()) {
conf = YamlConfiguration.loadConfiguration(confFile);
height = conf.getInt("global.defaults.height");
genMode = conf.getString("global.defaults.mode");
block1 = conf.getString("global.defaults.block1");
block2 = conf.getString("global.defaults.block2");
block3 = conf.getString("global.defaults.block3");
blacklist = conf.getStringList("global.blacklist");
if (conf.contains("worlds." + worldname)){
System.out.println(worldname + " exists in config, parsing settings");
}
String[] vars = new String[5];
vars[0] = "[FlatlandsBuilder] Default height is: " + Integer.toString(height);
vars[1] = "[FlatlandsBuilder] Default generation mode is: " + genMode;
vars[2] = "[FlatlandsBuilder] Default fill block is: " + block1;
vars[3] = "[FlatlandsBuilder] Default border 1 block is: " + block2;
- vars[4] = "[FlatlandsBuilder] Default border 2 block is: " + blacklist.get(0);
+ vars[4] = "[FlatlandsBuilder] Default border 2 block is: " + block3;
for(int s = 0; s < vars.length; s ++){
System.out.println(vars[s]);
}
}else{
conf = new YamlConfiguration();
conf.set("global.defaults.height", 64);
conf.set("global.defaults.mode", "grid2");
conf.set("global.defaults.block1", "wool:15");
conf.set("global.defaults.block2", "wool:7");
conf.set("global.defaults.block3", "wool:8");
conf.set("global.blacklist", blacklist);
conf.set("worlds.flatlands.height", 64);
conf.set("worlds.flatlands.mode", "grid2");
conf.set("worlds.flatlands.block1", "wool:15");
conf.set("worlds.flatlands.block2", "wool:7");
conf.set("worlds.flatlands.block3", "wool:8");
saveSettings();
}
this.log = new FLBLogger(this);
this.getCommand("flb").setExecutor(new FLBCommandExecutor(this));
}
public void onDisable(){
}
public boolean saveSettings() {
if (!confFile.exists()) {
confFile.getParentFile().mkdirs();
}try{
conf.save(confFile);
return true;
}catch (IOException e){
e.printStackTrace();
}
return false;
}
public ChunkGenerator getDefaultWorldGenerator(String worldName, String id){
return new FLBGenerator(id);
}
}
| true | true | public void onEnable(){
File dFolder = getDataFolder();
if(!dFolder.exists()) dFolder.mkdirs();
confFile = new File(dFolder, "config.yml");
this.getServer().getWorldContainer();
if (confFile.exists()) {
conf = YamlConfiguration.loadConfiguration(confFile);
height = conf.getInt("global.defaults.height");
genMode = conf.getString("global.defaults.mode");
block1 = conf.getString("global.defaults.block1");
block2 = conf.getString("global.defaults.block2");
block3 = conf.getString("global.defaults.block3");
blacklist = conf.getStringList("global.blacklist");
if (conf.contains("worlds." + worldname)){
System.out.println(worldname + " exists in config, parsing settings");
}
String[] vars = new String[5];
vars[0] = "[FlatlandsBuilder] Default height is: " + Integer.toString(height);
vars[1] = "[FlatlandsBuilder] Default generation mode is: " + genMode;
vars[2] = "[FlatlandsBuilder] Default fill block is: " + block1;
vars[3] = "[FlatlandsBuilder] Default border 1 block is: " + block2;
vars[4] = "[FlatlandsBuilder] Default border 2 block is: " + blacklist.get(0);
for(int s = 0; s < vars.length; s ++){
System.out.println(vars[s]);
}
}else{
conf = new YamlConfiguration();
conf.set("global.defaults.height", 64);
conf.set("global.defaults.mode", "grid2");
conf.set("global.defaults.block1", "wool:15");
conf.set("global.defaults.block2", "wool:7");
conf.set("global.defaults.block3", "wool:8");
conf.set("global.blacklist", blacklist);
conf.set("worlds.flatlands.height", 64);
conf.set("worlds.flatlands.mode", "grid2");
conf.set("worlds.flatlands.block1", "wool:15");
conf.set("worlds.flatlands.block2", "wool:7");
conf.set("worlds.flatlands.block3", "wool:8");
saveSettings();
}
this.log = new FLBLogger(this);
this.getCommand("flb").setExecutor(new FLBCommandExecutor(this));
}
| public void onEnable(){
File dFolder = getDataFolder();
if(!dFolder.exists()) dFolder.mkdirs();
confFile = new File(dFolder, "config.yml");
this.getServer().getWorldContainer();
if (confFile.exists()) {
conf = YamlConfiguration.loadConfiguration(confFile);
height = conf.getInt("global.defaults.height");
genMode = conf.getString("global.defaults.mode");
block1 = conf.getString("global.defaults.block1");
block2 = conf.getString("global.defaults.block2");
block3 = conf.getString("global.defaults.block3");
blacklist = conf.getStringList("global.blacklist");
if (conf.contains("worlds." + worldname)){
System.out.println(worldname + " exists in config, parsing settings");
}
String[] vars = new String[5];
vars[0] = "[FlatlandsBuilder] Default height is: " + Integer.toString(height);
vars[1] = "[FlatlandsBuilder] Default generation mode is: " + genMode;
vars[2] = "[FlatlandsBuilder] Default fill block is: " + block1;
vars[3] = "[FlatlandsBuilder] Default border 1 block is: " + block2;
vars[4] = "[FlatlandsBuilder] Default border 2 block is: " + block3;
for(int s = 0; s < vars.length; s ++){
System.out.println(vars[s]);
}
}else{
conf = new YamlConfiguration();
conf.set("global.defaults.height", 64);
conf.set("global.defaults.mode", "grid2");
conf.set("global.defaults.block1", "wool:15");
conf.set("global.defaults.block2", "wool:7");
conf.set("global.defaults.block3", "wool:8");
conf.set("global.blacklist", blacklist);
conf.set("worlds.flatlands.height", 64);
conf.set("worlds.flatlands.mode", "grid2");
conf.set("worlds.flatlands.block1", "wool:15");
conf.set("worlds.flatlands.block2", "wool:7");
conf.set("worlds.flatlands.block3", "wool:8");
saveSettings();
}
this.log = new FLBLogger(this);
this.getCommand("flb").setExecutor(new FLBCommandExecutor(this));
}
|
diff --git a/holmes-core/src/main/java/net/holmes/core/transport/session/SessionDaoImpl.java b/holmes-core/src/main/java/net/holmes/core/transport/session/SessionDaoImpl.java
index 7e9f4065..124a0aae 100644
--- a/holmes-core/src/main/java/net/holmes/core/transport/session/SessionDaoImpl.java
+++ b/holmes-core/src/main/java/net/holmes/core/transport/session/SessionDaoImpl.java
@@ -1,85 +1,85 @@
/*
* Copyright (C) 2012-2013 Cedric Cheneau
*
* 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 net.holmes.core.transport.session;
import com.google.common.collect.Maps;
import java.util.Map;
import static net.holmes.core.transport.session.SessionStatus.WAITING;
/**
* Streaming session DAO implementation.
*/
public class SessionDaoImpl implements SessionDao {
private final Map<String, StreamingSession> sessions;
/**
* Instantiates a new streaming session DAO implementation.
*/
public SessionDaoImpl() {
this.sessions = Maps.newConcurrentMap();
}
@Override
public void initSession(final String deviceId, final String contentUrl, final String contentName) {
StreamingSession session = new StreamingSession();
session.setContentUrl(contentUrl);
session.setContentName(contentName);
session.setStatus(WAITING);
session.setPosition(0l);
session.setDuration(0l);
sessions.put(deviceId, session);
}
@Override
public void updateSessionStatus(final String deviceId, final SessionStatus status) throws UnknownSessionException {
StreamingSession session = getSession(deviceId);
session.setStatus(status);
}
@Override
public void updateSessionPosition(final String deviceId, final Long position, final Long duration) throws UnknownSessionException {
StreamingSession session = getSession(deviceId);
// If duration is already set and end of streaming is reached, update session's status
- if (session.getDuration() > 0 && (position.equals(duration) || duration == 0))
+ if (session.getDuration() > 0 && (position >= duration || duration == 0))
session.setStatus(WAITING);
// Update position and duration
session.setPosition(position);
session.setDuration(duration);
}
@Override
public void removeDevice(final String deviceId) {
sessions.remove(deviceId);
}
@Override
public StreamingSession getSession(final String deviceId) throws UnknownSessionException {
StreamingSession session = sessions.get(deviceId);
if (session == null) throw new UnknownSessionException(deviceId);
return session;
}
@Override
public Map<String, StreamingSession> getSessions() {
return sessions;
}
}
| true | true | public void updateSessionPosition(final String deviceId, final Long position, final Long duration) throws UnknownSessionException {
StreamingSession session = getSession(deviceId);
// If duration is already set and end of streaming is reached, update session's status
if (session.getDuration() > 0 && (position.equals(duration) || duration == 0))
session.setStatus(WAITING);
// Update position and duration
session.setPosition(position);
session.setDuration(duration);
}
| public void updateSessionPosition(final String deviceId, final Long position, final Long duration) throws UnknownSessionException {
StreamingSession session = getSession(deviceId);
// If duration is already set and end of streaming is reached, update session's status
if (session.getDuration() > 0 && (position >= duration || duration == 0))
session.setStatus(WAITING);
// Update position and duration
session.setPosition(position);
session.setDuration(duration);
}
|
diff --git a/plugins/org.eclipse.tm.tcf.debug/src/org/eclipse/tm/internal/tcf/debug/tests/TestExpressions.java b/plugins/org.eclipse.tm.tcf.debug/src/org/eclipse/tm/internal/tcf/debug/tests/TestExpressions.java
index e638b7106..c5ad02ab5 100644
--- a/plugins/org.eclipse.tm.tcf.debug/src/org/eclipse/tm/internal/tcf/debug/tests/TestExpressions.java
+++ b/plugins/org.eclipse.tm.tcf.debug/src/org/eclipse/tm/internal/tcf/debug/tests/TestExpressions.java
@@ -1,594 +1,600 @@
/*******************************************************************************
* Copyright (c) 2008, 2010 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tm.internal.tcf.debug.tests;
import java.math.BigInteger;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.tm.tcf.protocol.IChannel;
import org.eclipse.tm.tcf.protocol.IErrorReport;
import org.eclipse.tm.tcf.protocol.IToken;
import org.eclipse.tm.tcf.protocol.Protocol;
import org.eclipse.tm.tcf.services.IBreakpoints;
import org.eclipse.tm.tcf.services.IDiagnostics;
import org.eclipse.tm.tcf.services.IExpressions;
import org.eclipse.tm.tcf.services.IRunControl;
import org.eclipse.tm.tcf.services.IStackTrace;
import org.eclipse.tm.tcf.services.ISymbols;
class TestExpressions implements ITCFTest,
IRunControl.RunControlListener, IExpressions.ExpressionsListener, IBreakpoints.BreakpointsListener {
private final TCFTestSuite test_suite;
private final IDiagnostics diag;
private final IExpressions expr;
private final ISymbols syms;
private final IStackTrace stk;
private final IRunControl rc;
private final IBreakpoints bp;
private String bp_id;
private boolean bp_ok;
private IDiagnostics.ISymbol sym_func3;
private String test_ctx_id;
private String process_id;
private String thread_id;
private boolean test_done;
private IRunControl.RunControlContext test_ctx;
private IRunControl.RunControlContext thread_ctx;
private String suspended_pc;
private boolean waiting_suspend;
private String[] stack_trace;
private IStackTrace.StackTraceContext[] stack_frames;
private String[] local_vars;
private final HashMap<String,IRunControl.RunControlContext> ctx_map = new HashMap<String,IRunControl.RunControlContext>();
private final Map<String,IExpressions.Expression> expr_ctx = new HashMap<String,IExpressions.Expression>();
private final Map<String,IExpressions.Value> expr_val = new HashMap<String,IExpressions.Value>();
private final Map<String,ISymbols.Symbol> expr_sym = new HashMap<String,ISymbols.Symbol>();
private final Map<String,String[]> expr_chld = new HashMap<String,String[]>();
private static String[] test_expressions = {
"func2_local1",
"func2_local2",
"func2_local3",
"func2_local1 == func2_local1",
"func2_local1 != func2_local2",
"1.34 == 1.34",
"1.34 != 1.35",
"1 ? 1 : 0",
"!func2_local1 ? 0 : 1",
"(0 || 0) == 0",
"(0 || func2_local1) == 1",
"(func2_local1 || 0) == 1",
"(func2_local1 || func2_local1) == 1",
"(0 && 0) == 0",
"(0 && func2_local1) == 0",
"(func2_local1 && 0) == 0",
"(func2_local1 && func2_local1) == 1",
"(func2_local1 | func2_local2) == 3",
"(func2_local1 & func2_local2) == 0",
"(func2_local1 ^ func2_local2) == 3",
"(func2_local1 < func2_local2)",
"(func2_local1 <= func2_local2)",
"!(func2_local1 > func2_local2)",
"!(func2_local1 >= func2_local2)",
"(func2_local1 < 1.1)",
"(func2_local1 <= 1.1)",
"!(func2_local1 > 1.1)",
"!(func2_local1 >= 1.1)",
"(func2_local2 << 2) == 8",
"(func2_local2 >> 1) == 1",
"+func2_local2 == 2",
"-func2_local2 == -2",
"(short)(int)(long)((char *)func2_local2 + 1) == 3",
"((func2_local1 + func2_local2) * 2 - 2) / 2 == 2",
"func2_local3.f_struct->f_struct->f_struct == &func2_local3"
};
TestExpressions(TCFTestSuite test_suite, IChannel channel) {
this.test_suite = test_suite;
diag = channel.getRemoteService(IDiagnostics.class);
expr = channel.getRemoteService(IExpressions.class);
syms = channel.getRemoteService(ISymbols.class);
stk = channel.getRemoteService(IStackTrace.class);
rc = channel.getRemoteService(IRunControl.class);
bp = channel.getRemoteService(IBreakpoints.class);
}
public void start() {
if (diag == null || expr == null || stk == null || rc == null || bp == null) {
test_suite.done(this, null);
}
else {
expr.addListener(this);
rc.addListener(this);
bp.addListener(this);
diag.getTestList(new IDiagnostics.DoneGetTestList() {
public void doneGetTestList(IToken token, Throwable error, String[] list) {
if (!test_suite.isActive(TestExpressions.this)) return;
if (error != null) {
exit(error);
}
else {
for (int i = 0; i < list.length; i++) {
if (list[i].equals("RCBP1")) {
runTest();
Protocol.invokeLater(1000, new Runnable() {
int cnt = 0;
public void run() {
if (!test_suite.isActive(TestExpressions.this)) return;
cnt++;
if (cnt < 60) {
Protocol.invokeLater(1000, this);
}
else if (test_suite.cancel) {
exit(null);
}
else {
exit(new Error("Missing 'contextRemoved' event for " + test_ctx_id));
}
}
});
return;
}
}
exit(null);
}
}
});
}
}
@SuppressWarnings("unchecked")
private void runTest() {
if (bp_id == null) {
bp.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_id = "TestExpressionsBP";
runTest();
}
}
});
return;
}
if (!bp_ok) {
Map<String,Object> m = new HashMap<String,Object>();
m.put(IBreakpoints.PROP_ID, bp_id);
m.put(IBreakpoints.PROP_ENABLED, Boolean.TRUE);
m.put(IBreakpoints.PROP_LOCATION, "tcf_test_func3");
bp.set(new Map[]{ m }, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_ok = true;
runTest();
}
}
});
return;
}
if (test_ctx_id == null) {
diag.runTest("RCBP1", new IDiagnostics.DoneRunTest() {
public void doneRunTest(IToken token, Throwable error, String id) {
if (error != null) {
exit(error);
}
+ else if (id == null) {
+ exit(new Exception("Test context ID must not be null"));
+ }
else {
test_ctx_id = id;
runTest();
}
}
});
return;
}
if (test_ctx == null) {
rc.getContext(test_ctx_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Invalid test execution context"));
}
else {
test_ctx = ctx;
process_id = test_ctx.getProcessID();
if (!process_id.equals(test_ctx_id)) {
thread_id = test_ctx_id;
}
runTest();
}
}
});
return;
}
if (thread_id == null) {
rc.getChildren(process_id, new IRunControl.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] ids) {
if (error != null) {
exit(error);
}
else if (ids == null || ids.length == 0) {
exit(new Exception("Test process has no threads"));
}
else if (ids.length != 1) {
exit(new Exception("Test process has too many threads"));
}
else {
thread_id = ids[0];
runTest();
}
}
});
return;
}
if (thread_ctx == null) {
rc.getContext(thread_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null || !ctx.hasState()) {
exit(new Exception("Invalid thread context"));
}
else {
thread_ctx = ctx;
runTest();
}
}
});
return;
}
if (suspended_pc == null) {
thread_ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error,
boolean suspended, String pc, String reason,
Map<String,Object> params) {
if (error != null) {
exit(error);
}
else if (suspended) {
suspended_pc = pc;
runTest();
}
else {
waiting_suspend = true;
}
}
});
return;
}
if (sym_func3 == null) {
diag.getSymbol(process_id, "tcf_test_func3", new IDiagnostics.DoneGetSymbol() {
public void doneGetSymbol(IToken token, Throwable error, IDiagnostics.ISymbol symbol) {
if (error != null) {
exit(error);
}
+ else if (symbol == null) {
+ exit(new Exception("Symbol must not be null: tcf_test_func3"));
+ }
else {
sym_func3 = symbol;
runTest();
}
}
});
return;
}
BigInteger pc0 = new BigInteger(sym_func3.getValue().toString());
BigInteger pc1 = new BigInteger(suspended_pc);
if (!pc0.equals(pc1)) {
suspended_pc = null;
waiting_suspend = true;
thread_ctx.resume(IRunControl.RM_RESUME, 1, new IRunControl.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) exit(error);
}
});
return;
}
if (stack_trace == null) {
stk.getChildren(thread_id, new IStackTrace.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else {
stack_trace = context_ids;
if (stack_trace == null || stack_trace.length < 2) {
exit(new Exception("Invalid stack trace"));
}
else {
runTest();
}
}
}
});
return;
}
if (stack_frames == null) {
stk.getContext(stack_trace, new IStackTrace.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IStackTrace.StackTraceContext[] frames) {
if (error != null) {
exit(error);
}
else {
stack_frames = frames;
if (stack_frames == null || stack_frames.length != stack_trace.length) {
exit(new Exception("Invalid stack trace"));
}
else {
runTest();
}
}
}
});
return;
}
if (local_vars == null) {
expr.getChildren(stack_trace[stack_trace.length - 2], new IExpressions.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
// Need to continue tests even if local variables info is not available.
// TODO: need to distinguish absence of debug info from other errors.
local_vars = new String[0];
runTest();
}
else {
local_vars = context_ids;
runTest();
}
}
});
return;
}
for (final String id : local_vars) {
if (expr_ctx.get(id) == null) {
expr.getContext(id, new IExpressions.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_ctx.put(id, ctx);
runTest();
}
}
});
return;
}
}
for (final String txt : test_expressions) {
if (local_vars.length == 0 && txt.indexOf("local") >= 0) continue;
if (expr_ctx.get(txt) == null) {
expr.create(stack_trace[stack_trace.length - 2], null, txt, new IExpressions.DoneCreate() {
public void doneCreate(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_ctx.put(txt, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : local_vars) {
if (expr_val.get(id) == null) {
expr.evaluate(id, new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : expr_ctx.keySet()) {
if (expr_val.get(id) == null) {
expr.evaluate(expr_ctx.get(id).getID(), new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
byte[] arr = ctx.getValue();
boolean b = false;
for (byte x : arr) {
if (x != 0) b = true;
}
if (!b) exit(new Exception("Invalid value of expression \"" + id + "\""));
runTest();
}
}
});
return;
}
}
if (syms != null) {
for (final String id : expr_val.keySet()) {
if (expr_sym.get(id) == null) {
IExpressions.Value v = expr_val.get(id);
String type_id = v.getTypeID();
if (type_id != null) {
syms.getContext(type_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, ISymbols.Symbol ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Symbol.getContext returned null"));
}
else {
expr_sym.put(id, ctx);
runTest();
}
}
});
return;
}
}
}
for (final String id : expr_sym.keySet()) {
if (expr_chld.get(id) == null) {
ISymbols.Symbol sym = expr_sym.get(id);
syms.getChildren(sym.getID(), new ISymbols.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else {
if (context_ids == null) context_ids = new String[0];
expr_chld.put(id, context_ids);
runTest();
}
}
});
return;
}
}
}
test_done = true;
diag.cancelTest(test_ctx_id, new IDiagnostics.DoneCancelTest() {
public void doneCancelTest(IToken token, Throwable error) {
if (error != null) exit(error);
}
});
}
private void exit(Throwable x) {
if (!test_suite.isActive(this)) return;
expr.removeListener(this);
bp.removeListener(this);
rc.removeListener(this);
test_suite.done(this, x);
}
//--------------------------- Run Control listener ---------------------------//
public void containerResumed(String[] context_ids) {
}
public void containerSuspended(String context, String pc, String reason,
Map<String,Object> params, String[] suspended_ids) {
for (String id : suspended_ids) {
assert id != null;
contextSuspended(id, null, null, null);
}
}
public void contextAdded(IRunControl.RunControlContext[] contexts) {
for (IRunControl.RunControlContext ctx : contexts) {
if (ctx_map.get(ctx.getID()) != null) exit(new Error("Invalid 'contextAdded' event"));
ctx_map.put(ctx.getID(), ctx);
}
}
public void contextChanged(IRunControl.RunControlContext[] contexts) {
for (IRunControl.RunControlContext ctx : contexts) {
if (ctx_map.get(ctx.getID()) == null) return;
ctx_map.put(ctx.getID(), ctx);
}
}
public void contextException(String context, String msg) {
}
public void contextRemoved(String[] context_ids) {
for (String id : context_ids) {
ctx_map.remove(id);
if (id.equals(test_ctx_id)) {
if (test_done) {
bp.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
exit(error);
}
});
}
else {
exit(new Exception("Test process exited too soon"));
}
return;
}
}
}
public void contextResumed(String context) {
}
public void contextSuspended(String context, String pc, String reason, Map<String,Object> params) {
if (context.equals(thread_id)) {
suspended_pc = pc;
if (waiting_suspend) {
waiting_suspend = false;
runTest();
}
}
if (test_done) {
IRunControl.RunControlContext ctx = ctx_map.get(context);
if (ctx != null && process_id != null && process_id.equals(ctx.getParentID())) {
ctx.resume(IRunControl.RM_RESUME, 1, new IRunControl.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error instanceof IErrorReport) {
int code = ((IErrorReport)error).getErrorCode();
if (code == IErrorReport.TCF_ERROR_ALREADY_RUNNING) return;
if (code == IErrorReport.TCF_ERROR_INV_CONTEXT) return;
}
if (error != null) exit(error);
}
});
}
}
}
//--------------------------- Expressions listener ---------------------------//
public void valueChanged(String id) {
}
//--------------------------- Breakpoints listener ---------------------------//
@SuppressWarnings("unchecked")
public void breakpointStatusChanged(String id, Map<String,Object> status) {
if (id.equals(bp_id) && process_id != null) {
String s = (String)status.get(IBreakpoints.STATUS_ERROR);
if (s != null) exit(new Exception("Invalid BP status: " + s));
Collection<Map<String,Object>> list = (Collection<Map<String,Object>>)status.get(IBreakpoints.STATUS_INSTANCES);
if (list == null) return;
String err = null;
for (Map<String,Object> map : list) {
String ctx = (String)map.get(IBreakpoints.INSTANCE_CONTEXT);
if (process_id.equals(ctx) && map.get(IBreakpoints.INSTANCE_ERROR) != null)
err = (String)map.get(IBreakpoints.INSTANCE_ERROR);
}
if (err != null) exit(new Exception("Invalid BP status: " + err));
}
}
public void contextAdded(Map<String,Object>[] bps) {
}
public void contextChanged(Map<String,Object>[] bps) {
}
}
| false | true | private void runTest() {
if (bp_id == null) {
bp.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_id = "TestExpressionsBP";
runTest();
}
}
});
return;
}
if (!bp_ok) {
Map<String,Object> m = new HashMap<String,Object>();
m.put(IBreakpoints.PROP_ID, bp_id);
m.put(IBreakpoints.PROP_ENABLED, Boolean.TRUE);
m.put(IBreakpoints.PROP_LOCATION, "tcf_test_func3");
bp.set(new Map[]{ m }, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_ok = true;
runTest();
}
}
});
return;
}
if (test_ctx_id == null) {
diag.runTest("RCBP1", new IDiagnostics.DoneRunTest() {
public void doneRunTest(IToken token, Throwable error, String id) {
if (error != null) {
exit(error);
}
else {
test_ctx_id = id;
runTest();
}
}
});
return;
}
if (test_ctx == null) {
rc.getContext(test_ctx_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Invalid test execution context"));
}
else {
test_ctx = ctx;
process_id = test_ctx.getProcessID();
if (!process_id.equals(test_ctx_id)) {
thread_id = test_ctx_id;
}
runTest();
}
}
});
return;
}
if (thread_id == null) {
rc.getChildren(process_id, new IRunControl.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] ids) {
if (error != null) {
exit(error);
}
else if (ids == null || ids.length == 0) {
exit(new Exception("Test process has no threads"));
}
else if (ids.length != 1) {
exit(new Exception("Test process has too many threads"));
}
else {
thread_id = ids[0];
runTest();
}
}
});
return;
}
if (thread_ctx == null) {
rc.getContext(thread_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null || !ctx.hasState()) {
exit(new Exception("Invalid thread context"));
}
else {
thread_ctx = ctx;
runTest();
}
}
});
return;
}
if (suspended_pc == null) {
thread_ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error,
boolean suspended, String pc, String reason,
Map<String,Object> params) {
if (error != null) {
exit(error);
}
else if (suspended) {
suspended_pc = pc;
runTest();
}
else {
waiting_suspend = true;
}
}
});
return;
}
if (sym_func3 == null) {
diag.getSymbol(process_id, "tcf_test_func3", new IDiagnostics.DoneGetSymbol() {
public void doneGetSymbol(IToken token, Throwable error, IDiagnostics.ISymbol symbol) {
if (error != null) {
exit(error);
}
else {
sym_func3 = symbol;
runTest();
}
}
});
return;
}
BigInteger pc0 = new BigInteger(sym_func3.getValue().toString());
BigInteger pc1 = new BigInteger(suspended_pc);
if (!pc0.equals(pc1)) {
suspended_pc = null;
waiting_suspend = true;
thread_ctx.resume(IRunControl.RM_RESUME, 1, new IRunControl.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) exit(error);
}
});
return;
}
if (stack_trace == null) {
stk.getChildren(thread_id, new IStackTrace.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else {
stack_trace = context_ids;
if (stack_trace == null || stack_trace.length < 2) {
exit(new Exception("Invalid stack trace"));
}
else {
runTest();
}
}
}
});
return;
}
if (stack_frames == null) {
stk.getContext(stack_trace, new IStackTrace.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IStackTrace.StackTraceContext[] frames) {
if (error != null) {
exit(error);
}
else {
stack_frames = frames;
if (stack_frames == null || stack_frames.length != stack_trace.length) {
exit(new Exception("Invalid stack trace"));
}
else {
runTest();
}
}
}
});
return;
}
if (local_vars == null) {
expr.getChildren(stack_trace[stack_trace.length - 2], new IExpressions.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
// Need to continue tests even if local variables info is not available.
// TODO: need to distinguish absence of debug info from other errors.
local_vars = new String[0];
runTest();
}
else {
local_vars = context_ids;
runTest();
}
}
});
return;
}
for (final String id : local_vars) {
if (expr_ctx.get(id) == null) {
expr.getContext(id, new IExpressions.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_ctx.put(id, ctx);
runTest();
}
}
});
return;
}
}
for (final String txt : test_expressions) {
if (local_vars.length == 0 && txt.indexOf("local") >= 0) continue;
if (expr_ctx.get(txt) == null) {
expr.create(stack_trace[stack_trace.length - 2], null, txt, new IExpressions.DoneCreate() {
public void doneCreate(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_ctx.put(txt, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : local_vars) {
if (expr_val.get(id) == null) {
expr.evaluate(id, new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : expr_ctx.keySet()) {
if (expr_val.get(id) == null) {
expr.evaluate(expr_ctx.get(id).getID(), new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
byte[] arr = ctx.getValue();
boolean b = false;
for (byte x : arr) {
if (x != 0) b = true;
}
if (!b) exit(new Exception("Invalid value of expression \"" + id + "\""));
runTest();
}
}
});
return;
}
}
if (syms != null) {
for (final String id : expr_val.keySet()) {
if (expr_sym.get(id) == null) {
IExpressions.Value v = expr_val.get(id);
String type_id = v.getTypeID();
if (type_id != null) {
syms.getContext(type_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, ISymbols.Symbol ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Symbol.getContext returned null"));
}
else {
expr_sym.put(id, ctx);
runTest();
}
}
});
return;
}
}
}
for (final String id : expr_sym.keySet()) {
if (expr_chld.get(id) == null) {
ISymbols.Symbol sym = expr_sym.get(id);
syms.getChildren(sym.getID(), new ISymbols.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else {
if (context_ids == null) context_ids = new String[0];
expr_chld.put(id, context_ids);
runTest();
}
}
});
return;
}
}
}
test_done = true;
diag.cancelTest(test_ctx_id, new IDiagnostics.DoneCancelTest() {
public void doneCancelTest(IToken token, Throwable error) {
if (error != null) exit(error);
}
});
}
| private void runTest() {
if (bp_id == null) {
bp.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_id = "TestExpressionsBP";
runTest();
}
}
});
return;
}
if (!bp_ok) {
Map<String,Object> m = new HashMap<String,Object>();
m.put(IBreakpoints.PROP_ID, bp_id);
m.put(IBreakpoints.PROP_ENABLED, Boolean.TRUE);
m.put(IBreakpoints.PROP_LOCATION, "tcf_test_func3");
bp.set(new Map[]{ m }, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
bp_ok = true;
runTest();
}
}
});
return;
}
if (test_ctx_id == null) {
diag.runTest("RCBP1", new IDiagnostics.DoneRunTest() {
public void doneRunTest(IToken token, Throwable error, String id) {
if (error != null) {
exit(error);
}
else if (id == null) {
exit(new Exception("Test context ID must not be null"));
}
else {
test_ctx_id = id;
runTest();
}
}
});
return;
}
if (test_ctx == null) {
rc.getContext(test_ctx_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Invalid test execution context"));
}
else {
test_ctx = ctx;
process_id = test_ctx.getProcessID();
if (!process_id.equals(test_ctx_id)) {
thread_id = test_ctx_id;
}
runTest();
}
}
});
return;
}
if (thread_id == null) {
rc.getChildren(process_id, new IRunControl.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] ids) {
if (error != null) {
exit(error);
}
else if (ids == null || ids.length == 0) {
exit(new Exception("Test process has no threads"));
}
else if (ids.length != 1) {
exit(new Exception("Test process has too many threads"));
}
else {
thread_id = ids[0];
runTest();
}
}
});
return;
}
if (thread_ctx == null) {
rc.getContext(thread_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null || !ctx.hasState()) {
exit(new Exception("Invalid thread context"));
}
else {
thread_ctx = ctx;
runTest();
}
}
});
return;
}
if (suspended_pc == null) {
thread_ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error,
boolean suspended, String pc, String reason,
Map<String,Object> params) {
if (error != null) {
exit(error);
}
else if (suspended) {
suspended_pc = pc;
runTest();
}
else {
waiting_suspend = true;
}
}
});
return;
}
if (sym_func3 == null) {
diag.getSymbol(process_id, "tcf_test_func3", new IDiagnostics.DoneGetSymbol() {
public void doneGetSymbol(IToken token, Throwable error, IDiagnostics.ISymbol symbol) {
if (error != null) {
exit(error);
}
else if (symbol == null) {
exit(new Exception("Symbol must not be null: tcf_test_func3"));
}
else {
sym_func3 = symbol;
runTest();
}
}
});
return;
}
BigInteger pc0 = new BigInteger(sym_func3.getValue().toString());
BigInteger pc1 = new BigInteger(suspended_pc);
if (!pc0.equals(pc1)) {
suspended_pc = null;
waiting_suspend = true;
thread_ctx.resume(IRunControl.RM_RESUME, 1, new IRunControl.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) exit(error);
}
});
return;
}
if (stack_trace == null) {
stk.getChildren(thread_id, new IStackTrace.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else {
stack_trace = context_ids;
if (stack_trace == null || stack_trace.length < 2) {
exit(new Exception("Invalid stack trace"));
}
else {
runTest();
}
}
}
});
return;
}
if (stack_frames == null) {
stk.getContext(stack_trace, new IStackTrace.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IStackTrace.StackTraceContext[] frames) {
if (error != null) {
exit(error);
}
else {
stack_frames = frames;
if (stack_frames == null || stack_frames.length != stack_trace.length) {
exit(new Exception("Invalid stack trace"));
}
else {
runTest();
}
}
}
});
return;
}
if (local_vars == null) {
expr.getChildren(stack_trace[stack_trace.length - 2], new IExpressions.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
// Need to continue tests even if local variables info is not available.
// TODO: need to distinguish absence of debug info from other errors.
local_vars = new String[0];
runTest();
}
else {
local_vars = context_ids;
runTest();
}
}
});
return;
}
for (final String id : local_vars) {
if (expr_ctx.get(id) == null) {
expr.getContext(id, new IExpressions.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_ctx.put(id, ctx);
runTest();
}
}
});
return;
}
}
for (final String txt : test_expressions) {
if (local_vars.length == 0 && txt.indexOf("local") >= 0) continue;
if (expr_ctx.get(txt) == null) {
expr.create(stack_trace[stack_trace.length - 2], null, txt, new IExpressions.DoneCreate() {
public void doneCreate(IToken token, Exception error, IExpressions.Expression ctx) {
if (error != null) {
exit(error);
}
else {
expr_ctx.put(txt, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : local_vars) {
if (expr_val.get(id) == null) {
expr.evaluate(id, new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
runTest();
}
}
});
return;
}
}
for (final String id : expr_ctx.keySet()) {
if (expr_val.get(id) == null) {
expr.evaluate(expr_ctx.get(id).getID(), new IExpressions.DoneEvaluate() {
public void doneEvaluate(IToken token, Exception error, IExpressions.Value ctx) {
if (error != null) {
exit(error);
}
else {
expr_val.put(id, ctx);
byte[] arr = ctx.getValue();
boolean b = false;
for (byte x : arr) {
if (x != 0) b = true;
}
if (!b) exit(new Exception("Invalid value of expression \"" + id + "\""));
runTest();
}
}
});
return;
}
}
if (syms != null) {
for (final String id : expr_val.keySet()) {
if (expr_sym.get(id) == null) {
IExpressions.Value v = expr_val.get(id);
String type_id = v.getTypeID();
if (type_id != null) {
syms.getContext(type_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, ISymbols.Symbol ctx) {
if (error != null) {
exit(error);
}
else if (ctx == null) {
exit(new Exception("Symbol.getContext returned null"));
}
else {
expr_sym.put(id, ctx);
runTest();
}
}
});
return;
}
}
}
for (final String id : expr_sym.keySet()) {
if (expr_chld.get(id) == null) {
ISymbols.Symbol sym = expr_sym.get(id);
syms.getChildren(sym.getID(), new ISymbols.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error != null) {
exit(error);
}
else {
if (context_ids == null) context_ids = new String[0];
expr_chld.put(id, context_ids);
runTest();
}
}
});
return;
}
}
}
test_done = true;
diag.cancelTest(test_ctx_id, new IDiagnostics.DoneCancelTest() {
public void doneCancelTest(IToken token, Throwable error) {
if (error != null) exit(error);
}
});
}
|
diff --git a/src/test/java/com/od/filtertable/TestTableModelIndexer.java b/src/test/java/com/od/filtertable/TestTableModelIndexer.java
index db541eb..44857c0 100644
--- a/src/test/java/com/od/filtertable/TestTableModelIndexer.java
+++ b/src/test/java/com/od/filtertable/TestTableModelIndexer.java
@@ -1,404 +1,404 @@
/**
* Copyright (C) Nick Ebbutt September 2009
*
* This file is part of ObjectDefinitions Ltd. FilterTable.
* [email protected]
* http://www.objectdefinitions.com/filtertable
*
* FilterTable 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.
*
* ObjectDefinitions Ltd. FilterTable 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 ObjectDefinitions Ltd. FilterTable.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.od.filtertable;
import java.util.*;
import com.od.filtertable.TableModelIndexer;
import com.od.filtertable.MutableTableCell;
/**
* Created by IntelliJ IDEA.
* User: Nick Ebbutt
* Date: 02-Sep-2008
* Time: 16:04:04
*/
public class TestTableModelIndexer extends AbstractFilteredTableTest {
private static final int IT_Strips_match_count = 128;
private static final int IT_Strips_last_row_matching = 447;
private static final int IT_Strips_first_row_matching = 142;
private static final String IT_STRIPS = "IT_Strips";
public TestTableModelIndexer() {
super("/test1.csv");
}
public void testIndexing() {
long start = System.currentTimeMillis();
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 1);
System.out.println("Indexing took " + (System.currentTimeMillis() - start) + " millis");
testRowIndexes(indexer);
start = System.currentTimeMillis();
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
System.out.println("Find took " + (System.currentTimeMillis() - start) + " millis");
start = System.currentTimeMillis();
indexer.getCellsContaining(IT_STRIPS);
System.out.println("Find took " + (System.currentTimeMillis() - start) + " millis");
cells = indexer.getCellsContaining("1Aug2013");
assertEquals(4, cells.size());
}
public void testReindexCells() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 0);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
//now change the value in 10 of those 128 cells so that it no longer matches, and reindex the cells
MutableTableCell[] cellArray = cells.toArray(new MutableTableCell[IT_Strips_match_count]);
String newValue = "wibble";
for ( int loop=0; loop < 10; loop ++ ) {
testTableModel.setValueAt(newValue, cellArray[loop].getRow(), cellArray[loop].getCol());
indexer.reIndexCell(cellArray[loop].getRow(), cellArray[loop].getCol());
//note that after reindexing, the value stored in the MutableTableCell instance has been updated to reflect the
//new value in the TableModel. The old value previously cached in MutableTableCell was used during the reIndex
//operation, to remove the old MutableTableCell references from the index, before reindexing with the new value
assertEquals(newValue, cellArray[loop].getValue());
}
cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count - 10, cells.size());
}
public void testInsertRow() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 1);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
int lastMatchingRow = getLastRow(cells);
assertEquals(IT_Strips_last_row_matching, lastMatchingRow);
//now copy a row which matched the query and insert it near the start
ArrayList<Object> newRow = (ArrayList<Object>)testTableModel.getRow(lastMatchingRow).clone();
testTableModel.insertRow(10, newRow);
indexer.insertRows(10, 10);
testRowIndexes(indexer);
cells = indexer.getCellsContaining(IT_STRIPS);
//there should now be one more cell which matches since we copied a row with a match
assertEquals(IT_Strips_match_count + 1, cells.size());
//the last matching row should now be shifted down one by the insert
lastMatchingRow = getLastRow(cells);
assertEquals(IT_Strips_last_row_matching + 1, lastMatchingRow);
}
public void testInsertRows() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 2);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
int lastMatchingRow = getLastRow(cells);
assertEquals(IT_Strips_last_row_matching, lastMatchingRow);
//now copy a row which matched the query and insert it near the start
ArrayList<Object> newRow = (ArrayList<Object>)testTableModel.getRow(lastMatchingRow).clone();
ArrayList<Object> newRow2 = (ArrayList<Object>)testTableModel.getRow(lastMatchingRow).clone();
testTableModel.insertRow(10, newRow);
testTableModel.insertRow(11, newRow2);
indexer.insertRows(10, 11);
testRowIndexes(indexer);
cells = indexer.getCellsContaining(IT_STRIPS);
//there should now be one more cell which matches since we copied a row with a match
assertEquals(IT_Strips_match_count + 2, cells.size());
//the last matching row should now be shifted down one by the insert
lastMatchingRow = getLastRow(cells);
assertEquals(IT_Strips_last_row_matching + 2, lastMatchingRow);
}
/**
* The indexer is like java.util.ArrayList in the way it manages its capacity
* the available capacity is maintained usually in excess of the actual required size.
* When enough inserts take place to exceed current capacity the internal arrays are resized to a new capacity
* This is more efficient than resizing the arrays on each insert
*/
public void testEnsureCapacity() {
FixtureTableModel tableModel = readTableModel("/testEnsureCapacity.csv");
TableModelIndexer indexer = new TableModelIndexer(tableModel, 1);
assertEquals(2, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 1);
- assertEquals(4, indexer.tableCells.length);
+ assertEquals(5, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 1);
- assertEquals(7, indexer.tableCells.length);
+ assertEquals(5, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 2);
- assertEquals(11, indexer.tableCells.length);
+ assertEquals(13, indexer.tableCells.length);
for (int loop=0; loop < 20; loop++ ) {
tableModel.insertRows(0, (ArrayList<Object>)tableModel.getRow(0).clone()
);
}
//the table is growing to more than ((capacity*3)/2)+1 so the next capacity is the total new rows
indexer.insertRows(0, 19);
- assertEquals(28, indexer.tableCells.length);
+ assertEquals(43, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 0);
assertEquals(43, indexer.tableCells.length);
}
public void testRemoveRow() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 1);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
int firstMatchingRow = getFirstRow(cells);
int lastMatchingRow = getLastRow(cells);
assertEquals(IT_Strips_first_row_matching, firstMatchingRow);
assertEquals(IT_Strips_last_row_matching, lastMatchingRow);
testTableModel.removeRows(IT_Strips_first_row_matching, IT_Strips_first_row_matching);
indexer.removeRows(IT_Strips_first_row_matching, IT_Strips_first_row_matching);
testRowIndexes(indexer);
cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count - 1, cells.size());
//the last matching row should now be shifted down one by the insert
lastMatchingRow = getLastRow(cells);
assertEquals(IT_Strips_last_row_matching - 1, lastMatchingRow);
}
public void testRemoveRows() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 1);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
int firstMatchingRow = getFirstRow(cells);
int lastMatchingRow = getLastRow(cells);
assertEquals(IT_Strips_first_row_matching, firstMatchingRow);
assertEquals(IT_Strips_last_row_matching, lastMatchingRow);
assertNotNull(indexer.tableCells[453][0]);
assertNotNull(indexer.tableCells[452][0]);
testTableModel.removeRows(IT_Strips_first_row_matching, IT_Strips_first_row_matching + 1);
indexer.removeRows(IT_Strips_first_row_matching, IT_Strips_first_row_matching + 1);
assertNull(indexer.tableCells[453][0]);
assertNull(indexer.tableCells[452][0]); //ensure references to cells are cleared when array reduces
testRowIndexes(indexer);
cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count - 1, cells.size()); //one of the two rows removed did not match
//the last matching row should now be shifted down one by the insert
lastMatchingRow = getLastRow(cells);
assertEquals(IT_Strips_last_row_matching-2, lastMatchingRow);
}
public void testExcludeFromFilterFormatterByColumnName() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 0);
indexer.setFormatter(FilterFormatter.EXCLUDE_FROM_FILTER_INDEX, "2");
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(0, cells.size());
clearFormattersAndCheckRowCount(indexer);
}
public void testExcludeFromFilterFormatterByColumnIndex() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 1);
indexer.setFormatter(FilterFormatter.EXCLUDE_FROM_FILTER_INDEX, 2);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(0, cells.size());
clearFormattersAndCheckRowCount(indexer);
}
public void testExcludeFromFilterFormatterByColumnClass() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 1);
indexer.setFormatter(FilterFormatter.EXCLUDE_FROM_FILTER_INDEX, String.class);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(0, cells.size());
clearFormattersAndCheckRowCount(indexer);
}
public void testIndexTrimmingDoesNotAffectSearch() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 2);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
indexer.trimIndexToInitialDepth();
cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
}
//when the column structure is changed it renders the formatters by index
//meaningless so they should get cleared down
public void testFormattersByIndexClearedWhenTableStructureChanged() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 1);
indexer.setFormatter(FilterFormatter.EXCLUDE_FROM_FILTER_INDEX, 2);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(0, cells.size());
indexer.tableStructureChanged();
cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
indexer.setFormatter(FilterFormatter.EXCLUDE_FROM_FILTER_INDEX, 2);
cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(0, cells.size());
indexer.setTableModel(testTableModel);
cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
}
public void testFormattersByNameAndClassNotClearedWhenTableStructureChanged() {
TableModelIndexer indexer = new TableModelIndexer(testTableModel, 1);
indexer.setFormatter(FilterFormatter.EXCLUDE_FROM_FILTER_INDEX, "2");
indexer.setFormatter(FilterFormatter.EXCLUDE_FROM_FILTER_INDEX, String.class);
Collection<MutableTableCell> cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(0, cells.size());
indexer.tableStructureChanged();
indexer.setTableModel(testTableModel);
cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(0, cells.size());
}
public void testSetOfRowIndexesInstanceNotChangedIfUpdateDoesNotAffectFilteredView() {
FixtureTableModel tableModel = readTableModel("/filteredTableTestData.csv");
TableModelIndexer indexer = new TableModelIndexer(tableModel, 1);
Map<MutableRowIndex, TreeSet<Integer>> tableCollsByRow = indexer.getCellsContaining("string4").getRowColumnMap();
tableModel.setValueAt("wibble", 8, 1);
indexer.reIndexCell(8, 1);
assertTrue(tableCollsByRow == indexer.getCellsContaining("string4").getRowColumnMap());
}
public void testSetOfRowIndexesInstanceChangedIfUpdateCausesNewRowToPassFilters() {
FixtureTableModel tableModel = readTableModel("/filteredTableTestData.csv");
TableModelIndexer indexer = new TableModelIndexer(tableModel, 1);
Map<MutableRowIndex, TreeSet<Integer>> colsByRow = indexer.getCellsContaining("string4").getRowColumnMap();
tableModel.setValueAt("string4", 8, 1);
indexer.reIndexCell(8, 1);
assertFalse(colsByRow == indexer.getCellsContaining("string4").getRowColumnMap());
}
public void testSetOfRowIndexesInstanceChangedIfUpdateCausesOldRowToFailFilters() {
FixtureTableModel tableModel = readTableModel("/filteredTableTestData.csv");
TableModelIndexer indexer = new TableModelIndexer(tableModel, 1);
Map<MutableRowIndex, TreeSet<Integer>> colsByRow = indexer.getCellsContaining("string4").getRowColumnMap();
tableModel.setValueAt("string5", 9, 1);
indexer.reIndexCell(9, 1);
assertFalse(colsByRow == indexer.getCellsContaining("string4").getRowColumnMap());
}
public void testSetOfRowIndexesInstanceUnChangedButMutableRowIndexValuesChangedOnInsertOfNewRowWhichFailsFilters() {
FixtureTableModel tableModel = readTableModel("/filteredTableTestData.csv");
TableModelIndexer indexer = new TableModelIndexer(tableModel, 1);
Map<MutableRowIndex, TreeSet<Integer>> colsByRow = indexer.getCellsContaining("string4").getRowColumnMap();
Set<Integer> rowsIndexesInOldFilterView = getRowSet(colsByRow);
tableModel.insertRow(1, new ArrayList<Object>(Arrays.asList(new String[] {"wibble", "wibble"})));
indexer.insertRows(1,1);
Map<MutableRowIndex, TreeSet<Integer>> newColsByRow = indexer.getCellsContaining("string4").getRowColumnMap();
Set<Integer> rowsIndexesInNewFilterView = getRowSet(newColsByRow);
assertTrue(colsByRow == newColsByRow);
assertTrue(rowsIndexesInOldFilterView.contains(9));
assertTrue(rowsIndexesInOldFilterView.contains(11));
assertTrue(rowsIndexesInNewFilterView.contains(10));
assertTrue(rowsIndexesInNewFilterView.contains(12));
}
public void testSetOfRowIndexesInstanceUnChangedButMutableRowIndexValuesChangedOnDeleteOfNewRowWhichFailsFilters() {
FixtureTableModel tableModel = readTableModel("/filteredTableTestData.csv");
TableModelIndexer indexer = new TableModelIndexer(tableModel, 1);
Map<MutableRowIndex, TreeSet<Integer>> colsByRow = indexer.getCellsContaining("string4").getRowColumnMap();
Set<Integer> rowsIndexesInOldFilterView = getRowSet(colsByRow);
tableModel.removeRow(1); tableModel.removeRow(2);
indexer.removeRows(1,2);
Map<MutableRowIndex, TreeSet<Integer>> newColsByRow = indexer.getCellsContaining("string4").getRowColumnMap();
Set<Integer> rowsIndexesInNewFilterView = getRowSet(newColsByRow);
assertTrue(colsByRow == newColsByRow);
assertTrue(rowsIndexesInOldFilterView.contains(9));
assertTrue(rowsIndexesInOldFilterView.contains(11));
assertTrue(rowsIndexesInNewFilterView.contains(7));
assertTrue(rowsIndexesInNewFilterView.contains(9));
}
public void testSetOfRowIndexesInstanceChangedAndMutableRowIndexValuesChangedOnDeleteOfRowWhichUsedToPassFilters() {
FixtureTableModel tableModel = readTableModel("/filteredTableTestData.csv");
TableModelIndexer indexer = new TableModelIndexer(tableModel, 1);
Map<MutableRowIndex, TreeSet<Integer>> colsByRow = indexer.getCellsContaining("string4").getRowColumnMap();
Set<Integer> rowsIndexesInOldFilterView = getRowSet(colsByRow);
tableModel.removeRow(9); tableModel.removeRow(9);
indexer.removeRows(9,10);
Map<MutableRowIndex, TreeSet<Integer>> newColsByRow = indexer.getCellsContaining("string4").getRowColumnMap();
Set<Integer> rowsIndexesInNewFilterView = getRowSet(newColsByRow);
assertTrue(colsByRow != newColsByRow);
assertTrue(rowsIndexesInOldFilterView.contains(9));
assertTrue(rowsIndexesInOldFilterView.contains(11));
assertEquals(1, rowsIndexesInNewFilterView.size());
assertTrue(rowsIndexesInNewFilterView.contains(9));
}
private Set<Integer> getRowSet(Map<MutableRowIndex, TreeSet<Integer>> tableRows) {
HashSet<Integer> rows = new HashSet<Integer>();
for (MutableRowIndex i : tableRows.keySet() ) {
rows.add(i.index);
}
return rows;
}
private void clearFormattersAndCheckRowCount(TableModelIndexer indexer) {
Collection<MutableTableCell> cells;
indexer.clearFormatters();
cells = indexer.getCellsContaining(IT_STRIPS);
assertEquals(IT_Strips_match_count, cells.size());
}
/**
* test that after each operation we end up with the correct row indexes in the table cells array
*/
private void testRowIndexes(TableModelIndexer tableModelIndexer) {
for ( int loop=0; loop < tableModelIndexer.size; loop++) {
assertEquals(loop, tableModelIndexer.tableCells[loop][0].getRow());
}
}
}
| false | true | public void testEnsureCapacity() {
FixtureTableModel tableModel = readTableModel("/testEnsureCapacity.csv");
TableModelIndexer indexer = new TableModelIndexer(tableModel, 1);
assertEquals(2, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 1);
assertEquals(4, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 1);
assertEquals(7, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 2);
assertEquals(11, indexer.tableCells.length);
for (int loop=0; loop < 20; loop++ ) {
tableModel.insertRows(0, (ArrayList<Object>)tableModel.getRow(0).clone()
);
}
//the table is growing to more than ((capacity*3)/2)+1 so the next capacity is the total new rows
indexer.insertRows(0, 19);
assertEquals(28, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 0);
assertEquals(43, indexer.tableCells.length);
}
| public void testEnsureCapacity() {
FixtureTableModel tableModel = readTableModel("/testEnsureCapacity.csv");
TableModelIndexer indexer = new TableModelIndexer(tableModel, 1);
assertEquals(2, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 1);
assertEquals(5, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 1);
assertEquals(5, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone(),
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 2);
assertEquals(13, indexer.tableCells.length);
for (int loop=0; loop < 20; loop++ ) {
tableModel.insertRows(0, (ArrayList<Object>)tableModel.getRow(0).clone()
);
}
//the table is growing to more than ((capacity*3)/2)+1 so the next capacity is the total new rows
indexer.insertRows(0, 19);
assertEquals(43, indexer.tableCells.length);
tableModel.insertRows(0,
(ArrayList<Object>)tableModel.getRow(0).clone()
);
indexer.insertRows(0, 0);
assertEquals(43, indexer.tableCells.length);
}
|
diff --git a/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/util/FurnaceHelper.java b/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/util/FurnaceHelper.java
index a3b49ebf..b085a667 100644
--- a/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/util/FurnaceHelper.java
+++ b/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/util/FurnaceHelper.java
@@ -1,63 +1,63 @@
package org.jboss.tools.forge.ui.ext.util;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.jboss.tools.forge.core.process.ForgeRuntime;
import org.jboss.tools.forge.ext.core.runtime.FurnaceRuntime;
public class FurnaceHelper {
public static void startFurnace() {
final ForgeRuntime runtime = FurnaceRuntime.INSTANCE;
if (runtime == null || ForgeRuntime.STATE_RUNNING.equals(runtime.getState())) return;
createStartFurnaceJob().schedule();
}
public static void stopFurnace() {
final ForgeRuntime runtime = FurnaceRuntime.INSTANCE;
if (runtime == null || ForgeRuntime.STATE_NOT_RUNNING.equals(runtime.getState())) return;
Job job = new Job("Stopping Forge " + runtime.getVersion()) {
@Override
protected IStatus run(IProgressMonitor monitor) {
runtime.stop(monitor);
return Status.OK_STATUS;
}
};
job.schedule();
}
public static Job createStartFurnaceJob() {
final FurnaceRuntime runtime = FurnaceRuntime.INSTANCE;
final String version = runtime.getVersion();
- WorkspaceJob job = new WorkspaceJob("Starting Forge" + version) {
+ WorkspaceJob job = new WorkspaceJob("Starting Forge " + version) {
@Override
public IStatus runInWorkspace(IProgressMonitor monitor)
throws CoreException {
String taskName = "Please wait while Forge " + version + " is started.";
monitor.beginTask(taskName, IProgressMonitor.UNKNOWN);
runtime.start(monitor);
if (runtime.getErrorMessage() != null) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openError(
null,
"Forge Startup Error",
runtime.getErrorMessage());
}
});
}
return Status.OK_STATUS;
}
};
job.setUser(true);
return job;
}
}
| true | true | public static Job createStartFurnaceJob() {
final FurnaceRuntime runtime = FurnaceRuntime.INSTANCE;
final String version = runtime.getVersion();
WorkspaceJob job = new WorkspaceJob("Starting Forge" + version) {
@Override
public IStatus runInWorkspace(IProgressMonitor monitor)
throws CoreException {
String taskName = "Please wait while Forge " + version + " is started.";
monitor.beginTask(taskName, IProgressMonitor.UNKNOWN);
runtime.start(monitor);
if (runtime.getErrorMessage() != null) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openError(
null,
"Forge Startup Error",
runtime.getErrorMessage());
}
});
}
return Status.OK_STATUS;
}
};
job.setUser(true);
return job;
}
| public static Job createStartFurnaceJob() {
final FurnaceRuntime runtime = FurnaceRuntime.INSTANCE;
final String version = runtime.getVersion();
WorkspaceJob job = new WorkspaceJob("Starting Forge " + version) {
@Override
public IStatus runInWorkspace(IProgressMonitor monitor)
throws CoreException {
String taskName = "Please wait while Forge " + version + " is started.";
monitor.beginTask(taskName, IProgressMonitor.UNKNOWN);
runtime.start(monitor);
if (runtime.getErrorMessage() != null) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openError(
null,
"Forge Startup Error",
runtime.getErrorMessage());
}
});
}
return Status.OK_STATUS;
}
};
job.setUser(true);
return job;
}
|
diff --git a/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java b/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java
index a74701d..a412703 100644
--- a/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java
+++ b/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java
@@ -1,996 +1,1000 @@
package org.agmip.translators.dssat;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import org.agmip.core.types.AdvancedHashMap;
/**
* DSSAT Experiment Data I/O API Class
*
* @author Meng Zhang
* @version 1.0
*/
public class DssatXFileInput extends DssatCommonInput {
/**
* Constructor with no parameters
* Set jsonKey as "experiment"
*
*/
public DssatXFileInput() {
super();
jsonKey = "experiment";
}
/**
* DSSAT XFile Data input method for Controller using
*
* @param brMap The holder for BufferReader objects for all files
* @return result data holder object
*/
@Override
protected AdvancedHashMap readFile(HashMap brMap) throws IOException {
AdvancedHashMap ret = new AdvancedHashMap();
String line;
BufferedReader br;
char[] buf;
BufferedReader brw = null;
char[] bufW = null;
HashMap mapW;
String wid;
String fileName;
LinkedHashMap formats = new LinkedHashMap();
ArrayList trArr = new ArrayList();
ArrayList cuArr = new ArrayList();
ArrayList flArr = new ArrayList();
ArrayList saArr = new ArrayList();
ArrayList sadArr = new ArrayList();
ArrayList icArr = new ArrayList();
ArrayList icdArr = new ArrayList();
ArrayList plArr = new ArrayList();
ArrayList irArr = new ArrayList();
ArrayList irdArr = new ArrayList();
ArrayList feArr = new ArrayList();
ArrayList omArr = new ArrayList();
ArrayList chArr = new ArrayList();
ArrayList tiArr = new ArrayList();
ArrayList emArr = new ArrayList();
ArrayList haArr = new ArrayList();
ArrayList smArr = new ArrayList();
String eventKey = "data";
buf = (char[]) brMap.get("X");
mapW = (HashMap) brMap.get("W");
fileName = (String) brMap.get("Z");
wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName;
// If XFile is no been found
if (buf == null) {
// TODO reprot file not exist error
return ret;
} else {
br = new BufferedReader(new CharArrayReader(buf));
}
ret.put("treatment", trArr);
// ret.put("cultivar", cuArr);
// ret.put("field", flArr);
// ret.put("soil_analysis", saArr);
// ret.put("initial_condition", icArr);
// ret.put("plant", plArr);
// ret.put("irrigation", irArr);
// ret.put("fertilizer", feArr);
// ret.put("residue_organic", omArr);
// ret.put("chemical", chArr);
// ret.put("tillage", tiArr);
// ret.put("emvironment", emArr);
// ret.put("harvest", haArr);
// ret.put("simulation", smArr);
while ((line = br.readLine()) != null) {
// Get content type of line
judgeContentType(line);
// Read Exp title info
if (flg[0].startsWith("exp.details:") && flg[2].equals("")) {
// Set variables' formats
formats.clear();
formats.put("exname", 11);
formats.put("local_name", 61);
// Read line and save into return holder
ret.put(readLine(line.substring(13), formats));
ret.put("institutes", line.substring(14, 16).trim());
} // Read General Section
else if (flg[0].startsWith("general")) {
// People info
if (flg[1].equals("people") && flg[2].equals("data")) {
ret.put("people", line.trim());
} // Address info
else if (flg[1].equals("address") && flg[2].equals("data")) {
String[] addr = line.split(",[ ]*");
ret.put("fl_loc_1", "");
ret.put("fl_loc_2", "");
ret.put("fl_loc_3", "");
ret.put("institutes", line.trim());
// ret.put("address", line.trim()); // P.S. no longer to use this field
switch (addr.length) {
case 0:
break;
case 1:
ret.put("fl_loc_1", addr[0]);
break;
case 2:
ret.put("fl_loc_1", addr[1]);
ret.put("fl_loc_2", addr[0]);
break;
case 3:
ret.put("fl_loc_1", addr[2]);
ret.put("fl_loc_2", addr[1]);
ret.put("fl_loc_3", addr[0]);
break;
default:
ret.put("fl_loc_1", addr[addr.length - 1]);
ret.put("fl_loc_2", addr[addr.length - 2]);
String loc3 = "";
for (int i = 0; i < addr.length - 2; i++) {
loc3 += addr[i] + ", ";
}
ret.put("fl_loc_3", loc3.substring(0, loc3.length() - 2));
}
} // Site info
else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) {
//$ret[$flg[0]]["site"] = trim($line);
// P.S. site is missing in the master variables list
ret.put("site", line.trim());
} // Plot Info
else if (flg[1].startsWith("parea") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("parea", 7);
formats.put("prno", 6);
formats.put("plen", 6);
formats.put("pldr", 6);
formats.put("plsp", 6);
formats.put("play", 6);
formats.put("pltha", 6);
formats.put("hrno", 6);
formats.put("hlen", 6);
formats.put("plthm", 16);
// Read line and save into return holder
ret.put("plot_info", readLine(line, formats));
} // Notes field
else if (flg[1].equals("notes") && flg[2].equals("data")) {
//$ret[$flg[0]]["notes"] = addArray($ret[$flg[0]]["notes"], " ". trim($line), "");
if (!ret.containsKey("notes")) {
ret.put("notes", line.trim() + "\\r\\n");
} else {
String notes = (String) ret.get("notes");
notes += line.trim() + "\\r\\n";
ret.put("notes", notes);
}
} else {
}
} // Read TREATMENTS Section
else if (flg[0].startsWith("treatments")) {
// Read TREATMENTS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("trno", 2);
formats.put("sq", 2);
formats.put("op", 2);
formats.put("co", 2);
formats.put("tr_name", 26);
formats.put("ge", 3);
formats.put("fl", 3);
formats.put("sa", 3);
formats.put("ic", 3);
formats.put("pl", 3);
formats.put("ir", 3);
formats.put("fe", 3);
formats.put("om", 3);
formats.put("ch", 3);
formats.put("ti", 3);
formats.put("em", 3);
formats.put("ha", 3);
formats.put("sm", 3);
// Read line and save into return holder
trArr.add(readLine(line, formats));
} else {
}
} // Read CULTIVARS Section
else if (flg[0].startsWith("cultivars")) {
// Read CULTIVARS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ge", 2);
formats.put("cr", 3);
formats.put("cul_id", 7);
formats.put("cul_name", 17);
// Read line and save into return holder
cuArr.add(readLine(line, formats));
if (cuArr.size() == 1) {
ret.put("cr", line.substring(3, 5).trim()); // TODO keep for the early version; just first entry
}
} else {
}
} // Read FIELDS Section
else if (flg[0].startsWith("fields")) {
// Read field info 1st line
if (flg[1].startsWith("l id_") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("id_field", 9);
formats.put("wsta_id", 9); //P.S. id do not match with the master list "wth_id"; might have another id name
formats.put("flsl", 6);
formats.put("flob", 6);
formats.put("fl_drntype", 6);
formats.put("fldrd", 6);
formats.put("fldrs", 6);
formats.put("flst", 6);
formats.put("sltx", 6);
formats.put("sldp", 6);
formats.put("soil_id", 11);
formats.put("fl_name", line.length());
// Read line and save into return holder
addToArray(flArr, readLine(line, formats), "fl");
// Read weather station id
wid = line.substring(12, 20).trim();
}// // Read field info 2nd line
else if (flg[1].startsWith("l ...") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("fl_lat", 16);
formats.put("fl_long", 16);
formats.put("flele", 10);
formats.put("farea", 18);
formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields)
formats.put("fllwr", 6);
formats.put("flsla", 6);
formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code)
formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years)
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// Read lat and long
String strLat = (String) tmp.get("fl_lat");
String strLong = (String) tmp.get("fl_long");
// If lat or long is not valid data, read data from weather file
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
// check if weather is validable
for (Object key : mapW.keySet()) {
if (((String) key).contains(wid)) {
bufW = (char[]) mapW.get(key);
break;
}
}
if (bufW != null) {
brw = new BufferedReader(new CharArrayReader(bufW));
String lineW;
while ((lineW = brw.readLine()) != null) {
if (lineW.startsWith("@ INSI")) {
lineW = brw.readLine();
strLat = lineW.substring(6, 15).trim();
strLong = lineW.substring(15, 24).trim();
break;
}
}
// check if lat and long are valid in the weather file; if not, set invalid value for them
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
strLat = defValI;
strLong = defValI;
}
} // if weather file is not avaliable to read, set invalid value for lat and long
else {
strLat = defValI;
strLong = defValI;
}
}
if (flArr.isEmpty()) {
ret.put("fl_lat", strLat); // TODO Keep the meta data handling for the early version
ret.put("fl_long", strLong); // TODO Keep the meta data handling for the early version
}
tmp.put("fl_lat", strLat);
tmp.put("fl_long", strLong);
addToArray(flArr, tmp, "fl");
}
} // Read SOIL ANALYSIS Section
else if (flg[0].startsWith("soil")) {
// Read SOIL ANALYSIS global data
if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sa", 2);
formats.put("sadat", 6);
formats.put("samhb", 6);
formats.put("sampx", 6);
formats.put("samke", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("sadat", translateDateStr((String) tmp.get("sadat")));
saArr.add(tmp);
sadArr = new ArrayList();
tmp.put(eventKey, sadArr);
} // Read SOIL ANALYSIS layer data
else if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "sa"
formats.put("sabl", 6);
formats.put("sabdm", 6);
formats.put("saoc", 6);
formats.put("sani", 6);
formats.put("saphw", 6);
formats.put("saphb", 6);
formats.put("sapx", 6);
formats.put("sake", 6);
formats.put("sasc", 6); // P.S. id do not find in the master list (Measured stable organic C by soil layer, g[C]/100g[Soil])
// Read line and save into return holder
sadArr.add(readLine(line, formats));
} else {
}
} // Read INITIAL CONDITIONS Section
else if (flg[0].startsWith("initial")) {
// Read INITIAL CONDITIONS global data
if (flg[1].startsWith("c pcr") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ic", 2);
formats.put("icpcr", 6);
formats.put("icdat", 6);
formats.put("icrt", 6);
formats.put("icnd", 6);
formats.put("icrz#", 6); // P.S. use the "icrz#" instead of "icrzno"
formats.put("icrze", 6);
formats.put("icwt", 6);
formats.put("icrag", 6);
formats.put("icrn", 6);
formats.put("icrp", 6);
formats.put("icrip", 6);
formats.put("icrdp", 6);
formats.put("ic_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("icdat", translateDateStr((String) tmp.get("icdat")));
icArr.add(tmp);
icdArr = new ArrayList();
tmp.put(eventKey, icdArr);
} else // INITIAL CONDITIONS layer data
if (flg[1].startsWith("c icbl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the detail (event) data index "ic"
formats.put("icbl", 6);
formats.put("ich2o", 6);
formats.put("icnh4", 6);
formats.put("icno3", 6);
// Read line and save into return holder
icdArr.add(readLine(line, formats));
} else {
}
} // Read PLANTING DETAILS Section
else if (flg[0].startsWith("planting")) {
// Read PLANTING data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("pl", 2);
formats.put("pdate", 6);
formats.put("pldae", 6);
formats.put("plpop", 6);
formats.put("plpoe", 6);
formats.put("plme", 6);
formats.put("plds", 6);
formats.put("plrs", 6);
formats.put("plrd", 6);
formats.put("pldp", 6);
formats.put("plmwt", 6);
formats.put("page", 6);
formats.put("penv", 6);
formats.put("plph", 6);
formats.put("plspl", 6);
formats.put("pl_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("pdate", translateDateStr((String) tmp.get("pdate")));
tmp.put("pldae", translateDateStr((String) tmp.get("pldae")));
plArr.add(tmp);
if (plArr.size() == 1) {
ret.put("pdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for the early version
}
} else {
}
} // Read IRRIGATION AND WATER MANAGEMENT Section
else if (flg[0].startsWith("irrigation")) {
// Read IRRIGATION global data
if (flg[1].startsWith("i efir") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ir", 2);
formats.put("ireff", 6);
formats.put("irmdp", 6);
formats.put("irthr", 6);
formats.put("irept", 6);
formats.put("irstg", 6);
formats.put("iame", 6);
formats.put("iamt", 6);
formats.put("ir_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
irArr.add(tmp);
irdArr = new ArrayList();
tmp.put(eventKey, irdArr);
} // Read IRRIGATION appliction data
else if (flg[1].startsWith("i idate") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "ir"
formats.put("idate", 6);
formats.put("irop", 6);
formats.put("irval", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("idate", translateDateStr((String) tmp.get("idate"))); // TODO DOY handling
irdArr.add(tmp);
} else {
}
} // Read FERTILIZERS (INORGANIC) Section
else if (flg[0].startsWith("fertilizers")) {
// Read FERTILIZERS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fe", 2);
formats.put("fdate", 6);
formats.put("fecd", 6);
formats.put("feacd", 6);
formats.put("fedep", 6);
formats.put("feamn", 6);
formats.put("feamp", 6);
formats.put("feamk", 6);
formats.put("feamc", 6);
formats.put("feamo", 6);
formats.put("feocd", 6);
formats.put("fe_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("fdate", translateDateStr((String) tmp.get("fdate"))); // TODO DOY handling
feArr.add(tmp);
} else {
}
} // Read RESIDUES AND OTHER ORGANIC MATERIALS Section
else if (flg[0].startsWith("residues")) {
// Read ORGANIC MATERIALS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("om", 2);
formats.put("omdat", 6); // P.S. id do not match with the master list "omday"
formats.put("omcd", 6);
formats.put("omamt", 6);
formats.put("omn%", 6); // P.S. id do not match with the master list "omnpct"
formats.put("omp%", 6); // P.S. id do not match with the master list "omppct"
formats.put("omk%", 6); // P.S. id do not match with the master list "omkpct"
formats.put("ominp", 6);
formats.put("omdep", 6);
formats.put("omacd", 6);
formats.put("om_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("omdat", translateDateStr((String) tmp.get("omdat"))); // TODO DOY handling
omArr.add(tmp);
} else {
}
} // Read CHEMICAL APPLICATIONS Section
else if (flg[0].startsWith("chemical")) {
// Read CHEMICAL APPLICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ch", 2);
formats.put("cdate", 6);
formats.put("chcd", 6);
formats.put("chamt", 6);
formats.put("chacd", 6);
formats.put("chdep", 6);
formats.put("ch_targets", 6);
formats.put("ch_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("cdate", translateDateStr((String) tmp.get("cdate")));
chArr.add(tmp);
} else {
}
} // Read TILLAGE Section
else if (flg[0].startsWith("tillage")) {
// Read TILLAGE data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ti", 2);
formats.put("tdate", 6);
formats.put("tiimp", 6);
formats.put("tidep", 6);
formats.put("ti_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("tdate", translateDateStr((String) tmp.get("tdate")));
tiArr.add(tmp);
} else {
}
} // Read ENVIRONMENT MODIFICATIONS Section
else if (flg[0].startsWith("environment")) {
// Read ENVIRONMENT MODIFICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("em", 2);
formats.put("emday", 6);
formats.put("ecdyl", 2);
formats.put("emdyl", 4);
formats.put("ecrad", 2);
formats.put("emrad", 4);
formats.put("ecmax", 2);
formats.put("emmax", 4);
formats.put("ecmin", 2);
formats.put("emmin", 4);
formats.put("ecrai", 2);
formats.put("emrai", 4);
formats.put("ecco2", 2);
formats.put("emco2", 4);
formats.put("ecdew", 2);
formats.put("emdew", 4);
formats.put("ecwnd", 2);
formats.put("emwnd", 4);
formats.put("em_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("emday", translateDateStr((String) tmp.get("emday")));
emArr.add(tmp);
} else {
}
} // Read HARVEST DETAILS Section
else if (flg[0].startsWith("harvest")) {
// Read HARVEST data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ha", 2);
formats.put("hdate", 6);
formats.put("hastg", 6);
formats.put("hacom", 6);
formats.put("hasiz", 6);
formats.put("hapc", 6);
formats.put("habpc", 6);
formats.put("ha_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("hdate", translateDateStr((String) tmp.get("hdate")));
haArr.add(tmp);
if (haArr.size() == 1) {
ret.put("hdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for early version
}
} else {
}
} // Read SIMULATION CONTROLS Section // P.S. no need to be divided
else if (flg[0].startsWith("simulation")) {
// Read general info
if (flg[1].startsWith("n general") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("general", 12);
// formats.put("nyers", 6);
// formats.put("nreps", 6);
// formats.put("start", 6);
// formats.put("sdate", 6);
// formats.put("rseed", 6);
// formats.put("sname", 26);
// formats.put("model", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("sdate", translateDateStr((String) tmp.get("sdate")));
tmp.put("general", line);
addToArray(smArr, tmp, "sm");
} // Read options info
else if (flg[1].startsWith("n options") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("options", 12);
// formats.put("water", 6);
// formats.put("nitro", 6);
// formats.put("symbi", 6);
// formats.put("phosp", 6);
// formats.put("potas", 6);
// formats.put("dises", 6);
// formats.put("chem", 6);
// formats.put("till", 6);
// formats.put("co2", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("options", line);
addToArray(smArr, tmp, "sm");
} // Read methods info
else if (flg[1].startsWith("n methods") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("methods", 12);
// formats.put("wther", 6);
// formats.put("incon", 6);
// formats.put("light", 6);
// formats.put("evapo", 6);
// formats.put("infil", 6);
// formats.put("photo", 6);
// formats.put("hydro", 6);
// formats.put("nswit", 6);
// formats.put("mesom", 6);
// formats.put("mesev", 6);
// formats.put("mesol", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("methods", line);
addToArray(smArr, tmp, "sm");
} // Read management info
else if (flg[1].startsWith("n management") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("management", 12);
// formats.put("plant", 6);
// formats.put("irrig", 6);
// formats.put("ferti", 6);
// formats.put("resid", 6);
// formats.put("harvs", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("management", line);
addToArray(smArr, tmp, "sm");
} // Read outputs info
else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("outputs", 12);
// formats.put("fname", 6);
// formats.put("ovvew", 6);
// formats.put("sumry", 6);
// formats.put("fropt", 6);
// formats.put("grout", 6);
// formats.put("caout", 6);
// formats.put("waout", 6);
// formats.put("niout", 6);
// formats.put("miout", 6);
// formats.put("diout", 6);
// formats.put("long", 6);
// formats.put("chout", 6);
// formats.put("opout", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("outputs", line);
addToArray(smArr, tmp, "sm");
} // Read planting info
else if (flg[1].startsWith("n planting") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("planting", 12);
// formats.put("pfrst", 6);
// formats.put("plast", 6);
// formats.put("ph20l", 6);
// formats.put("ph2ou", 6);
// formats.put("ph20d", 6);
// formats.put("pstmx", 6);
// formats.put("pstmn", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("pfrst", translateDateStr((String) tmp.get("pfrst")));
// tmp.put("plast", translateDateStr((String) tmp.get("plast")));
tmp.put("planting", line);
addToArray(smArr, tmp, "sm");
} // Read irrigation info
else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("irrigation", 12);
// formats.put("imdep", 6);
// formats.put("ithrl", 6);
// formats.put("ithru", 6);
// formats.put("iroff", 6);
// formats.put("imeth", 6);
// formats.put("iramt", 6);
// formats.put("ireff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("irrigation", line);
addToArray(smArr, tmp, "sm");
} // Read nitrogen info
else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("nitrogen", 12);
// formats.put("nmdep", 6);
// formats.put("nmthr", 6);
// formats.put("namnt", 6);
// formats.put("ncode", 6);
// formats.put("naoff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("nitrogen", line);
addToArray(smArr, tmp, "sm");
} // Read residues info
else if (flg[1].startsWith("n residues") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("residues", 12);
// formats.put("ripcn", 6);
// formats.put("rtime", 6);
// formats.put("ridep", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("residues", line);
addToArray(smArr, tmp, "sm");
} // Read harvest info
else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("harvests", 12);
// formats.put("hfrst", 6); // P.S. Keep the original value
// formats.put("hlast", 6);
// formats.put("hpcnp", 6);
// formats.put("hrcnr", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("hlast", translateDateStr((String) tmp.get("hlast")));
tmp.put("harvests", line);
addToArray(smArr, tmp, "sm");
} else {
}
} else {
}
}
br.close();
if (brw != null) {
brw.close();
}
for (int i = 0; i < trArr.size(); i++) {
AdvancedHashMap treatment = (AdvancedHashMap) trArr.get(i);
// cultivar
if (!treatment.getOr("ge", "0").equals("0")) {
treatment.put("cultivar", getSectionData(cuArr, "ge", treatment.get("ge").toString()));
}
// field
if (!treatment.getOr("fl", "0").equals("0")) {
treatment.put("field", getSectionData(flArr, "fl", treatment.get("fl").toString()));
}
// soil_analysis
if (!treatment.getOr("sa", "0").equals("0")) {
treatment.put("soil_analysis", getSectionData(saArr, "sa", treatment.get("sa").toString()));
}
// initial_condition
if (!treatment.getOr("ic", "0").equals("0")) {
treatment.put("initial_condition", getSectionData(icArr, "ic", treatment.get("ic").toString()));
}
// plant
if (!treatment.getOr("pl", "0").equals("0")) {
treatment.put("plant", getSectionData(plArr, "pl", treatment.get("pl").toString()));
}
// irrigation
if (!treatment.getOr("ir", "0").equals("0")) {
treatment.put("irrigation", getSectionData(irArr, "ir", treatment.get("ir").toString()));
}
// fertilizer
if (!treatment.getOr("fe", "0").equals("0")) {
treatment.put("fertilizer", getSectionData(feArr, "fe", treatment.get("fe").toString()));
}
// residue_organic
if (!treatment.getOr("om", "0").equals("0")) {
treatment.put("residue_organic", getSectionData(omArr, "om", treatment.get("om").toString()));
}
// chemical
if (!treatment.getOr("ch", "0").equals("0")) {
treatment.put("chemical", getSectionData(chArr, "ch", treatment.get("ch").toString()));
}
// tillage
if (!treatment.getOr("ti", "0").equals("0")) {
treatment.put("tillage", getSectionData(tiArr, "ti", treatment.get("ti").toString()));
}
// emvironment
if (!treatment.getOr("em", "0").equals("0")) {
treatment.put("emvironment", getSectionData(emArr, "em", treatment.get("em").toString()));
}
// harvest
if (!treatment.getOr("ha", "0").equals("0")) {
treatment.put("harvest", getSectionData(haArr, "ha", treatment.get("ha").toString()));
}
// simulation
if (!treatment.getOr("sm", "0").equals("0")) {
treatment.put("simulation", getSectionData(smArr, "sm", treatment.get("sm").toString()));
}
// Revise the date value for FEDATE, IDATE, MLADAT
// Get Planting date
String pdate = "";
ArrayList plTmps = (ArrayList) treatment.getOr("planting", new ArrayList());
if (!plTmps.isEmpty()) {
pdate = (String) ((AdvancedHashMap) plTmps.get(0)).getOr("pdate", "");
if (pdate.length() > 5) {
pdate = pdate.substring(2);
}
}
// Fertilizer Date
ArrayList feTmps = (ArrayList) treatment.getOr("fertilizer", new ArrayList());
AdvancedHashMap feTmp;
for (int j = 0; j < feTmps.size(); j++) {
feTmp = (AdvancedHashMap) feTmps.get(j);
feTmp.put("fdate", translateDateStrForDOY((String) feTmp.get("fdate"), pdate));
}
- // Initial condition date
- AdvancedHashMap icTmp = (AdvancedHashMap) treatment.get("initial_condition");
- if (icTmp != null) {
- icTmp.put("idate", translateDateStrForDOY((String) icTmp.getOr("idate", defValI), pdate));
+ // Irrigation date
+ AdvancedHashMap irTmp = (AdvancedHashMap) treatment.get("irrigation");
+ if (irTmp != null) {
+ ArrayList irTmpSubs = (ArrayList) irTmp.getOr("data", new ArrayList());
+ for (int j = 0; j < irTmpSubs.size(); j++) {
+ AdvancedHashMap irTmpSub = (AdvancedHashMap) irTmpSubs.get(j);
+ irTmpSub.put("idate", translateDateStrForDOY((String) irTmpSub.getOr("idate", defValI), pdate));
+ }
}
// Mulch application date
ArrayList omTmps = (ArrayList) treatment.getOr("residue_organic", new ArrayList());
AdvancedHashMap omTmp;
for (int j = 0; j < omTmps.size(); j++) {
omTmp = (AdvancedHashMap) omTmps.get(j);
omTmp.put("omdat", translateDateStrForDOY((String) omTmp.get("omdat"), pdate));
}
}
compressData(ret);
return ret;
}
/**
* Set reading flgs for title lines (marked with *)
*
* @param line the string of reading line
*/
@Override
protected void setTitleFlgs(String line) {
flg[0] = line.substring(1).trim().toLowerCase();
flg[1] = "";
flg[2] = "";
}
/**
* Get the section data by given index value and key
*
* @param secArr Section data array
* @param key index variable name
* @param value index variable value
*/
private Object getSectionData(ArrayList secArr, Object key, String value) {
ArrayList ret = null;
// Get First data node
if (secArr.isEmpty()) {
return null;
}
// Define the section with single sub data
ArrayList singleSubRecSecList = new ArrayList();
singleSubRecSecList.add("ge");
singleSubRecSecList.add("fl");
singleSubRecSecList.add("pl");
// singleSubRecSecList.add("om"); // P.S. wait for confirmation that single sub record
// singleSubRecSecList.add("ti"); // P.S. wait for confirmation that single sub record
singleSubRecSecList.add("sm");
AdvancedHashMap fstNode = (AdvancedHashMap) secArr.get(0);
// If it contains multiple sub array of data, or it does not have multiple sub records
if (fstNode.containsKey("data") || singleSubRecSecList.contains(key)) {
for (int i = 0; i < secArr.size(); i++) {
if (((AdvancedHashMap) secArr.get(i)).get(key).equals(value)) {
return CopyMap((AdvancedHashMap) secArr.get(i));
}
}
} // If it is simple array
else {
ret = new ArrayList();
AdvancedHashMap node;
for (int i = 0; i < secArr.size(); i++) {
node = (AdvancedHashMap) secArr.get(i);
if (node.get(key).equals(value)) {
ret.add(CopyMap(node));
}
}
}
return ret;
}
}
| true | true | protected AdvancedHashMap readFile(HashMap brMap) throws IOException {
AdvancedHashMap ret = new AdvancedHashMap();
String line;
BufferedReader br;
char[] buf;
BufferedReader brw = null;
char[] bufW = null;
HashMap mapW;
String wid;
String fileName;
LinkedHashMap formats = new LinkedHashMap();
ArrayList trArr = new ArrayList();
ArrayList cuArr = new ArrayList();
ArrayList flArr = new ArrayList();
ArrayList saArr = new ArrayList();
ArrayList sadArr = new ArrayList();
ArrayList icArr = new ArrayList();
ArrayList icdArr = new ArrayList();
ArrayList plArr = new ArrayList();
ArrayList irArr = new ArrayList();
ArrayList irdArr = new ArrayList();
ArrayList feArr = new ArrayList();
ArrayList omArr = new ArrayList();
ArrayList chArr = new ArrayList();
ArrayList tiArr = new ArrayList();
ArrayList emArr = new ArrayList();
ArrayList haArr = new ArrayList();
ArrayList smArr = new ArrayList();
String eventKey = "data";
buf = (char[]) brMap.get("X");
mapW = (HashMap) brMap.get("W");
fileName = (String) brMap.get("Z");
wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName;
// If XFile is no been found
if (buf == null) {
// TODO reprot file not exist error
return ret;
} else {
br = new BufferedReader(new CharArrayReader(buf));
}
ret.put("treatment", trArr);
// ret.put("cultivar", cuArr);
// ret.put("field", flArr);
// ret.put("soil_analysis", saArr);
// ret.put("initial_condition", icArr);
// ret.put("plant", plArr);
// ret.put("irrigation", irArr);
// ret.put("fertilizer", feArr);
// ret.put("residue_organic", omArr);
// ret.put("chemical", chArr);
// ret.put("tillage", tiArr);
// ret.put("emvironment", emArr);
// ret.put("harvest", haArr);
// ret.put("simulation", smArr);
while ((line = br.readLine()) != null) {
// Get content type of line
judgeContentType(line);
// Read Exp title info
if (flg[0].startsWith("exp.details:") && flg[2].equals("")) {
// Set variables' formats
formats.clear();
formats.put("exname", 11);
formats.put("local_name", 61);
// Read line and save into return holder
ret.put(readLine(line.substring(13), formats));
ret.put("institutes", line.substring(14, 16).trim());
} // Read General Section
else if (flg[0].startsWith("general")) {
// People info
if (flg[1].equals("people") && flg[2].equals("data")) {
ret.put("people", line.trim());
} // Address info
else if (flg[1].equals("address") && flg[2].equals("data")) {
String[] addr = line.split(",[ ]*");
ret.put("fl_loc_1", "");
ret.put("fl_loc_2", "");
ret.put("fl_loc_3", "");
ret.put("institutes", line.trim());
// ret.put("address", line.trim()); // P.S. no longer to use this field
switch (addr.length) {
case 0:
break;
case 1:
ret.put("fl_loc_1", addr[0]);
break;
case 2:
ret.put("fl_loc_1", addr[1]);
ret.put("fl_loc_2", addr[0]);
break;
case 3:
ret.put("fl_loc_1", addr[2]);
ret.put("fl_loc_2", addr[1]);
ret.put("fl_loc_3", addr[0]);
break;
default:
ret.put("fl_loc_1", addr[addr.length - 1]);
ret.put("fl_loc_2", addr[addr.length - 2]);
String loc3 = "";
for (int i = 0; i < addr.length - 2; i++) {
loc3 += addr[i] + ", ";
}
ret.put("fl_loc_3", loc3.substring(0, loc3.length() - 2));
}
} // Site info
else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) {
//$ret[$flg[0]]["site"] = trim($line);
// P.S. site is missing in the master variables list
ret.put("site", line.trim());
} // Plot Info
else if (flg[1].startsWith("parea") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("parea", 7);
formats.put("prno", 6);
formats.put("plen", 6);
formats.put("pldr", 6);
formats.put("plsp", 6);
formats.put("play", 6);
formats.put("pltha", 6);
formats.put("hrno", 6);
formats.put("hlen", 6);
formats.put("plthm", 16);
// Read line and save into return holder
ret.put("plot_info", readLine(line, formats));
} // Notes field
else if (flg[1].equals("notes") && flg[2].equals("data")) {
//$ret[$flg[0]]["notes"] = addArray($ret[$flg[0]]["notes"], " ". trim($line), "");
if (!ret.containsKey("notes")) {
ret.put("notes", line.trim() + "\\r\\n");
} else {
String notes = (String) ret.get("notes");
notes += line.trim() + "\\r\\n";
ret.put("notes", notes);
}
} else {
}
} // Read TREATMENTS Section
else if (flg[0].startsWith("treatments")) {
// Read TREATMENTS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("trno", 2);
formats.put("sq", 2);
formats.put("op", 2);
formats.put("co", 2);
formats.put("tr_name", 26);
formats.put("ge", 3);
formats.put("fl", 3);
formats.put("sa", 3);
formats.put("ic", 3);
formats.put("pl", 3);
formats.put("ir", 3);
formats.put("fe", 3);
formats.put("om", 3);
formats.put("ch", 3);
formats.put("ti", 3);
formats.put("em", 3);
formats.put("ha", 3);
formats.put("sm", 3);
// Read line and save into return holder
trArr.add(readLine(line, formats));
} else {
}
} // Read CULTIVARS Section
else if (flg[0].startsWith("cultivars")) {
// Read CULTIVARS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ge", 2);
formats.put("cr", 3);
formats.put("cul_id", 7);
formats.put("cul_name", 17);
// Read line and save into return holder
cuArr.add(readLine(line, formats));
if (cuArr.size() == 1) {
ret.put("cr", line.substring(3, 5).trim()); // TODO keep for the early version; just first entry
}
} else {
}
} // Read FIELDS Section
else if (flg[0].startsWith("fields")) {
// Read field info 1st line
if (flg[1].startsWith("l id_") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("id_field", 9);
formats.put("wsta_id", 9); //P.S. id do not match with the master list "wth_id"; might have another id name
formats.put("flsl", 6);
formats.put("flob", 6);
formats.put("fl_drntype", 6);
formats.put("fldrd", 6);
formats.put("fldrs", 6);
formats.put("flst", 6);
formats.put("sltx", 6);
formats.put("sldp", 6);
formats.put("soil_id", 11);
formats.put("fl_name", line.length());
// Read line and save into return holder
addToArray(flArr, readLine(line, formats), "fl");
// Read weather station id
wid = line.substring(12, 20).trim();
}// // Read field info 2nd line
else if (flg[1].startsWith("l ...") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("fl_lat", 16);
formats.put("fl_long", 16);
formats.put("flele", 10);
formats.put("farea", 18);
formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields)
formats.put("fllwr", 6);
formats.put("flsla", 6);
formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code)
formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years)
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// Read lat and long
String strLat = (String) tmp.get("fl_lat");
String strLong = (String) tmp.get("fl_long");
// If lat or long is not valid data, read data from weather file
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
// check if weather is validable
for (Object key : mapW.keySet()) {
if (((String) key).contains(wid)) {
bufW = (char[]) mapW.get(key);
break;
}
}
if (bufW != null) {
brw = new BufferedReader(new CharArrayReader(bufW));
String lineW;
while ((lineW = brw.readLine()) != null) {
if (lineW.startsWith("@ INSI")) {
lineW = brw.readLine();
strLat = lineW.substring(6, 15).trim();
strLong = lineW.substring(15, 24).trim();
break;
}
}
// check if lat and long are valid in the weather file; if not, set invalid value for them
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
strLat = defValI;
strLong = defValI;
}
} // if weather file is not avaliable to read, set invalid value for lat and long
else {
strLat = defValI;
strLong = defValI;
}
}
if (flArr.isEmpty()) {
ret.put("fl_lat", strLat); // TODO Keep the meta data handling for the early version
ret.put("fl_long", strLong); // TODO Keep the meta data handling for the early version
}
tmp.put("fl_lat", strLat);
tmp.put("fl_long", strLong);
addToArray(flArr, tmp, "fl");
}
} // Read SOIL ANALYSIS Section
else if (flg[0].startsWith("soil")) {
// Read SOIL ANALYSIS global data
if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sa", 2);
formats.put("sadat", 6);
formats.put("samhb", 6);
formats.put("sampx", 6);
formats.put("samke", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("sadat", translateDateStr((String) tmp.get("sadat")));
saArr.add(tmp);
sadArr = new ArrayList();
tmp.put(eventKey, sadArr);
} // Read SOIL ANALYSIS layer data
else if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "sa"
formats.put("sabl", 6);
formats.put("sabdm", 6);
formats.put("saoc", 6);
formats.put("sani", 6);
formats.put("saphw", 6);
formats.put("saphb", 6);
formats.put("sapx", 6);
formats.put("sake", 6);
formats.put("sasc", 6); // P.S. id do not find in the master list (Measured stable organic C by soil layer, g[C]/100g[Soil])
// Read line and save into return holder
sadArr.add(readLine(line, formats));
} else {
}
} // Read INITIAL CONDITIONS Section
else if (flg[0].startsWith("initial")) {
// Read INITIAL CONDITIONS global data
if (flg[1].startsWith("c pcr") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ic", 2);
formats.put("icpcr", 6);
formats.put("icdat", 6);
formats.put("icrt", 6);
formats.put("icnd", 6);
formats.put("icrz#", 6); // P.S. use the "icrz#" instead of "icrzno"
formats.put("icrze", 6);
formats.put("icwt", 6);
formats.put("icrag", 6);
formats.put("icrn", 6);
formats.put("icrp", 6);
formats.put("icrip", 6);
formats.put("icrdp", 6);
formats.put("ic_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("icdat", translateDateStr((String) tmp.get("icdat")));
icArr.add(tmp);
icdArr = new ArrayList();
tmp.put(eventKey, icdArr);
} else // INITIAL CONDITIONS layer data
if (flg[1].startsWith("c icbl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the detail (event) data index "ic"
formats.put("icbl", 6);
formats.put("ich2o", 6);
formats.put("icnh4", 6);
formats.put("icno3", 6);
// Read line and save into return holder
icdArr.add(readLine(line, formats));
} else {
}
} // Read PLANTING DETAILS Section
else if (flg[0].startsWith("planting")) {
// Read PLANTING data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("pl", 2);
formats.put("pdate", 6);
formats.put("pldae", 6);
formats.put("plpop", 6);
formats.put("plpoe", 6);
formats.put("plme", 6);
formats.put("plds", 6);
formats.put("plrs", 6);
formats.put("plrd", 6);
formats.put("pldp", 6);
formats.put("plmwt", 6);
formats.put("page", 6);
formats.put("penv", 6);
formats.put("plph", 6);
formats.put("plspl", 6);
formats.put("pl_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("pdate", translateDateStr((String) tmp.get("pdate")));
tmp.put("pldae", translateDateStr((String) tmp.get("pldae")));
plArr.add(tmp);
if (plArr.size() == 1) {
ret.put("pdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for the early version
}
} else {
}
} // Read IRRIGATION AND WATER MANAGEMENT Section
else if (flg[0].startsWith("irrigation")) {
// Read IRRIGATION global data
if (flg[1].startsWith("i efir") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ir", 2);
formats.put("ireff", 6);
formats.put("irmdp", 6);
formats.put("irthr", 6);
formats.put("irept", 6);
formats.put("irstg", 6);
formats.put("iame", 6);
formats.put("iamt", 6);
formats.put("ir_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
irArr.add(tmp);
irdArr = new ArrayList();
tmp.put(eventKey, irdArr);
} // Read IRRIGATION appliction data
else if (flg[1].startsWith("i idate") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "ir"
formats.put("idate", 6);
formats.put("irop", 6);
formats.put("irval", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("idate", translateDateStr((String) tmp.get("idate"))); // TODO DOY handling
irdArr.add(tmp);
} else {
}
} // Read FERTILIZERS (INORGANIC) Section
else if (flg[0].startsWith("fertilizers")) {
// Read FERTILIZERS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fe", 2);
formats.put("fdate", 6);
formats.put("fecd", 6);
formats.put("feacd", 6);
formats.put("fedep", 6);
formats.put("feamn", 6);
formats.put("feamp", 6);
formats.put("feamk", 6);
formats.put("feamc", 6);
formats.put("feamo", 6);
formats.put("feocd", 6);
formats.put("fe_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("fdate", translateDateStr((String) tmp.get("fdate"))); // TODO DOY handling
feArr.add(tmp);
} else {
}
} // Read RESIDUES AND OTHER ORGANIC MATERIALS Section
else if (flg[0].startsWith("residues")) {
// Read ORGANIC MATERIALS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("om", 2);
formats.put("omdat", 6); // P.S. id do not match with the master list "omday"
formats.put("omcd", 6);
formats.put("omamt", 6);
formats.put("omn%", 6); // P.S. id do not match with the master list "omnpct"
formats.put("omp%", 6); // P.S. id do not match with the master list "omppct"
formats.put("omk%", 6); // P.S. id do not match with the master list "omkpct"
formats.put("ominp", 6);
formats.put("omdep", 6);
formats.put("omacd", 6);
formats.put("om_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("omdat", translateDateStr((String) tmp.get("omdat"))); // TODO DOY handling
omArr.add(tmp);
} else {
}
} // Read CHEMICAL APPLICATIONS Section
else if (flg[0].startsWith("chemical")) {
// Read CHEMICAL APPLICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ch", 2);
formats.put("cdate", 6);
formats.put("chcd", 6);
formats.put("chamt", 6);
formats.put("chacd", 6);
formats.put("chdep", 6);
formats.put("ch_targets", 6);
formats.put("ch_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("cdate", translateDateStr((String) tmp.get("cdate")));
chArr.add(tmp);
} else {
}
} // Read TILLAGE Section
else if (flg[0].startsWith("tillage")) {
// Read TILLAGE data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ti", 2);
formats.put("tdate", 6);
formats.put("tiimp", 6);
formats.put("tidep", 6);
formats.put("ti_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("tdate", translateDateStr((String) tmp.get("tdate")));
tiArr.add(tmp);
} else {
}
} // Read ENVIRONMENT MODIFICATIONS Section
else if (flg[0].startsWith("environment")) {
// Read ENVIRONMENT MODIFICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("em", 2);
formats.put("emday", 6);
formats.put("ecdyl", 2);
formats.put("emdyl", 4);
formats.put("ecrad", 2);
formats.put("emrad", 4);
formats.put("ecmax", 2);
formats.put("emmax", 4);
formats.put("ecmin", 2);
formats.put("emmin", 4);
formats.put("ecrai", 2);
formats.put("emrai", 4);
formats.put("ecco2", 2);
formats.put("emco2", 4);
formats.put("ecdew", 2);
formats.put("emdew", 4);
formats.put("ecwnd", 2);
formats.put("emwnd", 4);
formats.put("em_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("emday", translateDateStr((String) tmp.get("emday")));
emArr.add(tmp);
} else {
}
} // Read HARVEST DETAILS Section
else if (flg[0].startsWith("harvest")) {
// Read HARVEST data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ha", 2);
formats.put("hdate", 6);
formats.put("hastg", 6);
formats.put("hacom", 6);
formats.put("hasiz", 6);
formats.put("hapc", 6);
formats.put("habpc", 6);
formats.put("ha_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("hdate", translateDateStr((String) tmp.get("hdate")));
haArr.add(tmp);
if (haArr.size() == 1) {
ret.put("hdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for early version
}
} else {
}
} // Read SIMULATION CONTROLS Section // P.S. no need to be divided
else if (flg[0].startsWith("simulation")) {
// Read general info
if (flg[1].startsWith("n general") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("general", 12);
// formats.put("nyers", 6);
// formats.put("nreps", 6);
// formats.put("start", 6);
// formats.put("sdate", 6);
// formats.put("rseed", 6);
// formats.put("sname", 26);
// formats.put("model", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("sdate", translateDateStr((String) tmp.get("sdate")));
tmp.put("general", line);
addToArray(smArr, tmp, "sm");
} // Read options info
else if (flg[1].startsWith("n options") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("options", 12);
// formats.put("water", 6);
// formats.put("nitro", 6);
// formats.put("symbi", 6);
// formats.put("phosp", 6);
// formats.put("potas", 6);
// formats.put("dises", 6);
// formats.put("chem", 6);
// formats.put("till", 6);
// formats.put("co2", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("options", line);
addToArray(smArr, tmp, "sm");
} // Read methods info
else if (flg[1].startsWith("n methods") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("methods", 12);
// formats.put("wther", 6);
// formats.put("incon", 6);
// formats.put("light", 6);
// formats.put("evapo", 6);
// formats.put("infil", 6);
// formats.put("photo", 6);
// formats.put("hydro", 6);
// formats.put("nswit", 6);
// formats.put("mesom", 6);
// formats.put("mesev", 6);
// formats.put("mesol", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("methods", line);
addToArray(smArr, tmp, "sm");
} // Read management info
else if (flg[1].startsWith("n management") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("management", 12);
// formats.put("plant", 6);
// formats.put("irrig", 6);
// formats.put("ferti", 6);
// formats.put("resid", 6);
// formats.put("harvs", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("management", line);
addToArray(smArr, tmp, "sm");
} // Read outputs info
else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("outputs", 12);
// formats.put("fname", 6);
// formats.put("ovvew", 6);
// formats.put("sumry", 6);
// formats.put("fropt", 6);
// formats.put("grout", 6);
// formats.put("caout", 6);
// formats.put("waout", 6);
// formats.put("niout", 6);
// formats.put("miout", 6);
// formats.put("diout", 6);
// formats.put("long", 6);
// formats.put("chout", 6);
// formats.put("opout", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("outputs", line);
addToArray(smArr, tmp, "sm");
} // Read planting info
else if (flg[1].startsWith("n planting") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("planting", 12);
// formats.put("pfrst", 6);
// formats.put("plast", 6);
// formats.put("ph20l", 6);
// formats.put("ph2ou", 6);
// formats.put("ph20d", 6);
// formats.put("pstmx", 6);
// formats.put("pstmn", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("pfrst", translateDateStr((String) tmp.get("pfrst")));
// tmp.put("plast", translateDateStr((String) tmp.get("plast")));
tmp.put("planting", line);
addToArray(smArr, tmp, "sm");
} // Read irrigation info
else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("irrigation", 12);
// formats.put("imdep", 6);
// formats.put("ithrl", 6);
// formats.put("ithru", 6);
// formats.put("iroff", 6);
// formats.put("imeth", 6);
// formats.put("iramt", 6);
// formats.put("ireff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("irrigation", line);
addToArray(smArr, tmp, "sm");
} // Read nitrogen info
else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("nitrogen", 12);
// formats.put("nmdep", 6);
// formats.put("nmthr", 6);
// formats.put("namnt", 6);
// formats.put("ncode", 6);
// formats.put("naoff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("nitrogen", line);
addToArray(smArr, tmp, "sm");
} // Read residues info
else if (flg[1].startsWith("n residues") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("residues", 12);
// formats.put("ripcn", 6);
// formats.put("rtime", 6);
// formats.put("ridep", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("residues", line);
addToArray(smArr, tmp, "sm");
} // Read harvest info
else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("harvests", 12);
// formats.put("hfrst", 6); // P.S. Keep the original value
// formats.put("hlast", 6);
// formats.put("hpcnp", 6);
// formats.put("hrcnr", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("hlast", translateDateStr((String) tmp.get("hlast")));
tmp.put("harvests", line);
addToArray(smArr, tmp, "sm");
} else {
}
} else {
}
}
br.close();
if (brw != null) {
brw.close();
}
for (int i = 0; i < trArr.size(); i++) {
AdvancedHashMap treatment = (AdvancedHashMap) trArr.get(i);
// cultivar
if (!treatment.getOr("ge", "0").equals("0")) {
treatment.put("cultivar", getSectionData(cuArr, "ge", treatment.get("ge").toString()));
}
// field
if (!treatment.getOr("fl", "0").equals("0")) {
treatment.put("field", getSectionData(flArr, "fl", treatment.get("fl").toString()));
}
// soil_analysis
if (!treatment.getOr("sa", "0").equals("0")) {
treatment.put("soil_analysis", getSectionData(saArr, "sa", treatment.get("sa").toString()));
}
// initial_condition
if (!treatment.getOr("ic", "0").equals("0")) {
treatment.put("initial_condition", getSectionData(icArr, "ic", treatment.get("ic").toString()));
}
// plant
if (!treatment.getOr("pl", "0").equals("0")) {
treatment.put("plant", getSectionData(plArr, "pl", treatment.get("pl").toString()));
}
// irrigation
if (!treatment.getOr("ir", "0").equals("0")) {
treatment.put("irrigation", getSectionData(irArr, "ir", treatment.get("ir").toString()));
}
// fertilizer
if (!treatment.getOr("fe", "0").equals("0")) {
treatment.put("fertilizer", getSectionData(feArr, "fe", treatment.get("fe").toString()));
}
// residue_organic
if (!treatment.getOr("om", "0").equals("0")) {
treatment.put("residue_organic", getSectionData(omArr, "om", treatment.get("om").toString()));
}
// chemical
if (!treatment.getOr("ch", "0").equals("0")) {
treatment.put("chemical", getSectionData(chArr, "ch", treatment.get("ch").toString()));
}
// tillage
if (!treatment.getOr("ti", "0").equals("0")) {
treatment.put("tillage", getSectionData(tiArr, "ti", treatment.get("ti").toString()));
}
// emvironment
if (!treatment.getOr("em", "0").equals("0")) {
treatment.put("emvironment", getSectionData(emArr, "em", treatment.get("em").toString()));
}
// harvest
if (!treatment.getOr("ha", "0").equals("0")) {
treatment.put("harvest", getSectionData(haArr, "ha", treatment.get("ha").toString()));
}
// simulation
if (!treatment.getOr("sm", "0").equals("0")) {
treatment.put("simulation", getSectionData(smArr, "sm", treatment.get("sm").toString()));
}
// Revise the date value for FEDATE, IDATE, MLADAT
// Get Planting date
String pdate = "";
ArrayList plTmps = (ArrayList) treatment.getOr("planting", new ArrayList());
if (!plTmps.isEmpty()) {
pdate = (String) ((AdvancedHashMap) plTmps.get(0)).getOr("pdate", "");
if (pdate.length() > 5) {
pdate = pdate.substring(2);
}
}
// Fertilizer Date
ArrayList feTmps = (ArrayList) treatment.getOr("fertilizer", new ArrayList());
AdvancedHashMap feTmp;
for (int j = 0; j < feTmps.size(); j++) {
feTmp = (AdvancedHashMap) feTmps.get(j);
feTmp.put("fdate", translateDateStrForDOY((String) feTmp.get("fdate"), pdate));
}
// Initial condition date
AdvancedHashMap icTmp = (AdvancedHashMap) treatment.get("initial_condition");
if (icTmp != null) {
icTmp.put("idate", translateDateStrForDOY((String) icTmp.getOr("idate", defValI), pdate));
}
// Mulch application date
ArrayList omTmps = (ArrayList) treatment.getOr("residue_organic", new ArrayList());
AdvancedHashMap omTmp;
for (int j = 0; j < omTmps.size(); j++) {
omTmp = (AdvancedHashMap) omTmps.get(j);
omTmp.put("omdat", translateDateStrForDOY((String) omTmp.get("omdat"), pdate));
}
}
compressData(ret);
return ret;
}
| protected AdvancedHashMap readFile(HashMap brMap) throws IOException {
AdvancedHashMap ret = new AdvancedHashMap();
String line;
BufferedReader br;
char[] buf;
BufferedReader brw = null;
char[] bufW = null;
HashMap mapW;
String wid;
String fileName;
LinkedHashMap formats = new LinkedHashMap();
ArrayList trArr = new ArrayList();
ArrayList cuArr = new ArrayList();
ArrayList flArr = new ArrayList();
ArrayList saArr = new ArrayList();
ArrayList sadArr = new ArrayList();
ArrayList icArr = new ArrayList();
ArrayList icdArr = new ArrayList();
ArrayList plArr = new ArrayList();
ArrayList irArr = new ArrayList();
ArrayList irdArr = new ArrayList();
ArrayList feArr = new ArrayList();
ArrayList omArr = new ArrayList();
ArrayList chArr = new ArrayList();
ArrayList tiArr = new ArrayList();
ArrayList emArr = new ArrayList();
ArrayList haArr = new ArrayList();
ArrayList smArr = new ArrayList();
String eventKey = "data";
buf = (char[]) brMap.get("X");
mapW = (HashMap) brMap.get("W");
fileName = (String) brMap.get("Z");
wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName;
// If XFile is no been found
if (buf == null) {
// TODO reprot file not exist error
return ret;
} else {
br = new BufferedReader(new CharArrayReader(buf));
}
ret.put("treatment", trArr);
// ret.put("cultivar", cuArr);
// ret.put("field", flArr);
// ret.put("soil_analysis", saArr);
// ret.put("initial_condition", icArr);
// ret.put("plant", plArr);
// ret.put("irrigation", irArr);
// ret.put("fertilizer", feArr);
// ret.put("residue_organic", omArr);
// ret.put("chemical", chArr);
// ret.put("tillage", tiArr);
// ret.put("emvironment", emArr);
// ret.put("harvest", haArr);
// ret.put("simulation", smArr);
while ((line = br.readLine()) != null) {
// Get content type of line
judgeContentType(line);
// Read Exp title info
if (flg[0].startsWith("exp.details:") && flg[2].equals("")) {
// Set variables' formats
formats.clear();
formats.put("exname", 11);
formats.put("local_name", 61);
// Read line and save into return holder
ret.put(readLine(line.substring(13), formats));
ret.put("institutes", line.substring(14, 16).trim());
} // Read General Section
else if (flg[0].startsWith("general")) {
// People info
if (flg[1].equals("people") && flg[2].equals("data")) {
ret.put("people", line.trim());
} // Address info
else if (flg[1].equals("address") && flg[2].equals("data")) {
String[] addr = line.split(",[ ]*");
ret.put("fl_loc_1", "");
ret.put("fl_loc_2", "");
ret.put("fl_loc_3", "");
ret.put("institutes", line.trim());
// ret.put("address", line.trim()); // P.S. no longer to use this field
switch (addr.length) {
case 0:
break;
case 1:
ret.put("fl_loc_1", addr[0]);
break;
case 2:
ret.put("fl_loc_1", addr[1]);
ret.put("fl_loc_2", addr[0]);
break;
case 3:
ret.put("fl_loc_1", addr[2]);
ret.put("fl_loc_2", addr[1]);
ret.put("fl_loc_3", addr[0]);
break;
default:
ret.put("fl_loc_1", addr[addr.length - 1]);
ret.put("fl_loc_2", addr[addr.length - 2]);
String loc3 = "";
for (int i = 0; i < addr.length - 2; i++) {
loc3 += addr[i] + ", ";
}
ret.put("fl_loc_3", loc3.substring(0, loc3.length() - 2));
}
} // Site info
else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) {
//$ret[$flg[0]]["site"] = trim($line);
// P.S. site is missing in the master variables list
ret.put("site", line.trim());
} // Plot Info
else if (flg[1].startsWith("parea") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("parea", 7);
formats.put("prno", 6);
formats.put("plen", 6);
formats.put("pldr", 6);
formats.put("plsp", 6);
formats.put("play", 6);
formats.put("pltha", 6);
formats.put("hrno", 6);
formats.put("hlen", 6);
formats.put("plthm", 16);
// Read line and save into return holder
ret.put("plot_info", readLine(line, formats));
} // Notes field
else if (flg[1].equals("notes") && flg[2].equals("data")) {
//$ret[$flg[0]]["notes"] = addArray($ret[$flg[0]]["notes"], " ". trim($line), "");
if (!ret.containsKey("notes")) {
ret.put("notes", line.trim() + "\\r\\n");
} else {
String notes = (String) ret.get("notes");
notes += line.trim() + "\\r\\n";
ret.put("notes", notes);
}
} else {
}
} // Read TREATMENTS Section
else if (flg[0].startsWith("treatments")) {
// Read TREATMENTS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("trno", 2);
formats.put("sq", 2);
formats.put("op", 2);
formats.put("co", 2);
formats.put("tr_name", 26);
formats.put("ge", 3);
formats.put("fl", 3);
formats.put("sa", 3);
formats.put("ic", 3);
formats.put("pl", 3);
formats.put("ir", 3);
formats.put("fe", 3);
formats.put("om", 3);
formats.put("ch", 3);
formats.put("ti", 3);
formats.put("em", 3);
formats.put("ha", 3);
formats.put("sm", 3);
// Read line and save into return holder
trArr.add(readLine(line, formats));
} else {
}
} // Read CULTIVARS Section
else if (flg[0].startsWith("cultivars")) {
// Read CULTIVARS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ge", 2);
formats.put("cr", 3);
formats.put("cul_id", 7);
formats.put("cul_name", 17);
// Read line and save into return holder
cuArr.add(readLine(line, formats));
if (cuArr.size() == 1) {
ret.put("cr", line.substring(3, 5).trim()); // TODO keep for the early version; just first entry
}
} else {
}
} // Read FIELDS Section
else if (flg[0].startsWith("fields")) {
// Read field info 1st line
if (flg[1].startsWith("l id_") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("id_field", 9);
formats.put("wsta_id", 9); //P.S. id do not match with the master list "wth_id"; might have another id name
formats.put("flsl", 6);
formats.put("flob", 6);
formats.put("fl_drntype", 6);
formats.put("fldrd", 6);
formats.put("fldrs", 6);
formats.put("flst", 6);
formats.put("sltx", 6);
formats.put("sldp", 6);
formats.put("soil_id", 11);
formats.put("fl_name", line.length());
// Read line and save into return holder
addToArray(flArr, readLine(line, formats), "fl");
// Read weather station id
wid = line.substring(12, 20).trim();
}// // Read field info 2nd line
else if (flg[1].startsWith("l ...") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("fl_lat", 16);
formats.put("fl_long", 16);
formats.put("flele", 10);
formats.put("farea", 18);
formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields)
formats.put("fllwr", 6);
formats.put("flsla", 6);
formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code)
formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years)
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// Read lat and long
String strLat = (String) tmp.get("fl_lat");
String strLong = (String) tmp.get("fl_long");
// If lat or long is not valid data, read data from weather file
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
// check if weather is validable
for (Object key : mapW.keySet()) {
if (((String) key).contains(wid)) {
bufW = (char[]) mapW.get(key);
break;
}
}
if (bufW != null) {
brw = new BufferedReader(new CharArrayReader(bufW));
String lineW;
while ((lineW = brw.readLine()) != null) {
if (lineW.startsWith("@ INSI")) {
lineW = brw.readLine();
strLat = lineW.substring(6, 15).trim();
strLong = lineW.substring(15, 24).trim();
break;
}
}
// check if lat and long are valid in the weather file; if not, set invalid value for them
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
strLat = defValI;
strLong = defValI;
}
} // if weather file is not avaliable to read, set invalid value for lat and long
else {
strLat = defValI;
strLong = defValI;
}
}
if (flArr.isEmpty()) {
ret.put("fl_lat", strLat); // TODO Keep the meta data handling for the early version
ret.put("fl_long", strLong); // TODO Keep the meta data handling for the early version
}
tmp.put("fl_lat", strLat);
tmp.put("fl_long", strLong);
addToArray(flArr, tmp, "fl");
}
} // Read SOIL ANALYSIS Section
else if (flg[0].startsWith("soil")) {
// Read SOIL ANALYSIS global data
if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sa", 2);
formats.put("sadat", 6);
formats.put("samhb", 6);
formats.put("sampx", 6);
formats.put("samke", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("sadat", translateDateStr((String) tmp.get("sadat")));
saArr.add(tmp);
sadArr = new ArrayList();
tmp.put(eventKey, sadArr);
} // Read SOIL ANALYSIS layer data
else if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "sa"
formats.put("sabl", 6);
formats.put("sabdm", 6);
formats.put("saoc", 6);
formats.put("sani", 6);
formats.put("saphw", 6);
formats.put("saphb", 6);
formats.put("sapx", 6);
formats.put("sake", 6);
formats.put("sasc", 6); // P.S. id do not find in the master list (Measured stable organic C by soil layer, g[C]/100g[Soil])
// Read line and save into return holder
sadArr.add(readLine(line, formats));
} else {
}
} // Read INITIAL CONDITIONS Section
else if (flg[0].startsWith("initial")) {
// Read INITIAL CONDITIONS global data
if (flg[1].startsWith("c pcr") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ic", 2);
formats.put("icpcr", 6);
formats.put("icdat", 6);
formats.put("icrt", 6);
formats.put("icnd", 6);
formats.put("icrz#", 6); // P.S. use the "icrz#" instead of "icrzno"
formats.put("icrze", 6);
formats.put("icwt", 6);
formats.put("icrag", 6);
formats.put("icrn", 6);
formats.put("icrp", 6);
formats.put("icrip", 6);
formats.put("icrdp", 6);
formats.put("ic_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("icdat", translateDateStr((String) tmp.get("icdat")));
icArr.add(tmp);
icdArr = new ArrayList();
tmp.put(eventKey, icdArr);
} else // INITIAL CONDITIONS layer data
if (flg[1].startsWith("c icbl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the detail (event) data index "ic"
formats.put("icbl", 6);
formats.put("ich2o", 6);
formats.put("icnh4", 6);
formats.put("icno3", 6);
// Read line and save into return holder
icdArr.add(readLine(line, formats));
} else {
}
} // Read PLANTING DETAILS Section
else if (flg[0].startsWith("planting")) {
// Read PLANTING data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("pl", 2);
formats.put("pdate", 6);
formats.put("pldae", 6);
formats.put("plpop", 6);
formats.put("plpoe", 6);
formats.put("plme", 6);
formats.put("plds", 6);
formats.put("plrs", 6);
formats.put("plrd", 6);
formats.put("pldp", 6);
formats.put("plmwt", 6);
formats.put("page", 6);
formats.put("penv", 6);
formats.put("plph", 6);
formats.put("plspl", 6);
formats.put("pl_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("pdate", translateDateStr((String) tmp.get("pdate")));
tmp.put("pldae", translateDateStr((String) tmp.get("pldae")));
plArr.add(tmp);
if (plArr.size() == 1) {
ret.put("pdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for the early version
}
} else {
}
} // Read IRRIGATION AND WATER MANAGEMENT Section
else if (flg[0].startsWith("irrigation")) {
// Read IRRIGATION global data
if (flg[1].startsWith("i efir") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ir", 2);
formats.put("ireff", 6);
formats.put("irmdp", 6);
formats.put("irthr", 6);
formats.put("irept", 6);
formats.put("irstg", 6);
formats.put("iame", 6);
formats.put("iamt", 6);
formats.put("ir_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
irArr.add(tmp);
irdArr = new ArrayList();
tmp.put(eventKey, irdArr);
} // Read IRRIGATION appliction data
else if (flg[1].startsWith("i idate") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "ir"
formats.put("idate", 6);
formats.put("irop", 6);
formats.put("irval", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("idate", translateDateStr((String) tmp.get("idate"))); // TODO DOY handling
irdArr.add(tmp);
} else {
}
} // Read FERTILIZERS (INORGANIC) Section
else if (flg[0].startsWith("fertilizers")) {
// Read FERTILIZERS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fe", 2);
formats.put("fdate", 6);
formats.put("fecd", 6);
formats.put("feacd", 6);
formats.put("fedep", 6);
formats.put("feamn", 6);
formats.put("feamp", 6);
formats.put("feamk", 6);
formats.put("feamc", 6);
formats.put("feamo", 6);
formats.put("feocd", 6);
formats.put("fe_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("fdate", translateDateStr((String) tmp.get("fdate"))); // TODO DOY handling
feArr.add(tmp);
} else {
}
} // Read RESIDUES AND OTHER ORGANIC MATERIALS Section
else if (flg[0].startsWith("residues")) {
// Read ORGANIC MATERIALS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("om", 2);
formats.put("omdat", 6); // P.S. id do not match with the master list "omday"
formats.put("omcd", 6);
formats.put("omamt", 6);
formats.put("omn%", 6); // P.S. id do not match with the master list "omnpct"
formats.put("omp%", 6); // P.S. id do not match with the master list "omppct"
formats.put("omk%", 6); // P.S. id do not match with the master list "omkpct"
formats.put("ominp", 6);
formats.put("omdep", 6);
formats.put("omacd", 6);
formats.put("om_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("omdat", translateDateStr((String) tmp.get("omdat"))); // TODO DOY handling
omArr.add(tmp);
} else {
}
} // Read CHEMICAL APPLICATIONS Section
else if (flg[0].startsWith("chemical")) {
// Read CHEMICAL APPLICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ch", 2);
formats.put("cdate", 6);
formats.put("chcd", 6);
formats.put("chamt", 6);
formats.put("chacd", 6);
formats.put("chdep", 6);
formats.put("ch_targets", 6);
formats.put("ch_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("cdate", translateDateStr((String) tmp.get("cdate")));
chArr.add(tmp);
} else {
}
} // Read TILLAGE Section
else if (flg[0].startsWith("tillage")) {
// Read TILLAGE data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ti", 2);
formats.put("tdate", 6);
formats.put("tiimp", 6);
formats.put("tidep", 6);
formats.put("ti_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("tdate", translateDateStr((String) tmp.get("tdate")));
tiArr.add(tmp);
} else {
}
} // Read ENVIRONMENT MODIFICATIONS Section
else if (flg[0].startsWith("environment")) {
// Read ENVIRONMENT MODIFICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("em", 2);
formats.put("emday", 6);
formats.put("ecdyl", 2);
formats.put("emdyl", 4);
formats.put("ecrad", 2);
formats.put("emrad", 4);
formats.put("ecmax", 2);
formats.put("emmax", 4);
formats.put("ecmin", 2);
formats.put("emmin", 4);
formats.put("ecrai", 2);
formats.put("emrai", 4);
formats.put("ecco2", 2);
formats.put("emco2", 4);
formats.put("ecdew", 2);
formats.put("emdew", 4);
formats.put("ecwnd", 2);
formats.put("emwnd", 4);
formats.put("em_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("emday", translateDateStr((String) tmp.get("emday")));
emArr.add(tmp);
} else {
}
} // Read HARVEST DETAILS Section
else if (flg[0].startsWith("harvest")) {
// Read HARVEST data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ha", 2);
formats.put("hdate", 6);
formats.put("hastg", 6);
formats.put("hacom", 6);
formats.put("hasiz", 6);
formats.put("hapc", 6);
formats.put("habpc", 6);
formats.put("ha_name", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("hdate", translateDateStr((String) tmp.get("hdate")));
haArr.add(tmp);
if (haArr.size() == 1) {
ret.put("hdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for early version
}
} else {
}
} // Read SIMULATION CONTROLS Section // P.S. no need to be divided
else if (flg[0].startsWith("simulation")) {
// Read general info
if (flg[1].startsWith("n general") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("general", 12);
// formats.put("nyers", 6);
// formats.put("nreps", 6);
// formats.put("start", 6);
// formats.put("sdate", 6);
// formats.put("rseed", 6);
// formats.put("sname", 26);
// formats.put("model", line.length());
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("sdate", translateDateStr((String) tmp.get("sdate")));
tmp.put("general", line);
addToArray(smArr, tmp, "sm");
} // Read options info
else if (flg[1].startsWith("n options") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("options", 12);
// formats.put("water", 6);
// formats.put("nitro", 6);
// formats.put("symbi", 6);
// formats.put("phosp", 6);
// formats.put("potas", 6);
// formats.put("dises", 6);
// formats.put("chem", 6);
// formats.put("till", 6);
// formats.put("co2", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("options", line);
addToArray(smArr, tmp, "sm");
} // Read methods info
else if (flg[1].startsWith("n methods") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("methods", 12);
// formats.put("wther", 6);
// formats.put("incon", 6);
// formats.put("light", 6);
// formats.put("evapo", 6);
// formats.put("infil", 6);
// formats.put("photo", 6);
// formats.put("hydro", 6);
// formats.put("nswit", 6);
// formats.put("mesom", 6);
// formats.put("mesev", 6);
// formats.put("mesol", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("methods", line);
addToArray(smArr, tmp, "sm");
} // Read management info
else if (flg[1].startsWith("n management") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("management", 12);
// formats.put("plant", 6);
// formats.put("irrig", 6);
// formats.put("ferti", 6);
// formats.put("resid", 6);
// formats.put("harvs", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("management", line);
addToArray(smArr, tmp, "sm");
} // Read outputs info
else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("outputs", 12);
// formats.put("fname", 6);
// formats.put("ovvew", 6);
// formats.put("sumry", 6);
// formats.put("fropt", 6);
// formats.put("grout", 6);
// formats.put("caout", 6);
// formats.put("waout", 6);
// formats.put("niout", 6);
// formats.put("miout", 6);
// formats.put("diout", 6);
// formats.put("long", 6);
// formats.put("chout", 6);
// formats.put("opout", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("outputs", line);
addToArray(smArr, tmp, "sm");
} // Read planting info
else if (flg[1].startsWith("n planting") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("planting", 12);
// formats.put("pfrst", 6);
// formats.put("plast", 6);
// formats.put("ph20l", 6);
// formats.put("ph2ou", 6);
// formats.put("ph20d", 6);
// formats.put("pstmx", 6);
// formats.put("pstmn", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("pfrst", translateDateStr((String) tmp.get("pfrst")));
// tmp.put("plast", translateDateStr((String) tmp.get("plast")));
tmp.put("planting", line);
addToArray(smArr, tmp, "sm");
} // Read irrigation info
else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("irrigation", 12);
// formats.put("imdep", 6);
// formats.put("ithrl", 6);
// formats.put("ithru", 6);
// formats.put("iroff", 6);
// formats.put("imeth", 6);
// formats.put("iramt", 6);
// formats.put("ireff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("irrigation", line);
addToArray(smArr, tmp, "sm");
} // Read nitrogen info
else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("nitrogen", 12);
// formats.put("nmdep", 6);
// formats.put("nmthr", 6);
// formats.put("namnt", 6);
// formats.put("ncode", 6);
// formats.put("naoff", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("nitrogen", line);
addToArray(smArr, tmp, "sm");
} // Read residues info
else if (flg[1].startsWith("n residues") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("residues", 12);
// formats.put("ripcn", 6);
// formats.put("rtime", 6);
// formats.put("ridep", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
tmp.put("residues", line);
addToArray(smArr, tmp, "sm");
} // Read harvest info
else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
// formats.put("harvests", 12);
// formats.put("hfrst", 6); // P.S. Keep the original value
// formats.put("hlast", 6);
// formats.put("hpcnp", 6);
// formats.put("hrcnr", 6);
// Read line and save into return holder
AdvancedHashMap tmp = readLine(line, formats);
// tmp.put("hlast", translateDateStr((String) tmp.get("hlast")));
tmp.put("harvests", line);
addToArray(smArr, tmp, "sm");
} else {
}
} else {
}
}
br.close();
if (brw != null) {
brw.close();
}
for (int i = 0; i < trArr.size(); i++) {
AdvancedHashMap treatment = (AdvancedHashMap) trArr.get(i);
// cultivar
if (!treatment.getOr("ge", "0").equals("0")) {
treatment.put("cultivar", getSectionData(cuArr, "ge", treatment.get("ge").toString()));
}
// field
if (!treatment.getOr("fl", "0").equals("0")) {
treatment.put("field", getSectionData(flArr, "fl", treatment.get("fl").toString()));
}
// soil_analysis
if (!treatment.getOr("sa", "0").equals("0")) {
treatment.put("soil_analysis", getSectionData(saArr, "sa", treatment.get("sa").toString()));
}
// initial_condition
if (!treatment.getOr("ic", "0").equals("0")) {
treatment.put("initial_condition", getSectionData(icArr, "ic", treatment.get("ic").toString()));
}
// plant
if (!treatment.getOr("pl", "0").equals("0")) {
treatment.put("plant", getSectionData(plArr, "pl", treatment.get("pl").toString()));
}
// irrigation
if (!treatment.getOr("ir", "0").equals("0")) {
treatment.put("irrigation", getSectionData(irArr, "ir", treatment.get("ir").toString()));
}
// fertilizer
if (!treatment.getOr("fe", "0").equals("0")) {
treatment.put("fertilizer", getSectionData(feArr, "fe", treatment.get("fe").toString()));
}
// residue_organic
if (!treatment.getOr("om", "0").equals("0")) {
treatment.put("residue_organic", getSectionData(omArr, "om", treatment.get("om").toString()));
}
// chemical
if (!treatment.getOr("ch", "0").equals("0")) {
treatment.put("chemical", getSectionData(chArr, "ch", treatment.get("ch").toString()));
}
// tillage
if (!treatment.getOr("ti", "0").equals("0")) {
treatment.put("tillage", getSectionData(tiArr, "ti", treatment.get("ti").toString()));
}
// emvironment
if (!treatment.getOr("em", "0").equals("0")) {
treatment.put("emvironment", getSectionData(emArr, "em", treatment.get("em").toString()));
}
// harvest
if (!treatment.getOr("ha", "0").equals("0")) {
treatment.put("harvest", getSectionData(haArr, "ha", treatment.get("ha").toString()));
}
// simulation
if (!treatment.getOr("sm", "0").equals("0")) {
treatment.put("simulation", getSectionData(smArr, "sm", treatment.get("sm").toString()));
}
// Revise the date value for FEDATE, IDATE, MLADAT
// Get Planting date
String pdate = "";
ArrayList plTmps = (ArrayList) treatment.getOr("planting", new ArrayList());
if (!plTmps.isEmpty()) {
pdate = (String) ((AdvancedHashMap) plTmps.get(0)).getOr("pdate", "");
if (pdate.length() > 5) {
pdate = pdate.substring(2);
}
}
// Fertilizer Date
ArrayList feTmps = (ArrayList) treatment.getOr("fertilizer", new ArrayList());
AdvancedHashMap feTmp;
for (int j = 0; j < feTmps.size(); j++) {
feTmp = (AdvancedHashMap) feTmps.get(j);
feTmp.put("fdate", translateDateStrForDOY((String) feTmp.get("fdate"), pdate));
}
// Irrigation date
AdvancedHashMap irTmp = (AdvancedHashMap) treatment.get("irrigation");
if (irTmp != null) {
ArrayList irTmpSubs = (ArrayList) irTmp.getOr("data", new ArrayList());
for (int j = 0; j < irTmpSubs.size(); j++) {
AdvancedHashMap irTmpSub = (AdvancedHashMap) irTmpSubs.get(j);
irTmpSub.put("idate", translateDateStrForDOY((String) irTmpSub.getOr("idate", defValI), pdate));
}
}
// Mulch application date
ArrayList omTmps = (ArrayList) treatment.getOr("residue_organic", new ArrayList());
AdvancedHashMap omTmp;
for (int j = 0; j < omTmps.size(); j++) {
omTmp = (AdvancedHashMap) omTmps.get(j);
omTmp.put("omdat", translateDateStrForDOY((String) omTmp.get("omdat"), pdate));
}
}
compressData(ret);
return ret;
}
|
diff --git a/htroot/yacysearchitem.java b/htroot/yacysearchitem.java
index b693cb2d0..9644560df 100644
--- a/htroot/yacysearchitem.java
+++ b/htroot/yacysearchitem.java
@@ -1,238 +1,239 @@
// yacysearchitem.java
// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
// first published 28.08.2007 on http://yacy.net
//
// This is a part of YaCy, a peer-to-peer based web search engine
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
// LICENSE
//
// 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
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.TreeSet;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.util.EventTracker;
import net.yacy.kelondro.util.Formatter;
import de.anomic.http.server.HeaderFramework;
import de.anomic.http.server.RequestHeader;
import de.anomic.search.ContentDomain;
import de.anomic.search.MediaSnippet;
import de.anomic.search.QueryParams;
import de.anomic.search.SearchEvent;
import de.anomic.search.RankingProcess;
import de.anomic.search.ResultEntry;
import de.anomic.search.SearchEventCache;
import de.anomic.search.Switchboard;
import de.anomic.search.TextSnippet;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.tools.crypt;
import de.anomic.tools.nxTools;
import de.anomic.yacy.yacyNewsPool;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.graphics.ProfilingGraph;
public class yacysearchitem {
private static boolean col = true;
private static final int namelength = 60;
private static final int urllength = 120;
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
final String eventID = post.get("eventID", "");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int item = post.getInt("item", -1);
final boolean auth = (header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
final int display = (post == null) ? 0 : post.getInt("display", 0);
// default settings for blank item
prop.put("content", "0");
prop.put("rss", "0");
prop.put("references", "0");
prop.put("rssreferences", "0");
prop.put("dynamic", "0");
// find search event
final SearchEvent theSearch = SearchEventCache.getEvent(eventID);
if (theSearch == null) {
// the event does not exist, show empty page
return prop;
}
final QueryParams theQuery = theSearch.getQuery();
// dynamically update count values
final int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize();
final int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
prop.put("offset", offset);
prop.put("itemscount", Formatter.number(Math.min((item < 0) ? theQuery.neededResults() : item + 1, totalcount)));
prop.put("totalcount", Formatter.number(totalcount, true));
prop.put("localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalResourceSize(), true));
prop.put("remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
if (theQuery.contentdom == ContentDomain.TEXT) {
// text search
// generate result object
final ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
final int port=result.url().getPort();
DigestURI faviconURL = null;
if (!result.url().isLocal()) try {
faviconURL = new DigestURI(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null);
} catch (final MalformedURLException e1) {
faviconURL = null;
}
prop.put("content", 1); // switch on specific content
prop.put("content_authorized", authenticated ? "1" : "0");
prop.put("content_authorized_recommend", (sb.peers.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.urlstring()) == null) ? "1" : "0");
prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + result.hash() + "&urlmaskfilter=.*");
prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + result.hash() + "&urlmaskfilter=.*");
prop.put("content_authorized_urlhash", result.hash());
prop.putHTML("content_title", result.title());
prop.putXML("content_title-xml", result.title());
prop.putJSON("content_title-json", result.title());
prop.putHTML("content_link", result.urlstring());
prop.put("content_display", display);
prop.putHTML("content_faviconCode", sb.licensedURLs.aquireLicense(faviconURL)); // aquire license for favicon url loading
prop.put("content_urlhash", result.hash());
prop.put("content_urlhexhash", yacySeed.b64Hash2hexHash(result.hash()));
prop.putHTML("content_urlname", nxTools.shortenURLString(result.urlname(), urllength));
prop.put("content_date", Switchboard.dateString(result.modified()));
prop.put("content_date822", Switchboard.dateString822(result.modified()));
prop.put("content_ybr", RankingProcess.ybr(result.hash()));
prop.putHTML("content_size", Integer.toString(result.filesize())); // we don't use putNUM here because that number shall be usable as sorting key. To print the size, use 'sizename'
prop.putHTML("content_sizename", sizename(result.filesize()));
prop.putHTML("content_host", result.url().getHost());
prop.putHTML("content_file", result.url().getFile());
prop.putHTML("content_path", result.url().getPath());
prop.put("content_nl", (item == 0) ? 0 : 1);
final TreeSet<String>[] query = theQuery.queryWords();
DigestURI wordURL = null;
try {
prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
} catch (final UnsupportedEncodingException e) {}
prop.putHTML("content_former", theQuery.queryString);
prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + DigestURI.domLengthEstimation(result.hash()) +
((DigestURI.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") +
(((wordURL = DigestURI.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : ""));
final TextSnippet snippet = result.textSnippet();
final String desc = (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes);
prop.put("content_description", desc);
prop.putXML("content_description-xml", desc);
prop.putJSON("content_description-json", desc);
EventTracker.update("SEARCH", new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.FINALIZATION + "-" + item, 0, 0), false, 30000, ProfilingGraph.maxTime);
return prop;
}
if (theQuery.contentdom == ContentDomain.IMAGE) {
// image search; shows thumbnails
prop.put("content", theQuery.contentdom.getCode() + 1); // switch on specific content
final MediaSnippet ms = theSearch.result().oneImage(item);
if (ms == null) {
prop.put("content_item", "0");
} else {
prop.putHTML("content_item_hrefCache", (auth) ? "/ViewImage.png?url=" + ms.href.toNormalform(true, false) : ms.href.toNormalform(true, false));
prop.putHTML("content_item_href", ms.href.toNormalform(true, false));
prop.put("content_item_code", sb.licensedURLs.aquireLicense(ms.href));
prop.putHTML("content_item_name", shorten(ms.name, namelength));
prop.put("content_item_mimetype", ms.mime);
prop.put("content_item_fileSize", ms.fileSize);
prop.put("content_item_width", ms.width);
prop.put("content_item_height", ms.height);
prop.put("content_item_attr", (ms.attr.equals("-1 x -1")) ? "" : "(" + ms.attr + ")"); // attributes, here: original size of image
prop.put("content_item_urlhash", ms.source.hash());
prop.put("content_item_source", ms.source.toNormalform(true, false));
+ prop.putXML("content_item_source-xml", ms.source.toNormalform(true, false));
prop.put("content_item_sourcedom", ms.source.getHost());
prop.put("content_item_nl", (item == 0) ? 0 : 1);
prop.put("content_item", 1);
}
return prop;
}
if ((theQuery.contentdom == ContentDomain.AUDIO) ||
(theQuery.contentdom == ContentDomain.VIDEO) ||
(theQuery.contentdom == ContentDomain.APP)) {
// any other media content
// generate result object
final ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
prop.put("content", theQuery.contentdom.getCode() + 1); // switch on specific content
final ArrayList<MediaSnippet> media = result.mediaSnippets();
if (item == 0) col = true;
if (media != null) {
MediaSnippet ms;
int c = 0;
for (int i = 0; i < media.size(); i++) {
ms = media.get(i);
prop.putHTML("content_items_" + i + "_href", ms.href.toNormalform(true, false));
prop.putHTML("content_items_" + i + "_hrefshort", nxTools.shortenURLString(ms.href.toNormalform(true, false), urllength));
prop.putHTML("content_items_" + i + "_name", shorten(ms.name, namelength));
prop.put("content_items_" + i + "_col", (col) ? "0" : "1");
c++;
col = !col;
}
prop.put("content_items", c);
} else {
prop.put("content_items", "0");
}
return prop;
}
return prop;
}
private static String shorten(final String s, final int length) {
if (s.length() <= length) return s;
final int p = s.lastIndexOf('.');
if (p < 0) return s.substring(0, length - 3) + "...";
return s.substring(0, length - (s.length() - p) - 3) + "..." + s.substring(p); // TODO check oob
}
private static String sizename(int size) {
if (size < 1024) return size + " bytes";
size = size / 1024;
if (size < 1024) return size + " kbyte";
size = size / 1024;
if (size < 1024) return size + " mbyte";
size = size / 1024;
return size + " gbyte";
}
}
| true | true | public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
final String eventID = post.get("eventID", "");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int item = post.getInt("item", -1);
final boolean auth = (header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
final int display = (post == null) ? 0 : post.getInt("display", 0);
// default settings for blank item
prop.put("content", "0");
prop.put("rss", "0");
prop.put("references", "0");
prop.put("rssreferences", "0");
prop.put("dynamic", "0");
// find search event
final SearchEvent theSearch = SearchEventCache.getEvent(eventID);
if (theSearch == null) {
// the event does not exist, show empty page
return prop;
}
final QueryParams theQuery = theSearch.getQuery();
// dynamically update count values
final int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize();
final int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
prop.put("offset", offset);
prop.put("itemscount", Formatter.number(Math.min((item < 0) ? theQuery.neededResults() : item + 1, totalcount)));
prop.put("totalcount", Formatter.number(totalcount, true));
prop.put("localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalResourceSize(), true));
prop.put("remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
if (theQuery.contentdom == ContentDomain.TEXT) {
// text search
// generate result object
final ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
final int port=result.url().getPort();
DigestURI faviconURL = null;
if (!result.url().isLocal()) try {
faviconURL = new DigestURI(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null);
} catch (final MalformedURLException e1) {
faviconURL = null;
}
prop.put("content", 1); // switch on specific content
prop.put("content_authorized", authenticated ? "1" : "0");
prop.put("content_authorized_recommend", (sb.peers.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.urlstring()) == null) ? "1" : "0");
prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + result.hash() + "&urlmaskfilter=.*");
prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + result.hash() + "&urlmaskfilter=.*");
prop.put("content_authorized_urlhash", result.hash());
prop.putHTML("content_title", result.title());
prop.putXML("content_title-xml", result.title());
prop.putJSON("content_title-json", result.title());
prop.putHTML("content_link", result.urlstring());
prop.put("content_display", display);
prop.putHTML("content_faviconCode", sb.licensedURLs.aquireLicense(faviconURL)); // aquire license for favicon url loading
prop.put("content_urlhash", result.hash());
prop.put("content_urlhexhash", yacySeed.b64Hash2hexHash(result.hash()));
prop.putHTML("content_urlname", nxTools.shortenURLString(result.urlname(), urllength));
prop.put("content_date", Switchboard.dateString(result.modified()));
prop.put("content_date822", Switchboard.dateString822(result.modified()));
prop.put("content_ybr", RankingProcess.ybr(result.hash()));
prop.putHTML("content_size", Integer.toString(result.filesize())); // we don't use putNUM here because that number shall be usable as sorting key. To print the size, use 'sizename'
prop.putHTML("content_sizename", sizename(result.filesize()));
prop.putHTML("content_host", result.url().getHost());
prop.putHTML("content_file", result.url().getFile());
prop.putHTML("content_path", result.url().getPath());
prop.put("content_nl", (item == 0) ? 0 : 1);
final TreeSet<String>[] query = theQuery.queryWords();
DigestURI wordURL = null;
try {
prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
} catch (final UnsupportedEncodingException e) {}
prop.putHTML("content_former", theQuery.queryString);
prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + DigestURI.domLengthEstimation(result.hash()) +
((DigestURI.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") +
(((wordURL = DigestURI.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : ""));
final TextSnippet snippet = result.textSnippet();
final String desc = (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes);
prop.put("content_description", desc);
prop.putXML("content_description-xml", desc);
prop.putJSON("content_description-json", desc);
EventTracker.update("SEARCH", new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.FINALIZATION + "-" + item, 0, 0), false, 30000, ProfilingGraph.maxTime);
return prop;
}
if (theQuery.contentdom == ContentDomain.IMAGE) {
// image search; shows thumbnails
prop.put("content", theQuery.contentdom.getCode() + 1); // switch on specific content
final MediaSnippet ms = theSearch.result().oneImage(item);
if (ms == null) {
prop.put("content_item", "0");
} else {
prop.putHTML("content_item_hrefCache", (auth) ? "/ViewImage.png?url=" + ms.href.toNormalform(true, false) : ms.href.toNormalform(true, false));
prop.putHTML("content_item_href", ms.href.toNormalform(true, false));
prop.put("content_item_code", sb.licensedURLs.aquireLicense(ms.href));
prop.putHTML("content_item_name", shorten(ms.name, namelength));
prop.put("content_item_mimetype", ms.mime);
prop.put("content_item_fileSize", ms.fileSize);
prop.put("content_item_width", ms.width);
prop.put("content_item_height", ms.height);
prop.put("content_item_attr", (ms.attr.equals("-1 x -1")) ? "" : "(" + ms.attr + ")"); // attributes, here: original size of image
prop.put("content_item_urlhash", ms.source.hash());
prop.put("content_item_source", ms.source.toNormalform(true, false));
prop.put("content_item_sourcedom", ms.source.getHost());
prop.put("content_item_nl", (item == 0) ? 0 : 1);
prop.put("content_item", 1);
}
return prop;
}
if ((theQuery.contentdom == ContentDomain.AUDIO) ||
(theQuery.contentdom == ContentDomain.VIDEO) ||
(theQuery.contentdom == ContentDomain.APP)) {
// any other media content
// generate result object
final ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
prop.put("content", theQuery.contentdom.getCode() + 1); // switch on specific content
final ArrayList<MediaSnippet> media = result.mediaSnippets();
if (item == 0) col = true;
if (media != null) {
MediaSnippet ms;
int c = 0;
for (int i = 0; i < media.size(); i++) {
ms = media.get(i);
prop.putHTML("content_items_" + i + "_href", ms.href.toNormalform(true, false));
prop.putHTML("content_items_" + i + "_hrefshort", nxTools.shortenURLString(ms.href.toNormalform(true, false), urllength));
prop.putHTML("content_items_" + i + "_name", shorten(ms.name, namelength));
prop.put("content_items_" + i + "_col", (col) ? "0" : "1");
c++;
col = !col;
}
prop.put("content_items", c);
} else {
prop.put("content_items", "0");
}
return prop;
}
return prop;
}
| public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
final String eventID = post.get("eventID", "");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int item = post.getInt("item", -1);
final boolean auth = (header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
final int display = (post == null) ? 0 : post.getInt("display", 0);
// default settings for blank item
prop.put("content", "0");
prop.put("rss", "0");
prop.put("references", "0");
prop.put("rssreferences", "0");
prop.put("dynamic", "0");
// find search event
final SearchEvent theSearch = SearchEventCache.getEvent(eventID);
if (theSearch == null) {
// the event does not exist, show empty page
return prop;
}
final QueryParams theQuery = theSearch.getQuery();
// dynamically update count values
final int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize();
final int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
prop.put("offset", offset);
prop.put("itemscount", Formatter.number(Math.min((item < 0) ? theQuery.neededResults() : item + 1, totalcount)));
prop.put("totalcount", Formatter.number(totalcount, true));
prop.put("localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalResourceSize(), true));
prop.put("remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
if (theQuery.contentdom == ContentDomain.TEXT) {
// text search
// generate result object
final ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
final int port=result.url().getPort();
DigestURI faviconURL = null;
if (!result.url().isLocal()) try {
faviconURL = new DigestURI(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null);
} catch (final MalformedURLException e1) {
faviconURL = null;
}
prop.put("content", 1); // switch on specific content
prop.put("content_authorized", authenticated ? "1" : "0");
prop.put("content_authorized_recommend", (sb.peers.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.urlstring()) == null) ? "1" : "0");
prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + result.hash() + "&urlmaskfilter=.*");
prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + result.hash() + "&urlmaskfilter=.*");
prop.put("content_authorized_urlhash", result.hash());
prop.putHTML("content_title", result.title());
prop.putXML("content_title-xml", result.title());
prop.putJSON("content_title-json", result.title());
prop.putHTML("content_link", result.urlstring());
prop.put("content_display", display);
prop.putHTML("content_faviconCode", sb.licensedURLs.aquireLicense(faviconURL)); // aquire license for favicon url loading
prop.put("content_urlhash", result.hash());
prop.put("content_urlhexhash", yacySeed.b64Hash2hexHash(result.hash()));
prop.putHTML("content_urlname", nxTools.shortenURLString(result.urlname(), urllength));
prop.put("content_date", Switchboard.dateString(result.modified()));
prop.put("content_date822", Switchboard.dateString822(result.modified()));
prop.put("content_ybr", RankingProcess.ybr(result.hash()));
prop.putHTML("content_size", Integer.toString(result.filesize())); // we don't use putNUM here because that number shall be usable as sorting key. To print the size, use 'sizename'
prop.putHTML("content_sizename", sizename(result.filesize()));
prop.putHTML("content_host", result.url().getHost());
prop.putHTML("content_file", result.url().getFile());
prop.putHTML("content_path", result.url().getPath());
prop.put("content_nl", (item == 0) ? 0 : 1);
final TreeSet<String>[] query = theQuery.queryWords();
DigestURI wordURL = null;
try {
prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
} catch (final UnsupportedEncodingException e) {}
prop.putHTML("content_former", theQuery.queryString);
prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + DigestURI.domLengthEstimation(result.hash()) +
((DigestURI.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") +
(((wordURL = DigestURI.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : ""));
final TextSnippet snippet = result.textSnippet();
final String desc = (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes);
prop.put("content_description", desc);
prop.putXML("content_description-xml", desc);
prop.putJSON("content_description-json", desc);
EventTracker.update("SEARCH", new ProfilingGraph.searchEvent(theQuery.id(true), SearchEvent.FINALIZATION + "-" + item, 0, 0), false, 30000, ProfilingGraph.maxTime);
return prop;
}
if (theQuery.contentdom == ContentDomain.IMAGE) {
// image search; shows thumbnails
prop.put("content", theQuery.contentdom.getCode() + 1); // switch on specific content
final MediaSnippet ms = theSearch.result().oneImage(item);
if (ms == null) {
prop.put("content_item", "0");
} else {
prop.putHTML("content_item_hrefCache", (auth) ? "/ViewImage.png?url=" + ms.href.toNormalform(true, false) : ms.href.toNormalform(true, false));
prop.putHTML("content_item_href", ms.href.toNormalform(true, false));
prop.put("content_item_code", sb.licensedURLs.aquireLicense(ms.href));
prop.putHTML("content_item_name", shorten(ms.name, namelength));
prop.put("content_item_mimetype", ms.mime);
prop.put("content_item_fileSize", ms.fileSize);
prop.put("content_item_width", ms.width);
prop.put("content_item_height", ms.height);
prop.put("content_item_attr", (ms.attr.equals("-1 x -1")) ? "" : "(" + ms.attr + ")"); // attributes, here: original size of image
prop.put("content_item_urlhash", ms.source.hash());
prop.put("content_item_source", ms.source.toNormalform(true, false));
prop.putXML("content_item_source-xml", ms.source.toNormalform(true, false));
prop.put("content_item_sourcedom", ms.source.getHost());
prop.put("content_item_nl", (item == 0) ? 0 : 1);
prop.put("content_item", 1);
}
return prop;
}
if ((theQuery.contentdom == ContentDomain.AUDIO) ||
(theQuery.contentdom == ContentDomain.VIDEO) ||
(theQuery.contentdom == ContentDomain.APP)) {
// any other media content
// generate result object
final ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
prop.put("content", theQuery.contentdom.getCode() + 1); // switch on specific content
final ArrayList<MediaSnippet> media = result.mediaSnippets();
if (item == 0) col = true;
if (media != null) {
MediaSnippet ms;
int c = 0;
for (int i = 0; i < media.size(); i++) {
ms = media.get(i);
prop.putHTML("content_items_" + i + "_href", ms.href.toNormalform(true, false));
prop.putHTML("content_items_" + i + "_hrefshort", nxTools.shortenURLString(ms.href.toNormalform(true, false), urllength));
prop.putHTML("content_items_" + i + "_name", shorten(ms.name, namelength));
prop.put("content_items_" + i + "_col", (col) ? "0" : "1");
c++;
col = !col;
}
prop.put("content_items", c);
} else {
prop.put("content_items", "0");
}
return prop;
}
return prop;
}
|
diff --git a/src/main/java/hudson/ivy/AbstractIvyProject.java b/src/main/java/hudson/ivy/AbstractIvyProject.java
index a5341b6..90b94d2 100644
--- a/src/main/java/hudson/ivy/AbstractIvyProject.java
+++ b/src/main/java/hudson/ivy/AbstractIvyProject.java
@@ -1,91 +1,91 @@
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Timothy Bingaman
*
* 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 hudson.ivy;
import hudson.ivy.AbstractIvyBuild.ParameterizedUpstreamCause;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.Cause;
import hudson.model.ItemGroup;
import hudson.model.ParametersAction;
import hudson.triggers.Trigger;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Common part between {@link IvyModule} and {@link IvyModuleSet}.
*
* @author Timothy Bingaman
*/
public abstract class AbstractIvyProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends AbstractProject<P,R> {
protected AbstractIvyProject(ItemGroup parent, String name) {
super(parent, name);
}
@Override
protected List<Action> createTransientActions() {
List<Action> r = super.createTransientActions();
// if we just pick up the project actions from the last build,
// and if the last build failed very early, then the reports that
// kick in later (like test results) won't be displayed.
// so pick up last successful build, too.
Set<Class> added = new HashSet<Class>();
addTransientActionsFromBuild(getLastBuild(), r, added);
addTransientActionsFromBuild(getLastSuccessfulBuild(), r, added);
- for (Trigger<?> trigger : triggers)
+ for (Trigger<?> trigger : getTriggers().values())
r.addAll(trigger.getProjectActions());
return r;
}
/**
* @param collection
* Add the transient actions to this collection.
*/
protected abstract void addTransientActionsFromBuild(R lastBuild, List<Action> collection, Set<Class> added);
public abstract boolean isUseUpstreamParameters();
@Override
public boolean scheduleBuild(Cause c) {
if(c instanceof ParameterizedUpstreamCause) {
ParameterizedUpstreamCause upc = (ParameterizedUpstreamCause) c;
if(isUseUpstreamParameters()) {
List<ParametersAction> upStreamParams = upc.getUpStreamParameters();
return scheduleBuild(getQuietPeriod(),c,upStreamParams.toArray(new ParametersAction[upStreamParams.size()]));
}
}
return super.scheduleBuild(c);
}
}
| true | true | protected List<Action> createTransientActions() {
List<Action> r = super.createTransientActions();
// if we just pick up the project actions from the last build,
// and if the last build failed very early, then the reports that
// kick in later (like test results) won't be displayed.
// so pick up last successful build, too.
Set<Class> added = new HashSet<Class>();
addTransientActionsFromBuild(getLastBuild(), r, added);
addTransientActionsFromBuild(getLastSuccessfulBuild(), r, added);
for (Trigger<?> trigger : triggers)
r.addAll(trigger.getProjectActions());
return r;
}
| protected List<Action> createTransientActions() {
List<Action> r = super.createTransientActions();
// if we just pick up the project actions from the last build,
// and if the last build failed very early, then the reports that
// kick in later (like test results) won't be displayed.
// so pick up last successful build, too.
Set<Class> added = new HashSet<Class>();
addTransientActionsFromBuild(getLastBuild(), r, added);
addTransientActionsFromBuild(getLastSuccessfulBuild(), r, added);
for (Trigger<?> trigger : getTriggers().values())
r.addAll(trigger.getProjectActions());
return r;
}
|
diff --git a/SeriesGuideMovies/src/com/uwetrottmann/movies/ui/MovieDetailsFragment.java b/SeriesGuideMovies/src/com/uwetrottmann/movies/ui/MovieDetailsFragment.java
index c324cc7..fe1d5e2 100644
--- a/SeriesGuideMovies/src/com/uwetrottmann/movies/ui/MovieDetailsFragment.java
+++ b/SeriesGuideMovies/src/com/uwetrottmann/movies/ui/MovieDetailsFragment.java
@@ -1,254 +1,254 @@
/*
* Copyright 2012 Uwe Trottmann
*
* 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.uwetrottmann.movies.ui;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
import com.uwetrottmann.androidutils.AndroidUtils;
import com.uwetrottmann.movies.Constants;
import com.uwetrottmann.movies.R;
import com.uwetrottmann.movies.entities.MovieDetails;
import com.uwetrottmann.movies.loaders.TmdbMovieLoader;
import com.uwetrottmann.movies.util.ImageDownloader;
import com.uwetrottmann.tmdb.entities.Casts;
import com.uwetrottmann.tmdb.entities.Casts.CastMember;
import com.uwetrottmann.tmdb.entities.Casts.CrewMember;
import com.uwetrottmann.tmdb.entities.Movie;
import com.uwetrottmann.tmdb.entities.Trailers;
public class MovieDetailsFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<MovieDetails> {
public static MovieDetailsFragment newInstance(int tmdbId) {
MovieDetailsFragment f = new MovieDetailsFragment();
Bundle args = new Bundle();
args.putInt(InitBundle.TMDBID, tmdbId);
f.setArguments(args);
return f;
}
public interface InitBundle {
String TMDBID = "tmdbid";
}
// Use layout id for always in-app unique id
private static final int MOVIE_LOADER_ID = R.layout.details_row;
private MovieSummaryAdapter mAdapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// set list adapter
mAdapter = new MovieSummaryAdapter(getSherlockActivity(), getFragmentManager());
setListAdapter(mAdapter);
// style list view
final ListView list = getListView();
list.setDivider(null);
list.setSelector(R.color.transparent);
// nag about no connectivity
if (!AndroidUtils.isNetworkConnected(getActivity())) {
setEmptyText(getString(R.string.offline));
setListShown(true);
} else {
setEmptyText(getString(R.string.details_empty));
setListShown(false);
getLoaderManager().initLoader(MOVIE_LOADER_ID, getArguments(), this);
}
}
@Override
public Loader<MovieDetails> onCreateLoader(int id, Bundle args) {
return new TmdbMovieLoader(getSherlockActivity(), args.getInt(InitBundle.TMDBID));
}
@Override
public void onLoadFinished(Loader<MovieDetails> loader, MovieDetails data) {
mAdapter.setData(data);
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
@Override
public void onLoaderReset(Loader<MovieDetails> loader) {
mAdapter.setData(null);
}
private static class MovieSummaryAdapter extends ArrayAdapter<MovieDetails> {
private LayoutInflater mLayoutInflater;
private static final int LAYOUT = R.layout.details_row;
private ImageDownloader mImageDownloader;
private FragmentManager mFm;
public MovieSummaryAdapter(Context context, FragmentManager fm) {
super(context, LAYOUT);
mLayoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImageDownloader = ImageDownloader.getInstance(context);
mFm = fm;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mLayoutInflater.inflate(LAYOUT, parent, false);
} else {
view = convertView;
}
final MovieDetails item = getItem(position);
final Movie movie = item.movie;
final Trailers trailers = item.trailers;
final Casts cast = item.casts;
((TextView) view.findViewById(R.id.title)).setText(movie.title);
((TextView) view.findViewById(R.id.description)).setText(movie.overview);
((RatingBar) view.findViewById(R.id.ratingBar))
.setRating((float) (double) movie.vote_average);
((TextView) view.findViewById(R.id.votes)).setText(getContext().getResources()
- .getQuantityString(R.plurals.votes, movie.vote_count));
+ .getQuantityString(R.plurals.votes, movie.vote_count, movie.vote_count));
((TextView) view.findViewById(R.id.releaseDate)).setText(DateUtils.formatDateTime(
getContext(), movie.release_date.getTime(), DateUtils.FORMAT_SHOW_DATE));
((TextView) view.findViewById(R.id.runtime)).setText(getContext().getString(
R.string.timeunit, movie.runtime));
if (cast != null) {
// cast
StringBuilder actors = new StringBuilder();
for (CastMember castMember : cast.cast) {
if (actors.length() > 0) {
actors.append("\n");
}
actors.append(castMember.name).append(" ");
actors.append(getContext().getString(R.string.cast_as)).append(" ");
actors.append(castMember.character);
}
((TextView) view.findViewById(R.id.actors)).setText(actors);
// crew
StringBuilder crew = new StringBuilder();
for (CrewMember crewMember : cast.crew) {
if (crew.length() > 0) {
crew.append("\n");
}
crew.append(crewMember.name).append(" (");
crew.append(crewMember.job).append(")");
}
((TextView) view.findViewById(R.id.crew)).setText(crew);
}
view.findViewById(R.id.checkinButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CheckInDialogFragment dialog = CheckInDialogFragment.newInstance(movie.imdb_id,
movie.title);
dialog.show(mFm, "checkin-dialog");
}
});
// IMDb button
View buttonImdb = view.findViewById(R.id.buttonIMDB);
if (!TextUtils.isEmpty(movie.imdb_id)) {
buttonImdb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("imdb:///title/"
+ movie.imdb_id + "/"));
try {
getContext().startActivity(myIntent);
} catch (ActivityNotFoundException e) {
myIntent = new Intent(Intent.ACTION_VIEW, Uri
.parse(Constants.IMDB_TITLE_URL + movie.imdb_id));
getContext().startActivity(myIntent);
}
}
});
} else {
buttonImdb.setVisibility(View.GONE);
}
// Trailer button
// TODO use new YouTube API to display inline
View buttonTrailer = view.findViewById(R.id.buttonTrailer);
if (trailers != null) {
if (trailers.youtube.size() > 0) {
buttonTrailer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v="
+ trailers.youtube.get(0).source));
getContext().startActivity(myIntent);
}
});
}
} else {
buttonTrailer.setVisibility(View.GONE);
}
ImageView imageView = (ImageView) view.findViewById(R.id.fanart);
if (!TextUtils.isEmpty(movie.backdrop_path)) {
String url = "http://cf2.imgobject.com/t/p/w780" + movie.backdrop_path;
mImageDownloader.download(url, imageView, false);
}
return view;
}
public void setData(MovieDetails movie) {
clear();
if (movie != null) {
add(movie);
}
}
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mLayoutInflater.inflate(LAYOUT, parent, false);
} else {
view = convertView;
}
final MovieDetails item = getItem(position);
final Movie movie = item.movie;
final Trailers trailers = item.trailers;
final Casts cast = item.casts;
((TextView) view.findViewById(R.id.title)).setText(movie.title);
((TextView) view.findViewById(R.id.description)).setText(movie.overview);
((RatingBar) view.findViewById(R.id.ratingBar))
.setRating((float) (double) movie.vote_average);
((TextView) view.findViewById(R.id.votes)).setText(getContext().getResources()
.getQuantityString(R.plurals.votes, movie.vote_count));
((TextView) view.findViewById(R.id.releaseDate)).setText(DateUtils.formatDateTime(
getContext(), movie.release_date.getTime(), DateUtils.FORMAT_SHOW_DATE));
((TextView) view.findViewById(R.id.runtime)).setText(getContext().getString(
R.string.timeunit, movie.runtime));
if (cast != null) {
// cast
StringBuilder actors = new StringBuilder();
for (CastMember castMember : cast.cast) {
if (actors.length() > 0) {
actors.append("\n");
}
actors.append(castMember.name).append(" ");
actors.append(getContext().getString(R.string.cast_as)).append(" ");
actors.append(castMember.character);
}
((TextView) view.findViewById(R.id.actors)).setText(actors);
// crew
StringBuilder crew = new StringBuilder();
for (CrewMember crewMember : cast.crew) {
if (crew.length() > 0) {
crew.append("\n");
}
crew.append(crewMember.name).append(" (");
crew.append(crewMember.job).append(")");
}
((TextView) view.findViewById(R.id.crew)).setText(crew);
}
view.findViewById(R.id.checkinButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CheckInDialogFragment dialog = CheckInDialogFragment.newInstance(movie.imdb_id,
movie.title);
dialog.show(mFm, "checkin-dialog");
}
});
// IMDb button
View buttonImdb = view.findViewById(R.id.buttonIMDB);
if (!TextUtils.isEmpty(movie.imdb_id)) {
buttonImdb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("imdb:///title/"
+ movie.imdb_id + "/"));
try {
getContext().startActivity(myIntent);
} catch (ActivityNotFoundException e) {
myIntent = new Intent(Intent.ACTION_VIEW, Uri
.parse(Constants.IMDB_TITLE_URL + movie.imdb_id));
getContext().startActivity(myIntent);
}
}
});
} else {
buttonImdb.setVisibility(View.GONE);
}
// Trailer button
// TODO use new YouTube API to display inline
View buttonTrailer = view.findViewById(R.id.buttonTrailer);
if (trailers != null) {
if (trailers.youtube.size() > 0) {
buttonTrailer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v="
+ trailers.youtube.get(0).source));
getContext().startActivity(myIntent);
}
});
}
} else {
buttonTrailer.setVisibility(View.GONE);
}
ImageView imageView = (ImageView) view.findViewById(R.id.fanart);
if (!TextUtils.isEmpty(movie.backdrop_path)) {
String url = "http://cf2.imgobject.com/t/p/w780" + movie.backdrop_path;
mImageDownloader.download(url, imageView, false);
}
return view;
}
| public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mLayoutInflater.inflate(LAYOUT, parent, false);
} else {
view = convertView;
}
final MovieDetails item = getItem(position);
final Movie movie = item.movie;
final Trailers trailers = item.trailers;
final Casts cast = item.casts;
((TextView) view.findViewById(R.id.title)).setText(movie.title);
((TextView) view.findViewById(R.id.description)).setText(movie.overview);
((RatingBar) view.findViewById(R.id.ratingBar))
.setRating((float) (double) movie.vote_average);
((TextView) view.findViewById(R.id.votes)).setText(getContext().getResources()
.getQuantityString(R.plurals.votes, movie.vote_count, movie.vote_count));
((TextView) view.findViewById(R.id.releaseDate)).setText(DateUtils.formatDateTime(
getContext(), movie.release_date.getTime(), DateUtils.FORMAT_SHOW_DATE));
((TextView) view.findViewById(R.id.runtime)).setText(getContext().getString(
R.string.timeunit, movie.runtime));
if (cast != null) {
// cast
StringBuilder actors = new StringBuilder();
for (CastMember castMember : cast.cast) {
if (actors.length() > 0) {
actors.append("\n");
}
actors.append(castMember.name).append(" ");
actors.append(getContext().getString(R.string.cast_as)).append(" ");
actors.append(castMember.character);
}
((TextView) view.findViewById(R.id.actors)).setText(actors);
// crew
StringBuilder crew = new StringBuilder();
for (CrewMember crewMember : cast.crew) {
if (crew.length() > 0) {
crew.append("\n");
}
crew.append(crewMember.name).append(" (");
crew.append(crewMember.job).append(")");
}
((TextView) view.findViewById(R.id.crew)).setText(crew);
}
view.findViewById(R.id.checkinButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CheckInDialogFragment dialog = CheckInDialogFragment.newInstance(movie.imdb_id,
movie.title);
dialog.show(mFm, "checkin-dialog");
}
});
// IMDb button
View buttonImdb = view.findViewById(R.id.buttonIMDB);
if (!TextUtils.isEmpty(movie.imdb_id)) {
buttonImdb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("imdb:///title/"
+ movie.imdb_id + "/"));
try {
getContext().startActivity(myIntent);
} catch (ActivityNotFoundException e) {
myIntent = new Intent(Intent.ACTION_VIEW, Uri
.parse(Constants.IMDB_TITLE_URL + movie.imdb_id));
getContext().startActivity(myIntent);
}
}
});
} else {
buttonImdb.setVisibility(View.GONE);
}
// Trailer button
// TODO use new YouTube API to display inline
View buttonTrailer = view.findViewById(R.id.buttonTrailer);
if (trailers != null) {
if (trailers.youtube.size() > 0) {
buttonTrailer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v="
+ trailers.youtube.get(0).source));
getContext().startActivity(myIntent);
}
});
}
} else {
buttonTrailer.setVisibility(View.GONE);
}
ImageView imageView = (ImageView) view.findViewById(R.id.fanart);
if (!TextUtils.isEmpty(movie.backdrop_path)) {
String url = "http://cf2.imgobject.com/t/p/w780" + movie.backdrop_path;
mImageDownloader.download(url, imageView, false);
}
return view;
}
|
diff --git a/opal-upgrade/src/main/java/org/obiba/opal/core/upgrade/v2_0_x/database/MoveQuartzTablesUpgradeStep.java b/opal-upgrade/src/main/java/org/obiba/opal/core/upgrade/v2_0_x/database/MoveQuartzTablesUpgradeStep.java
index 46be7b337..dcfcceeb0 100644
--- a/opal-upgrade/src/main/java/org/obiba/opal/core/upgrade/v2_0_x/database/MoveQuartzTablesUpgradeStep.java
+++ b/opal-upgrade/src/main/java/org/obiba/opal/core/upgrade/v2_0_x/database/MoveQuartzTablesUpgradeStep.java
@@ -1,38 +1,37 @@
package org.obiba.opal.core.upgrade.v2_0_x.database;
import javax.sql.DataSource;
import org.obiba.opal.core.service.database.DatabaseRegistry;
import org.obiba.runtime.Version;
import org.obiba.runtime.upgrade.AbstractUpgradeStep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
public class MoveQuartzTablesUpgradeStep extends AbstractUpgradeStep {
private static final Logger log = LoggerFactory.getLogger(MoveQuartzTablesUpgradeStep.class);
private static final String[] DELETE_TABLES = { "QRTZ_LOCKS", "QRTZ_SCHEDULER_STATE", "QRTZ_FIRED_TRIGGERS",
"QRTZ_PAUSED_TRIGGER_GRPS", "QRTZ_CALENDARS", "QRTZ_TRIGGER_LISTENERS", "QRTZ_BLOB_TRIGGERS",
"QRTZ_CRON_TRIGGERS", "QRTZ_SIMPLE_TRIGGERS", "QRTZ_TRIGGERS", "QRTZ_JOB_LISTENERS", "QRTZ_JOB_DETAILS" };
@Autowired
private DatabaseRegistry databaseRegistry;
@Autowired
private DataSource configDataSource;
@Override
public void execute(Version currentVersion) {
JdbcOperations dataJdbcTemplate = new JdbcTemplate(databaseRegistry.getDataSource("opal-data", null));
- JdbcOperations configJdbcTemplate = new JdbcTemplate(configDataSource);
// no need to copy data as BIRT reports are removed from config
for(String table : DELETE_TABLES) {
dataJdbcTemplate.execute("drop table " + table);
}
}
}
| true | true | public void execute(Version currentVersion) {
JdbcOperations dataJdbcTemplate = new JdbcTemplate(databaseRegistry.getDataSource("opal-data", null));
JdbcOperations configJdbcTemplate = new JdbcTemplate(configDataSource);
// no need to copy data as BIRT reports are removed from config
for(String table : DELETE_TABLES) {
dataJdbcTemplate.execute("drop table " + table);
}
}
| public void execute(Version currentVersion) {
JdbcOperations dataJdbcTemplate = new JdbcTemplate(databaseRegistry.getDataSource("opal-data", null));
// no need to copy data as BIRT reports are removed from config
for(String table : DELETE_TABLES) {
dataJdbcTemplate.execute("drop table " + table);
}
}
|
diff --git a/java/server/src/org/openqa/selenium/server/log/DefaultPerSessionLogHandler.java b/java/server/src/org/openqa/selenium/server/log/DefaultPerSessionLogHandler.java
index ae6c86740..24600ffeb 100644
--- a/java/server/src/org/openqa/selenium/server/log/DefaultPerSessionLogHandler.java
+++ b/java/server/src/org/openqa/selenium/server/log/DefaultPerSessionLogHandler.java
@@ -1,248 +1,248 @@
package org.openqa.selenium.server.log;
/*
Copyright 2007-2011 WebDriver committers
Copyright 2007-2011 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.
*/
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* RestishHandler which keeps in memory the log records per session so that users can retrieve logs per
* session.
*/
public class DefaultPerSessionLogHandler extends PerSessionLogHandler {
private final Map<String, List<LogRecord>> perSessionRecords;
// Used to store log records that doesnt have associated session.
// These records get mapped to session id once the session gets created
// Useful for commands like: getNewBrowseSession() which doesnt have session
// associated till the session gets created.
private final Map<ThreadKey, List<LogRecord>> perThreadTempRecords;
private final Formatter formatter;
private Map<ThreadKey, String> threadToSessionMap;
private Map<String, ThreadKey> sessionToThreadMap;
private SessionLogsToFileRepository logFileRepository;
private int capacity;
/**
* New handler keeping track of log records per session.
*
* @param capacity The capacity
* @param minimumLevel Only keep track of records whose level is equal or greater than
* minimumLevel.
* @param formatter Formatter to use when retrieving log messages.
*/
public DefaultPerSessionLogHandler(int capacity, Level minimumLevel, Formatter formatter) {
this.capacity = capacity;
this.formatter = formatter;
this.perSessionRecords = new HashMap<String, List<LogRecord>>();
this.perThreadTempRecords = new HashMap<ThreadKey, List<LogRecord>>();
this.threadToSessionMap = new HashMap<ThreadKey, String>();
this.sessionToThreadMap = new HashMap<String, ThreadKey>();
this.logFileRepository = new SessionLogsToFileRepository();
}
@Override
synchronized public void publish(LogRecord record) {
ThreadKey threadId = new ThreadKey();
String sessionId = threadToSessionMap.get(threadId);
if (sessionId != null) {
List<LogRecord> records = perSessionRecords.get(sessionId);
if (records == null) {
records = new ArrayList<LogRecord>();
}
records.add(record);
perSessionRecords.put(sessionId, records);
if (records.size() > capacity) {
+ perSessionRecords.put( sessionId, new ArrayList<LogRecord>());
// flush records to file;
try {
logFileRepository.flushRecordsToLogFile(sessionId, records);
// clear in memory session records
records.clear();
- perSessionRecords.put(sessionId, records);
} catch (IOException ex) {
ex.printStackTrace();
}
}
} else {
List<LogRecord> records = perThreadTempRecords.get(threadId);
if (records == null) {
records = new ArrayList<LogRecord>();
+ perThreadTempRecords.put(threadId, records);
}
records.add(record);
- perThreadTempRecords.put(threadId, records);
}
}
@Override
public void flush() {
/* NOOP */
}
@Override
public synchronized void close() throws SecurityException {
perSessionRecords.clear();
perThreadTempRecords.clear();
}
private LogRecord[] records(String sessionId) throws IOException {
List<LogRecord> logFileRecords = logFileRepository.getLogRecords(sessionId);
List<LogRecord> records = perSessionRecords.get(sessionId);
if (records != null) {
logFileRecords.addAll(records);
}
return logFileRecords.toArray(new LogRecord[logFileRecords.size()]);
}
private String formattedRecords(String sessionId) throws IOException {
final StringWriter writer;
writer = new StringWriter();
for (LogRecord record : records(sessionId)) {
writer.append(formatter.format(record));
}
return writer.toString();
}
@Override
public synchronized void attachToCurrentThread(String sessionId) {
ThreadKey threadId = new ThreadKey();
if (threadToSessionMap.get(threadId) == null
|| threadToSessionMap.get(threadId).equals(sessionId)) {
threadToSessionMap.put(threadId, sessionId);
sessionToThreadMap.put(sessionId, threadId);
}
transferThreadTempLogsToSessionLogs(sessionId);
}
@Override
public void transferThreadTempLogsToSessionLogs(String sessionId) {
ThreadKey threadId = new ThreadKey();
List<LogRecord> threadRecords = perThreadTempRecords.get(threadId);
List<LogRecord> sessionRecords = perSessionRecords.get(sessionId);
if (threadRecords != null) {
if (sessionRecords == null) {
sessionRecords = new ArrayList<LogRecord>();
perSessionRecords.put(sessionId, sessionRecords);
}
sessionRecords.addAll(threadRecords);
}
clearThreadTempLogs();
}
@Override
public synchronized void detachFromCurrentThread() {
ThreadKey threadId = new ThreadKey();
String sessionId = threadToSessionMap.get(threadId);
if (sessionId != null) {
threadToSessionMap.remove(threadId);
sessionToThreadMap.remove(sessionId);
clearThreadTempLogs();
}
}
@Override
public synchronized void removeSessionLogs(String sessionId) {
ThreadKey threadId = sessionToThreadMap.get(sessionId);
String sessionIdForThread = threadToSessionMap.get(threadId);
if (threadId != null && sessionIdForThread != null && sessionIdForThread.equals(sessionId)) {
threadToSessionMap.remove(threadId);
sessionToThreadMap.remove(sessionId);
}
perSessionRecords.remove(sessionId);
logFileRepository.removeLogFile(sessionId);
}
/**
* Clears the logging events attached to the thread.
*
* The logging is globally added to the jvm and is effectively used by both classic selenium and
* WebDriver.
*
* WebDriver must call this to avoid leaking memory, even though it is not really used.
*
* Ideally we should probably attach the *request* somewhere we could pick it up, so we could
* attach the pre-session logging to the request instead of the logging. Unfortunately this is no
* small task.
*/
@Override
public synchronized void clearThreadTempLogs() {
ThreadKey threadId = new ThreadKey();
perThreadTempRecords.remove(threadId);
}
/**
* This returns Selenium Remote Control logs associated with the sessionId.
*
* @param sessionId session-id for which the RC logs will be returned.
* @return String RC logs for the sessionId
* @throws IOException when the elves go bad
*/
@Override
public synchronized String getLog(String sessionId) throws IOException {
// TODO(chandra): Provide option to clear logs after getLog()
String logs = formattedRecords(sessionId);
logs = "\n<RC_Logs RC_Session_ID=" + sessionId + ">\n" + logs
+ "\n</RC_Logs>\n";
return logs;
}
private static class ThreadKey {
private final String name;
private final Long id;
ThreadKey() {
this.name = Thread.currentThread().toString();
this.id = Thread.currentThread().getId();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ThreadKey threadKey = (ThreadKey) o;
return !(id != null ? !id.equals(threadKey.id) : threadKey.id != null);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
@Override
public String toString() {
return "id" + id + "," + name;
}
}
}
| false | true | synchronized public void publish(LogRecord record) {
ThreadKey threadId = new ThreadKey();
String sessionId = threadToSessionMap.get(threadId);
if (sessionId != null) {
List<LogRecord> records = perSessionRecords.get(sessionId);
if (records == null) {
records = new ArrayList<LogRecord>();
}
records.add(record);
perSessionRecords.put(sessionId, records);
if (records.size() > capacity) {
// flush records to file;
try {
logFileRepository.flushRecordsToLogFile(sessionId, records);
// clear in memory session records
records.clear();
perSessionRecords.put(sessionId, records);
} catch (IOException ex) {
ex.printStackTrace();
}
}
} else {
List<LogRecord> records = perThreadTempRecords.get(threadId);
if (records == null) {
records = new ArrayList<LogRecord>();
}
records.add(record);
perThreadTempRecords.put(threadId, records);
}
}
| synchronized public void publish(LogRecord record) {
ThreadKey threadId = new ThreadKey();
String sessionId = threadToSessionMap.get(threadId);
if (sessionId != null) {
List<LogRecord> records = perSessionRecords.get(sessionId);
if (records == null) {
records = new ArrayList<LogRecord>();
}
records.add(record);
perSessionRecords.put(sessionId, records);
if (records.size() > capacity) {
perSessionRecords.put( sessionId, new ArrayList<LogRecord>());
// flush records to file;
try {
logFileRepository.flushRecordsToLogFile(sessionId, records);
// clear in memory session records
records.clear();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} else {
List<LogRecord> records = perThreadTempRecords.get(threadId);
if (records == null) {
records = new ArrayList<LogRecord>();
perThreadTempRecords.put(threadId, records);
}
records.add(record);
}
}
|
diff --git a/src/Ne0nx3r0/QuantumConnectors/CircuitManager.java b/src/Ne0nx3r0/QuantumConnectors/CircuitManager.java
index 0e9bd91..2741e93 100644
--- a/src/Ne0nx3r0/QuantumConnectors/CircuitManager.java
+++ b/src/Ne0nx3r0/QuantumConnectors/CircuitManager.java
@@ -1,182 +1,183 @@
package Ne0nx3r0.QuantumConnectors;
import org.bukkit.util.config.Configuration;
import java.io.File;
import java.util.Map;
import java.util.HashMap;
import org.bukkit.block.Block;
import org.bukkit.Material;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.Location;
import java.util.ArrayList;
public final class CircuitManager{
private final QuantumConnectors plugin;
public static Configuration yml;
private static Map<Location,Circuit> circuits;
public CircuitManager(File ymlFile,final QuantumConnectors plugin){
this.plugin = plugin;
circuits = new HashMap<Location,Circuit>();
yml = new Configuration(ymlFile);
yml.load();
Load();
}
public void addCircuit(Location lSender,Location lReceiver,int iType){
circuits.put(lSender,new Circuit(iType,lReceiver));
}
public boolean circuitExists(Location lSender){
return circuits.containsKey(lSender);
}
public Circuit getCircuit(Location lSender){
return circuits.get(lSender);
}
public void removeCircuit(Location lSender){
if(circuits.containsKey(lSender)){
circuits.remove(lSender);
}
}
private Material[] validSenders = new Material[]{
Material.LEVER,
Material.REDSTONE_WIRE,
Material.STONE_BUTTON,
Material.STONE_PLATE,
Material.WOOD_PLATE,
Material.REDSTONE_TORCH_OFF,
Material.REDSTONE_TORCH_ON,
Material.IRON_DOOR_BLOCK,
Material.WOODEN_DOOR,
Material.TRAP_DOOR,
Material.STONE_BUTTON,
Material.POWERED_RAIL,
Material.DIODE_BLOCK_OFF,
Material.DIODE_BLOCK_ON
};
private Material[] validReceivers = new Material[]{
Material.LEVER,
Material.IRON_DOOR_BLOCK,
Material.WOODEN_DOOR,
Material.TRAP_DOOR,
Material.POWERED_RAIL
};
public boolean isValidSender(Block block){
Material mBlock = block.getType();
for(int i=0;i<validSenders.length;i++){
if(mBlock == validSenders[i]){
return true;
}
}
return false;
}
public String getValidSendersString(){
String sMessage = "";
for(int i=0;i<validSenders.length;i++){
sMessage += validSenders[i].name().toLowerCase().replace("_"," ")+", ";
}
return sMessage.substring(0,sMessage.length()-2);
}
public boolean isValidReceiver(Block block){
Material mBlock = block.getType();
for(int i=0;i<validReceivers.length;i++){
if(mBlock == validReceivers[i]){
return true;
}
}
return false;
}
public String getValidReceiversString(){
String sMessage = "";
for(int i=0;i<validReceivers.length;i++){
sMessage += validReceivers[i].name().toLowerCase().replace("_"," ")+", ";
}
return sMessage.substring(0,sMessage.length()-2);
}
public void Load(){
List tempCircuits = yml.getList("circuits");
if(tempCircuits == null){
System.out.println("[Quantum Connectors] No circuits.yml file found, will be created on the next save.");
return;
}
Server server = Bukkit.getServer();
Location lSender;
Location lReceiver;
int iType;
Map<String,Object> temp;
for(int i=0; i< tempCircuits.size(); i++){
temp = (Map<String,Object>) tempCircuits.get(i);
iType = (Integer) temp.get("type");
lSender = new Location(
server.getWorld((String) temp.get("sw")),
(Integer) temp.get("sx"),
(Integer) temp.get("sy"),
(Integer) temp.get("sz")
);
lReceiver = new Location(
server.getWorld((String) temp.get("rw")),
(Integer) temp.get("rx"),
(Integer) temp.get("ry"),
(Integer) temp.get("rz")
);
if(isValidSender(lSender.getBlock())
&& isValidReceiver(lReceiver.getBlock())
- && plugin.circuitTypes.containsValue(iType)){
+ && plugin.circuitTypes.containsValue(iType)
+ && !lReceiver.toString().equals(lSender.toString())){
addCircuit(lSender,lReceiver,iType);
}else{
System.out.println("[QuantumConnectors] Removing invalid circuit.");
}
}
}
public void Save(){
List<Object> tempCircuits = new ArrayList<Object>();
Map<String,Object> temp;
Circuit currentCircuit;
for(Location lKey : circuits.keySet()){
currentCircuit = circuits.get(lKey);
temp = new HashMap<String,Object>();
temp.put("sw",lKey.getWorld().getName());
temp.put("sx",lKey.getBlockX());
temp.put("sy",lKey.getBlockY());
temp.put("sz",lKey.getBlockZ());
temp.put("rw",currentCircuit.reciever.getWorld().getName());
temp.put("rx",currentCircuit.reciever.getBlockX());
temp.put("ry",currentCircuit.reciever.getBlockY());
temp.put("rz",currentCircuit.reciever.getBlockZ());
temp.put("type",currentCircuit.type);
tempCircuits.add(temp);
}
yml.setProperty("circuits", tempCircuits);
yml.save();
}
}
| true | true | public void Load(){
List tempCircuits = yml.getList("circuits");
if(tempCircuits == null){
System.out.println("[Quantum Connectors] No circuits.yml file found, will be created on the next save.");
return;
}
Server server = Bukkit.getServer();
Location lSender;
Location lReceiver;
int iType;
Map<String,Object> temp;
for(int i=0; i< tempCircuits.size(); i++){
temp = (Map<String,Object>) tempCircuits.get(i);
iType = (Integer) temp.get("type");
lSender = new Location(
server.getWorld((String) temp.get("sw")),
(Integer) temp.get("sx"),
(Integer) temp.get("sy"),
(Integer) temp.get("sz")
);
lReceiver = new Location(
server.getWorld((String) temp.get("rw")),
(Integer) temp.get("rx"),
(Integer) temp.get("ry"),
(Integer) temp.get("rz")
);
if(isValidSender(lSender.getBlock())
&& isValidReceiver(lReceiver.getBlock())
&& plugin.circuitTypes.containsValue(iType)){
addCircuit(lSender,lReceiver,iType);
}else{
System.out.println("[QuantumConnectors] Removing invalid circuit.");
}
}
}
| public void Load(){
List tempCircuits = yml.getList("circuits");
if(tempCircuits == null){
System.out.println("[Quantum Connectors] No circuits.yml file found, will be created on the next save.");
return;
}
Server server = Bukkit.getServer();
Location lSender;
Location lReceiver;
int iType;
Map<String,Object> temp;
for(int i=0; i< tempCircuits.size(); i++){
temp = (Map<String,Object>) tempCircuits.get(i);
iType = (Integer) temp.get("type");
lSender = new Location(
server.getWorld((String) temp.get("sw")),
(Integer) temp.get("sx"),
(Integer) temp.get("sy"),
(Integer) temp.get("sz")
);
lReceiver = new Location(
server.getWorld((String) temp.get("rw")),
(Integer) temp.get("rx"),
(Integer) temp.get("ry"),
(Integer) temp.get("rz")
);
if(isValidSender(lSender.getBlock())
&& isValidReceiver(lReceiver.getBlock())
&& plugin.circuitTypes.containsValue(iType)
&& !lReceiver.toString().equals(lSender.toString())){
addCircuit(lSender,lReceiver,iType);
}else{
System.out.println("[QuantumConnectors] Removing invalid circuit.");
}
}
}
|
diff --git a/topcat/src/main/uk/ac/starlink/topcat/PlotWindow.java b/topcat/src/main/uk/ac/starlink/topcat/PlotWindow.java
index 9c3795bfc..c5202b2e1 100644
--- a/topcat/src/main/uk/ac/starlink/topcat/PlotWindow.java
+++ b/topcat/src/main/uk/ac/starlink/topcat/PlotWindow.java
@@ -1,962 +1,962 @@
package uk.ac.starlink.topcat;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Date;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultButtonModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.filechooser.FileFilter;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import ptolemy.plot.Plot;
import ptolemy.plot.PlotBox;
import uk.ac.starlink.table.ColumnInfo;
import uk.ac.starlink.table.RowSequence;
import uk.ac.starlink.table.StarTable;
import uk.ac.starlink.table.gui.ProgressBarStarTable;
import uk.ac.starlink.table.gui.StarTableColumn;
import uk.ac.starlink.util.ErrorDialog;
/**
* Top level window which presents plots derived from a <tt>StarTable</tt>.
* A number of plot configuration options are available to be configured
* interactively by the user.
*
* @author Mark Taylor (Starlink)
*/
public class PlotWindow extends AuxWindow implements ActionListener {
private TableViewer tv;
private StarTable dataModel;
private TableColumnModel columnModel;
private OptionsListModel subsets;
private JComboBox xColBox;
private JComboBox yColBox;
private JCheckBox xLogBox;
private JCheckBox yLogBox;
private ListSelectionModel subSelModel;
private JPanel plotPanel;
private JProgressBar progBar;
private JFileChooser printSaver;
private PlotState lastState;
private PlotBox lastPlot;
private BitSet plottedRows;
private ScatterPlotter activePlotter;
private boolean showGrid = true;
private String markStyle = "dots";
private Action fromvisibleAction;
private static final double MILLISECONDS_PER_YEAR
= 365.25 * 24 * 60 * 60 * 1000;
private static final ActionEvent FORCE_REPLOT =
new ActionEvent( new Object(), 0, null );
/**
* Constructs a PlotWindow for a given <tt>TableModel</tt> and
* <tt>TableColumnModel</tt>.
*
* @param tableviewer the viewer whose data are to be plotted
*/
public PlotWindow( TableViewer tableviewer ) {
super( "Table Plotter", tableviewer );
this.tv = tableviewer;
this.dataModel = tv.getDataModel();
this.columnModel = tv.getColumnModel();
this.subsets = tv.getSubsets();
/* Do some window setup. */
setSize( 400, 400 );
/* Construct a panel for configuration of X and Y axes. */
Border lineBorder = BorderFactory.createLineBorder( Color.BLACK );
JPanel xConfig = new JPanel();
JPanel yConfig = new JPanel();
xConfig.setBorder( BorderFactory
.createTitledBorder( lineBorder, "X axis" ) );
yConfig.setBorder( BorderFactory
.createTitledBorder( lineBorder, "Y axis" ) );
Box axisBox = new Box( BoxLayout.Y_AXIS );
axisBox.add( xConfig );
axisBox.add( Box.createGlue() );
axisBox.add( yConfig );
getControlPanel().add( axisBox );
/* Construct axis selectors for X and Y. */
xColBox = makePlottableColumnComboBox();
yColBox = makePlottableColumnComboBox();
/* If there are too few numeric columns then inform the user and
* bail out. */
assert xColBox.getItemCount() == yColBox.getItemCount();
if ( xColBox.getItemCount() < 2 ) {
JOptionPane.showMessageDialog( null,
"Too few numeric columns in table",
"Plot error",
JOptionPane.ERROR_MESSAGE );
dispose();
}
/* Place the selectors in this window. */
xConfig.add( xColBox );
yConfig.add( yColBox );
xColBox.setSelectedIndex( 0 );
yColBox.setSelectedIndex( 1 );
xColBox.addActionListener( this );
yColBox.addActionListener( this );
/* Add linear/log selectors for X and Y. */
xLogBox = new JCheckBox( "Log plot" );
yLogBox = new JCheckBox( "Log plot" );
xConfig.add( xLogBox );
yConfig.add( yLogBox );
xLogBox.addActionListener( this );
yLogBox.addActionListener( this );
/* Add a menu for printing the graph. */
Action printAction = new BasicAction( "Print as EPS",
ResourceIcon.PRINT,
"Print the graph to an " +
"EPS file" ) {
public void actionPerformed( ActionEvent evt ) {
/* Ask the user where to output the postscript. */
Component parent = PlotWindow.this;
JFileChooser chooser = getPrintSaver();
if ( chooser.showSaveDialog( parent )
== JFileChooser.APPROVE_OPTION ) {
try {
File file = chooser.getSelectedFile();
OutputStream ostrm = new FileOutputStream( file );
/* Only one mark style makes much sense for the
* EPSGraphics class used here, so change the plot
* to that for the duration of the write, then
* back again. */
setMarkStyle( lastPlot, "various" );
try {
lastPlot.export( ostrm );
}
finally {
setMarkStyle( lastPlot, markStyle );
ostrm.close();
}
}
catch ( IOException e ) {
ErrorDialog.showError( e, "Error writing EPS", parent );
}
}
}
};
getFileMenu().insert( printAction, 0 ).setIcon( null );
/* Get a menu for selecting row subsets to plot. */
CheckBoxMenu subMenu = subsets.makeCheckBoxMenu( "Subsets to plot" );
subSelModel = subMenu.getSelectionModel();
/* Do the same thing as a scrollable box in the control panel. */
CheckBoxStack stack = new CheckBoxStack( subsets );
JComponent stackPanel = new JScrollPane( stack );
stackPanel.setBorder( BorderFactory
.createTitledBorder( lineBorder, "Row subsets" ) );
getControlPanel().add( stackPanel );
stack.setSelectionModel( subSelModel );
/* Initialise its selections so that both ALL and the current subset,
* of the viewer, if any, are plotted. */
subSelModel.addSelectionInterval( 0, 0 ); // ALL
int nrsets = subsets.size();
RowSubset currentSet = tv.getViewModel().getSubset();
if ( currentSet != RowSubset.ALL ) {
for ( int i = 1; i < nrsets; i++ ) {
if ( subsets.get( i ) == currentSet ) {
subSelModel.addSelectionInterval( i, i );
}
}
}
/* Ensure that the plot will respond to the subset selection being
* changed. */
subSelModel.addListSelectionListener( new ListSelectionListener() {
public void valueChanged( ListSelectionEvent evt ) {
/* If the only changed items are ones which have been
* deselected, we can do this cheaply. */
int first = evt.getFirstIndex();
int last = evt.getLastIndex();
PlotState state = getPlotState();
RowSubset[] mask = state.subsetMask;
RowSubset[] lastMask = lastState.subsetMask;
boolean allClear = true;
for ( int i = first; i <= last && allClear; i++ ) {
- if ( i >= mask.length || i > lastMask.length ||
+ if ( i >= mask.length || i >= lastMask.length ||
( mask[ i ] != null && lastMask[ i ] == null ) ) {
allClear = false;
}
}
if ( allClear && lastPlot instanceof Plot ) {
Plot plot = (Plot) lastPlot;
for ( int i = first; i <= last; i++ ) {
if ( mask[ i ] == null && lastMask[ i ] != null ) {
plot.clear( setFor( i ) );
}
}
lastState = state;
}
/* Otherwise, a proper replot will be necesary. */
else {
PlotWindow.this.actionPerformed( null );
}
}
} );
/* Construct a panel which will hold the plot itself. */
plotPanel = new JPanel( new BorderLayout() );
/* Arrange the components in the top level window. */
JPanel mainArea = getMainArea();
mainArea.add( plotPanel, BorderLayout.CENTER );
/* Add a progress bar. */
progBar = placeProgressBar();
/* Action for showing the grid. */
final ButtonModel gridModel = new DefaultButtonModel();
gridModel.setSelected( showGrid );
gridModel.addItemListener( new ItemListener() {
public void itemStateChanged( ItemEvent evt ) {
if ( gridModel.isSelected() != showGrid ) {
showGrid = ! showGrid;
lastPlot.setGrid( showGrid );
}
lastPlot.repaint();
}
} );
Action gridAction = new BasicAction( "Show grid",
ResourceIcon.GRID_ON,
"Select whether grid " +
"lines are displayed" ) {
public void actionPerformed( ActionEvent evt ) {
gridModel.setSelected( ! gridModel.isSelected() );
}
};
final AbstractButton gridToolButton = new JButton( gridAction );
gridToolButton.setText( null );
gridModel.addItemListener( new ItemListener() {
{ itemStateChanged( null ); }
public void itemStateChanged( ItemEvent evt ) {
gridToolButton.setIcon( gridModel.isSelected()
? ResourceIcon.GRID_OFF
: ResourceIcon.GRID_ON );
}
} );
/* Action for resizing the plot. */
Action resizeAction = new BasicAction( "Rescale",
ResourceIcon.RESIZE,
"Rescale the plot to show " +
"all points points" ) {
public void actionPerformed( ActionEvent evt ) {
lastPlot.fillPlot();
}
};
/* Menu item for selecting marker types. */
JMenu markMenu = new JMenu( "Marker type" );
String[] markStyles =
new String[] { "points", "dots", "various", "pixels" };
ButtonGroup bgroup = new ButtonGroup();
for ( int i = 0; i < markStyles.length; i++ ) {
String style = markStyles[ i ];
Action act = new MarkerAction( style );
JMenuItem item = new JRadioButtonMenuItem( act );
if ( style.equals( this.markStyle ) ) {
item.setSelected( true );
}
markMenu.add( item );
bgroup.add( item );
}
/* Action for repdrawing the current plot. */
Action replotAction = new BasicAction( "Replot", ResourceIcon.REDO,
"Redraw the plot with current table data" ) {
public void actionPerformed( ActionEvent evt ) {
PlotWindow.this.actionPerformed( FORCE_REPLOT );
}
};
/* Construct a new menu for general plot operations. */
JMenu plotMenu = new JMenu( "Plot" );
plotMenu.add( resizeAction ).setIcon( null );
plotMenu.add( replotAction ).setIcon( null );
JMenuItem gridItem = new JCheckBoxMenuItem( gridAction );
gridItem.setModel( gridModel );
plotMenu.add( gridItem ).setIcon( null );
plotMenu.add( markMenu );
getJMenuBar().add( plotMenu );
/* Construct a new menu for subset operations. */
JMenu subsetMenu = new JMenu( "Subsets" );
subsetMenu.add( subMenu );
fromvisibleAction = new BasicAction( "New subset from visible",
ResourceIcon.VISIBLE_SUBSET,
"Define a new row subset " +
"containing only currently " +
"visible points" ) {
public void actionPerformed( ActionEvent evt ) {
String name = TableViewer.enquireSubsetName( PlotWindow.this );
if ( name != null ) {
int inew = subsets.size();
subsets.add( new BitsRowSubset( name, calcVisibleRows() ) );
subSelModel.addSelectionInterval( inew, inew );
}
}
};
subsetMenu.add( fromvisibleAction ).setIcon( null );
getJMenuBar().add( subsetMenu );
/* Add actions to the toolbar. */
getToolBar().add( printAction );
getToolBar().add( replotAction );
getToolBar().add( resizeAction );
getToolBar().add( gridToolButton );
getToolBar().add( fromvisibleAction );
getToolBar().addSeparator();
/* Add standard help actions. */
addHelp( "PlotWindow" );
/* Do the plotting. */
actionPerformed( FORCE_REPLOT );
/* Render this component visible. */
pack();
setVisible( true );
}
/**
* Constructs, installs and fills a plot component based on a given
* plotting state.
*/
private void makePlot( PlotState state, double[] xrange, double[] yrange ) {
/* If there is already a plotter doing plotting, stop it. */
if ( activePlotter != null ) {
activePlotter.interrupt();
}
/* Interrogate the plot state. */
int xcol = getColumnIndex( state.xCol );
int ycol = getColumnIndex( state.yCol );
ColumnInfo xColumn = state.xCol.getColumnInfo();
ColumnInfo yColumn = state.yCol.getColumnInfo();
RowSubset[] rsets = state.subsetMask;
int nrsets = rsets.length;
boolean autoSize = xrange == null || yrange == null;
/* Configure the plot. */
PlotBox plotbox;
if ( state.type.equals( "Scatter" ) ) {
Plot plot = new Plot();
plot.setGrid( showGrid );
plotbox = plot;
for ( int i = 0; i < nrsets; i++ ) {
RowSubset rset = rsets[ i ];
if ( rset != null ) {
plot.addLegend( setFor( i ), rset.getName() );
}
}
setMarkStyle( plot, markStyle );
plot.setXLog( state.xLog );
plot.setYLog( state.yLog );
if ( ! autoSize ) {
plot.setXRange( xrange[ 0 ], xrange[ 1 ] );
plot.setYRange( yrange[ 0 ], yrange[ 1 ] );
}
}
else {
throw new AssertionError( "Unknown plot type" );
}
/* Generic configuration. */
plotbox.setTitle( dataModel.getName() );
/* Axis labels. */
String xName = xColumn.getName();
String yName = yColumn.getName();
String xUnit = xColumn.getUnitString();
String yUnit = yColumn.getUnitString();
String xLabel = xName;
String yLabel = yName;
if ( xUnit != null && xUnit.trim().length() > 0 ) {
xLabel = xName + " / " + xUnit;
}
if ( yUnit != null && yUnit.trim().length() > 0 ) {
yLabel = yName + " / " + yUnit;
}
plotbox.setXLabel( xLabel );
plotbox.setYLabel( yLabel );
/* Replace any old plot by the new one. */
plotPanel.removeAll();
plotPanel.add( plotbox, BorderLayout.CENTER );
plotPanel.revalidate();
lastPlot = plotbox;
lastState = state;
/* Initiate plotting of the points. */
if ( state.type.equals( "Scatter" ) ) {
activePlotter = new ScatterPlotter( state, (Plot) plotbox,
autoSize );
}
else {
throw new AssertionError();
}
activePlotter.start();
}
/**
* Maps a subset index to the index of a dataset to use in the
* plot.
*
* @param rsetIndex index of the RowSubset
* @return corresponding dataset index
*/
private int setFor( int rsetIndex ) {
if ( rsetIndex <= 9 ) {
return 9 - rsetIndex;
}
else {
return rsetIndex;
}
}
/**
* Records the bitset which contains the set of points plotted on
* the currently visible plotting surface.
*
* @param prows a BitSet representing all rows in any of the
* currently selected row subsets. This should include only
* those which have actually appeared on the plotting surface,
* though not necesarily in its visible bounds.
* May be null.
*/
public void setPlottedRows( BitSet prows ) {
plottedRows = prows;
fromvisibleAction.setEnabled( plottedRows != null );
}
/**
* Returns a BitSet which corresponds to those rows which have are
* currently visible; that is they were plotted and they fall within
* the bounds of the curretly visible PlotBox.
*
* @return a vector of flags representing visible rows
*/
private BitSet calcVisibleRows() {
/* The list of plotted rows shouldn't be null, but it might just
* be if the timing is unlucky - return an empty list. */
if ( plottedRows == null ) {
return new BitSet();
}
/* Otherwise work out the proper answer. */
int xcol = getColumnIndex( lastState.xCol );
int ycol = getColumnIndex( lastState.yCol );
int nrow = (int) dataModel.getRowCount();
double[] xr = lastPlot.getXRange();
double[] yr = lastPlot.getYRange();
double x0 = xr[ 0 ];
double y0 = yr[ 0 ];
double x1 = xr[ 1 ];
double y1 = yr[ 1 ];
BitSet visibleRows = new BitSet();
try {
for ( int irow = 0; irow < nrow; irow++ ) {
long lrow = (long) irow;
if ( plottedRows.get( irow ) ) {
Object xval = dataModel.getCell( lrow, xcol );
Object yval = dataModel.getCell( lrow, ycol );
double x = doubleValue( xval );
double y = doubleValue( yval );
if ( x >= x0 && x <= x1 && y >= y0 && y <= y1 ) {
visibleRows.set( irow );
}
}
}
}
catch ( IOException e ) {
// oh well
}
return visibleRows;
}
/**
* Returns a list of all the RowSubsets which are currently selected
* for plotting in this window.
*
* @return a List of RowSubsets
*/
public List getSelectedSubsets() {
int min = subSelModel.getMinSelectionIndex();
int max = subSelModel.getMaxSelectionIndex();
List selected = new ArrayList();
if ( min >= 0 ) { // selection not empty
assert max >= 0;
for ( int i = min; i <= max; i++ ) {
if ( subSelModel.isSelectedIndex( i ) ) {
selected.add( subsets.get( i ) );
}
}
}
return selected;
}
/**
* Returns a new JComboBox from which can be selected any of the
* columns of the table which can be plotted.
* This box will be updated when new columns are added to the
* table model and so on.
*
* @param combo box
*/
public JComboBox makePlottableColumnComboBox() {
/* Construct a model which contains an entry for each column
* which contains Numbers or Dates. */
ComboBoxModel boxModel =
new RestrictedColumnComboBoxModel( tv.getColumnModel(), false ) {
protected boolean acceptColumn( TableColumn tcol ) {
StarTableColumn stcol = (StarTableColumn) tcol;
Class clazz = stcol.getColumnInfo().getContentClass();
return Number.class.isAssignableFrom( clazz )
|| Date.class.isAssignableFrom( clazz );
}
};
/* Create a new combobox. */
JComboBox box = new JComboBox( boxModel );
/* Give it a suitable renderer. */
box.setRenderer( tv.getColumnRenderer() );
return box;
}
/**
* Returns the index in the TableModel (not the TableColumnModel) of
* the given TableColumn.
*
* @param tcol the column whose index is to be found
* @return the index of <tt>tcol</tt> in the table model
*/
public int getColumnIndex( TableColumn tcol ) {
return tcol.getModelIndex();
}
/**
* This method is called whenever something happens which may cause
* the plot to need to be updated.
*
* @param evt ignored
*/
public void actionPerformed( ActionEvent evt ) {
/* Action is only required if the requested state of the plot has
* changed since last time we plotted it. */
PlotState state = getPlotState();
if ( ! state.equals( lastState ) || evt == FORCE_REPLOT ) {
/* Configure the visible range of the plot. If the axes are the
* same as for the last plot, we will retain the last plot's range;
* otherwise, fit to include all the data points. */
double[] xrange;
double[] yrange;
if ( state.sameAxes( lastState ) ) {
xrange = lastPlot.getXRange();
yrange = lastPlot.getYRange();
}
else {
xrange = null;
yrange = null;
}
makePlot( state, xrange, yrange );
}
}
/**
* Returns a numeric (double) value for the given object where it
* can be done.
*
* @param value an object
* @return floating point representation of <tt>value</tt>, or
* NaN if it can't be done
*/
private double doubleValue( Object value ) {
if ( value instanceof Number ) {
return ((Number) value).doubleValue();
}
else if ( value instanceof Date ) {
long milliseconds = ((Date) value).getTime();
return 1970.0 + milliseconds / MILLISECONDS_PER_YEAR;
}
else {
return Double.NaN;
}
}
/**
* Action implementation for changing the markers used in plotting.
*/
private class MarkerAction extends BasicAction {
private String style;
MarkerAction( String style ) {
super( style, "Change point markers to style " + style );
this.style = style;
}
public void actionPerformed( ActionEvent evt ) {
markStyle = style;
setMarkStyle( lastPlot, style );
lastPlot.repaint();
}
}
/**
* Sets the style of all the markers in a given plot to a given type.
* This will only have an affect if the plot in question is a Plot
* object; a Histogram for instance has no markers to affect.
*
* @param plotbox the plot to affect
* @param style the name of the style, as per the
* {@link ptolemy.plot.Plot#setMarksStyle} method
*/
private void setMarkStyle( PlotBox plotbox, String style ) {
if ( plotbox instanceof Plot ) {
Plot plot = (Plot) plotbox;
int nset = plot.getNumDataSets();
for ( int i = 0; i < nset; i++ ) {
plot.setMarksStyle( style, i );
}
}
}
/**
* Returns a file chooser widget with which the user can select a
* file to output postscript of the currently plotted graph to.
*
* @return a file chooser
*/
private JFileChooser getPrintSaver() {
if ( printSaver == null ) {
printSaver = new JFileChooser( "." );
printSaver.setAcceptAllFileFilterUsed( true );
FileFilter psFilter = new FileFilter() {
public String getDescription() {
return ".ps, .eps";
}
public boolean accept( File file ) {
if ( file.isDirectory() ) {
return true;
}
String name = file.getName();
int dotpos = name.indexOf( '.' );
if ( dotpos > 0 ) {
String ext = name.substring( dotpos + 1 ).toLowerCase();
return ext.equals( "ps" )
|| ext.equals( "eps" );
}
return false;
}
};
printSaver.addChoosableFileFilter( psFilter );
printSaver.setFileFilter( psFilter );
}
return printSaver;
}
/**
* Extends the dispose method to interrupt any pending calculations.
*/
public void dispose() {
super.dispose();
if ( activePlotter != null ) {
activePlotter.interrupt();
activePlotter = null;
}
}
/**
* This class does the work of turning points in the table data model
* into points in a scatter graph. The table reading and point posting
* is done in a separate thread.
*/
private class ScatterPlotter extends Thread {
PlotState state;
Plot plot;
boolean autoSize;
BitSet plottedRows = new BitSet();
/**
* Construct a new plotter object.
*
* @param state the state which controls how the plot is to be done
* @param plot the Plot object into which the points must be put
* @param autoSize true iff the plot should be resized to fit the
* plotted points
*/
public ScatterPlotter( PlotState state, Plot plot, boolean autoSize ) {
this.state = state;
this.plot = plot;
this.autoSize = autoSize;
}
/**
* Invokes the plotting routine. Also sets the busy cursor as
* appropriate at the start/end of the calculation, as long as
* this plotter has not been superceded as the active plotter
* of the window.
*/
public void run() {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
if ( ScatterPlotter.this == activePlotter ) {
setBusy( true );
}
}
} );
try {
setPlottedRows( null );
doPlotting();
if ( autoSize ) {
plot.fillPlot();
}
setPlottedRows( ScatterPlotter.this.plottedRows );
}
catch ( IOException e ) {
// no action
}
finally {
plot.repaint();
SwingUtilities.invokeLater( new Runnable() {
public void run() {
if ( ScatterPlotter.this == activePlotter ) {
activePlotter = null;
setBusy( false );
}
}
} );
}
}
/**
* Actually does the adding of points to the plot.
*/
private void doPlotting() throws IOException {
/* Obtain the things we need to know from the plot state. */
int xcol = getColumnIndex( state.xCol );
int ycol = getColumnIndex( state.yCol );
boolean xLog = state.xLog;
boolean yLog = state.yLog;
boolean plotline = state.plotline;
RowSubset[] rsets = state.subsetMask;
int nrsets = rsets.length;
boolean[] inclusions = new boolean[ nrsets ];
/* Iterate over the rows in the table. */
long ngood = 0;
long nerror = 0;
RowSequence rseq = new ProgressBarStarTable( dataModel, progBar )
.getRowSequence();
long sincePaint = new Date().getTime();
for ( long lrow = 0; rseq.hasNext(); lrow++ ) {
/* Move to the next row. Note this may throw an IOException
* due to thread interruption (see ProgressBarStarTable). */
rseq.next();
/* See which subsets need to be plotted for this row. */
boolean any = false;
for ( int i = 0; i < nrsets; i++ ) {
RowSubset rset = rsets[ i ];
boolean in = ( rset != null ) && rset.isIncluded( lrow );
inclusions[ i ] = in;
any = any || in;
}
if ( any ) {
Object xval = rseq.getCell( xcol );
Object yval = rseq.getCell( ycol );
double x = doubleValue( xval );
double y = doubleValue( yval );
if ( ! Double.isNaN( x ) && ! Double.isNaN( y ) ) {
if ( xLog && x < 0.0 || yLog && y < 0.0 ) {
// can't take log of negative value
}
else {
for ( int i = nrsets - 1; i >= 0; i-- ) {
if ( inclusions[ i ] ) {
plot.addPoint( setFor( i ), x, y,
plotline );
}
}
ngood++;
plottedRows.set( (int) lrow );
}
}
}
/* If we are autosizing this plot, make sure that we
* haven't gone too long without a repaint, since this
* ensures that the visible region contains all the points. */
if ( autoSize ) {
long now = new Date().getTime();
if ( now - sincePaint > 1000L ) {
plot.fillPlot();
sincePaint = now;
}
}
}
}
}
/**
* Returns the current PlotState of this window.
*
* @return the current state
*/
private PlotState getPlotState() {
PlotState state = new PlotState();
state.xCol = (StarTableColumn) xColBox.getSelectedItem();
state.yCol = (StarTableColumn) yColBox.getSelectedItem();
state.xLog = xLogBox.isSelected();
state.yLog = yLogBox.isSelected();
state.plotline = false;
state.type = "Scatter";
/* Construct an array of the subsets that are used. */
int nrsets = subsets.size();
RowSubset[] subsetMask = new RowSubset[ nrsets ];
List useList = getSelectedSubsets();
for ( int i = 0; i < nrsets; i++ ) {
RowSubset rset = (RowSubset) subsets.getElementAt( i );
subsetMask[ i ] = useList.contains( rset ) ? rset : null;
}
state.subsetMask = subsetMask;
return state;
}
/**
* Private class for characterising the state of a plot.
* An <tt>equals</tt> comparison is used to find out whether two
* states of this window differ in such a way as to require a
* new plot to be made.
* <p>
* Note this is not designed for general purpose use; in particular the
* <tt>hashCode</tt> method is not re-implemented for consistency with
* the <tt>equals</tt> method.
*/
private static class PlotState {
StarTableColumn xCol;
StarTableColumn yCol;
boolean xLog;
boolean yLog;
RowSubset[] subsetMask;
boolean plotline;
String type;
public boolean equals( Object otherObject ) {
if ( otherObject instanceof PlotState ) {
PlotState other = (PlotState) otherObject;
return other instanceof PlotState
&& xCol.equals( other.xCol )
&& yCol.equals( other.yCol )
&& xLog == other.xLog
&& yLog == other.yLog
&& Arrays.equals( subsetMask, other.subsetMask )
&& plotline == other.plotline
&& type.equals( other.type );
}
else {
return false;
}
}
public boolean sameAxes( PlotState other ) {
return other != null
&& xCol.equals( other.xCol )
&& yCol.equals( other.yCol )
&& xLog == other.xLog
&& yLog == other.yLog;
}
public String toString() {
return new StringBuffer()
.append( "xCol=" )
.append( xCol )
.append( "," )
.append( "yCol=" )
.append( yCol )
.append( "," )
.append( "xLog=" )
.append( xLog )
.append( "," )
.append( "yLog=" )
.append( yLog )
.append( "," )
.append( "plotline=" )
.append( plotline )
.append( "," )
.append( "type=" )
.append( type )
.toString();
}
}
}
| true | true | public PlotWindow( TableViewer tableviewer ) {
super( "Table Plotter", tableviewer );
this.tv = tableviewer;
this.dataModel = tv.getDataModel();
this.columnModel = tv.getColumnModel();
this.subsets = tv.getSubsets();
/* Do some window setup. */
setSize( 400, 400 );
/* Construct a panel for configuration of X and Y axes. */
Border lineBorder = BorderFactory.createLineBorder( Color.BLACK );
JPanel xConfig = new JPanel();
JPanel yConfig = new JPanel();
xConfig.setBorder( BorderFactory
.createTitledBorder( lineBorder, "X axis" ) );
yConfig.setBorder( BorderFactory
.createTitledBorder( lineBorder, "Y axis" ) );
Box axisBox = new Box( BoxLayout.Y_AXIS );
axisBox.add( xConfig );
axisBox.add( Box.createGlue() );
axisBox.add( yConfig );
getControlPanel().add( axisBox );
/* Construct axis selectors for X and Y. */
xColBox = makePlottableColumnComboBox();
yColBox = makePlottableColumnComboBox();
/* If there are too few numeric columns then inform the user and
* bail out. */
assert xColBox.getItemCount() == yColBox.getItemCount();
if ( xColBox.getItemCount() < 2 ) {
JOptionPane.showMessageDialog( null,
"Too few numeric columns in table",
"Plot error",
JOptionPane.ERROR_MESSAGE );
dispose();
}
/* Place the selectors in this window. */
xConfig.add( xColBox );
yConfig.add( yColBox );
xColBox.setSelectedIndex( 0 );
yColBox.setSelectedIndex( 1 );
xColBox.addActionListener( this );
yColBox.addActionListener( this );
/* Add linear/log selectors for X and Y. */
xLogBox = new JCheckBox( "Log plot" );
yLogBox = new JCheckBox( "Log plot" );
xConfig.add( xLogBox );
yConfig.add( yLogBox );
xLogBox.addActionListener( this );
yLogBox.addActionListener( this );
/* Add a menu for printing the graph. */
Action printAction = new BasicAction( "Print as EPS",
ResourceIcon.PRINT,
"Print the graph to an " +
"EPS file" ) {
public void actionPerformed( ActionEvent evt ) {
/* Ask the user where to output the postscript. */
Component parent = PlotWindow.this;
JFileChooser chooser = getPrintSaver();
if ( chooser.showSaveDialog( parent )
== JFileChooser.APPROVE_OPTION ) {
try {
File file = chooser.getSelectedFile();
OutputStream ostrm = new FileOutputStream( file );
/* Only one mark style makes much sense for the
* EPSGraphics class used here, so change the plot
* to that for the duration of the write, then
* back again. */
setMarkStyle( lastPlot, "various" );
try {
lastPlot.export( ostrm );
}
finally {
setMarkStyle( lastPlot, markStyle );
ostrm.close();
}
}
catch ( IOException e ) {
ErrorDialog.showError( e, "Error writing EPS", parent );
}
}
}
};
getFileMenu().insert( printAction, 0 ).setIcon( null );
/* Get a menu for selecting row subsets to plot. */
CheckBoxMenu subMenu = subsets.makeCheckBoxMenu( "Subsets to plot" );
subSelModel = subMenu.getSelectionModel();
/* Do the same thing as a scrollable box in the control panel. */
CheckBoxStack stack = new CheckBoxStack( subsets );
JComponent stackPanel = new JScrollPane( stack );
stackPanel.setBorder( BorderFactory
.createTitledBorder( lineBorder, "Row subsets" ) );
getControlPanel().add( stackPanel );
stack.setSelectionModel( subSelModel );
/* Initialise its selections so that both ALL and the current subset,
* of the viewer, if any, are plotted. */
subSelModel.addSelectionInterval( 0, 0 ); // ALL
int nrsets = subsets.size();
RowSubset currentSet = tv.getViewModel().getSubset();
if ( currentSet != RowSubset.ALL ) {
for ( int i = 1; i < nrsets; i++ ) {
if ( subsets.get( i ) == currentSet ) {
subSelModel.addSelectionInterval( i, i );
}
}
}
/* Ensure that the plot will respond to the subset selection being
* changed. */
subSelModel.addListSelectionListener( new ListSelectionListener() {
public void valueChanged( ListSelectionEvent evt ) {
/* If the only changed items are ones which have been
* deselected, we can do this cheaply. */
int first = evt.getFirstIndex();
int last = evt.getLastIndex();
PlotState state = getPlotState();
RowSubset[] mask = state.subsetMask;
RowSubset[] lastMask = lastState.subsetMask;
boolean allClear = true;
for ( int i = first; i <= last && allClear; i++ ) {
if ( i >= mask.length || i > lastMask.length ||
( mask[ i ] != null && lastMask[ i ] == null ) ) {
allClear = false;
}
}
if ( allClear && lastPlot instanceof Plot ) {
Plot plot = (Plot) lastPlot;
for ( int i = first; i <= last; i++ ) {
if ( mask[ i ] == null && lastMask[ i ] != null ) {
plot.clear( setFor( i ) );
}
}
lastState = state;
}
/* Otherwise, a proper replot will be necesary. */
else {
PlotWindow.this.actionPerformed( null );
}
}
} );
/* Construct a panel which will hold the plot itself. */
plotPanel = new JPanel( new BorderLayout() );
/* Arrange the components in the top level window. */
JPanel mainArea = getMainArea();
mainArea.add( plotPanel, BorderLayout.CENTER );
/* Add a progress bar. */
progBar = placeProgressBar();
/* Action for showing the grid. */
final ButtonModel gridModel = new DefaultButtonModel();
gridModel.setSelected( showGrid );
gridModel.addItemListener( new ItemListener() {
public void itemStateChanged( ItemEvent evt ) {
if ( gridModel.isSelected() != showGrid ) {
showGrid = ! showGrid;
lastPlot.setGrid( showGrid );
}
lastPlot.repaint();
}
} );
Action gridAction = new BasicAction( "Show grid",
ResourceIcon.GRID_ON,
"Select whether grid " +
"lines are displayed" ) {
public void actionPerformed( ActionEvent evt ) {
gridModel.setSelected( ! gridModel.isSelected() );
}
};
final AbstractButton gridToolButton = new JButton( gridAction );
gridToolButton.setText( null );
gridModel.addItemListener( new ItemListener() {
{ itemStateChanged( null ); }
public void itemStateChanged( ItemEvent evt ) {
gridToolButton.setIcon( gridModel.isSelected()
? ResourceIcon.GRID_OFF
: ResourceIcon.GRID_ON );
}
} );
/* Action for resizing the plot. */
Action resizeAction = new BasicAction( "Rescale",
ResourceIcon.RESIZE,
"Rescale the plot to show " +
"all points points" ) {
public void actionPerformed( ActionEvent evt ) {
lastPlot.fillPlot();
}
};
/* Menu item for selecting marker types. */
JMenu markMenu = new JMenu( "Marker type" );
String[] markStyles =
new String[] { "points", "dots", "various", "pixels" };
ButtonGroup bgroup = new ButtonGroup();
for ( int i = 0; i < markStyles.length; i++ ) {
String style = markStyles[ i ];
Action act = new MarkerAction( style );
JMenuItem item = new JRadioButtonMenuItem( act );
if ( style.equals( this.markStyle ) ) {
item.setSelected( true );
}
markMenu.add( item );
bgroup.add( item );
}
/* Action for repdrawing the current plot. */
Action replotAction = new BasicAction( "Replot", ResourceIcon.REDO,
"Redraw the plot with current table data" ) {
public void actionPerformed( ActionEvent evt ) {
PlotWindow.this.actionPerformed( FORCE_REPLOT );
}
};
/* Construct a new menu for general plot operations. */
JMenu plotMenu = new JMenu( "Plot" );
plotMenu.add( resizeAction ).setIcon( null );
plotMenu.add( replotAction ).setIcon( null );
JMenuItem gridItem = new JCheckBoxMenuItem( gridAction );
gridItem.setModel( gridModel );
plotMenu.add( gridItem ).setIcon( null );
plotMenu.add( markMenu );
getJMenuBar().add( plotMenu );
/* Construct a new menu for subset operations. */
JMenu subsetMenu = new JMenu( "Subsets" );
subsetMenu.add( subMenu );
fromvisibleAction = new BasicAction( "New subset from visible",
ResourceIcon.VISIBLE_SUBSET,
"Define a new row subset " +
"containing only currently " +
"visible points" ) {
public void actionPerformed( ActionEvent evt ) {
String name = TableViewer.enquireSubsetName( PlotWindow.this );
if ( name != null ) {
int inew = subsets.size();
subsets.add( new BitsRowSubset( name, calcVisibleRows() ) );
subSelModel.addSelectionInterval( inew, inew );
}
}
};
subsetMenu.add( fromvisibleAction ).setIcon( null );
getJMenuBar().add( subsetMenu );
/* Add actions to the toolbar. */
getToolBar().add( printAction );
getToolBar().add( replotAction );
getToolBar().add( resizeAction );
getToolBar().add( gridToolButton );
getToolBar().add( fromvisibleAction );
getToolBar().addSeparator();
/* Add standard help actions. */
addHelp( "PlotWindow" );
/* Do the plotting. */
actionPerformed( FORCE_REPLOT );
/* Render this component visible. */
pack();
setVisible( true );
}
| public PlotWindow( TableViewer tableviewer ) {
super( "Table Plotter", tableviewer );
this.tv = tableviewer;
this.dataModel = tv.getDataModel();
this.columnModel = tv.getColumnModel();
this.subsets = tv.getSubsets();
/* Do some window setup. */
setSize( 400, 400 );
/* Construct a panel for configuration of X and Y axes. */
Border lineBorder = BorderFactory.createLineBorder( Color.BLACK );
JPanel xConfig = new JPanel();
JPanel yConfig = new JPanel();
xConfig.setBorder( BorderFactory
.createTitledBorder( lineBorder, "X axis" ) );
yConfig.setBorder( BorderFactory
.createTitledBorder( lineBorder, "Y axis" ) );
Box axisBox = new Box( BoxLayout.Y_AXIS );
axisBox.add( xConfig );
axisBox.add( Box.createGlue() );
axisBox.add( yConfig );
getControlPanel().add( axisBox );
/* Construct axis selectors for X and Y. */
xColBox = makePlottableColumnComboBox();
yColBox = makePlottableColumnComboBox();
/* If there are too few numeric columns then inform the user and
* bail out. */
assert xColBox.getItemCount() == yColBox.getItemCount();
if ( xColBox.getItemCount() < 2 ) {
JOptionPane.showMessageDialog( null,
"Too few numeric columns in table",
"Plot error",
JOptionPane.ERROR_MESSAGE );
dispose();
}
/* Place the selectors in this window. */
xConfig.add( xColBox );
yConfig.add( yColBox );
xColBox.setSelectedIndex( 0 );
yColBox.setSelectedIndex( 1 );
xColBox.addActionListener( this );
yColBox.addActionListener( this );
/* Add linear/log selectors for X and Y. */
xLogBox = new JCheckBox( "Log plot" );
yLogBox = new JCheckBox( "Log plot" );
xConfig.add( xLogBox );
yConfig.add( yLogBox );
xLogBox.addActionListener( this );
yLogBox.addActionListener( this );
/* Add a menu for printing the graph. */
Action printAction = new BasicAction( "Print as EPS",
ResourceIcon.PRINT,
"Print the graph to an " +
"EPS file" ) {
public void actionPerformed( ActionEvent evt ) {
/* Ask the user where to output the postscript. */
Component parent = PlotWindow.this;
JFileChooser chooser = getPrintSaver();
if ( chooser.showSaveDialog( parent )
== JFileChooser.APPROVE_OPTION ) {
try {
File file = chooser.getSelectedFile();
OutputStream ostrm = new FileOutputStream( file );
/* Only one mark style makes much sense for the
* EPSGraphics class used here, so change the plot
* to that for the duration of the write, then
* back again. */
setMarkStyle( lastPlot, "various" );
try {
lastPlot.export( ostrm );
}
finally {
setMarkStyle( lastPlot, markStyle );
ostrm.close();
}
}
catch ( IOException e ) {
ErrorDialog.showError( e, "Error writing EPS", parent );
}
}
}
};
getFileMenu().insert( printAction, 0 ).setIcon( null );
/* Get a menu for selecting row subsets to plot. */
CheckBoxMenu subMenu = subsets.makeCheckBoxMenu( "Subsets to plot" );
subSelModel = subMenu.getSelectionModel();
/* Do the same thing as a scrollable box in the control panel. */
CheckBoxStack stack = new CheckBoxStack( subsets );
JComponent stackPanel = new JScrollPane( stack );
stackPanel.setBorder( BorderFactory
.createTitledBorder( lineBorder, "Row subsets" ) );
getControlPanel().add( stackPanel );
stack.setSelectionModel( subSelModel );
/* Initialise its selections so that both ALL and the current subset,
* of the viewer, if any, are plotted. */
subSelModel.addSelectionInterval( 0, 0 ); // ALL
int nrsets = subsets.size();
RowSubset currentSet = tv.getViewModel().getSubset();
if ( currentSet != RowSubset.ALL ) {
for ( int i = 1; i < nrsets; i++ ) {
if ( subsets.get( i ) == currentSet ) {
subSelModel.addSelectionInterval( i, i );
}
}
}
/* Ensure that the plot will respond to the subset selection being
* changed. */
subSelModel.addListSelectionListener( new ListSelectionListener() {
public void valueChanged( ListSelectionEvent evt ) {
/* If the only changed items are ones which have been
* deselected, we can do this cheaply. */
int first = evt.getFirstIndex();
int last = evt.getLastIndex();
PlotState state = getPlotState();
RowSubset[] mask = state.subsetMask;
RowSubset[] lastMask = lastState.subsetMask;
boolean allClear = true;
for ( int i = first; i <= last && allClear; i++ ) {
if ( i >= mask.length || i >= lastMask.length ||
( mask[ i ] != null && lastMask[ i ] == null ) ) {
allClear = false;
}
}
if ( allClear && lastPlot instanceof Plot ) {
Plot plot = (Plot) lastPlot;
for ( int i = first; i <= last; i++ ) {
if ( mask[ i ] == null && lastMask[ i ] != null ) {
plot.clear( setFor( i ) );
}
}
lastState = state;
}
/* Otherwise, a proper replot will be necesary. */
else {
PlotWindow.this.actionPerformed( null );
}
}
} );
/* Construct a panel which will hold the plot itself. */
plotPanel = new JPanel( new BorderLayout() );
/* Arrange the components in the top level window. */
JPanel mainArea = getMainArea();
mainArea.add( plotPanel, BorderLayout.CENTER );
/* Add a progress bar. */
progBar = placeProgressBar();
/* Action for showing the grid. */
final ButtonModel gridModel = new DefaultButtonModel();
gridModel.setSelected( showGrid );
gridModel.addItemListener( new ItemListener() {
public void itemStateChanged( ItemEvent evt ) {
if ( gridModel.isSelected() != showGrid ) {
showGrid = ! showGrid;
lastPlot.setGrid( showGrid );
}
lastPlot.repaint();
}
} );
Action gridAction = new BasicAction( "Show grid",
ResourceIcon.GRID_ON,
"Select whether grid " +
"lines are displayed" ) {
public void actionPerformed( ActionEvent evt ) {
gridModel.setSelected( ! gridModel.isSelected() );
}
};
final AbstractButton gridToolButton = new JButton( gridAction );
gridToolButton.setText( null );
gridModel.addItemListener( new ItemListener() {
{ itemStateChanged( null ); }
public void itemStateChanged( ItemEvent evt ) {
gridToolButton.setIcon( gridModel.isSelected()
? ResourceIcon.GRID_OFF
: ResourceIcon.GRID_ON );
}
} );
/* Action for resizing the plot. */
Action resizeAction = new BasicAction( "Rescale",
ResourceIcon.RESIZE,
"Rescale the plot to show " +
"all points points" ) {
public void actionPerformed( ActionEvent evt ) {
lastPlot.fillPlot();
}
};
/* Menu item for selecting marker types. */
JMenu markMenu = new JMenu( "Marker type" );
String[] markStyles =
new String[] { "points", "dots", "various", "pixels" };
ButtonGroup bgroup = new ButtonGroup();
for ( int i = 0; i < markStyles.length; i++ ) {
String style = markStyles[ i ];
Action act = new MarkerAction( style );
JMenuItem item = new JRadioButtonMenuItem( act );
if ( style.equals( this.markStyle ) ) {
item.setSelected( true );
}
markMenu.add( item );
bgroup.add( item );
}
/* Action for repdrawing the current plot. */
Action replotAction = new BasicAction( "Replot", ResourceIcon.REDO,
"Redraw the plot with current table data" ) {
public void actionPerformed( ActionEvent evt ) {
PlotWindow.this.actionPerformed( FORCE_REPLOT );
}
};
/* Construct a new menu for general plot operations. */
JMenu plotMenu = new JMenu( "Plot" );
plotMenu.add( resizeAction ).setIcon( null );
plotMenu.add( replotAction ).setIcon( null );
JMenuItem gridItem = new JCheckBoxMenuItem( gridAction );
gridItem.setModel( gridModel );
plotMenu.add( gridItem ).setIcon( null );
plotMenu.add( markMenu );
getJMenuBar().add( plotMenu );
/* Construct a new menu for subset operations. */
JMenu subsetMenu = new JMenu( "Subsets" );
subsetMenu.add( subMenu );
fromvisibleAction = new BasicAction( "New subset from visible",
ResourceIcon.VISIBLE_SUBSET,
"Define a new row subset " +
"containing only currently " +
"visible points" ) {
public void actionPerformed( ActionEvent evt ) {
String name = TableViewer.enquireSubsetName( PlotWindow.this );
if ( name != null ) {
int inew = subsets.size();
subsets.add( new BitsRowSubset( name, calcVisibleRows() ) );
subSelModel.addSelectionInterval( inew, inew );
}
}
};
subsetMenu.add( fromvisibleAction ).setIcon( null );
getJMenuBar().add( subsetMenu );
/* Add actions to the toolbar. */
getToolBar().add( printAction );
getToolBar().add( replotAction );
getToolBar().add( resizeAction );
getToolBar().add( gridToolButton );
getToolBar().add( fromvisibleAction );
getToolBar().addSeparator();
/* Add standard help actions. */
addHelp( "PlotWindow" );
/* Do the plotting. */
actionPerformed( FORCE_REPLOT );
/* Render this component visible. */
pack();
setVisible( true );
}
|
diff --git a/src/com/ubhave/dataformatter/json/push/PhoneStateFormatter.java b/src/com/ubhave/dataformatter/json/push/PhoneStateFormatter.java
index 1983347..3a37d62 100644
--- a/src/com/ubhave/dataformatter/json/push/PhoneStateFormatter.java
+++ b/src/com/ubhave/dataformatter/json/push/PhoneStateFormatter.java
@@ -1,58 +1,58 @@
/* **************************************************
Copyright (c) 2012, University of Cambridge
Neal Lathia, [email protected]
This library was developed as part of the EPSRC Ubhave (Ubiquitous and
Social Computing for Positive Behaviour Change) Project. For more
information, please visit http://www.emotionsense.org
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
************************************************** */
package com.ubhave.dataformatter.json.push;
import org.json.simple.JSONObject;
import com.ubhave.dataformatter.json.PushSensorJSONFormatter;
import com.ubhave.sensormanager.data.SensorData;
import com.ubhave.sensormanager.data.pushsensor.PhoneStateData;
public class PhoneStateFormatter extends PushSensorJSONFormatter
{
private final static String EVENT_TYPE = "eventType";
private final static String DATA = "data";
@SuppressWarnings("unchecked")
@Override
protected void addSensorSpecificData(JSONObject json, SensorData data)
{
PhoneStateData phoneStateData = (PhoneStateData) data;
json.put(EVENT_TYPE, phoneStateData.getEventType());
json.put(DATA, phoneStateData.getData());
}
@Override
public SensorData toSensorData(String jsonString)
{
JSONObject jsonData = super.parseData(jsonString);
if (jsonData != null)
{
long dataReceivedTimestamp = super.parseTimeStamp(jsonData);
- int eventType = (Integer) jsonData.get(EVENT_TYPE);
+ int eventType = ((Long) jsonData.get(EVENT_TYPE)).intValue();
String data = (String) jsonData.get(DATA);
return new PhoneStateData(dataReceivedTimestamp, eventType, data, null);
}
else return null;
}
}
| true | true | public SensorData toSensorData(String jsonString)
{
JSONObject jsonData = super.parseData(jsonString);
if (jsonData != null)
{
long dataReceivedTimestamp = super.parseTimeStamp(jsonData);
int eventType = (Integer) jsonData.get(EVENT_TYPE);
String data = (String) jsonData.get(DATA);
return new PhoneStateData(dataReceivedTimestamp, eventType, data, null);
}
else return null;
}
| public SensorData toSensorData(String jsonString)
{
JSONObject jsonData = super.parseData(jsonString);
if (jsonData != null)
{
long dataReceivedTimestamp = super.parseTimeStamp(jsonData);
int eventType = ((Long) jsonData.get(EVENT_TYPE)).intValue();
String data = (String) jsonData.get(DATA);
return new PhoneStateData(dataReceivedTimestamp, eventType, data, null);
}
else return null;
}
|
diff --git a/src/util/Assets.java b/src/util/Assets.java
index 55e2298..649410d 100644
--- a/src/util/Assets.java
+++ b/src/util/Assets.java
@@ -1,53 +1,53 @@
package util;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Assets {
public static Image TILE_ONE;
public static Image ROCK;
public static Image FENCE;
public static Image CREATURE;
public static Image PLAYER;
public static Image IRISH_DRESS;
public static Image TREE;
public static Image TORCH;
public static Image SHADOW;
public static Image BULLET;
public static Image EXPLOSION;
public static Image MINECRAFT;
public static Image HEALTH_BAR;
public static Image HEALTH_BAR_BASE;
public Assets() throws SlickException {
- TILE_ONE = new Image("bin/data/grass.png");
- ROCK = new Image("bin/data/new rock.png");
+ TILE_ONE = new Image("data/grass.png");
+ ROCK = new Image("data/new rock.png");
- CREATURE = new Image("bin/data/creature.png");
+ CREATURE = new Image("data/creature.png");
- PLAYER = new Image("bin/data/overlap test.png");
+ PLAYER = new Image("data/overlap test.png");
- FENCE = new Image("bin/data/fence.png");
+ FENCE = new Image("data/fence.png");
- TREE = new Image("bin/data/Tree no shadow.png");
+ TREE = new Image("data/Tree no shadow.png");
- SHADOW = new Image("bin/data/shadow.png");
- BULLET = new Image("bin/data/Bullet.png");
- EXPLOSION = new Image("bin/data/splosion.png");
- MINECRAFT = new Image("bin/data/minecraft.png");
+ SHADOW = new Image("data/shadow.png");
+ BULLET = new Image("data/Bullet.png");
+ EXPLOSION = new Image("data/splosion.png");
+ MINECRAFT = new Image("data/minecraft.png");
- TORCH = new Image("bin/data/torch.png");
- IRISH_DRESS = new Image("bin/data/irishdress.png");
+ TORCH = new Image("data/torch.png");
+ IRISH_DRESS = new Image("data/irishdress.png");
- HEALTH_BAR = new Image("bin/data/healthBar.png");
- HEALTH_BAR_BASE = new Image("bin/data/healthBarBase.png");
+ HEALTH_BAR = new Image("data/healthBar.png");
+ HEALTH_BAR_BASE = new Image("data/healthBarBase.png");
}
}
| false | true | public Assets() throws SlickException {
TILE_ONE = new Image("bin/data/grass.png");
ROCK = new Image("bin/data/new rock.png");
CREATURE = new Image("bin/data/creature.png");
PLAYER = new Image("bin/data/overlap test.png");
FENCE = new Image("bin/data/fence.png");
TREE = new Image("bin/data/Tree no shadow.png");
SHADOW = new Image("bin/data/shadow.png");
BULLET = new Image("bin/data/Bullet.png");
EXPLOSION = new Image("bin/data/splosion.png");
MINECRAFT = new Image("bin/data/minecraft.png");
TORCH = new Image("bin/data/torch.png");
IRISH_DRESS = new Image("bin/data/irishdress.png");
HEALTH_BAR = new Image("bin/data/healthBar.png");
HEALTH_BAR_BASE = new Image("bin/data/healthBarBase.png");
}
| public Assets() throws SlickException {
TILE_ONE = new Image("data/grass.png");
ROCK = new Image("data/new rock.png");
CREATURE = new Image("data/creature.png");
PLAYER = new Image("data/overlap test.png");
FENCE = new Image("data/fence.png");
TREE = new Image("data/Tree no shadow.png");
SHADOW = new Image("data/shadow.png");
BULLET = new Image("data/Bullet.png");
EXPLOSION = new Image("data/splosion.png");
MINECRAFT = new Image("data/minecraft.png");
TORCH = new Image("data/torch.png");
IRISH_DRESS = new Image("data/irishdress.png");
HEALTH_BAR = new Image("data/healthBar.png");
HEALTH_BAR_BASE = new Image("data/healthBarBase.png");
}
|
diff --git a/src/walledin/engine/TexturePartManager.java b/src/walledin/engine/TexturePartManager.java
index d4c5128..602ae9e 100644
--- a/src/walledin/engine/TexturePartManager.java
+++ b/src/walledin/engine/TexturePartManager.java
@@ -1,40 +1,42 @@
package walledin.engine;
import java.util.logging.Logger;
import walledin.engine.math.Rectangle;
import walledin.engine.math.Vector2f;
import com.sun.opengl.util.texture.Texture;
/**
*
* @author ben
*/
public class TexturePartManager extends ResourceManager<String, TexturePart> {
private final static Logger LOG = Logger.getLogger(TexturePartManager.class
.getName());
private static final TexturePartManager INSTANCE = new TexturePartManager();
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public static TexturePartManager getInstance() {
return INSTANCE;
}
private TexturePartManager() {
}
public boolean createTexturePart(String texturePartID, String textureID,
Rectangle rectangle) {
Texture texture = TextureManager.getInstance().get(textureID);
- Rectangle scaledRectangle = rectangle.scaleAll(new Vector2f(texture
- .getWidth(), texture.getHeight()));
+ float width = (float) texture.getWidth();
+ float height = (float) texture.getHeight();
+ Vector2f scale = new Vector2f(1 / width, 1 / height);
+ Rectangle scaledRectangle = rectangle.scaleAll(scale);
TexturePart part = new TexturePart(texture, scaledRectangle);
return put(texturePartID, part);
}
}
| true | true | public boolean createTexturePart(String texturePartID, String textureID,
Rectangle rectangle) {
Texture texture = TextureManager.getInstance().get(textureID);
Rectangle scaledRectangle = rectangle.scaleAll(new Vector2f(texture
.getWidth(), texture.getHeight()));
TexturePart part = new TexturePart(texture, scaledRectangle);
return put(texturePartID, part);
}
| public boolean createTexturePart(String texturePartID, String textureID,
Rectangle rectangle) {
Texture texture = TextureManager.getInstance().get(textureID);
float width = (float) texture.getWidth();
float height = (float) texture.getHeight();
Vector2f scale = new Vector2f(1 / width, 1 / height);
Rectangle scaledRectangle = rectangle.scaleAll(scale);
TexturePart part = new TexturePart(texture, scaledRectangle);
return put(texturePartID, part);
}
|
diff --git a/core/src/java/liquibase/change/ModifyColumnChange.java b/core/src/java/liquibase/change/ModifyColumnChange.java
index d3ee80a2..1c91330b 100644
--- a/core/src/java/liquibase/change/ModifyColumnChange.java
+++ b/core/src/java/liquibase/change/ModifyColumnChange.java
@@ -1,131 +1,131 @@
package liquibase.change;
import liquibase.database.*;
import liquibase.database.sql.RawSqlStatement;
import liquibase.database.sql.SqlStatement;
import liquibase.database.sql.ReorganizeTableStatement;
import liquibase.database.structure.Column;
import liquibase.database.structure.DatabaseObject;
import liquibase.database.structure.Table;
import liquibase.exception.UnsupportedChangeException;
import liquibase.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Modifies the data type of an existing column.
*/
public class ModifyColumnChange extends AbstractChange {
private String schemaName;
private String tableName;
private List<ColumnConfig> columns;
public ModifyColumnChange() {
super("modifyColumn", "Modify Column");
columns = new ArrayList<ColumnConfig>();
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public List<ColumnConfig> getColumns() {
return columns;
}
public void addColumn(ColumnConfig column) {
columns.add(column);
}
public void removeColumn(ColumnConfig column) {
columns.remove(column);
}
public SqlStatement[] generateStatements(Database database) throws UnsupportedChangeException {
List<SqlStatement> sql = new ArrayList<SqlStatement>();
for (ColumnConfig aColumn : columns) {
String schemaName = getSchemaName() == null?database.getDefaultSchemaName():getSchemaName();
if(database instanceof SybaseDatabase) {
- sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY " + aColumn.getName() + " " + aColumn.getType()));
+ sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY " + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof MSSQLDatabase) {
- sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " " + aColumn.getType()));
+ sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof MySQLDatabase) {
- sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY COLUMN " + aColumn.getName() + " " + aColumn.getType()));
+ sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY COLUMN " + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof OracleDatabase || database instanceof MaxDBDatabase) {
- sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY (" + aColumn.getName() + " " + aColumn.getType() + ")"));
+ sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY (" + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false) + ")"));
} else if (database instanceof DerbyDatabase) {
- sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN "+aColumn.getName()+" SET DATA TYPE " + aColumn.getType()));
+ sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN "+aColumn.getName()+" SET DATA TYPE " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof HsqlDatabase) {
- sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN "+aColumn.getName()+" "+aColumn.getType()));
+ sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN "+aColumn.getName()+" "+database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof CacheDatabase) {
- sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " " + aColumn.getType()));
+ sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof DB2Database) {
- sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " SET DATA TYPE " + aColumn.getType()));
+ sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " SET DATA TYPE " + database.getColumnType(aColumn.getType(), false)));
sql.add(new ReorganizeTableStatement(schemaName, getTableName()));
} else {
- sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " TYPE " + aColumn.getType()));
+ sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " TYPE " + database.getColumnType(aColumn.getType(), false)));
}
}
return sql.toArray(new SqlStatement[sql.size()]);
}
public String getConfirmationMessage() {
List<String> names = new ArrayList<String>(columns.size());
for (ColumnConfig col : columns) {
names.add(col.getName() + "(" + col.getType() + ")");
}
return "Columns " + StringUtils.join(names, ",") + " of " + getTableName() + " modified";
}
public Element createNode(Document currentChangeLogFileDOM) {
Element node = currentChangeLogFileDOM.createElement("modifyColumn");
if (getSchemaName() != null) {
node.setAttribute("schemaName", getSchemaName());
}
node.setAttribute("tableName", getTableName());
for (ColumnConfig col : getColumns()) {
Element subNode = col.createNode(currentChangeLogFileDOM);
node.appendChild(subNode);
}
return node;
}
public Set<DatabaseObject> getAffectedDatabaseObjects() {
List<DatabaseObject> result = new ArrayList<DatabaseObject>(columns.size());
Table table = new Table(getTableName());
for (ColumnConfig aColumn : columns) {
Column each = new Column();
each.setTable(table);
each.setName(aColumn.getName());
result.add(each);
}
return new HashSet<DatabaseObject>(result);
}
}
| false | true | public SqlStatement[] generateStatements(Database database) throws UnsupportedChangeException {
List<SqlStatement> sql = new ArrayList<SqlStatement>();
for (ColumnConfig aColumn : columns) {
String schemaName = getSchemaName() == null?database.getDefaultSchemaName():getSchemaName();
if(database instanceof SybaseDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY " + aColumn.getName() + " " + aColumn.getType()));
} else if (database instanceof MSSQLDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " " + aColumn.getType()));
} else if (database instanceof MySQLDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY COLUMN " + aColumn.getName() + " " + aColumn.getType()));
} else if (database instanceof OracleDatabase || database instanceof MaxDBDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY (" + aColumn.getName() + " " + aColumn.getType() + ")"));
} else if (database instanceof DerbyDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN "+aColumn.getName()+" SET DATA TYPE " + aColumn.getType()));
} else if (database instanceof HsqlDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN "+aColumn.getName()+" "+aColumn.getType()));
} else if (database instanceof CacheDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " " + aColumn.getType()));
} else if (database instanceof DB2Database) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " SET DATA TYPE " + aColumn.getType()));
sql.add(new ReorganizeTableStatement(schemaName, getTableName()));
} else {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " TYPE " + aColumn.getType()));
}
}
return sql.toArray(new SqlStatement[sql.size()]);
}
| public SqlStatement[] generateStatements(Database database) throws UnsupportedChangeException {
List<SqlStatement> sql = new ArrayList<SqlStatement>();
for (ColumnConfig aColumn : columns) {
String schemaName = getSchemaName() == null?database.getDefaultSchemaName():getSchemaName();
if(database instanceof SybaseDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY " + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof MSSQLDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof MySQLDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY COLUMN " + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof OracleDatabase || database instanceof MaxDBDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " MODIFY (" + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false) + ")"));
} else if (database instanceof DerbyDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN "+aColumn.getName()+" SET DATA TYPE " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof HsqlDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN "+aColumn.getName()+" "+database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof CacheDatabase) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " " + database.getColumnType(aColumn.getType(), false)));
} else if (database instanceof DB2Database) {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " SET DATA TYPE " + database.getColumnType(aColumn.getType(), false)));
sql.add(new ReorganizeTableStatement(schemaName, getTableName()));
} else {
sql.add(new RawSqlStatement("ALTER TABLE " + database.escapeTableName(schemaName, getTableName()) + " ALTER COLUMN " + aColumn.getName() + " TYPE " + database.getColumnType(aColumn.getType(), false)));
}
}
return sql.toArray(new SqlStatement[sql.size()]);
}
|
diff --git a/src/xi/linker/Linker.java b/src/xi/linker/Linker.java
index 76d7339..6b4eb2a 100644
--- a/src/xi/linker/Linker.java
+++ b/src/xi/linker/Linker.java
@@ -1,141 +1,141 @@
package xi.linker;
import static xi.go.VM.UTF8;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Map.Entry;
import stefan.Cout;
import xi.ast.Expr;
import xi.ast.LetIn;
import xi.ast.Module;
import xi.ast.Name;
import xi.ast.stefan.LazyTree;
/**
* A linker for the SK output.
*
* @author Leo
*/
public class Linker {
/** Definition map. */
final Map<String, Expr> defs = new HashMap<String, Expr>();
/**
* Constructor.
*
* @param ins
* SKLib inputs
* @throws IOException
* I/O exception
*/
public Linker(final List<Reader> ins) throws IOException {
final Map<String, Expr> module = new HashMap<String, Expr>();
final AstSKParser parser = new AstSKParser(module);
for (final Reader r : ins) {
// keeps the possibility to overwrite functions in other files
parser.read(r);
defs.putAll(module);
module.clear();
}
}
public Expr link(final String startSym) {
final Map<String, Expr> required = new HashMap<String, Expr>();
final Queue<String> queue = new ArrayDeque<String>();
queue.add(startSym);
while (!queue.isEmpty()) {
final String sym = queue.poll();
if (!required.containsKey(sym)) {
final Expr body = defs.get(sym);
if (body == null) {
throw new IllegalArgumentException("Symbol '" + sym
+ "' not found.");
}
required.put(sym, body);
for (final Name n : body.freeVars()) {
queue.add(n.toString());
}
}
}
final Expr start = required.remove(startSym);
final Module mod = new Module(false);
for (final Entry<String, Expr> e : required.entrySet()) {
mod.addDefinition(Name.valueOf(e.getKey()), e.getValue());
}
final LetIn let = new LetIn(mod, start);
return let.unLambda();
}
public static void main(final String[] args) throws Exception {
String start = "main";
final ArrayList<Reader> inputs = new ArrayList<Reader>();
Writer out = new OutputStreamWriter(System.out);
boolean invalid = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-help")) {
invalid = true;
break;
}
if (args[i].equals("-start")) {
if (i == args.length - 1) {
invalid = true;
break;
}
start = args[++i];
} else if ("-out".equals(args[i])) {
if (i == args.length - 1) {
invalid = true;
break;
}
- out = new OutputStreamWriter(new FileOutputStream(args[i]),
+ out = new OutputStreamWriter(new FileOutputStream(args[++i]),
UTF8);
} else if ("-".equals(args[i])) {
inputs.add(new InputStreamReader(System.in));
} else {
final File f = new File(args[i]);
if (!f.isFile()) {
invalid = true;
break;
}
inputs.add(new InputStreamReader(new FileInputStream(f), UTF8));
}
}
if (invalid) {
System.err.println("Usage: sasln [-help] [-start <start_sym>] "
+ "[-out <dest_file>] <sklib>...\n"
+ "\t<start_sym>: function name used as entry point,"
+ " default is 'main'.\n"
+ "\t<dest_file>: File to write to, default is STDOUT.\n"
+ "\t<sklib>: a file containing an SK library,"
+ " '-' means STDIN.\n");
return;
}
if (inputs.isEmpty()) {
inputs.add(new InputStreamReader(System.in));
}
final Linker linker = new Linker(inputs);
final Expr linked = linker.link(start);
final Module mod = new Module(false);
mod.addDefinition(Name.valueOf("main"), linked);
Cout.module(LazyTree.create(mod), out);
}
}
| true | true | public static void main(final String[] args) throws Exception {
String start = "main";
final ArrayList<Reader> inputs = new ArrayList<Reader>();
Writer out = new OutputStreamWriter(System.out);
boolean invalid = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-help")) {
invalid = true;
break;
}
if (args[i].equals("-start")) {
if (i == args.length - 1) {
invalid = true;
break;
}
start = args[++i];
} else if ("-out".equals(args[i])) {
if (i == args.length - 1) {
invalid = true;
break;
}
out = new OutputStreamWriter(new FileOutputStream(args[i]),
UTF8);
} else if ("-".equals(args[i])) {
inputs.add(new InputStreamReader(System.in));
} else {
final File f = new File(args[i]);
if (!f.isFile()) {
invalid = true;
break;
}
inputs.add(new InputStreamReader(new FileInputStream(f), UTF8));
}
}
if (invalid) {
System.err.println("Usage: sasln [-help] [-start <start_sym>] "
+ "[-out <dest_file>] <sklib>...\n"
+ "\t<start_sym>: function name used as entry point,"
+ " default is 'main'.\n"
+ "\t<dest_file>: File to write to, default is STDOUT.\n"
+ "\t<sklib>: a file containing an SK library,"
+ " '-' means STDIN.\n");
return;
}
if (inputs.isEmpty()) {
inputs.add(new InputStreamReader(System.in));
}
final Linker linker = new Linker(inputs);
final Expr linked = linker.link(start);
final Module mod = new Module(false);
mod.addDefinition(Name.valueOf("main"), linked);
Cout.module(LazyTree.create(mod), out);
}
| public static void main(final String[] args) throws Exception {
String start = "main";
final ArrayList<Reader> inputs = new ArrayList<Reader>();
Writer out = new OutputStreamWriter(System.out);
boolean invalid = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-help")) {
invalid = true;
break;
}
if (args[i].equals("-start")) {
if (i == args.length - 1) {
invalid = true;
break;
}
start = args[++i];
} else if ("-out".equals(args[i])) {
if (i == args.length - 1) {
invalid = true;
break;
}
out = new OutputStreamWriter(new FileOutputStream(args[++i]),
UTF8);
} else if ("-".equals(args[i])) {
inputs.add(new InputStreamReader(System.in));
} else {
final File f = new File(args[i]);
if (!f.isFile()) {
invalid = true;
break;
}
inputs.add(new InputStreamReader(new FileInputStream(f), UTF8));
}
}
if (invalid) {
System.err.println("Usage: sasln [-help] [-start <start_sym>] "
+ "[-out <dest_file>] <sklib>...\n"
+ "\t<start_sym>: function name used as entry point,"
+ " default is 'main'.\n"
+ "\t<dest_file>: File to write to, default is STDOUT.\n"
+ "\t<sklib>: a file containing an SK library,"
+ " '-' means STDIN.\n");
return;
}
if (inputs.isEmpty()) {
inputs.add(new InputStreamReader(System.in));
}
final Linker linker = new Linker(inputs);
final Expr linked = linker.link(start);
final Module mod = new Module(false);
mod.addDefinition(Name.valueOf("main"), linked);
Cout.module(LazyTree.create(mod), out);
}
|
diff --git a/src/pt/up/fe/dceg/neptus/util/llf/LogTableModel.java b/src/pt/up/fe/dceg/neptus/util/llf/LogTableModel.java
index ac91bd234..9596a6457 100644
--- a/src/pt/up/fe/dceg/neptus/util/llf/LogTableModel.java
+++ b/src/pt/up/fe/dceg/neptus/util/llf/LogTableModel.java
@@ -1,149 +1,149 @@
/*
* Copyright (c) 2004-2013 Universidade do Porto - Faculdade de Engenharia
* Laboratório de Sistemas e Tecnologia Subaquática (LSTS)
* All rights reserved.
* Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal
*
* This file is part of Neptus, Command and Control Framework.
*
* Commercial Licence Usage
* Licencees holding valid commercial Neptus licences may use this file
* in accordance with the commercial licence agreement provided with the
* Software or, alternatively, in accordance with the terms contained in a
* written agreement between you and Universidade do Porto. For licensing
* terms, conditions, and further information contact [email protected].
*
* European Union Public Licence - EUPL v.1.1 Usage
* Alternatively, this file may be used under the terms of the EUPL,
* Version 1.1 only (the "Licence"), appearing in the file LICENCE.md
* included in the packaging of this file. You may not use this work
* except in compliance with the Licence. Unless required by applicable
* law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the Licence for the specific
* language governing permissions and limitations at
* https://www.lsts.pt/neptus/licence.
*
* For more information please see <http://lsts.fe.up.pt/neptus>.
*
* Author:
* 20??/??/??
*/
package pt.up.fe.dceg.neptus.util.llf;
import java.util.LinkedHashMap;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import pt.up.fe.dceg.neptus.imc.IMCMessage;
import pt.up.fe.dceg.neptus.imc.IMCMessageType;
import pt.up.fe.dceg.neptus.mra.importers.IMraLog;
import pt.up.fe.dceg.neptus.mra.importers.IMraLogGroup;
@SuppressWarnings("serial")
public class LogTableModel extends AbstractTableModel {
//RandomAccessFile raf = null;
private LinkedHashMap<Integer, Vector<Object>> cache = new LinkedHashMap<Integer, Vector<Object>>();
protected int rowCount = 1;
protected IMraLog parser;
protected IMraLogGroup source;
protected IMCMessageType msgType;
protected long initTimeMillis = 0;
protected long finalTimeMillis = 0;
protected void load(IMraLog parser, long initTime, long finalTime) {
IMCMessage msg = parser.getEntryAtOrAfter(initTime);
int rowIndex = 0;
System.out.println(initTime + " " + finalTime);
- while (msg.getTimestampMillis() < finalTime && msg != null) {
+ while (msg.getTimestampMillis() <= finalTime && msg != null) {
Vector<Object> values = new Vector<Object>();
values.add(msg.getTimestampMillis());
int src = msg.getInteger("src");
int src_ent = msg.getInteger("src_ent");
int dst = msg.getInteger("dst");
int dst_ent = msg.getInteger("dst_ent");
values.add(source.getSystemName(src));
values.add(source.getEntityName(src, src_ent));
values.add(source.getSystemName(dst));
values.add(source.getEntityName(dst, dst_ent));
for (String key : msg.getMessageType().getFieldNames())
values.add(msg.getString(key));
cache.put(rowIndex, values);
msg = parser.nextLogEntry();
rowIndex++;
}
rowCount = rowIndex;
}
public LogTableModel(IMraLogGroup source, IMraLog log) {
this(source, log, log.firstLogEntry().getTimestampMillis(), log.getLastEntry().getTimestampMillis());
}
public LogTableModel(IMraLogGroup source, IMraLog log, long initTime, long finalTime) {
this.source = source;
parser = log;
try {
msgType = parser.firstLogEntry().getMessageType();
load(parser, initTime, finalTime);
}
catch (Exception e) {
e.printStackTrace();
}
}
public int getColumnCount() {
if (msgType == null)
return 1;
return 5+msgType.getFieldNames().size();
}
public int getRowCount() {
if (parser == null)
return 1;
return rowCount;
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (parser == null) {
return "Unable to load data";
}
if (cache.containsKey(rowIndex)) {
return cache.get(rowIndex).get(columnIndex);
}
return null;
}
@Override
public String getColumnName(int column) {
if (parser == null)
return "Error";
Vector<String> names = new Vector<String>();
names.add("time");
names.add("src");
names.add("src_ent");
names.add("dst");
names.add("dst_ent");
names.addAll(msgType.getFieldNames());
return names.get(column);
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
}
| true | true | protected void load(IMraLog parser, long initTime, long finalTime) {
IMCMessage msg = parser.getEntryAtOrAfter(initTime);
int rowIndex = 0;
System.out.println(initTime + " " + finalTime);
while (msg.getTimestampMillis() < finalTime && msg != null) {
Vector<Object> values = new Vector<Object>();
values.add(msg.getTimestampMillis());
int src = msg.getInteger("src");
int src_ent = msg.getInteger("src_ent");
int dst = msg.getInteger("dst");
int dst_ent = msg.getInteger("dst_ent");
values.add(source.getSystemName(src));
values.add(source.getEntityName(src, src_ent));
values.add(source.getSystemName(dst));
values.add(source.getEntityName(dst, dst_ent));
for (String key : msg.getMessageType().getFieldNames())
values.add(msg.getString(key));
cache.put(rowIndex, values);
msg = parser.nextLogEntry();
rowIndex++;
}
rowCount = rowIndex;
}
| protected void load(IMraLog parser, long initTime, long finalTime) {
IMCMessage msg = parser.getEntryAtOrAfter(initTime);
int rowIndex = 0;
System.out.println(initTime + " " + finalTime);
while (msg.getTimestampMillis() <= finalTime && msg != null) {
Vector<Object> values = new Vector<Object>();
values.add(msg.getTimestampMillis());
int src = msg.getInteger("src");
int src_ent = msg.getInteger("src_ent");
int dst = msg.getInteger("dst");
int dst_ent = msg.getInteger("dst_ent");
values.add(source.getSystemName(src));
values.add(source.getEntityName(src, src_ent));
values.add(source.getSystemName(dst));
values.add(source.getEntityName(dst, dst_ent));
for (String key : msg.getMessageType().getFieldNames())
values.add(msg.getString(key));
cache.put(rowIndex, values);
msg = parser.nextLogEntry();
rowIndex++;
}
rowCount = rowIndex;
}
|
diff --git a/javasvn/src/org/tmatesoft/svn/core/internal/SVNWorkspace.java b/javasvn/src/org/tmatesoft/svn/core/internal/SVNWorkspace.java
index 213db5652..b93c9a01f 100644
--- a/javasvn/src/org/tmatesoft/svn/core/internal/SVNWorkspace.java
+++ b/javasvn/src/org/tmatesoft/svn/core/internal/SVNWorkspace.java
@@ -1,1731 +1,1734 @@
/*
* ====================================================================
* Copyright (c) 2004 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://tmate.org/svn/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import org.tmatesoft.svn.core.ISVNCommitHandler;
import org.tmatesoft.svn.core.ISVNDirectoryEntry;
import org.tmatesoft.svn.core.ISVNEntry;
import org.tmatesoft.svn.core.ISVNEntryContent;
import org.tmatesoft.svn.core.ISVNExternalsHandler;
import org.tmatesoft.svn.core.ISVNFileContent;
import org.tmatesoft.svn.core.ISVNRootEntry;
import org.tmatesoft.svn.core.ISVNRunnable;
import org.tmatesoft.svn.core.ISVNStatusHandler;
import org.tmatesoft.svn.core.ISVNWorkspace;
import org.tmatesoft.svn.core.ISVNWorkspaceListener;
import org.tmatesoft.svn.core.SVNCommitPacket;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.SVNStatus;
import org.tmatesoft.svn.core.SVNWorkspaceManager;
import org.tmatesoft.svn.core.internal.ws.fs.FSDirEntry;
import org.tmatesoft.svn.core.internal.ws.fs.FSUtil;
import org.tmatesoft.svn.core.io.ISVNCredentialsProvider;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.io.ISVNReporterBaton;
import org.tmatesoft.svn.core.io.SVNCommitInfo;
import org.tmatesoft.svn.core.io.SVNError;
import org.tmatesoft.svn.core.io.SVNException;
import org.tmatesoft.svn.core.io.SVNLock;
import org.tmatesoft.svn.core.io.SVNNodeKind;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepositoryLocation;
import org.tmatesoft.svn.core.io.SVNSimpleCredentialsProvider;
import org.tmatesoft.svn.core.progress.ISVNProgressViewer;
import org.tmatesoft.svn.util.DebugLog;
import org.tmatesoft.svn.util.PathUtil;
import org.tmatesoft.svn.util.SVNUtil;
import org.tmatesoft.svn.util.TimeUtil;
/**
* @author TMate Software Ltd.
*/
public class SVNWorkspace implements ISVNWorkspace {
private ISVNRootEntry myRoot;
private SVNRepositoryLocation myLocation;
private Map myAutoProperties;
private Map myCompiledAutoProperties;
private Collection myListeners;
private ISVNCredentialsProvider myCredentialsProvider;
private ISVNExternalsHandler myExternalsHandler;
private boolean myIsCommandRunning;
private boolean myIsNeedToSleepForTimestamp;
private boolean myIsCopyCommit;
public SVNWorkspace(ISVNRootEntry root) {
setAutoProperties(null);
setExternalsHandler(new DefaultSVNExternalsHandler());
myRoot = root;
}
public String getID() {
if (myRoot == null) {
return null;
}
return myRoot.getID();
}
public void setGlobalIgnore(String ignore) {
myRoot.setGlobalIgnore(ignore == null ? "" : ignore);
}
public String getGlobalIgnore() {
return myRoot.getGlobalIgnore();
}
public void setUseCommitTimes(boolean useCommitTimes) {
myRoot.setUseCommitTimes(useCommitTimes);
}
public boolean isUseCommitTimes() {
return myRoot.isUseCommitTimes();
}
public void setAutoProperties(Map properties) {
myAutoProperties = properties == null ? new HashMap() : new HashMap(properties);
myCompiledAutoProperties = null;
}
public Map getAutoProperties() {
return Collections.unmodifiableMap(myAutoProperties);
}
public void setExternalsHandler(ISVNExternalsHandler handler) {
myExternalsHandler = handler;
}
public void addWorkspaceListener(ISVNWorkspaceListener listener) {
if (listener != null) {
if (myListeners == null) {
myListeners = new HashSet();
}
myListeners.add(listener);
}
}
public void removeWorkspaceListener(ISVNWorkspaceListener listener) {
if (listener != null && myListeners != null) {
myListeners.remove(listener);
if (myListeners.isEmpty()) {
myListeners = null;
}
}
}
public SVNRepositoryLocation getLocation() throws SVNException {
if (myLocation == null) {
String url = getRoot().getPropertyValue(SVNProperty.URL);
url = PathUtil.decode(url);
if (url != null) {
try {
myLocation = SVNRepositoryLocation.parseURL(url);
} catch (SVNException e) {}
}
}
return myLocation;
}
public void setCredentials(String userName, String password) {
if (userName != null && password != null) {
myCredentialsProvider = new SVNSimpleCredentialsProvider(userName, password);
} else {
myCredentialsProvider = null;
}
}
public ISVNCredentialsProvider getCredentialsProvider() {
return myCredentialsProvider;
}
public void setCredentials(ISVNCredentialsProvider provider) {
myCredentialsProvider = provider;
}
public void refresh() throws SVNException {
if (getRoot() != null) {
getRoot().dispose();
}
}
public ISVNWorkspace getRootWorkspace(boolean stopOnExternals, boolean stopOnSwitch) {
ISVNWorkspace workspace = this;
while (true) {
String name = PathUtil.tail(workspace.getID());
if (name.trim().length() == 0 || PathUtil.isEmpty(name)) {
return workspace;
}
String parentID = PathUtil.removeTail(workspace.getID().replace(File.separatorChar, '/'));
ISVNWorkspace parentWorkspace = null;
SVNRepositoryLocation location = null;
DebugLog.log("creating parent workspace for " + workspace.getID());
DebugLog.log("parent id " + parentID);
try {
parentWorkspace = SVNWorkspaceManager.createWorkspace(getRoot().getType(), parentID);
if (parentWorkspace == null) {
return workspace;
}
parentWorkspace.setCredentials(myCredentialsProvider);
if (workspace.getLocation() == null && parentWorkspace.getLocation() != null) {
return parentWorkspace;
}
if (workspace.getLocation() == null) {
return workspace;
}
location = parentWorkspace.getLocation();
if (location == null) {
return workspace;
}
String expectedUrl = PathUtil.append(location.toString(), PathUtil.encode(name));
if (!expectedUrl.equals(workspace.getLocation().toString())) {
// check that ws.url at least starts with
// as an external ws should be "unversioned".
// as switched it should has "switched" status (at least not
// unversioned).
DebugLog.log("existing url: " + workspace.getLocation());
DebugLog.log("expected url: " + expectedUrl);
SVNStatus wsStatus = parentWorkspace.status(name, false);
if (wsStatus == null) {
return workspace;
}
int status = wsStatus.getContentsStatus();
if ((status == SVNStatus.UNVERSIONED || status == SVNStatus.IGNORED || status == SVNStatus.EXTERNAL)) {
if (stopOnExternals) {
return workspace;
}
} else if (((status != SVNStatus.UNVERSIONED && status != SVNStatus.IGNORED) || wsStatus.isSwitched())) {
if (stopOnSwitch) {
return workspace;
}
}
}
} catch (SVNException e1) {
return workspace;
}
workspace = parentWorkspace;
}
}
public SVNRepositoryLocation getLocation(String path) throws SVNException {
if (path == null || "".equals(path)) {
return getLocation();
}
ISVNEntry entry = locateEntry(path);
if (entry == null) {
return null;
}
String url = entry.getPropertyValue(SVNProperty.URL);
if (url == null) {
return null;
}
url = PathUtil.decode(url);
return SVNRepositoryLocation.parseURL(url);
}
public void setLocation(SVNRepositoryLocation location) throws SVNException {
if (getLocation() == null && location != null) {
getRoot().setPropertyValue(SVNProperty.URL, location.toString());
myLocation = location;
}
}
public long checkout(SVNRepositoryLocation location, long revision, boolean export) throws SVNException {
return checkout(location, revision, export, true);
}
public long checkout(SVNRepositoryLocation location, long revision, boolean export, boolean recurse) throws SVNException {
return checkout(location, revision, export, recurse, null);
}
public long checkout(SVNRepositoryLocation location, long revision, boolean export, boolean recurse, ISVNProgressViewer progressViewer) throws SVNException {
if (getLocation() != null) {
throw new SVNException(getRoot().getID() + " already contains working copy files");
}
try {
SVNRepository repository = null;
if (!export) {
setLocation(location);
repository = SVNUtil.createRepository(this, "");
} else {
repository = SVNRepositoryFactory.create(location);
repository.setCredentialsProvider(myCredentialsProvider);
}
final SVNCheckoutProgressProcessor processor = progressViewer != null ? new SVNCheckoutProgressProcessor(progressViewer, repository, revision) : null;
SVNCheckoutEditor editor = new SVNCheckoutEditor(getRoot(), this, getRoot(), export, null, true, processor);
repository.checkout(revision, null, recurse, editor);
if (myExternalsHandler != null) {
Collection paths = new HashSet();
for (Iterator externals = editor.getExternals().iterator(); externals.hasNext();) {
SVNExternal external = (SVNExternal) externals.next();
if (paths.contains(external.getPath())) {
continue;
}
paths.add(external.getPath());
try {
String path = PathUtil.append(getID(), external.getPath());
new File(path).mkdirs();
ISVNWorkspace extWorkspace = createWorkspace(external);
myExternalsHandler.handleCheckout(this, external.getPath(), extWorkspace, external.getLocation(), external.getRevision(), export, true);
} catch (Throwable th) {
DebugLog.error(th);
}
}
}
if (!export && editor.isTimestampsChanged()) {
sleepForTimestamp();
}
return editor.getTargetRevision();
} finally {
getRoot().dispose();
}
}
public long update(long revision) throws SVNException {
return update("", revision, true);
}
public long update(String path, long revision, boolean recursive) throws SVNException {
if (getLocation() == null) {
throw new SVNException(getRoot().getID() + " does not contain working copy files");
}
try {
ISVNEntry targetEntry = locateEntry(path);
Collection externalsSet = createExternals(path);
String target = null;
if (targetEntry == null || !targetEntry.isDirectory()) {
target = targetEntry != null ? targetEntry.getName() : PathUtil.tail(path);
targetEntry = locateParentEntry(path);
}
if (targetEntry.isMissing()) {
target = targetEntry.getName();
targetEntry = locateParentEntry(path);
}
SVNRepository repository = SVNUtil.createRepository(this, targetEntry.getPath());
SVNCheckoutEditor editor = new SVNCheckoutEditor(getRoot(), this, targetEntry, false, target, recursive, null);
SVNReporterBaton reporterBaton = new SVNReporterBaton(this, targetEntry, target, recursive);
repository.update(revision, target, recursive, reporterBaton, editor);
for(Iterator missingPaths = reporterBaton.missingEntries(); missingPaths.hasNext();) {
ISVNEntry missingEntry = (ISVNEntry) missingPaths.next();
if (locateEntry(missingEntry.getPath()) == null) {
fireEntryUpdated(missingEntry, SVNStatus.DELETED, 0, -1);
}
}
if (myExternalsHandler != null) {
Collection existingExternals = reporterBaton.getExternals();
Collection updatedExternals = editor.getExternals();
Collection allExternals = new HashSet(existingExternals);
allExternals.addAll(externalsSet);
existingExternals.addAll(updatedExternals);
Collection paths = new HashSet();
for (Iterator externals = allExternals.iterator(); externals.hasNext();) {
SVNExternal external = (SVNExternal) externals.next();
if (paths.contains(external.getPath())) {
continue;
}
paths.add(external.getPath());
if (!external.getPath().startsWith(path)) {
continue;
}
try {
ISVNWorkspace extWorkspace = createWorkspace(external);
myExternalsHandler.handleUpdate(this, external.getPath(), extWorkspace, external.getRevision());
} catch (Throwable th) {
DebugLog.error(th);
}
}
}
if (editor.isTimestampsChanged()) {
sleepForTimestamp();
}
return editor.getTargetRevision();
} finally {
getRoot().dispose();
}
}
public long update(SVNRepositoryLocation url, String path, long revision, boolean recursive) throws SVNException {
if (getLocation() == null) {
throw new SVNException(getRoot().getID() + " does not contain working copy files");
}
try {
ISVNEntry targetEntry = locateEntry(path);
if (targetEntry == null) {
throw new SVNException("could not find directory '" + path + "'");
}
String target = null;
if (!targetEntry.isDirectory()) {
target = targetEntry.getName();
targetEntry = locateParentEntry(targetEntry.getPath());
}
SVNRepository repository = SVNUtil.createRepository(this, targetEntry.getPath());
SVNCheckoutEditor editor = new SVNCheckoutEditor(getRoot(), this, targetEntry, false, target);
ISVNReporterBaton reporterBaton = new SVNReporterBaton(this, targetEntry, null, recursive);
repository.update(url.toString(), revision, target, recursive, reporterBaton, editor);
if (myExternalsHandler != null) {
Collection paths = new HashSet();
for (Iterator externals = editor.getExternals().iterator(); externals.hasNext();) {
SVNExternal external = (SVNExternal) externals.next();
if (paths.contains(external.getPath())) {
continue;
}
paths.add(external.getPath());
try {
ISVNWorkspace extWorkspace = createWorkspace(external);
myExternalsHandler.handleCheckout(this, external.getPath(), extWorkspace, external.getLocation(), external.getRevision(), false, true);
} catch (Throwable th) {
DebugLog.error(th);
}
}
}
// update urls.
String newURL = url.toString();
if (target != null) {
targetEntry = locateEntry(path);
}
targetEntry.setPropertyValue(SVNProperty.URL, newURL);
DebugLog.log("setting new url for " + targetEntry.getPath() + " : " + newURL);
if (targetEntry.isDirectory()) {
for (Iterator children = targetEntry.asDirectory().childEntries(); children.hasNext();) {
ISVNEntry child = (ISVNEntry) children.next();
updateURL(child, newURL, recursive);
}
targetEntry.save();
} else {
locateParentEntry(path).save();
}
if (targetEntry.equals(getRoot())) {
setLocation(url);
}
if (editor.isTimestampsChanged()) {
sleepForTimestamp();
}
return editor.getTargetRevision();
} finally {
getRoot().dispose();
}
}
private ISVNWorkspace createWorkspace(SVNExternal external) throws SVNException {
ISVNWorkspace extWorkspace = SVNWorkspaceManager.createWorkspace(getRoot().getType(), PathUtil.append(getID(), external.getPath()));
extWorkspace.setCredentials(myCredentialsProvider);
return extWorkspace;
}
public void relocate(SVNRepositoryLocation newLocation, String path, boolean recursive) throws SVNException {
try {
ISVNEntry targetEntry = locateEntry(path);
if (targetEntry == null) {
throw new SVNException("could not find directory '" + path + "'");
}
if (!targetEntry.isDirectory()) {
throw new SVNException("could not relocate file '" + path + "' only directories could be switched");
}
String newURL = newLocation.toString();
targetEntry.setPropertyValue(SVNProperty.URL, newURL);
for (Iterator children = targetEntry.asDirectory().childEntries(); children.hasNext();) {
ISVNEntry child = (ISVNEntry) children.next();
updateURL(child, newURL, recursive);
}
targetEntry.save();
if (targetEntry.equals(getRoot())) {
setLocation(newLocation);
}
} finally {
getRoot().dispose();
}
}
public long status(String path, boolean remote, ISVNStatusHandler handler, boolean descend, boolean includeUnmodified, boolean includeIgnored)
throws SVNException {
return status(path, remote, handler, descend, includeUnmodified, includeIgnored, false, false);
}
public long status(String path, boolean remote, ISVNStatusHandler handler, boolean descend, boolean includeUnmodified, boolean includeIgnored,
boolean descendInUnversioned, boolean descendFurtherInIgnored) throws SVNException {
return status(path, remote, handler, descend, includeUnmodified, includeIgnored, descendInUnversioned, descendFurtherInIgnored, null);
}
public long status(String path, boolean remote, ISVNStatusHandler handler, boolean descend, boolean includeUnmodified, boolean includeIgnored, boolean descendInUnversioned, boolean descendFurtherInIgnored, ISVNProgressViewer progressViewer) throws SVNException {
long start = System.currentTimeMillis();
if (getLocation() == null) {
// throw new SVNException(getRoot().getID() + " does not contain
// working copy files");
return -1;
}
if (path == null) {
path = "";
}
long revision = -1;
SVNStatusEditor editor = null;
ISVNEntry targetEntry = locateEntry(path, true);
if (targetEntry == null) {
return -1;
}
if (remote && targetEntry != null) {
ISVNEntry entry = targetEntry;
if (!entry.isDirectory()) {
entry = locateParentEntry(path);
}
SVNRepository repository = SVNUtil.createRepository(this, entry.getPath());
String target = null;
if (!targetEntry.isDirectory()) {
target = targetEntry.getName();
}
SVNLock[] locks = null;
try {
locks = repository.getLocks(target == null ? "" : target);
} catch (SVNException e) {}
editor = new SVNStatusEditor(entry.getPath(), locks);
SVNReporterBaton reporterBaton = new SVNReporterBaton(null, entry, target, descend);
repository.status(ISVNWorkspace.HEAD, target, descend, reporterBaton, editor);
revision = editor.getTargetRevision();
}
if (handler == null) {
return revision;
}
Collection externals = createExternals(path);
ISVNEntry parent = null;
if (!"".equals(path)) {
parent = locateParentEntry(path);
}
if (targetEntry != null && parent != null && parent.asDirectory().isIgnored(targetEntry.getName())) {
includeIgnored = true;
}
SVNStatusUtil.doStatus(this, parent != null ? parent.asDirectory() : null, editor, handler, path, externals, descend, includeUnmodified,
includeIgnored, descendInUnversioned, descendFurtherInIgnored, progressViewer);
if (myExternalsHandler != null && externals != null) {
Collection paths = new HashSet();
for (Iterator exts = externals.iterator(); exts.hasNext();) {
SVNExternal external = (SVNExternal) exts.next();
if (paths.contains(external.getPath())) {
continue;
}
paths.add(external.getPath());
if (!descend && !external.getPath().equals(path)) {
DebugLog.log("SKIPPING EXTERNAL STATUS FOR " + external.getPath());
continue;
} else if (!external.getPath().startsWith(path)) {
DebugLog.log("SKIPPING EXTERNAL STATUS FOR " + external.getPath());
continue;
}
DebugLog.log("EXTERNAL STATUS FOR " + external.getPath());
try {
ISVNWorkspace extWorkspace = createWorkspace(external);
myExternalsHandler.handleStatus(this, external.getPath(), extWorkspace, handler, remote, descend, includeUnmodified, includeIgnored,
descendInUnversioned);
} catch (Throwable th) {
DebugLog.error(th);
}
}
}
DebugLog.benchmark("STATUS COMPLETED IN " + (System.currentTimeMillis() - start));
return revision;
}
public SVNStatus status(final String filePath, boolean remote) throws SVNException {
final SVNStatus[] result = new SVNStatus[1];
status(filePath, remote, new ISVNStatusHandler() {
public void handleStatus(String path, SVNStatus status) {
if (status.getPath().equals(filePath)) {
result[0] = status;
}
}
}, false, true, true);
return result[0];
}
public void log(String path, long startRevision, long endRevison, boolean stopOnCopy, boolean discoverPath, ISVNLogEntryHandler handler)
throws SVNException {
if (getLocation() == null) {
throw new SVNException(getRoot().getID() + " does not contain working copy files");
}
ISVNEntry entry = locateEntry(path);
String targetPath = "";
SVNRepository repository;
if (!entry.isDirectory()) {
targetPath = entry.getName();
repository = SVNUtil.createRepository(this, PathUtil.removeTail(path));
} else {
repository = SVNUtil.createRepository(this, path);
}
repository.log(new String[] { targetPath }, startRevision, endRevison, discoverPath, stopOnCopy, handler);
}
// import
public long commit(SVNRepositoryLocation destination, String message) throws SVNException {
return commit(destination, null, message);
}
public long commit(SVNRepositoryLocation destination, String fileName, String message) throws SVNException {
if (fileName == null && getLocation() != null) {
throw new SVNException(getRoot().getID() + " already contains working copy files");
}
if (fileName != null && locateEntry(fileName) != null) {
throw new SVNException("'" + fileName + "' already under version control");
}
SVNRepository repository = SVNRepositoryFactory.create(destination);
repository.setCredentialsProvider(getCredentialsProvider());
repository.testConnection();
String rootPath = PathUtil.decode(destination.getPath());
rootPath = rootPath.substring(repository.getRepositoryRoot().length());
if (!rootPath.startsWith("/")) {
rootPath = "/" + rootPath;
}
rootPath = PathUtil.removeTrailingSlash(rootPath);
List dirsList = new LinkedList();
DebugLog.log("IMPORT: ROOT PATH: " + rootPath);
while(rootPath.lastIndexOf('/') >= 0) {
SVNNodeKind nodeKind = repository.checkPath(rootPath, -1);
if (nodeKind == SVNNodeKind.DIR) {
break;
} else if (nodeKind == SVNNodeKind.FILE) {
throw new SVNException("'" + rootPath + "' is file, could not import into it");
}
String dir = rootPath.substring(rootPath.lastIndexOf('/') + 1);
dirsList.add(0, dir);
rootPath = rootPath.substring(0, rootPath.lastIndexOf('/'));
}
destination = new SVNRepositoryLocation(destination.getProtocol(),
destination.getHost(), destination.getPort(), PathUtil.append(repository.getRepositoryRoot(), rootPath));
repository = SVNRepositoryFactory.create(destination);
repository.setCredentialsProvider(getCredentialsProvider());
DebugLog.log("IMPORT: REPOSITORY CREATED FOR: " + destination.toString());
ISVNEditor editor = repository.getCommitEditor(message, getRoot());
SVNCommitInfo info = null;
try {
String dir = "";
DebugLog.log("IMPORT: OPEN ROOT");
editor.openRoot(-1);
for(Iterator dirs = dirsList.iterator(); dirs.hasNext();) {
String nextDir = (String) dirs.next();
DebugLog.log("IMPORT: NEXT DIR: " + nextDir);
dir = dir + '/' + nextDir;
DebugLog.log("IMPORT: ADDING MISSING DIR: " + dir);
editor.addDir(dir, null, -1);
}
if (fileName == null) {
for(Iterator children = getRoot().asDirectory().unmanagedChildEntries(false); children.hasNext();) {
ISVNEntry child = (ISVNEntry) children.next();
doImport(dir, editor, getRoot(), child);
}
} else {
ISVNEntry child = locateEntry(fileName, true);
doImport(dir, editor, getRoot(), child);
}
for(Iterator dirs = dirsList.iterator(); dirs.hasNext();) {
dirs.next();
editor.closeDir();
}
editor.closeDir();
fireEntryCommitted(null, SVNStatus.ADDED);
info = editor.closeEdit();
} catch (SVNException e) {
try {
editor.abortEdit();
} catch (SVNException inner) {}
DebugLog.error(e);
throw e;
} finally {
getRoot().dispose();
}
return info != null ? info.getNewRevision() : -1;
}
// real commit
public long commit(String message) throws SVNException {
return commit("", message, true);
}
public long commit(String path, String message, boolean recursive) throws SVNException {
return commit(new String[] { path }, message, recursive, true);
}
public long commit(String[] paths, final String message, boolean recursive) throws SVNException {
return commit(paths, message, recursive, true);
}
public long commit(String[] paths, final String message, boolean recursive, boolean includeParents) throws SVNException {
return commit(paths, new ISVNCommitHandler() {
public String handleCommit(SVNStatus[] tobeCommited) {
return message == null ? "" : message;
}
}, recursive, includeParents);
}
public long commit(String[] paths, ISVNCommitHandler handler, boolean recursive) throws SVNException {
return commit(paths, handler, recursive, true);
}
public long commit(String[] paths, ISVNCommitHandler handler, boolean recursive, boolean includeParents) throws SVNException {
if (handler == null) {
handler = new ISVNCommitHandler() {
public String handleCommit(SVNStatus[] tobeCommited) {
return "";
}
};
}
final SVNCommitPacket packet = createCommitPacket(paths, recursive, includeParents);
if (packet == null) {
DebugLog.log("NOTHING TO COMMIT");
return -1;
}
return commit(packet, handler.handleCommit(packet.getStatuses()));
}
public SVNStatus[] getCommittables(String[] paths, boolean recursive, boolean includeParents) throws SVNException {
long start = System.currentTimeMillis();
for (int i = 0; i < paths.length; i++) {
ISVNEntry entry = locateEntry(paths[i]);
if (entry == null || !entry.isManaged()) {
throw new SVNException("'" + paths[i] + "' is not under version control");
}
else if (entry != null && entry.getPropertyValue(SVNProperty.COPIED) != null &&
!entry.isScheduledForAddition()) {
throw new SVNException("'" + entry.getPath() + "' is marked as 'copied' but is not itself scheduled for addition. " +
"Perhaps you're committing a target that is inside unversioned (or not-yet-versioned) directory?");
}
}
try {
final String root = getCommitRoot(paths);
final ISVNEntry rootEntry = locateEntry(root);
if (rootEntry == null || rootEntry.getPropertyValue(SVNProperty.URL) == null) {
throw new SVNException(root + " does not contain working copy files");
}
DebugLog.log("");
DebugLog.log("COMMIT ROOT: " + root);
for (int i = 0; i < paths.length; i++) {
DebugLog.log("COMMIT PATH " + i + " :" + paths[i]);
}
Collection modified = new HashSet();
if (recursive) {
SVNCommitUtil.harvestCommitables(rootEntry, paths, recursive, modified);
}
else {
for (int i = 0; i < paths.length; i++) {
String path = paths[i];
ISVNEntry entry = locateEntry(path);
SVNCommitUtil.harvestCommitables(entry, paths, recursive, modified);
}
}
Collection modifiedParents = new HashSet();
for (Iterator modifiedEntries = modified.iterator(); modifiedEntries.hasNext();) {
ISVNEntry entry = (ISVNEntry)modifiedEntries.next();
if (!entry.isDirectory() && entry.asFile().isCorrupted()) {
throw new SVNException("svn: Checksum of base file '" + entry.getPath() + "' is not valid");
}
String p = entry.getPath();
if (entry.isScheduledForAddition()) {
ISVNEntry parent = locateParentEntry(entry.getPath());
while (parent != null && parent.isScheduledForAddition() && !parent.isScheduledForDeletion()) {
if (!includeParents) {
if (!modified.contains(parent)) {
throw new SVNException("'" + p + "' is not under version control");
}
break;
}
modifiedParents.add(parent);
DebugLog.log("HV: 'added' parent added to transaction: " + parent.getPath());
parent = locateParentEntry(parent.getPath());
}
}
}
modified.addAll(modifiedParents);
if (modified.isEmpty()) {
return null;
}
SVNStatus[] statuses = new SVNStatus[modified.size()];
Map urls = new HashMap();
int index = 0;
String uuid = null;
for (Iterator entries = modified.iterator(); entries.hasNext();) {
ISVNEntry entry = (ISVNEntry)entries.next();
String url = entry.getPropertyValue(SVNProperty.URL);
String entryUUID = entry.getPropertyValue(SVNProperty.UUID);
if (entryUUID != null) {
if (uuid != null && !uuid.equals(entryUUID)) {
throw new SVNException("commit contains entries from the different repositories '" + entry.getPath() + "' and '" + urls.get(url) + "'");
}
uuid = entryUUID;
}
if (urls.containsKey(url)) {
throw new SVNException("commit contains entries with the same url '" + entry.getPath() + "' and '" + urls.get(url) + "'");
}
urls.put(url, entry.getPath());
if (entry.isConflict()) {
throw new SVNException("resolve conflict in '" + entry.getPath() + "' before commit");
}
statuses[index++] = SVNStatusUtil.createStatus(entry, -1, 0, 0, null);
}
DebugLog.log("Calculating committables took " + (System.currentTimeMillis() - start) + " ms.");
return statuses;
}
finally {
if (!myIsCopyCommit) {
getRoot().dispose();
}
}
}
public SVNCommitPacket createCommitPacket(String[] paths, boolean recursive, boolean includeParents) throws SVNException {
final SVNStatus[] committables = getCommittables(paths, recursive, includeParents);
return committables != null ? new SVNCommitPacket(getCommitRoot(paths), committables) : null;
}
public long commit(SVNCommitPacket packet, String message) throws SVNException {
final SVNStatus[] statuses = packet.getStatuses();
return commitPaths(getPathsFromStatuses(statuses), message, false, null);
}
public long commitPaths(List paths, String message, boolean keepLocks, ISVNProgressViewer progressViewer) throws SVNException {
long start = System.currentTimeMillis();
try {
final Set modified = new HashSet();
for (Iterator it = paths.iterator(); it.hasNext();) {
final String path = (String)it.next();
- ISVNEntry entry = locateEntry(path);
+ ISVNEntry entry = locateEntry(path);
modified.add(entry);
}
if (message == null || modified.isEmpty()) {
DebugLog.log("NOTHING TO COMMIT");
return -1;
}
String root = getCommitRoot((String[])paths.toArray(new String[paths.size()]));
ISVNEntry rootEntry = locateEntry(root);
if (rootEntry == null || rootEntry.getPropertyValue(SVNProperty.URL) == null) {
throw new SVNException(root + " does not contain working copy files");
}
DebugLog.log("COMMIT MESSAGE: " + message);
Map tree = new HashMap();
- Map locks = new HashMap();
+ Map locks = new HashMap();
String url = SVNCommitUtil.buildCommitTree(modified, tree, locks);
for (Iterator treePaths = tree.keySet().iterator(); treePaths.hasNext();) {
String treePath = (String)treePaths.next();
if (tree.get(treePath) != null) {
DebugLog.log("TREE ENTRY : " + treePath + " : " + ((ISVNEntry)tree.get(treePath)).getPath());
}
else {
DebugLog.log("TREE ENTRY : " + treePath + " : null");
}
}
DebugLog.log("COMMIT ROOT RECALCULATED: " + url);
DebugLog.log("COMMIT PREPARATIONS TOOK: " + (System.currentTimeMillis() - start) + " ms.");
SVNRepositoryLocation location = SVNRepositoryLocation.parseURL(url);
SVNRepository repository = SVNRepositoryFactory.create(location);
repository.setCredentialsProvider(getCredentialsProvider());
+ repository.testConnection();
String host = location.getProtocol() + "://" + location.getHost() + ":" + location.getPort();
String rootURL = PathUtil.append(host, repository.getRepositoryRoot());
if (!locks.isEmpty()) {
Map transaltedLocks = new HashMap();
for(Iterator lockedPaths = locks.keySet().iterator(); lockedPaths.hasNext();) {
String lockedPath = (String) lockedPaths.next();
String relativePath = lockedPath.substring(rootURL.length());
if (!relativePath.startsWith("/")) {
relativePath = "/" + relativePath;
}
transaltedLocks.put(relativePath, locks.get(lockedPath));
}
locks = transaltedLocks;
+ } else {
+ locks = null;
}
DebugLog.log("LOCKS ready for commit: " + locks);
ISVNEditor editor = repository.getCommitEditor(message, locks, keepLocks, new SVNWorkspaceMediatorAdapter(getRoot(), tree));
SVNCommitInfo info;
try {
SVNCommitUtil.doCommit("", rootURL, tree, editor, this, progressViewer);
info = editor.closeEdit();
}
catch (SVNException e) {
DebugLog.error("error: " + e.getMessage());
if (e.getErrors() != null) {
for (int i = 0; i < e.getErrors().length; i++) {
SVNError error = e.getErrors()[i];
if (error != null) {
DebugLog.error(error.toString());
}
}
}
try {
editor.abortEdit();
}
catch (SVNException inner) {
}
throw e;
}
catch (Throwable th) {
throw new SVNException(th);
}
DebugLog.log("COMMIT TOOK: " + (System.currentTimeMillis() - start) + " ms.");
if (!myIsCopyCommit) {
start = System.currentTimeMillis();
SVNCommitUtil.updateWorkingCopy(info, rootEntry.getPropertyValue(SVNProperty.UUID), tree, this);
sleepForTimestamp();
DebugLog.log("POST COMMIT ACTIONS TOOK: " + (System.currentTimeMillis() - start) + " ms.");
}
return info != null ? info.getNewRevision() : -1;
}
finally {
myIsCopyCommit = false;
getRoot().dispose();
}
}
public void add(String path, boolean mkdir, boolean recurse) throws SVNException {
try {
ISVNEntry entry = locateParentEntry(path);
String name = PathUtil.tail(path);
if (entry == null || entry.isMissing() || !entry.isDirectory()) {
throw new SVNException("can't locate versioned parent entry for '" + path + "'");
}
if (mkdir && entry != null && !entry.isManaged() && entry.isDirectory() && entry != getRoot()) {
add(entry.getPath(), mkdir, recurse);
getRoot().dispose();
entry = locateParentEntry(path);
}
if (entry != null && name != null &&
entry.isManaged() && !entry.isMissing() && entry.isDirectory()) {
ISVNEntry child = entry.asDirectory().scheduleForAddition(name, mkdir, recurse);
doApplyAutoProperties(child, recurse);
fireEntryModified(child, SVNStatus.ADDED, true);
entry.save();
entry.dispose();
} else {
throw new SVNException("can't locate versioned parent entry for '" + path + "'");
}
} finally {
getRoot().dispose();
}
}
private void doApplyAutoProperties(ISVNEntry addedEntry, boolean recurse) throws SVNException {
applyAutoProperties(addedEntry, null);
if (recurse && addedEntry.isDirectory()) {
for (Iterator children = addedEntry.asDirectory().childEntries(); children.hasNext();) {
ISVNEntry childEntry = (ISVNEntry) children.next();
if (childEntry.isScheduledForAddition()) {
doApplyAutoProperties(childEntry, recurse);
}
}
}
}
public void delete(String path) throws SVNException {
delete(path, false);
}
public void delete(String path, boolean force) throws SVNException {
try {
ISVNEntry entry = locateParentEntry(path);
String name = PathUtil.tail(path);
if (entry != null && name != null) {
if (!force) {
// check if files are modified.
assertNotModified(entry.asDirectory().getChild(name));
assertNotModified(entry.asDirectory().getUnmanagedChild(name));
}
ISVNEntry child = entry.asDirectory().scheduleForDeletion(name, force);
fireEntryModified(child, SVNStatus.DELETED, true);
entry.save();
entry.dispose();
} else if (entry == null) {
}
} finally {
getRoot().dispose();
}
}
private static void assertNotModified(ISVNEntry entry) throws SVNException {
if (entry == null) {
return;
}
if (!entry.isManaged()) {
throw new SVNException("'" + entry.getPath() + "' is unmanaged, use 'force' parameter to force deletion.");
} else if (entry.isScheduledForAddition() && !entry.isMissing()) {
throw new SVNException("'" + entry.getPath() + "' is modified locally, use 'force' parameter to force deletion.");
}
if (entry.isPropertiesModified()) {
throw new SVNException("'" + entry.getPath() + "' is modified locally, use 'force' parameter to force deletion.");
}
if (!entry.isDirectory()) {
if (entry.asFile().isContentsModified()) {
throw new SVNException("'" + entry.getPath() + "' is modified locally, use 'force' parameter to force deletion.");
}
} else {
for (Iterator children = entry.asDirectory().unmanagedChildEntries(true); children.hasNext();) {
assertNotModified((ISVNEntry) children.next());
}
for (Iterator children = entry.asDirectory().childEntries(); children.hasNext();) {
assertNotModified((ISVNEntry) children.next());
}
}
}
public void copy(String source, String destination, boolean move) throws SVNException {
copy(source, destination, move, false);
}
public void copy(String source, String destination, boolean move, boolean virtual) throws SVNException {
try {
if (virtual) {
// check if unversioned destination is already there
ISVNEntry dstEntry = locateEntry(destination, true);
if (dstEntry != null && dstEntry.isManaged()) {
throw new SVNException("'" + destination + "' already exists in working copy and it is versioned");
}
ISVNEntry srcEntry = locateEntry(source, false);
if (move) {
if (srcEntry == null || !srcEntry.isMissing()) {
throw new SVNException("'" + source + "' already exists in working copy and it is not missing");
}
} else {
if (srcEntry == null || !srcEntry.isManaged()) {
throw new SVNException("'" + source + "' does not exist in working copy.");
}
}
} else {
if (locateEntry(destination, true) != null) {
throw new SVNException("'" + destination + "' already exists in working copy");
}
}
ISVNEntry entry = locateParentEntry(destination);
String name = PathUtil.tail(destination);
ISVNEntry toCopyParent = locateParentEntry(source);
ISVNEntry sourceEntry = locateEntry(source);
if (entry == null || !entry.isDirectory()) {
throw new SVNException("'" + destination + "' is not under version control");
}
if (toCopyParent == null || !toCopyParent.isDirectory()) {
throw new SVNException("'" + source + "' is not under version control");
}
if (sourceEntry == null) {
throw new SVNException("'" + source + "' is not under version control");
}
String toCopyName = PathUtil.tail(source);
ISVNEntry toCopy = toCopyParent.asDirectory().getChild(toCopyName);
ISVNEntry copied = entry.asDirectory().copy(name, toCopy);
fireEntryModified(copied, SVNStatus.ADDED, true);
if (move && toCopyParent != null) {
toCopyParent.asDirectory().scheduleForDeletion(toCopy.getName(), true);
fireEntryModified(toCopy, SVNStatus.DELETED, false);
toCopyParent.save();
toCopyParent.dispose();
}
entry.save();
entry.dispose();
sleepForTimestamp();
} finally {
getRoot().dispose();
}
}
public void copy(SVNRepositoryLocation source, String destination, long revision) throws SVNException {
copy(source, destination, revision, null);
}
public void copy(SVNRepositoryLocation source, String destination, long revision, ISVNProgressViewer progressViewer) throws SVNException {
File tmpFile = null;
try {
SVNRepository repository = SVNRepositoryFactory.create(source);
repository.setCredentialsProvider(myCredentialsProvider);
ISVNEntry entry = locateEntry(destination);
if (entry != null) {
if (!entry.isDirectory()) {
throw new SVNException("can't copy over versioned file '" + entry.getPath() + "'");
}
destination = PathUtil.append(destination, PathUtil.tail(source.getPath()));
}
SVNNodeKind srcKind = repository.checkPath("", revision);
DebugLog.log("copy destination is : " + destination);
if (srcKind == SVNNodeKind.DIR) {
DebugLog.log("local uuid: " + getRoot().getPropertyValue(SVNProperty.UUID));
DebugLog.log("remote uuid: " + repository.getRepositoryUUID());
if (!repository.getRepositoryUUID().equals(getRoot().getPropertyValue(SVNProperty.UUID))) {
throw new SVNException("couldn't copy directory from another repository");
}
String root = PathUtil.append(getID(), destination);
DebugLog.log("checkout ws root : " + root);
ISVNWorkspace ws = SVNWorkspaceManager.createWorkspace(getRoot().getType(), root);
ws.setCredentials(myCredentialsProvider);
ws.setAutoProperties(getAutoProperties());
ws.setExternalsHandler(myExternalsHandler);
if (myListeners != null) {
for (Iterator listeners = myListeners.iterator(); listeners.hasNext();) {
ISVNWorkspaceListener listener = (ISVNWorkspaceListener) listeners.next();
ws.addWorkspaceListener(listener);
}
}
DebugLog.log("checking out revision: " + revision);
revision = ws.checkout(source, revision, false, true, progressViewer);
ISVNEntry dirEntry = locateEntry(PathUtil.removeTail(destination));
dirEntry.asDirectory().markAsCopied(PathUtil.tail(destination), source, revision);
} else if (srcKind == SVNNodeKind.FILE) {
Map properties = new HashMap();
tmpFile = File.createTempFile("svn.", ".tmp");
tmpFile.deleteOnExit();
OutputStream tmpStream = new FileOutputStream(tmpFile);
repository.getFile("", revision, properties, tmpStream);
tmpStream.close();
InputStream in = new FileInputStream(tmpFile);
String name = PathUtil.tail(destination);
ISVNEntry dirEntry = locateEntry(PathUtil.removeTail(destination));
if (repository.getRepositoryUUID().equals(getRoot().getPropertyValue(SVNProperty.UUID))) {
dirEntry.asDirectory().markAsCopied(in, tmpFile.length(), properties, name, source);
} else {
dirEntry.asDirectory().markAsCopied(in, tmpFile.length(), properties, name, null);
}
in.close();
} else {
throw new SVNException("can't copy from '" + source.toCanonicalForm() + "', location doesn't exist at revision " + revision);
}
} catch (IOException e) {
DebugLog.error(e);
} finally {
if (tmpFile != null) {
tmpFile.delete();
}
getRoot().dispose();
}
}
public long copy(String src, SVNRepositoryLocation destination, String message) throws SVNException {
return copy(src, destination, message, null);
}
public long copy(String src, SVNRepositoryLocation destination, String message, ISVNProgressViewer progressViewer) throws SVNException {
ISVNEntry entry = locateEntry(src);
ISVNEntry parent = locateParentEntry(src);
if (entry == null) {
throw new SVNException("no versioned entry found at '" + src + "'");
}
try {
String url = destination.toCanonicalForm();
String name = PathUtil.tail(src);
SVNRepository repository = SVNRepositoryFactory.create(destination);
repository.setCredentialsProvider(myCredentialsProvider);
if (repository.checkPath("", -1) == SVNNodeKind.NONE) {
name = PathUtil.tail(url);
name = PathUtil.decode(name);
url = PathUtil.removeTail(url);
}
entry.setAlias(name);
DebugLog.log("entry path: " + entry.getPath());
DebugLog.log("entry aliased path: " + entry.getAlias());
// set copyfrom url to original source url and revision.
entry.setPropertyValue(SVNProperty.COPYFROM_URL, entry.getPropertyValue(SVNProperty.URL));
entry.setPropertyValue(SVNProperty.COPYFROM_REVISION, entry.getPropertyValue(SVNProperty.REVISION));
entry.setPropertyValue(SVNProperty.SCHEDULE, SVNProperty.SCHEDULE_ADD);
entry.setPropertyValue(SVNProperty.SVN_WC_PREFIX + "ra_dav:version-url", null);
if (entry.isDirectory() && parent != null) {
Map entryProps = ((FSDirEntry) parent).getChildEntryMap(entry.getName());
entryProps.put(SVNProperty.COPYFROM_URL, entry.getPropertyValue(SVNProperty.URL));
entryProps.put(SVNProperty.COPYFROM_REVISION, entry.getPropertyValue(SVNProperty.REVISION));
entryProps.put(SVNProperty.SCHEDULE, SVNProperty.SCHEDULE_ADD);
entryProps.put(SVNProperty.COPIED, "true");
}
FSDirEntry.updateURL(entry, url);
FSDirEntry.setPropertyValueRecursively(entry, SVNProperty.COPIED, "true");
// commit without saving properties (no entry.save/commit calls).
repository = SVNRepositoryFactory.create(SVNRepositoryLocation.parseURL(url));
repository.setCredentialsProvider(myCredentialsProvider);
ISVNEditor editor = repository.getCommitEditor(message, getRoot());
myIsCopyCommit = true;
SVNStatus[] committablePaths = getCommittables(new String[] {src}, true, false);
return commitPaths(getPathsFromStatuses(committablePaths), message, false, progressViewer);
} finally {
getRoot().dispose();
myIsCopyCommit = false;
}
}
public Iterator propertyNames(String path) throws SVNException {
ISVNEntry entry = locateEntry(path);
if (entry == null) {
return Collections.EMPTY_LIST.iterator();
}
Collection names = new LinkedList();
for (Iterator propNames = entry.propertyNames(); propNames.hasNext();) {
names.add(propNames.next());
}
return names.iterator();
}
public String getPropertyValue(String path, String name) throws SVNException {
ISVNEntry entry = locateEntry(path);
if (entry == null) {
return null;
}
return entry.getPropertyValue(name);
}
public Map getProperties(String path, boolean reposProps, boolean entryProps) throws SVNException {
Map props = new HashMap();
ISVNEntry entry = locateEntry(path, true);
if (entry == null) {
return null;
}
boolean add = false;
for (Iterator names = entry.propertyNames(); names.hasNext();) {
String name = (String) names.next();
if (name.startsWith(SVNProperty.SVN_ENTRY_PREFIX)) {
add = entryProps;
} else {
add = reposProps;
}
if (add) {
props.put(name, entry.getPropertyValue(name));
add = false;
}
}
return props;
}
public void setPropertyValue(String path, String name, String value) throws SVNException {
setPropertyValue(path, name, value, false);
}
public void setPropertyValue(String path, String name, String value, boolean recurse) throws SVNException {
try {
ISVNEntry entry = locateEntry(path);
if (entry == null) {
return;
}
doSetProperty(entry, name, value, recurse);
entry.save();
entry.dispose();
} finally {
getRoot().dispose();
}
}
public void markResolved(String path, boolean recursive) throws SVNException {
try {
ISVNEntry entry = locateEntry(path);
ISVNEntry parent = null;
if (!entry.isDirectory()) {
parent = locateParentEntry(path);
}
doMarkResolved(entry, recursive);
fireEntryModified(entry, SVNStatus.RESOLVED, recursive);
if (parent != null) {
entry = parent;
}
entry.save();
entry.dispose();
sleepForTimestamp();
} finally {
getRoot().dispose();
}
}
public void revert(String path, boolean recursive) throws SVNException {
try {
ISVNEntry entry = locateEntry(path);
if (entry == null || (entry.isDirectory() && entry.isMissing())) {
if (entry != null) {
ISVNEntry parent = locateParentEntry(path);
if (parent != null && parent.isDirectory()) {
boolean reverted = parent.asDirectory().revert(entry.getName());
parent.save();
fireEntryModified(entry, reverted ? SVNStatus.REVERTED : SVNStatus.NOT_REVERTED, false);
return;
}
}
return;
}
ISVNDirectoryEntry parent = null;
parent = (ISVNDirectoryEntry) locateParentEntry(path);
doMarkResolved(entry, recursive);
doRevert(parent, entry, recursive);
if (parent == null && entry == getRoot()) {
entry.asDirectory().revert(null);
}
if (parent != null) {
entry = parent;
}
entry.save();
entry.dispose();
sleepForTimestamp();
} finally {
getRoot().dispose();
}
}
public void revert(String srcPath, String dstPath, boolean recursive) throws SVNException {
try {
myIsCommandRunning = true;
ISVNEntry src = locateEntry(srcPath);
if (src != null && src.isScheduledForDeletion()) {
revert(srcPath, recursive);
}
// copy props and contents from dst to source (for each file in src that exists in dst).
// revert dst.
revert(dstPath, recursive);
} finally {
myIsCommandRunning = false;
sleepForTimestamp();
getRoot().dispose();
}
}
public void unlock(String path, boolean force) throws SVNException {
try {
ISVNEntry entry = locateEntry(path);
if (entry == null) {
throw new SVNException("no versioned entry at '" + path + "'");
}
String token = entry.getPropertyValue(SVNProperty.LOCK_TOKEN);
if (token == null) {
throw new SVNException("'" + path + "' is not locked in repository");
}
String name = "";
if (!entry.isDirectory()) {
name = entry.getName();
}
SVNRepository repository = SVNUtil.createRepository(this, path);
repository.removeLock(name, token, force);
entry.setPropertyValue(SVNProperty.LOCK_TOKEN, null);
entry.setPropertyValue(SVNProperty.LOCK_COMMENT, null);
entry.setPropertyValue(SVNProperty.LOCK_CREATION_DATE, null);
entry.setPropertyValue(SVNProperty.LOCK_OWNER, null);
entry.save();
} finally {
getRoot().dispose();
}
}
public SVNLock lock(String path, String comment, boolean force) throws SVNException {
SVNLock lock = null;
try {
comment = comment == null ? "" : comment;
ISVNEntry entry = locateEntry(path);
if (entry == null) {
throw new SVNException("no versioned entry at '" + path + "'");
}
if (entry.isScheduledForAddition()) {
throw new SVNException("'" + path + "' is not added to repository yet");
}
String name = "";
if (!entry.isDirectory()) {
name = entry.getName();
}
SVNRepository repository = SVNUtil.createRepository(this, path);
long revision = SVNProperty.longValue(entry.getPropertyValue(SVNProperty.REVISION));
lock = repository.setLock(name, comment, force, revision);
if (lock != null) {
entry.setPropertyValue(SVNProperty.LOCK_TOKEN, lock.getID());
entry.setPropertyValue(SVNProperty.LOCK_COMMENT, comment);
entry.setPropertyValue(SVNProperty.LOCK_CREATION_DATE, TimeUtil.formatDate(lock.getCreationDate()));
entry.setPropertyValue(SVNProperty.LOCK_OWNER, lock.getOwner());
entry.save();
}
} finally {
getRoot().dispose();
}
return lock;
}
public ISVNEntryContent getContent(String path) throws SVNException {
ISVNEntry entry = locateEntry(path, true);
if (entry == null) {
throw new SVNException("Can't find entry for path " + path);
}
return entry.getContent();
}
public ISVNFileContent getFileContent(String path) throws SVNException {
ISVNEntry entry = locateEntry(path, true);
if (entry == null) {
throw new SVNException("Can't find entry for path " + path);
}
if (entry.isDirectory()) {
return null;
}
return (ISVNFileContent) entry.getContent();
}
protected void fireEntryCommitted(ISVNEntry entry, int kind) {
if (myListeners == null || entry == null) {
return;
}
for (Iterator listeners = myListeners.iterator(); listeners.hasNext();) {
ISVNWorkspaceListener listener = (ISVNWorkspaceListener) listeners.next();
listener.committed(entry.getPath(), kind);
}
}
protected void fireEntryUpdated(ISVNEntry entry, int contentsStatus, int propsStatus, long revision) {
if (myListeners == null || entry == null) {
return;
}
for (Iterator listeners = myListeners.iterator(); listeners.hasNext();) {
ISVNWorkspaceListener listener = (ISVNWorkspaceListener) listeners.next();
listener.updated(entry.getPath(), contentsStatus, propsStatus, revision);
}
}
protected void fireEntryModified(ISVNEntry entry, int kind, boolean recursive) {
if (myListeners == null || entry == null) {
return;
}
for (Iterator listeners = myListeners.iterator(); listeners.hasNext();) {
ISVNWorkspaceListener listener = (ISVNWorkspaceListener) listeners.next();
listener.modified(entry.getPath(), kind);
}
if (entry.isDirectory() && recursive) {
Iterator children = null;
try {
children = entry.asDirectory().childEntries();
} catch (SVNException e) {}
while (children != null && children.hasNext()) {
fireEntryModified((ISVNEntry) children.next(), kind, recursive);
}
}
}
private ISVNRootEntry getRoot() {
return myRoot;
}
private void doRevert(ISVNDirectoryEntry parent, ISVNEntry entry, boolean recursive) throws SVNException {
boolean restored = !entry.isDirectory() && entry.isMissing();
if (entry.isDirectory() && recursive) {
Collection namesList = new LinkedList();
for (Iterator children = entry.asDirectory().childEntries(); children.hasNext();) {
ISVNEntry child = (ISVNEntry) children.next();
namesList.add(child);
}
for (Iterator names = namesList.iterator(); names.hasNext();) {
ISVNEntry child = (ISVNEntry) names.next();
doRevert(entry.asDirectory(), child, recursive);
}
}
if (parent != null) {
boolean reverted = parent.revert(entry.getName());
if (!restored) {
fireEntryModified(entry, reverted ? SVNStatus.REVERTED : SVNStatus.NOT_REVERTED, false);
} else {
fireEntryModified(entry, SVNStatus.RESTORED, false);
}
}
if (!entry.isDirectory()) {
entry.dispose();
}
}
private void doMarkResolved(ISVNEntry entry, boolean recursive) throws SVNException {
if (entry.isDirectory() && recursive) {
for (Iterator children = entry.asDirectory().childEntries(); children.hasNext();) {
doMarkResolved((ISVNEntry) children.next(), recursive);
}
}
entry.markResolved();
}
private void doSetProperty(ISVNEntry entry, String name, String value, boolean recurse) throws SVNException {
entry.setPropertyValue(name, value);
fireEntryModified(entry, SVNStatus.MODIFIED, false);
if (recurse && entry.isDirectory()) {
for (Iterator entries = entry.asDirectory().childEntries(); entries.hasNext();) {
ISVNEntry child = (ISVNEntry) entries.next();
doSetProperty(child, name, value, recurse);
}
}
}
private void doImport(String rootPath, ISVNEditor editor, ISVNDirectoryEntry parent, ISVNEntry entry) throws SVNException {
if (rootPath.trim().length() > 0) {
rootPath += "/";
}
if (entry.isDirectory()) {
DebugLog.log("IMPORT: ADDING DIR: " + rootPath + entry.getPath());
editor.addDir(rootPath + entry.getPath(), null, -1);
applyAutoProperties(entry, editor);
for(Iterator children = entry.asDirectory().unmanagedChildEntries(false); children.hasNext();) {
ISVNEntry child = (ISVNEntry) children.next();
doImport(rootPath, editor, parent, child);
}
editor.closeDir();
} else {
DebugLog.log("IMPORT: ADDING FILE: " + rootPath + entry.getPath());
editor.addFile(rootPath + entry.getPath(), null, -1);
applyAutoProperties(entry, editor);
entry.setPropertyValue(SVNProperty.SCHEDULE, SVNProperty.SCHEDULE_ADD);
entry.asFile().generateDelta(editor);
editor.closeFile(null);
}
fireEntryCommitted(entry, SVNStatus.ADDED);
}
private void applyAutoProperties(ISVNEntry entry, ISVNEditor editor) throws SVNException {
if (myCompiledAutoProperties == null) {
myCompiledAutoProperties = compileAutoProperties(myAutoProperties);
}
for (Iterator keys = myCompiledAutoProperties.keySet().iterator(); keys.hasNext();) {
Pattern pattern = (Pattern) keys.next();
if (pattern.matcher(entry.getName().toLowerCase()).matches()) {
Map properties = (Map) myCompiledAutoProperties.get(pattern);
for (Iterator entries = properties.entrySet().iterator(); entries.hasNext();) {
Map.Entry propEntry = (Map.Entry) entries.next();
String name = (String) propEntry.getKey();
String value = (String) propEntry.getValue();
entry.setPropertyValue(name, value);
if (editor == null) {
continue;
}
if (entry.isDirectory()) {
editor.changeDirProperty(name, value);
} else {
editor.changeFileProperty(name, value);
}
}
}
}
}
private static Map compileAutoProperties(Map source) {
Map result = new HashMap();
for (Iterator entries = source.entrySet().iterator(); entries.hasNext();) {
Map.Entry entry = (Map.Entry) entries.next();
if (entry.getValue() == null) {
continue;
}
String key = (String) entry.getKey();
StringBuffer regex = new StringBuffer();
regex.append('^');
// convert key wildcard into regexp
for (int i = 0; i < key.length(); i++) {
char ch = key.charAt(i);
if (ch == '.') {
regex.append("\\.");
} else if (ch == '?') {
regex.append('.');
} else if (ch == '*') {
regex.append(".*");
} else {
regex.append(ch);
}
}
regex.append('$');
String properties = (String) entry.getValue();
Map parsedProperties = new HashMap();
for (StringTokenizer props = new StringTokenizer(properties, ";"); props.hasMoreTokens();) {
String propset = props.nextToken();
int index = propset.indexOf('=');
String value = "";
String name = null;
if (index < 0) {
name = propset;
} else {
name = propset.substring(0, index);
value = propset.substring(index + 1);
}
parsedProperties.put(name, value);
}
if (!parsedProperties.isEmpty()) {
result.put(Pattern.compile(regex.toString().toLowerCase()), parsedProperties);
}
}
return result;
}
ISVNEntry locateEntry(String path) throws SVNException {
return locateEntry(path, false);
}
ISVNEntry locateEntry(String path, boolean unmanaged) throws SVNException {
ISVNEntry entry = getRoot();
for (StringTokenizer tokens = new StringTokenizer(path, "/"); tokens.hasMoreTokens();) {
String token = tokens.nextToken();
if (entry == null) {
return null;
}
entry = entry.asDirectory().getUnmanagedChild(token);
}
if (entry != null && !unmanaged && !entry.isManaged()) {
return null;
}
return entry;
}
ISVNEntry locateParentEntry(String path) throws SVNException {
ISVNEntry entry = getRoot();
if ("".equals(path)) {
return null;
}
for (StringTokenizer tokens = new StringTokenizer(path, "/"); tokens.hasMoreTokens();) {
String token = tokens.nextToken();
if (!tokens.hasMoreTokens()) {
return entry;
}
entry = entry.asDirectory().getUnmanagedChild(token);
}
return null;
}
private static void updateURL(ISVNEntry target, String parentURL, boolean recursive) throws SVNException {
parentURL = PathUtil.append(parentURL, PathUtil.encode(target.getName()));
target.setPropertyValue(SVNProperty.URL, parentURL);
if (target.isDirectory() && recursive) {
for (Iterator children = target.asDirectory().childEntries(); children.hasNext();) {
ISVNEntry child = (ISVNEntry) children.next();
updateURL(child, parentURL, recursive);
}
}
}
private Collection createExternals(String path) throws SVNException {
Collection externals = new HashSet();
ISVNEntry parent = null;
if (!"".equals(path)) {
parent = locateParentEntry(path);
}
if (parent == null || !parent.isDirectory()) {
return externals;
}
ISVNDirectoryEntry current = parent.asDirectory();
while (current != null) {
externals = SVNExternal.create(current, externals);
current = (ISVNDirectoryEntry) locateParentEntry(current.getPath());
}
return externals;
}
public void runCommand(ISVNRunnable runnable) throws SVNException {
myIsCommandRunning = true;
myIsNeedToSleepForTimestamp = false;
try {
runnable.run(this);
} catch (Throwable th) {
if (th instanceof SVNException) {
throw ((SVNException) th);
}
throw new SVNException(th);
} finally {
myIsCommandRunning = false;
if (myIsNeedToSleepForTimestamp) {
sleepForTimestamp();
myIsNeedToSleepForTimestamp = false;
}
}
}
private void sleepForTimestamp() {
if (myIsCommandRunning) {
myIsNeedToSleepForTimestamp = true;
return;
}
FSUtil.sleepForTimestamp();
}
private String getCommitRoot(String[] paths) throws SVNException {
String root = "";
if (paths.length == 1) {
ISVNEntry entry = locateEntry(paths[0]);
if (entry != null && entry.isDirectory() && entry.isManaged()) {
root = entry.getPath();
}
}
if (root == null) {
root = PathUtil.getCommonRoot(paths);
if (root == null) {
root = "";
}
}
return root;
}
private List getPathsFromStatuses(final SVNStatus[] statuses) {
final List paths = new ArrayList();
for (int index = 0; index < statuses.length; index++) {
if (statuses[index] != null) {
final String path = statuses[index].getPath();
paths.add(path);
}
}
return paths;
}
}
| false | true | public long commitPaths(List paths, String message, boolean keepLocks, ISVNProgressViewer progressViewer) throws SVNException {
long start = System.currentTimeMillis();
try {
final Set modified = new HashSet();
for (Iterator it = paths.iterator(); it.hasNext();) {
final String path = (String)it.next();
ISVNEntry entry = locateEntry(path);
modified.add(entry);
}
if (message == null || modified.isEmpty()) {
DebugLog.log("NOTHING TO COMMIT");
return -1;
}
String root = getCommitRoot((String[])paths.toArray(new String[paths.size()]));
ISVNEntry rootEntry = locateEntry(root);
if (rootEntry == null || rootEntry.getPropertyValue(SVNProperty.URL) == null) {
throw new SVNException(root + " does not contain working copy files");
}
DebugLog.log("COMMIT MESSAGE: " + message);
Map tree = new HashMap();
Map locks = new HashMap();
String url = SVNCommitUtil.buildCommitTree(modified, tree, locks);
for (Iterator treePaths = tree.keySet().iterator(); treePaths.hasNext();) {
String treePath = (String)treePaths.next();
if (tree.get(treePath) != null) {
DebugLog.log("TREE ENTRY : " + treePath + " : " + ((ISVNEntry)tree.get(treePath)).getPath());
}
else {
DebugLog.log("TREE ENTRY : " + treePath + " : null");
}
}
DebugLog.log("COMMIT ROOT RECALCULATED: " + url);
DebugLog.log("COMMIT PREPARATIONS TOOK: " + (System.currentTimeMillis() - start) + " ms.");
SVNRepositoryLocation location = SVNRepositoryLocation.parseURL(url);
SVNRepository repository = SVNRepositoryFactory.create(location);
repository.setCredentialsProvider(getCredentialsProvider());
String host = location.getProtocol() + "://" + location.getHost() + ":" + location.getPort();
String rootURL = PathUtil.append(host, repository.getRepositoryRoot());
if (!locks.isEmpty()) {
Map transaltedLocks = new HashMap();
for(Iterator lockedPaths = locks.keySet().iterator(); lockedPaths.hasNext();) {
String lockedPath = (String) lockedPaths.next();
String relativePath = lockedPath.substring(rootURL.length());
if (!relativePath.startsWith("/")) {
relativePath = "/" + relativePath;
}
transaltedLocks.put(relativePath, locks.get(lockedPath));
}
locks = transaltedLocks;
}
DebugLog.log("LOCKS ready for commit: " + locks);
ISVNEditor editor = repository.getCommitEditor(message, locks, keepLocks, new SVNWorkspaceMediatorAdapter(getRoot(), tree));
SVNCommitInfo info;
try {
SVNCommitUtil.doCommit("", rootURL, tree, editor, this, progressViewer);
info = editor.closeEdit();
}
catch (SVNException e) {
DebugLog.error("error: " + e.getMessage());
if (e.getErrors() != null) {
for (int i = 0; i < e.getErrors().length; i++) {
SVNError error = e.getErrors()[i];
if (error != null) {
DebugLog.error(error.toString());
}
}
}
try {
editor.abortEdit();
}
catch (SVNException inner) {
}
throw e;
}
catch (Throwable th) {
throw new SVNException(th);
}
DebugLog.log("COMMIT TOOK: " + (System.currentTimeMillis() - start) + " ms.");
if (!myIsCopyCommit) {
start = System.currentTimeMillis();
SVNCommitUtil.updateWorkingCopy(info, rootEntry.getPropertyValue(SVNProperty.UUID), tree, this);
sleepForTimestamp();
DebugLog.log("POST COMMIT ACTIONS TOOK: " + (System.currentTimeMillis() - start) + " ms.");
}
return info != null ? info.getNewRevision() : -1;
}
finally {
myIsCopyCommit = false;
getRoot().dispose();
}
}
| public long commitPaths(List paths, String message, boolean keepLocks, ISVNProgressViewer progressViewer) throws SVNException {
long start = System.currentTimeMillis();
try {
final Set modified = new HashSet();
for (Iterator it = paths.iterator(); it.hasNext();) {
final String path = (String)it.next();
ISVNEntry entry = locateEntry(path);
modified.add(entry);
}
if (message == null || modified.isEmpty()) {
DebugLog.log("NOTHING TO COMMIT");
return -1;
}
String root = getCommitRoot((String[])paths.toArray(new String[paths.size()]));
ISVNEntry rootEntry = locateEntry(root);
if (rootEntry == null || rootEntry.getPropertyValue(SVNProperty.URL) == null) {
throw new SVNException(root + " does not contain working copy files");
}
DebugLog.log("COMMIT MESSAGE: " + message);
Map tree = new HashMap();
Map locks = new HashMap();
String url = SVNCommitUtil.buildCommitTree(modified, tree, locks);
for (Iterator treePaths = tree.keySet().iterator(); treePaths.hasNext();) {
String treePath = (String)treePaths.next();
if (tree.get(treePath) != null) {
DebugLog.log("TREE ENTRY : " + treePath + " : " + ((ISVNEntry)tree.get(treePath)).getPath());
}
else {
DebugLog.log("TREE ENTRY : " + treePath + " : null");
}
}
DebugLog.log("COMMIT ROOT RECALCULATED: " + url);
DebugLog.log("COMMIT PREPARATIONS TOOK: " + (System.currentTimeMillis() - start) + " ms.");
SVNRepositoryLocation location = SVNRepositoryLocation.parseURL(url);
SVNRepository repository = SVNRepositoryFactory.create(location);
repository.setCredentialsProvider(getCredentialsProvider());
repository.testConnection();
String host = location.getProtocol() + "://" + location.getHost() + ":" + location.getPort();
String rootURL = PathUtil.append(host, repository.getRepositoryRoot());
if (!locks.isEmpty()) {
Map transaltedLocks = new HashMap();
for(Iterator lockedPaths = locks.keySet().iterator(); lockedPaths.hasNext();) {
String lockedPath = (String) lockedPaths.next();
String relativePath = lockedPath.substring(rootURL.length());
if (!relativePath.startsWith("/")) {
relativePath = "/" + relativePath;
}
transaltedLocks.put(relativePath, locks.get(lockedPath));
}
locks = transaltedLocks;
} else {
locks = null;
}
DebugLog.log("LOCKS ready for commit: " + locks);
ISVNEditor editor = repository.getCommitEditor(message, locks, keepLocks, new SVNWorkspaceMediatorAdapter(getRoot(), tree));
SVNCommitInfo info;
try {
SVNCommitUtil.doCommit("", rootURL, tree, editor, this, progressViewer);
info = editor.closeEdit();
}
catch (SVNException e) {
DebugLog.error("error: " + e.getMessage());
if (e.getErrors() != null) {
for (int i = 0; i < e.getErrors().length; i++) {
SVNError error = e.getErrors()[i];
if (error != null) {
DebugLog.error(error.toString());
}
}
}
try {
editor.abortEdit();
}
catch (SVNException inner) {
}
throw e;
}
catch (Throwable th) {
throw new SVNException(th);
}
DebugLog.log("COMMIT TOOK: " + (System.currentTimeMillis() - start) + " ms.");
if (!myIsCopyCommit) {
start = System.currentTimeMillis();
SVNCommitUtil.updateWorkingCopy(info, rootEntry.getPropertyValue(SVNProperty.UUID), tree, this);
sleepForTimestamp();
DebugLog.log("POST COMMIT ACTIONS TOOK: " + (System.currentTimeMillis() - start) + " ms.");
}
return info != null ? info.getNewRevision() : -1;
}
finally {
myIsCopyCommit = false;
getRoot().dispose();
}
}
|
diff --git a/src/test/java/tv/floe/metronome/classification/neuralnetworks/network/TestMultiLayerPerceptronNetwork.java b/src/test/java/tv/floe/metronome/classification/neuralnetworks/network/TestMultiLayerPerceptronNetwork.java
index b50a29d..1f13087 100644
--- a/src/test/java/tv/floe/metronome/classification/neuralnetworks/network/TestMultiLayerPerceptronNetwork.java
+++ b/src/test/java/tv/floe/metronome/classification/neuralnetworks/network/TestMultiLayerPerceptronNetwork.java
@@ -1,246 +1,246 @@
package tv.floe.metronome.classification.neuralnetworks.network;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Iterator;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.junit.Test;
import tv.floe.metronome.classification.neuralnetworks.conf.Config;
import tv.floe.metronome.classification.neuralnetworks.core.Layer;
import tv.floe.metronome.classification.neuralnetworks.core.NeuralNetwork;
import tv.floe.metronome.classification.neuralnetworks.networks.MultiLayerPerceptronNetwork;
public class TestMultiLayerPerceptronNetwork {
@Test
public void testBasicConstruction() throws Exception {
Vector vec = new DenseVector(2);
vec.set(0, 1);
vec.set(1, 2);
Config c = new Config();
c.parse(null); // default layer: 2-3-2
MultiLayerPerceptronNetwork mlp_network = new MultiLayerPerceptronNetwork();
mlp_network.buildFromConf(c);
mlp_network.setInputVector(vec);
//mlp_network.
Layer l0 = mlp_network.getLayerByIndex(0);
assertEquals( 2, l0.getNeurons().size() );
assertEquals(0, l0.getNeuronAt(0).getInConnections().size() );
assertEquals(0, l0.getNeuronAt(1).getInConnections().size() );
assertEquals(3, l0.getNeuronAt(0).getOutConnections().size() );
assertEquals(3, l0.getNeuronAt(1).getOutConnections().size() );
Layer l1 = mlp_network.getLayerByIndex(1);
assertEquals( 3, l1.getNeurons().size() );
assertEquals(2, l1.getNeuronAt(0).getInConnections().size() );
assertEquals(2, l1.getNeuronAt(1).getInConnections().size() );
assertEquals(2, l1.getNeuronAt(2).getInConnections().size() );
assertEquals(2, l1.getNeuronAt(0).getOutConnections().size() );
assertEquals(2, l1.getNeuronAt(1).getOutConnections().size() );
assertEquals(2, l1.getNeuronAt(2).getOutConnections().size() );
Layer l2 = mlp_network.getLayerByIndex(2);
assertEquals( 2, l2.getNeurons().size() );
assertEquals(3, l2.getNeuronAt(0).getInConnections().size() );
assertEquals(3, l2.getNeuronAt(1).getInConnections().size() );
assertEquals(0, l2.getNeuronAt(0).getOutConnections().size() );
assertEquals(0, l2.getNeuronAt(1).getOutConnections().size() );
}
public void parseCSVRecord(Vector vec_inputs, int input_counts, Vector vec_outputs, int output_counts, String line) {
String[] parts = line.split(",");
for ( int x = 0 ; x < parts.length; x++ ) {
//vec_out.set(x, Double.parseDouble(parts[x]));
if (x < input_counts) {
vec_inputs.set(x, Double.parseDouble(parts[x]));
} else if ( x >= input_counts && x < output_counts + input_counts) {
vec_outputs.set(x - input_counts, Double.parseDouble(parts[x]));
}
}
//return Double.parseDouble( parts[6] );
}
public static void PrintVector(Vector v) {
boolean first = true;
Iterator<Vector.Element> nonZeros = v.iterator();
while (nonZeros.hasNext()) {
Vector.Element vec_loc = nonZeros.next();
if (!first) {
System.out.print(",");
} else {
first = false;
}
System.out.print(" " + vec_loc.get());
}
System.out.println("\n");
}
@Test
public void testIrisDatasetRun() throws Exception {
Config c = new Config();
c.parse(null); // default layer: 2-3-2
c.setConfValue("useBiasNeuron", "true");
int[] neurons = { 4, 16, 3 };
c.setLayerNeuronCounts( neurons );
// layers: 4, 16, 3
MultiLayerPerceptronNetwork neuralNet = new MultiLayerPerceptronNetwork();
neuralNet.buildFromConf(c);
int num_inputs = 4;
int num_outputs = 3;
for ( int x = 0; x < 200; x++ ) {
- BufferedReader reader = new BufferedReader( new FileReader("src/test/resources/datasets/iris/iris_data_normalised.txt") );
+ BufferedReader reader = new BufferedReader( new FileReader("src/test/resources/data/iris/iris_data_normalised.txt") );
String line = reader.readLine();
while (line != null && line.length() > 0) {
//System.out.println(line);
if (null == line || line.trim().equals("")) {
System.out.println("> bad line > " + line );
} else {
Vector vec_inputs = new RandomAccessSparseVector( num_inputs );
Vector vec_outputs = new RandomAccessSparseVector( num_outputs );
//double actual = factory.processLineAlt(line, vec);
parseCSVRecord(vec_inputs, num_inputs, vec_outputs, num_outputs, line);
/*
PrintVector( vec_inputs );
PrintVector( vec_outputs );
System.out.println(" ----------------- " );
*/
assertEquals( num_inputs, vec_inputs.size() );
assertEquals( num_outputs, vec_outputs.size() );
neuralNet.train(vec_outputs, vec_inputs);
} // if
line = reader.readLine();
} // while
- reader = new BufferedReader( new FileReader("src/test/resources/datasets/iris/iris_data_normalised.txt") );
+ reader = new BufferedReader( new FileReader("src/test/resources/data/iris/iris_data_normalised.txt") );
line = reader.readLine();
int total_records = 0;
int number_correct = 0;
while (line != null && line.length() > 0) {
if (null == line || line.trim().equals("")) {
System.out.println("> bad line > " + line );
} else {
total_records++;
Vector vec_inputs = new RandomAccessSparseVector( num_inputs );
Vector vec_outputs = new RandomAccessSparseVector( num_outputs );
parseCSVRecord(vec_inputs, num_inputs, vec_outputs, num_outputs, line);
neuralNet.setInputVector( vec_inputs );
neuralNet.calculate();
Vector networkOutput = neuralNet.getOutputVector();
//PrintVector( networkOutput );
//System.out.println( "Prediction: " + networkOutput.maxValueIndex() );
if (networkOutput.maxValueIndex() == 0 && vec_outputs.get(0) == 1.0 || networkOutput.maxValueIndex() == 1 && vec_outputs.get(1) == 1.0 || networkOutput.maxValueIndex() == 2 && vec_outputs.get(2) == 1.0) {
number_correct++;
}
} // if
line = reader.readLine();
} // while
System.out.println("> Total Records: " + total_records);
System.out.println("> Correct: " + number_correct);
System.out.println("----------------------- ");
} // for
}
}
| false | true | public void testIrisDatasetRun() throws Exception {
Config c = new Config();
c.parse(null); // default layer: 2-3-2
c.setConfValue("useBiasNeuron", "true");
int[] neurons = { 4, 16, 3 };
c.setLayerNeuronCounts( neurons );
// layers: 4, 16, 3
MultiLayerPerceptronNetwork neuralNet = new MultiLayerPerceptronNetwork();
neuralNet.buildFromConf(c);
int num_inputs = 4;
int num_outputs = 3;
for ( int x = 0; x < 200; x++ ) {
BufferedReader reader = new BufferedReader( new FileReader("src/test/resources/datasets/iris/iris_data_normalised.txt") );
String line = reader.readLine();
while (line != null && line.length() > 0) {
//System.out.println(line);
if (null == line || line.trim().equals("")) {
System.out.println("> bad line > " + line );
} else {
Vector vec_inputs = new RandomAccessSparseVector( num_inputs );
Vector vec_outputs = new RandomAccessSparseVector( num_outputs );
//double actual = factory.processLineAlt(line, vec);
parseCSVRecord(vec_inputs, num_inputs, vec_outputs, num_outputs, line);
/*
PrintVector( vec_inputs );
PrintVector( vec_outputs );
System.out.println(" ----------------- " );
*/
assertEquals( num_inputs, vec_inputs.size() );
assertEquals( num_outputs, vec_outputs.size() );
neuralNet.train(vec_outputs, vec_inputs);
} // if
line = reader.readLine();
} // while
reader = new BufferedReader( new FileReader("src/test/resources/datasets/iris/iris_data_normalised.txt") );
line = reader.readLine();
int total_records = 0;
int number_correct = 0;
while (line != null && line.length() > 0) {
if (null == line || line.trim().equals("")) {
System.out.println("> bad line > " + line );
} else {
total_records++;
Vector vec_inputs = new RandomAccessSparseVector( num_inputs );
Vector vec_outputs = new RandomAccessSparseVector( num_outputs );
parseCSVRecord(vec_inputs, num_inputs, vec_outputs, num_outputs, line);
neuralNet.setInputVector( vec_inputs );
neuralNet.calculate();
Vector networkOutput = neuralNet.getOutputVector();
//PrintVector( networkOutput );
//System.out.println( "Prediction: " + networkOutput.maxValueIndex() );
if (networkOutput.maxValueIndex() == 0 && vec_outputs.get(0) == 1.0 || networkOutput.maxValueIndex() == 1 && vec_outputs.get(1) == 1.0 || networkOutput.maxValueIndex() == 2 && vec_outputs.get(2) == 1.0) {
number_correct++;
}
} // if
line = reader.readLine();
} // while
System.out.println("> Total Records: " + total_records);
System.out.println("> Correct: " + number_correct);
System.out.println("----------------------- ");
} // for
}
| public void testIrisDatasetRun() throws Exception {
Config c = new Config();
c.parse(null); // default layer: 2-3-2
c.setConfValue("useBiasNeuron", "true");
int[] neurons = { 4, 16, 3 };
c.setLayerNeuronCounts( neurons );
// layers: 4, 16, 3
MultiLayerPerceptronNetwork neuralNet = new MultiLayerPerceptronNetwork();
neuralNet.buildFromConf(c);
int num_inputs = 4;
int num_outputs = 3;
for ( int x = 0; x < 200; x++ ) {
BufferedReader reader = new BufferedReader( new FileReader("src/test/resources/data/iris/iris_data_normalised.txt") );
String line = reader.readLine();
while (line != null && line.length() > 0) {
//System.out.println(line);
if (null == line || line.trim().equals("")) {
System.out.println("> bad line > " + line );
} else {
Vector vec_inputs = new RandomAccessSparseVector( num_inputs );
Vector vec_outputs = new RandomAccessSparseVector( num_outputs );
//double actual = factory.processLineAlt(line, vec);
parseCSVRecord(vec_inputs, num_inputs, vec_outputs, num_outputs, line);
/*
PrintVector( vec_inputs );
PrintVector( vec_outputs );
System.out.println(" ----------------- " );
*/
assertEquals( num_inputs, vec_inputs.size() );
assertEquals( num_outputs, vec_outputs.size() );
neuralNet.train(vec_outputs, vec_inputs);
} // if
line = reader.readLine();
} // while
reader = new BufferedReader( new FileReader("src/test/resources/data/iris/iris_data_normalised.txt") );
line = reader.readLine();
int total_records = 0;
int number_correct = 0;
while (line != null && line.length() > 0) {
if (null == line || line.trim().equals("")) {
System.out.println("> bad line > " + line );
} else {
total_records++;
Vector vec_inputs = new RandomAccessSparseVector( num_inputs );
Vector vec_outputs = new RandomAccessSparseVector( num_outputs );
parseCSVRecord(vec_inputs, num_inputs, vec_outputs, num_outputs, line);
neuralNet.setInputVector( vec_inputs );
neuralNet.calculate();
Vector networkOutput = neuralNet.getOutputVector();
//PrintVector( networkOutput );
//System.out.println( "Prediction: " + networkOutput.maxValueIndex() );
if (networkOutput.maxValueIndex() == 0 && vec_outputs.get(0) == 1.0 || networkOutput.maxValueIndex() == 1 && vec_outputs.get(1) == 1.0 || networkOutput.maxValueIndex() == 2 && vec_outputs.get(2) == 1.0) {
number_correct++;
}
} // if
line = reader.readLine();
} // while
System.out.println("> Total Records: " + total_records);
System.out.println("> Correct: " + number_correct);
System.out.println("----------------------- ");
} // for
}
|
diff --git a/DataProvider/testcases/test/nchelp/meteor/DataMessageHandlerTest.java b/DataProvider/testcases/test/nchelp/meteor/DataMessageHandlerTest.java
index e00f057b..333421ff 100755
--- a/DataProvider/testcases/test/nchelp/meteor/DataMessageHandlerTest.java
+++ b/DataProvider/testcases/test/nchelp/meteor/DataMessageHandlerTest.java
@@ -1,105 +1,105 @@
/**
*
* Copyright 2002 NCHELP
*
* Author: Tim Bornholtz, PriorityTechnologies, Inc.
*
*
* This code is part of the Meteor system as defined and specified
* by the National Council of Higher Education Loan Programs, Inc.
* (NCHELP) and the Meteor Sponsors, and developed by Priority
* Technologies, Inc. (PTI).
*
*
* 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 test.nchelp.meteor;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import junit.framework.TestCase;
import junit.textui.TestRunner;
import org.nchelp.hpc.HPCMessage;
import org.nchelp.meteor.logging.Logger;
import org.nchelp.meteor.message.MeteorDataRequest;
import org.nchelp.meteor.provider.DistributedRegistry;
import org.nchelp.meteor.provider.data.DataMessageHandler;
import org.nchelp.meteor.security.SecurityToken;
public class DataMessageHandlerTest extends TestCase {
private final Logger log = Logger.create(this.getClass());
public DataMessageHandlerTest(String name) {
super(name);
}
public static void main(String args[]) {
TestRunner.run(DataMessageHandlerTest.class);
}
public void testDataMessageHandler() {
DistributedRegistry registry = DistributedRegistry.singleton();
SecurityToken token = null;
try {
token = registry.getAuthentication();
token.setRole(SecurityToken.roleFAA);
} catch(Exception e) {
e.printStackTrace();
- fail();
+ fail(e.toString());
}
MeteorDataRequest req = new MeteorDataRequest();
req.setSSN("987654321");
req.setSecurityToken(token);
HPCMessage mess = new HPCMessage();
mess.setRecipientID("TEST");
String strMessage = req.toString();
mess.setContent(strMessage, "METEORDATA");
System.out.println(strMessage);
HPCMessage respMess = null;
DataMessageHandler dmh = new DataMessageHandler();
try {
respMess = dmh.handle(mess);
} catch(Exception e) {
e.printStackTrace();
- fail();
+ fail(e.toString());
}
try {
System.out.println("Response:" + new String(respMess.getContent()));
} catch(Exception e) {
e.printStackTrace();
- fail();
+ fail(e.toString());
}
}
}
| false | true | public void testDataMessageHandler() {
DistributedRegistry registry = DistributedRegistry.singleton();
SecurityToken token = null;
try {
token = registry.getAuthentication();
token.setRole(SecurityToken.roleFAA);
} catch(Exception e) {
e.printStackTrace();
fail();
}
MeteorDataRequest req = new MeteorDataRequest();
req.setSSN("987654321");
req.setSecurityToken(token);
HPCMessage mess = new HPCMessage();
mess.setRecipientID("TEST");
String strMessage = req.toString();
mess.setContent(strMessage, "METEORDATA");
System.out.println(strMessage);
HPCMessage respMess = null;
DataMessageHandler dmh = new DataMessageHandler();
try {
respMess = dmh.handle(mess);
} catch(Exception e) {
e.printStackTrace();
fail();
}
try {
System.out.println("Response:" + new String(respMess.getContent()));
} catch(Exception e) {
e.printStackTrace();
fail();
}
}
| public void testDataMessageHandler() {
DistributedRegistry registry = DistributedRegistry.singleton();
SecurityToken token = null;
try {
token = registry.getAuthentication();
token.setRole(SecurityToken.roleFAA);
} catch(Exception e) {
e.printStackTrace();
fail(e.toString());
}
MeteorDataRequest req = new MeteorDataRequest();
req.setSSN("987654321");
req.setSecurityToken(token);
HPCMessage mess = new HPCMessage();
mess.setRecipientID("TEST");
String strMessage = req.toString();
mess.setContent(strMessage, "METEORDATA");
System.out.println(strMessage);
HPCMessage respMess = null;
DataMessageHandler dmh = new DataMessageHandler();
try {
respMess = dmh.handle(mess);
} catch(Exception e) {
e.printStackTrace();
fail(e.toString());
}
try {
System.out.println("Response:" + new String(respMess.getContent()));
} catch(Exception e) {
e.printStackTrace();
fail(e.toString());
}
}
|
diff --git a/src/org/nutz/dao/impl/sql/run/NutDaoRunner.java b/src/org/nutz/dao/impl/sql/run/NutDaoRunner.java
index fd81fdb36..90fcffc67 100644
--- a/src/org/nutz/dao/impl/sql/run/NutDaoRunner.java
+++ b/src/org/nutz/dao/impl/sql/run/NutDaoRunner.java
@@ -1,101 +1,102 @@
package org.nutz.dao.impl.sql.run;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import javax.sql.DataSource;
import org.nutz.dao.ConnCallback;
import org.nutz.dao.DaoException;
import org.nutz.dao.impl.DaoRunner;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.trans.Trans;
import org.nutz.trans.Transaction;
public class NutDaoRunner implements DaoRunner {
private static final Log log = Logs.get();
public void run(DataSource dataSource, ConnCallback callback) {
Transaction t = Trans.get();
// 有事务
if (null != t) {
Connection conn = null;
Savepoint sp = null;
try {
conn = t.getConnection(dataSource);
sp = conn.setSavepoint();
callback.invoke(conn);
}
catch (Exception e) {
if (e instanceof DaoException)
if (null != conn
&& null != e.getCause()
&& e.getCause() instanceof SQLException) {
try {
if (null == sp)
conn.rollback();
else
conn.rollback(sp);
}
catch (SQLException e1) {
if (log.isErrorEnabled())
log.error(e1);
}
}
throw new DaoException(e);
}
}
// 无事务
else {
Connection conn = null;
boolean old = false;
// 开始一个连接
try {
conn = dataSource.getConnection();
// 多条语句运行,将自动提交设为 false
old = conn.getAutoCommit();
conn.setAutoCommit(false);
// 开始循环运行
callback.invoke(conn);
// 完成提交
if (!conn.getAutoCommit())
conn.commit();
}
// 异常回滚
catch (Exception e) {
try {
- conn.rollback();
+ if (conn != null) // 高并发时,从数据库连接池获取连接就已经抛错误,所以conn可能为null的
+ conn.rollback();
}
catch (SQLException e1) {}// TODO 简单记录一下?
throw new DaoException(e);
}
// 保证释放资源
finally {
if (null != conn) {
// 恢复链接自动提交设定
// 这种事情也要NutDao自己干?
try {
if (old != conn.getAutoCommit())
conn.setAutoCommit(old);
}
catch (SQLException autoE) {
if (log.isWarnEnabled())
log.warn("Fail to restore autoCommet to '" + old + "'", autoE);
}
// 关闭链接
try {
conn.close();
}
catch (SQLException closeE) {
if (log.isWarnEnabled())
log.warn("Fail to close connection!", closeE);
}
}
}
}
}
}
| true | true | public void run(DataSource dataSource, ConnCallback callback) {
Transaction t = Trans.get();
// 有事务
if (null != t) {
Connection conn = null;
Savepoint sp = null;
try {
conn = t.getConnection(dataSource);
sp = conn.setSavepoint();
callback.invoke(conn);
}
catch (Exception e) {
if (e instanceof DaoException)
if (null != conn
&& null != e.getCause()
&& e.getCause() instanceof SQLException) {
try {
if (null == sp)
conn.rollback();
else
conn.rollback(sp);
}
catch (SQLException e1) {
if (log.isErrorEnabled())
log.error(e1);
}
}
throw new DaoException(e);
}
}
// 无事务
else {
Connection conn = null;
boolean old = false;
// 开始一个连接
try {
conn = dataSource.getConnection();
// 多条语句运行,将自动提交设为 false
old = conn.getAutoCommit();
conn.setAutoCommit(false);
// 开始循环运行
callback.invoke(conn);
// 完成提交
if (!conn.getAutoCommit())
conn.commit();
}
// 异常回滚
catch (Exception e) {
try {
conn.rollback();
}
catch (SQLException e1) {}// TODO 简单记录一下?
throw new DaoException(e);
}
// 保证释放资源
finally {
if (null != conn) {
// 恢复链接自动提交设定
// 这种事情也要NutDao自己干?
try {
if (old != conn.getAutoCommit())
conn.setAutoCommit(old);
}
catch (SQLException autoE) {
if (log.isWarnEnabled())
log.warn("Fail to restore autoCommet to '" + old + "'", autoE);
}
// 关闭链接
try {
conn.close();
}
catch (SQLException closeE) {
if (log.isWarnEnabled())
log.warn("Fail to close connection!", closeE);
}
}
}
}
}
| public void run(DataSource dataSource, ConnCallback callback) {
Transaction t = Trans.get();
// 有事务
if (null != t) {
Connection conn = null;
Savepoint sp = null;
try {
conn = t.getConnection(dataSource);
sp = conn.setSavepoint();
callback.invoke(conn);
}
catch (Exception e) {
if (e instanceof DaoException)
if (null != conn
&& null != e.getCause()
&& e.getCause() instanceof SQLException) {
try {
if (null == sp)
conn.rollback();
else
conn.rollback(sp);
}
catch (SQLException e1) {
if (log.isErrorEnabled())
log.error(e1);
}
}
throw new DaoException(e);
}
}
// 无事务
else {
Connection conn = null;
boolean old = false;
// 开始一个连接
try {
conn = dataSource.getConnection();
// 多条语句运行,将自动提交设为 false
old = conn.getAutoCommit();
conn.setAutoCommit(false);
// 开始循环运行
callback.invoke(conn);
// 完成提交
if (!conn.getAutoCommit())
conn.commit();
}
// 异常回滚
catch (Exception e) {
try {
if (conn != null) // 高并发时,从数据库连接池获取连接就已经抛错误,所以conn可能为null的
conn.rollback();
}
catch (SQLException e1) {}// TODO 简单记录一下?
throw new DaoException(e);
}
// 保证释放资源
finally {
if (null != conn) {
// 恢复链接自动提交设定
// 这种事情也要NutDao自己干?
try {
if (old != conn.getAutoCommit())
conn.setAutoCommit(old);
}
catch (SQLException autoE) {
if (log.isWarnEnabled())
log.warn("Fail to restore autoCommet to '" + old + "'", autoE);
}
// 关闭链接
try {
conn.close();
}
catch (SQLException closeE) {
if (log.isWarnEnabled())
log.warn("Fail to close connection!", closeE);
}
}
}
}
}
|
diff --git a/src/main/java/br/octahedron/figgo/modules/bank/controller/validation/BankValidators.java b/src/main/java/br/octahedron/figgo/modules/bank/controller/validation/BankValidators.java
index 78937b3..8942906 100644
--- a/src/main/java/br/octahedron/figgo/modules/bank/controller/validation/BankValidators.java
+++ b/src/main/java/br/octahedron/figgo/modules/bank/controller/validation/BankValidators.java
@@ -1,94 +1,94 @@
/*
* Straight - A system to manage financial demands for small and decentralized
* organizations.
* Copyright (C) 2011 Octahedron
*
* 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 br.octahedron.figgo.modules.bank.controller.validation;
import static br.octahedron.commons.util.DateUtil.SHORT;
import static br.octahedron.cotopaxi.controller.Converter.Builder.bigDecimalNumber;
import static br.octahedron.cotopaxi.controller.Converter.Builder.date;
import static br.octahedron.cotopaxi.validation.Input.Builder.attribute;
import static br.octahedron.cotopaxi.validation.Rule.Builder.greaterThan;
import static br.octahedron.cotopaxi.validation.Rule.Builder.regex;
import static br.octahedron.cotopaxi.validation.Rule.Builder.required;
import static br.octahedron.cotopaxi.validation.Rule.Builder.type;
import java.math.BigDecimal;
import br.octahedron.cotopaxi.validation.Validator;
/**
* @author Vítor Avelino
*/
public class BankValidators {
private static Validator valueValidator;
private static Validator requiredValidator;
private static Validator dateValidator;
/**
* A validator for transfers that checks the required fields
*/
public static synchronized Validator getTransferValidator() {
if (requiredValidator == null) {
requiredValidator = new Validator();
requiredValidator.add("userId", required("REQUIRED_TRANSASCTION_USERID"),
- regex("([a-zA-ZáéíóúÁÉÍÓÚÂÊÎÔÛâêîôûÃÕãõçÇ] *){2,}", "INVALID_USERID"));
+ regex("[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}", "INVALID_USERID"));
requiredValidator.add("amount", required("REQUIRED_TRANSACTION_AMOUT"), type(bigDecimalNumber()));
requiredValidator.add("type", required("REQUIRED_TRANSACTION_TYPE"), new ExistentTransferTypeRule());
}
return requiredValidator;
}
/**
* A validator for ballast that checks the required fields
*/
public static synchronized Validator getBallastValidator() {
if (requiredValidator == null) {
requiredValidator = new Validator();
requiredValidator.add("userId", required("REQUIRED_TRANSASCTION_USERID"),
regex("([a-zA-ZáéíóúÁÉÍÓÚÂÊÎÔÛâêîôûÃÕãõçÇ] *){2,}", "INVALID_USERID"));
requiredValidator.add("amount", required("REQUIRED_TRANSACTION_AMOUT"), type(bigDecimalNumber()));
}
return requiredValidator;
}
/**
* A validator that check if the transfer's amount is positive
*/
public static synchronized Validator getAmountValidator() {
if (valueValidator == null) {
valueValidator = new Validator();
valueValidator.add("amount", type("NOT_VALID_VALUE", bigDecimalNumber()),
greaterThan(bigDecimalNumber(), new BigDecimal(0), "NOT_VALID_VALUE"));
}
return valueValidator;
}
/**
* A validator that check if start date is less than end date
*/
public static Validator getDateValidator() {
if (dateValidator == null) {
dateValidator = new Validator();
dateValidator.add("startDate", type("NOT_VALID_DATE", date(SHORT)));
dateValidator.add("endDate", type("NOT_VALID_DATE", date(SHORT)), greaterThan(attribute("startDate"),date(SHORT),"NOT_VALID_DATE"));
}
return dateValidator;
}
}
| true | true | public static synchronized Validator getTransferValidator() {
if (requiredValidator == null) {
requiredValidator = new Validator();
requiredValidator.add("userId", required("REQUIRED_TRANSASCTION_USERID"),
regex("([a-zA-ZáéíóúÁÉÍÓÚÂÊÎÔÛâêîôûÃÕãõçÇ] *){2,}", "INVALID_USERID"));
requiredValidator.add("amount", required("REQUIRED_TRANSACTION_AMOUT"), type(bigDecimalNumber()));
requiredValidator.add("type", required("REQUIRED_TRANSACTION_TYPE"), new ExistentTransferTypeRule());
}
return requiredValidator;
}
| public static synchronized Validator getTransferValidator() {
if (requiredValidator == null) {
requiredValidator = new Validator();
requiredValidator.add("userId", required("REQUIRED_TRANSASCTION_USERID"),
regex("[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}", "INVALID_USERID"));
requiredValidator.add("amount", required("REQUIRED_TRANSACTION_AMOUT"), type(bigDecimalNumber()));
requiredValidator.add("type", required("REQUIRED_TRANSACTION_TYPE"), new ExistentTransferTypeRule());
}
return requiredValidator;
}
|
diff --git a/src/org/egonet/wholenet/graph/WholeNetwork.java b/src/org/egonet/wholenet/graph/WholeNetwork.java
index 3eeaf1e..753a801 100644
--- a/src/org/egonet/wholenet/graph/WholeNetwork.java
+++ b/src/org/egonet/wholenet/graph/WholeNetwork.java
@@ -1,200 +1,201 @@
package org.egonet.wholenet.graph;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.functionalj.tuple.Pair;
import org.egonet.exceptions.MissingPairException;
import org.egonet.wholenet.gui.NameMapperFrame.NameMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.endlessloopsoftware.egonet.Interview;
import com.endlessloopsoftware.egonet.Question;
import com.endlessloopsoftware.egonet.Shared;
import com.endlessloopsoftware.egonet.Study;
/**
* This class encapsulates everything necessary to compile and retain data from
* a set of Egonet interviews into a whole network, including alter mappings.
*
* @author Martin
*
*/
public class WholeNetwork {
final private static Logger logger = LoggerFactory.getLogger(WholeNetwork.class);
final Study study;
final List<Pair<File, Interview>> interviewMap;
final List<NameMapping> nameMap;
// maps for fast access
final Map<Integer,WholeNetworkAlter> wholeNetworkAlters;
final Map<Pair<WholeNetworkAlter,WholeNetworkAlter>,WholeNetworkTie> wholeNetworkTies;
public WholeNetwork(Study study, List<Pair<File, Interview>> interviewMap,
List<NameMapping> nameMap) {
super();
this.study = study;
this.interviewMap = interviewMap;
this.nameMap = nameMap;
wholeNetworkAlters = new HashMap<Integer,WholeNetworkAlter>();
wholeNetworkTies = new HashMap<Pair<WholeNetworkAlter,WholeNetworkAlter>,WholeNetworkTie>();
}
public void recompile() {
wholeNetworkAlters.clear();
wholeNetworkTies.clear();
// add all alters
for(NameMapping mapping : nameMap) {
int group = mapping.getGroup();
if(!wholeNetworkAlters.containsKey(group)) {
wholeNetworkAlters.put(group, new WholeNetworkAlter(group));
}
WholeNetworkAlter alter = wholeNetworkAlters.get(group);
alter.addOccurence(mapping);
}
// build all ties
for(Pair<File, Interview> pair : interviewMap) {
Interview interview = pair.getSecond();
String [] thisInterviewAlterlist = interview.getAlterList();
// tie the ego to all alters
Pair<WholeNetworkAlter,NameMapping> ego = findAlter(interview, -1);
for(int i = 0; i < interview.getAlterList().length; i++) {
Pair<WholeNetworkAlter,NameMapping> alter = findAlter(interview, i);
tie(ego, alter, null);
}
// tie adjacent alters together
Iterator<Long> questions = study.getQuestionOrder(Shared.QuestionType.ALTER_PAIR).iterator();
while (questions.hasNext()) {
Question q = study.getQuestion((Long) questions.next());
try {
int [][] adj = interview.generateAdjacencyMatrix(q, false);
// loop through adj
// if adj[i][j] == 1, thisInterviewAlters[i] && thisInterviewAlters[j] are adjacent in final matrix
for(int i = 0; i < adj.length; i++)
{
for(int j = 0; j < adj[i].length; j++)
{
- if(adj[i][j] == 1 && i != j)
+ if(adj[i][j] == 1 && i != j &&
+ i < thisInterviewAlterlist.length && j < thisInterviewAlterlist.length)
{
String alter1 = thisInterviewAlterlist[i];
String alter2 = thisInterviewAlterlist[j];
logger.debug(alter1 + "("+i+") and " + alter2 + "("+j+") are adjacent");
// find whole network alters, tie them!
Pair<WholeNetworkAlter,NameMapping> wholeAlter1 = findAlter(interview, i);
Pair<WholeNetworkAlter,NameMapping> wholeAlter2 = findAlter(interview, j);
if(wholeAlter1.getFirst().compareTo(wholeAlter2.getFirst()) > 0) {
Pair<WholeNetworkAlter,NameMapping> swap = wholeAlter1;
wholeAlter1 = wholeAlter2;
wholeAlter2 = swap;
}
tie(wholeAlter1, wholeAlter2, q);
}
}
}
}
catch (MissingPairException ex) {
logger.error("Couldn't create adjacency matrix for question " + q, ex);
}
}
}
logger.info("# Alters: " + wholeNetworkAlters.size() + ", # Ties: " + wholeNetworkTies.size());
}
private Pair<WholeNetworkAlter,NameMapping> findAlter(Interview interview, Integer alterNumber) {
for(WholeNetworkAlter alter : wholeNetworkAlters.values()) {
for(NameMapping mapping : alter.getOccurences()) {
if(mapping.getInterview().equals(interview) && mapping.getAlterNumber().equals(alterNumber))
return new Pair<WholeNetworkAlter,NameMapping>(alter,mapping);
}
}
throw new IllegalArgumentException("Alter did not exist -- it must have been derived from somewhere, so we *must* find it");
}
public Map<Integer, WholeNetworkAlter> getWholeNetworkAlters() {
return wholeNetworkAlters;
}
public Map<Pair<WholeNetworkAlter, WholeNetworkAlter>, WholeNetworkTie> getWholeNetworkTies() {
return wholeNetworkTies;
}
private void tie(Pair<WholeNetworkAlter,NameMapping> wholeAlter1, Pair<WholeNetworkAlter,NameMapping> wholeAlter2, Question q) {
Pair<WholeNetworkAlter, WholeNetworkAlter> tieKey = new Pair<WholeNetworkAlter,WholeNetworkAlter>(wholeAlter1.getFirst(), wholeAlter2.getFirst());
if(!wholeNetworkTies.containsKey(tieKey)) {
wholeNetworkTies.put(tieKey, new WholeNetworkTie(tieKey));
logger.info("Saw new tie for first time: " + tieKey);
}
WholeNetworkTie tieEntry = wholeNetworkTies.get(tieKey);
tieEntry.addTie(wholeAlter1.getSecond(), wholeAlter1.getSecond(), q);
}
public Pair<String[],int[][]> getAdjacencyMatrix() {
List<WholeNetworkAlter> alterList =
new ArrayList<WholeNetworkAlter>(wholeNetworkAlters.values());
int size = alterList.size();
String [] names = new String[size];
for(int i = 0; i < names.length; i++) {
names[i] = alterList.get(i).toString();
}
int [][] adj = new int[size][size];
for(int x = 0; x < size; x++) {
for(int y = 0; y < size; y++) {
WholeNetworkAlter wholeAlter1 = alterList.get(x);
WholeNetworkAlter wholeAlter2 = alterList.get(y);
if(wholeAlter1.compareTo(wholeAlter2) > 0) {
WholeNetworkAlter swap = wholeAlter1;
wholeAlter1 = wholeAlter2;
wholeAlter2 = swap;
}
Pair<WholeNetworkAlter, WholeNetworkAlter> tieKey = new Pair<WholeNetworkAlter,WholeNetworkAlter>(wholeAlter1, wholeAlter2);
if(wholeNetworkTies.containsKey(tieKey)) {
WholeNetworkTie tie = wholeNetworkTies.get(tieKey);
adj[x][y] = tie.numberOfTies();
}
else {
adj[x][y] = 0;
}
}
}
return new Pair<String[],int[][]>(names,adj);
}
}
| true | true | public void recompile() {
wholeNetworkAlters.clear();
wholeNetworkTies.clear();
// add all alters
for(NameMapping mapping : nameMap) {
int group = mapping.getGroup();
if(!wholeNetworkAlters.containsKey(group)) {
wholeNetworkAlters.put(group, new WholeNetworkAlter(group));
}
WholeNetworkAlter alter = wholeNetworkAlters.get(group);
alter.addOccurence(mapping);
}
// build all ties
for(Pair<File, Interview> pair : interviewMap) {
Interview interview = pair.getSecond();
String [] thisInterviewAlterlist = interview.getAlterList();
// tie the ego to all alters
Pair<WholeNetworkAlter,NameMapping> ego = findAlter(interview, -1);
for(int i = 0; i < interview.getAlterList().length; i++) {
Pair<WholeNetworkAlter,NameMapping> alter = findAlter(interview, i);
tie(ego, alter, null);
}
// tie adjacent alters together
Iterator<Long> questions = study.getQuestionOrder(Shared.QuestionType.ALTER_PAIR).iterator();
while (questions.hasNext()) {
Question q = study.getQuestion((Long) questions.next());
try {
int [][] adj = interview.generateAdjacencyMatrix(q, false);
// loop through adj
// if adj[i][j] == 1, thisInterviewAlters[i] && thisInterviewAlters[j] are adjacent in final matrix
for(int i = 0; i < adj.length; i++)
{
for(int j = 0; j < adj[i].length; j++)
{
if(adj[i][j] == 1 && i != j)
{
String alter1 = thisInterviewAlterlist[i];
String alter2 = thisInterviewAlterlist[j];
logger.debug(alter1 + "("+i+") and " + alter2 + "("+j+") are adjacent");
// find whole network alters, tie them!
Pair<WholeNetworkAlter,NameMapping> wholeAlter1 = findAlter(interview, i);
Pair<WholeNetworkAlter,NameMapping> wholeAlter2 = findAlter(interview, j);
if(wholeAlter1.getFirst().compareTo(wholeAlter2.getFirst()) > 0) {
Pair<WholeNetworkAlter,NameMapping> swap = wholeAlter1;
wholeAlter1 = wholeAlter2;
wholeAlter2 = swap;
}
tie(wholeAlter1, wholeAlter2, q);
}
}
}
}
catch (MissingPairException ex) {
logger.error("Couldn't create adjacency matrix for question " + q, ex);
}
}
}
logger.info("# Alters: " + wholeNetworkAlters.size() + ", # Ties: " + wholeNetworkTies.size());
}
| public void recompile() {
wholeNetworkAlters.clear();
wholeNetworkTies.clear();
// add all alters
for(NameMapping mapping : nameMap) {
int group = mapping.getGroup();
if(!wholeNetworkAlters.containsKey(group)) {
wholeNetworkAlters.put(group, new WholeNetworkAlter(group));
}
WholeNetworkAlter alter = wholeNetworkAlters.get(group);
alter.addOccurence(mapping);
}
// build all ties
for(Pair<File, Interview> pair : interviewMap) {
Interview interview = pair.getSecond();
String [] thisInterviewAlterlist = interview.getAlterList();
// tie the ego to all alters
Pair<WholeNetworkAlter,NameMapping> ego = findAlter(interview, -1);
for(int i = 0; i < interview.getAlterList().length; i++) {
Pair<WholeNetworkAlter,NameMapping> alter = findAlter(interview, i);
tie(ego, alter, null);
}
// tie adjacent alters together
Iterator<Long> questions = study.getQuestionOrder(Shared.QuestionType.ALTER_PAIR).iterator();
while (questions.hasNext()) {
Question q = study.getQuestion((Long) questions.next());
try {
int [][] adj = interview.generateAdjacencyMatrix(q, false);
// loop through adj
// if adj[i][j] == 1, thisInterviewAlters[i] && thisInterviewAlters[j] are adjacent in final matrix
for(int i = 0; i < adj.length; i++)
{
for(int j = 0; j < adj[i].length; j++)
{
if(adj[i][j] == 1 && i != j &&
i < thisInterviewAlterlist.length && j < thisInterviewAlterlist.length)
{
String alter1 = thisInterviewAlterlist[i];
String alter2 = thisInterviewAlterlist[j];
logger.debug(alter1 + "("+i+") and " + alter2 + "("+j+") are adjacent");
// find whole network alters, tie them!
Pair<WholeNetworkAlter,NameMapping> wholeAlter1 = findAlter(interview, i);
Pair<WholeNetworkAlter,NameMapping> wholeAlter2 = findAlter(interview, j);
if(wholeAlter1.getFirst().compareTo(wholeAlter2.getFirst()) > 0) {
Pair<WholeNetworkAlter,NameMapping> swap = wholeAlter1;
wholeAlter1 = wholeAlter2;
wholeAlter2 = swap;
}
tie(wholeAlter1, wholeAlter2, q);
}
}
}
}
catch (MissingPairException ex) {
logger.error("Couldn't create adjacency matrix for question " + q, ex);
}
}
}
logger.info("# Alters: " + wholeNetworkAlters.size() + ", # Ties: " + wholeNetworkTies.size());
}
|
diff --git a/src/main/java/com/alta189/simplesave/internal/PreparedStatementUtils.java b/src/main/java/com/alta189/simplesave/internal/PreparedStatementUtils.java
index 580fb06..63ba80d 100644
--- a/src/main/java/com/alta189/simplesave/internal/PreparedStatementUtils.java
+++ b/src/main/java/com/alta189/simplesave/internal/PreparedStatementUtils.java
@@ -1,46 +1,50 @@
/*
* This file is part of SimpleSave
*
* SimpleSave 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.
*
* SimpleSave is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.alta189.simplesave.internal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class PreparedStatementUtils {
public static void setObject(PreparedStatement statement, int index, Object o) throws SQLException {
+ if (o == null) {
+ statement.setObject(index, null);
+ return;
+ }
Class clazz = o.getClass();
if (clazz.equals(int.class) || clazz.equals(Integer.class)) {
statement.setInt(index, ((Number) o).intValue());
} else if (clazz.equals(long.class) || clazz.equals(Long.class)) {
statement.setLong(index, ((Number) o).longValue());
} else if (clazz.equals(double.class) || clazz.equals(Double.class)) {
statement.setDouble(index, ((Number) o).doubleValue());
} else if (clazz.equals(String.class)) {
statement.setString(index, (String) o);
} else if (clazz.equals(boolean.class) || clazz.equals(Boolean.class)) {
statement.setInt(index, ((Boolean) o) ? 1 : 0);
} else if (clazz.equals(short.class) || clazz.equals(Short.class)) {
statement.setShort(index, ((Number) o).shortValue());
} else if (clazz.equals(float.class)|| clazz.equals(Float.class)) {
statement.setFloat(index, ((Number) o).floatValue());
} else if (clazz.equals(byte.class) || clazz.equals(Byte.class)) {
statement.setByte(index, ((Number) o).byteValue());
}
}
}
| true | true | public static void setObject(PreparedStatement statement, int index, Object o) throws SQLException {
Class clazz = o.getClass();
if (clazz.equals(int.class) || clazz.equals(Integer.class)) {
statement.setInt(index, ((Number) o).intValue());
} else if (clazz.equals(long.class) || clazz.equals(Long.class)) {
statement.setLong(index, ((Number) o).longValue());
} else if (clazz.equals(double.class) || clazz.equals(Double.class)) {
statement.setDouble(index, ((Number) o).doubleValue());
} else if (clazz.equals(String.class)) {
statement.setString(index, (String) o);
} else if (clazz.equals(boolean.class) || clazz.equals(Boolean.class)) {
statement.setInt(index, ((Boolean) o) ? 1 : 0);
} else if (clazz.equals(short.class) || clazz.equals(Short.class)) {
statement.setShort(index, ((Number) o).shortValue());
} else if (clazz.equals(float.class)|| clazz.equals(Float.class)) {
statement.setFloat(index, ((Number) o).floatValue());
} else if (clazz.equals(byte.class) || clazz.equals(Byte.class)) {
statement.setByte(index, ((Number) o).byteValue());
}
}
| public static void setObject(PreparedStatement statement, int index, Object o) throws SQLException {
if (o == null) {
statement.setObject(index, null);
return;
}
Class clazz = o.getClass();
if (clazz.equals(int.class) || clazz.equals(Integer.class)) {
statement.setInt(index, ((Number) o).intValue());
} else if (clazz.equals(long.class) || clazz.equals(Long.class)) {
statement.setLong(index, ((Number) o).longValue());
} else if (clazz.equals(double.class) || clazz.equals(Double.class)) {
statement.setDouble(index, ((Number) o).doubleValue());
} else if (clazz.equals(String.class)) {
statement.setString(index, (String) o);
} else if (clazz.equals(boolean.class) || clazz.equals(Boolean.class)) {
statement.setInt(index, ((Boolean) o) ? 1 : 0);
} else if (clazz.equals(short.class) || clazz.equals(Short.class)) {
statement.setShort(index, ((Number) o).shortValue());
} else if (clazz.equals(float.class)|| clazz.equals(Float.class)) {
statement.setFloat(index, ((Number) o).floatValue());
} else if (clazz.equals(byte.class) || clazz.equals(Byte.class)) {
statement.setByte(index, ((Number) o).byteValue());
}
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageBreakpointRulerAction.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageBreakpointRulerAction.java
index 921c44f3e..0b4d05014 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageBreakpointRulerAction.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageBreakpointRulerAction.java
@@ -1,303 +1,303 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui.actions;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IBreakpointManager;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.debug.core.IJavaLineBreakpoint;
import org.eclipse.jdt.debug.core.JDIDebugModel;
import org.eclipse.jdt.internal.debug.ui.BreakpointUtils;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IVerticalRulerInfo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.IUpdate;
public class ManageBreakpointRulerAction extends Action implements IUpdate {
private IVerticalRulerInfo fRuler;
private ITextEditor fTextEditor;
private List fMarkers;
private String fAddLabel;
private String fRemoveLabel;
public ManageBreakpointRulerAction(IVerticalRulerInfo ruler, ITextEditor editor) {
fRuler= ruler;
fTextEditor= editor;
fAddLabel= ActionMessages.getString("ManageBreakpointRulerAction.add.label"); //$NON-NLS-1$
fRemoveLabel= ActionMessages.getString("ManageBreakpointRulerAction.remove.label"); //$NON-NLS-1$
}
/**
* Returns the resource for which to create the marker,
* or <code>null</code> if there is no applicable resource.
*
* @return the resource for which to create the marker or <code>null</code>
*/
protected IResource getResource() {
IEditorInput input= fTextEditor.getEditorInput();
IResource resource= (IResource) input.getAdapter(IFile.class);
if (resource == null) {
resource= (IResource) input.getAdapter(IResource.class);
}
return resource;
}
/**
* Checks whether a position includes the ruler's line of activity.
*
* @param position the position to be checked
* @param document the document the position refers to
* @return <code>true</code> if the line is included by the given position
*/
protected boolean includesRulerLine(Position position, IDocument document) {
if (position != null) {
try {
int markerLine= document.getLineOfOffset(position.getOffset());
int line= fRuler.getLineOfLastMouseButtonActivity();
if (line == markerLine) {
return true;
}
} catch (BadLocationException x) {
}
}
return false;
}
/**
* Returns this action's vertical ruler info.
*
* @return this action's vertical ruler
*/
protected IVerticalRulerInfo getVerticalRulerInfo() {
return fRuler;
}
/**
* Returns this action's editor.
*
* @return this action's editor
*/
protected ITextEditor getTextEditor() {
return fTextEditor;
}
/**
* Returns the <code>AbstractMarkerAnnotationModel</code> of the editor's input.
*
* @return the marker annotation model
*/
protected AbstractMarkerAnnotationModel getAnnotationModel() {
IDocumentProvider provider= fTextEditor.getDocumentProvider();
IAnnotationModel model= provider.getAnnotationModel(fTextEditor.getEditorInput());
if (model instanceof AbstractMarkerAnnotationModel) {
return (AbstractMarkerAnnotationModel) model;
}
return null;
}
/**
* Returns the <code>IDocument</code> of the editor's input.
*
* @return the document of the editor's input
*/
protected IDocument getDocument() {
IDocumentProvider provider= fTextEditor.getDocumentProvider();
return provider.getDocument(fTextEditor.getEditorInput());
}
/**
* @see IUpdate#update()
*/
public void update() {
fMarkers= getMarkers();
setText(fMarkers.isEmpty() ? fAddLabel : fRemoveLabel);
}
/**
* @see Action#run()
*/
public void run() {
if (fMarkers.isEmpty()) {
addMarker();
} else {
removeMarkers(fMarkers);
}
}
protected List getMarkers() {
List breakpoints= new ArrayList();
IResource resource= getResource();
IDocument document= getDocument();
AbstractMarkerAnnotationModel model= getAnnotationModel();
if (model != null) {
try {
IMarker[] markers= null;
if (resource instanceof IFile)
markers= resource.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE);
else {
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
markers= root.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE);
}
if (markers != null) {
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
for (int i= 0; i < markers.length; i++) {
IBreakpoint breakpoint= breakpointManager.getBreakpoint(markers[i]);
if (breakpoint != null && breakpointManager.isRegistered(breakpoint) &&
includesRulerLine(model.getMarkerPosition(markers[i]), document))
breakpoints.add(markers[i]);
}
}
} catch (CoreException x) {
JDIDebugUIPlugin.log(x.getStatus());
}
}
return breakpoints;
}
protected void addMarker() {
IEditorInput editorInput= getTextEditor().getEditorInput();
try {
IDocument document= getDocument();
IRegion line= document.getLineInformation(getVerticalRulerInfo().getLineOfLastMouseButtonActivity());
IType type= null;
IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class);
if (classFile != null) {
type= classFile.getType();
// bug 34856 - if this is an inner type, ensure the breakpoint is not
// being added to the outer type
if (type.getDeclaringType() != null) {
ISourceRange sourceRange = type.getSourceRange();
int offset = line.getOffset();
int start = sourceRange.getOffset();
int end = start + sourceRange.getLength();
if (offset < start || offset > end) {
// not in the inner type
IStatusLineManager manager = getTextEditor().getEditorSite().getActionBars().getStatusLineManager();
manager.setErrorMessage(MessageFormat.format(ActionMessages.getString("ManageBreakpointRulerAction.Breakpoints_can_only_be_created_within_the_type_associated_with_the_editor__{0}._1"), new String[]{type.getTypeQualifiedName()})); //$NON-NLS-1$
Display.getCurrent().beep();
return;
}
}
} else if (editorInput instanceof IFileEditorInput) {
IWorkingCopyManager manager= JavaUI.getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(editorInput);
if (unit != null) {
synchronized (unit) {
unit.reconcile();
}
IJavaElement e= unit.getElementAt(line.getOffset());
if (e instanceof IType) {
type= (IType)e;
} else if (e instanceof IMember) {
type= ((IMember)e).getDeclaringType();
}
}
}
Map attributes= new HashMap(10);
IResource resource;
String typeName= null;
- int lineNumber= getVerticalRulerInfo().getLineOfLastMouseButtonActivity();
+ int lineNumber= getVerticalRulerInfo().getLineOfLastMouseButtonActivity() + 1; // Ruler is 0-based; editor is 1-based (nice :-/ )
IJavaLineBreakpoint breakpoint= null;
if (type == null) {
if (editorInput instanceof IFileEditorInput) {
resource= ((IFileEditorInput)editorInput).getFile();
} else {
resource= ResourcesPlugin.getWorkspace().getRoot();
}
} else {
IJavaProject project= type.getJavaProject();
typeName= type.getFullyQualifiedName();
if (type.exists() && project != null && project.isOnClasspath(type)) {
if (JDIDebugModel.lineBreakpointExists(typeName, lineNumber) == null) {
int start= line.getOffset();
int end= start + line.getLength() - 1;
BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(attributes, type, start, end);
}
}
resource= BreakpointUtils.getBreakpointResource(type);
breakpoint= JDIDebugModel.createLineBreakpoint(resource, typeName, lineNumber, -1, -1, 0, true, attributes);
}
new BreakpointLocationVerifierJob(document, line.getOffset(), breakpoint, lineNumber, typeName, type, resource).schedule();
} catch (DebugException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
} catch (CoreException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
} catch (BadLocationException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
}
}
protected void removeMarkers(List markers) {
IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager();
try {
Iterator e= markers.iterator();
while (e.hasNext()) {
IBreakpoint breakpoint= breakpointManager.getBreakpoint((IMarker) e.next());
breakpointManager.removeBreakpoint(breakpoint, true);
}
} catch (CoreException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.removing.message1"), e); //$NON-NLS-1$
}
}
}
| true | true | protected void addMarker() {
IEditorInput editorInput= getTextEditor().getEditorInput();
try {
IDocument document= getDocument();
IRegion line= document.getLineInformation(getVerticalRulerInfo().getLineOfLastMouseButtonActivity());
IType type= null;
IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class);
if (classFile != null) {
type= classFile.getType();
// bug 34856 - if this is an inner type, ensure the breakpoint is not
// being added to the outer type
if (type.getDeclaringType() != null) {
ISourceRange sourceRange = type.getSourceRange();
int offset = line.getOffset();
int start = sourceRange.getOffset();
int end = start + sourceRange.getLength();
if (offset < start || offset > end) {
// not in the inner type
IStatusLineManager manager = getTextEditor().getEditorSite().getActionBars().getStatusLineManager();
manager.setErrorMessage(MessageFormat.format(ActionMessages.getString("ManageBreakpointRulerAction.Breakpoints_can_only_be_created_within_the_type_associated_with_the_editor__{0}._1"), new String[]{type.getTypeQualifiedName()})); //$NON-NLS-1$
Display.getCurrent().beep();
return;
}
}
} else if (editorInput instanceof IFileEditorInput) {
IWorkingCopyManager manager= JavaUI.getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(editorInput);
if (unit != null) {
synchronized (unit) {
unit.reconcile();
}
IJavaElement e= unit.getElementAt(line.getOffset());
if (e instanceof IType) {
type= (IType)e;
} else if (e instanceof IMember) {
type= ((IMember)e).getDeclaringType();
}
}
}
Map attributes= new HashMap(10);
IResource resource;
String typeName= null;
int lineNumber= getVerticalRulerInfo().getLineOfLastMouseButtonActivity();
IJavaLineBreakpoint breakpoint= null;
if (type == null) {
if (editorInput instanceof IFileEditorInput) {
resource= ((IFileEditorInput)editorInput).getFile();
} else {
resource= ResourcesPlugin.getWorkspace().getRoot();
}
} else {
IJavaProject project= type.getJavaProject();
typeName= type.getFullyQualifiedName();
if (type.exists() && project != null && project.isOnClasspath(type)) {
if (JDIDebugModel.lineBreakpointExists(typeName, lineNumber) == null) {
int start= line.getOffset();
int end= start + line.getLength() - 1;
BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(attributes, type, start, end);
}
}
resource= BreakpointUtils.getBreakpointResource(type);
breakpoint= JDIDebugModel.createLineBreakpoint(resource, typeName, lineNumber, -1, -1, 0, true, attributes);
}
new BreakpointLocationVerifierJob(document, line.getOffset(), breakpoint, lineNumber, typeName, type, resource).schedule();
} catch (DebugException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
} catch (CoreException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
} catch (BadLocationException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
}
}
| protected void addMarker() {
IEditorInput editorInput= getTextEditor().getEditorInput();
try {
IDocument document= getDocument();
IRegion line= document.getLineInformation(getVerticalRulerInfo().getLineOfLastMouseButtonActivity());
IType type= null;
IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class);
if (classFile != null) {
type= classFile.getType();
// bug 34856 - if this is an inner type, ensure the breakpoint is not
// being added to the outer type
if (type.getDeclaringType() != null) {
ISourceRange sourceRange = type.getSourceRange();
int offset = line.getOffset();
int start = sourceRange.getOffset();
int end = start + sourceRange.getLength();
if (offset < start || offset > end) {
// not in the inner type
IStatusLineManager manager = getTextEditor().getEditorSite().getActionBars().getStatusLineManager();
manager.setErrorMessage(MessageFormat.format(ActionMessages.getString("ManageBreakpointRulerAction.Breakpoints_can_only_be_created_within_the_type_associated_with_the_editor__{0}._1"), new String[]{type.getTypeQualifiedName()})); //$NON-NLS-1$
Display.getCurrent().beep();
return;
}
}
} else if (editorInput instanceof IFileEditorInput) {
IWorkingCopyManager manager= JavaUI.getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(editorInput);
if (unit != null) {
synchronized (unit) {
unit.reconcile();
}
IJavaElement e= unit.getElementAt(line.getOffset());
if (e instanceof IType) {
type= (IType)e;
} else if (e instanceof IMember) {
type= ((IMember)e).getDeclaringType();
}
}
}
Map attributes= new HashMap(10);
IResource resource;
String typeName= null;
int lineNumber= getVerticalRulerInfo().getLineOfLastMouseButtonActivity() + 1; // Ruler is 0-based; editor is 1-based (nice :-/ )
IJavaLineBreakpoint breakpoint= null;
if (type == null) {
if (editorInput instanceof IFileEditorInput) {
resource= ((IFileEditorInput)editorInput).getFile();
} else {
resource= ResourcesPlugin.getWorkspace().getRoot();
}
} else {
IJavaProject project= type.getJavaProject();
typeName= type.getFullyQualifiedName();
if (type.exists() && project != null && project.isOnClasspath(type)) {
if (JDIDebugModel.lineBreakpointExists(typeName, lineNumber) == null) {
int start= line.getOffset();
int end= start + line.getLength() - 1;
BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(attributes, type, start, end);
}
}
resource= BreakpointUtils.getBreakpointResource(type);
breakpoint= JDIDebugModel.createLineBreakpoint(resource, typeName, lineNumber, -1, -1, 0, true, attributes);
}
new BreakpointLocationVerifierJob(document, line.getOffset(), breakpoint, lineNumber, typeName, type, resource).schedule();
} catch (DebugException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
} catch (CoreException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
} catch (BadLocationException e) {
JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$
}
}
|
diff --git a/melati/src/main/java/org/melati/servlet/ConfigServlet.java b/melati/src/main/java/org/melati/servlet/ConfigServlet.java
index 055694859..a0d933dd7 100644
--- a/melati/src/main/java/org/melati/servlet/ConfigServlet.java
+++ b/melati/src/main/java/org/melati/servlet/ConfigServlet.java
@@ -1,256 +1,256 @@
/*
* $Source$
* $Revision$
*
* Copyright (C) 2000 Tim Joyce
*
* Part of Melati (http://melati.org), a framework for the rapid
* development of clean, maintainable web applications.
*
* Melati is free software; Permission is granted to copy, distribute
* and/or modify this software under the terms either:
*
* a) 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,
*
* or
*
* b) any version of the Melati Software License, as published
* at http://melati.org
*
* You should have received a copy of the GNU General Public License and
* the Melati Software License along with this program;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the
* GNU General Public License and visit http://melati.org to obtain the
* Melati Software License.
*
* Feel free to contact the Developers of Melati (http://melati.org),
* if you would like to work out a different arrangement than the options
* outlined here. It is our intention to allow Melati to be used by as
* wide an audience as possible.
*
* 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.
*
* Contact details for copyright holder:
*
* Tim Joyce <[email protected]>
* http://paneris.org/
* 68 Sandbanks Rd, Poole, Dorset. BH14 8BY. UK
*/
/*
* Config Servlet is the simplest way to use Melati.
*
* All a ConfigServlet does is to configure a melati and combine the
* doGet and doPost methods. Importantly it does not establish a poem session
* leaving you to do this for yourself.
*
* if you want a poem session established, please extend PoemServlet
*
* <A NAME=pathinfoscan>ConfigServlet does set up a basic
* MelatiContext with the Method set,
* but not the POEM logicaldatabase, table or troid
*
* The URL is expected to take one of the following form:
*
* <BLOCKQUOTE><TT>
* http://<I>h</I>/<I>s</I>/<I>meth</I>
* </TT></BLOCKQUOTE>
*
* the method is broken out of the path info and passed to
* your application code in the <TT>Melati</TT> and
* <TT>MelatiContext</TT> parameter
*
* <TABLE>
* <TR>
* <TD><TT><I>h</I></TT></TD>
* <TD>host name, such as <TT>www.melati.org</TT></TD>
* </TR>
* <TR>
* <TD><TT><I>s</I></TT></TD>
* <TD>
* servlet-determining part, such as
* <TT>melati/org.melati.admin.Admin</TT>
* </TD>
* </TR>
* <TR>
* <TD><TT><I>meth</I></TT></TD>
* <TD>
* A freeform string telling your servlet what it is meant to do. This
* is automatically made available in templates as
* <TT>$melati.Method</TT>.
* </TD>
* </TR>
* </TABLE>
*
* You can change the way these things are determined by overriding
* <TT>melatiContext</TT>.
*/
package org.melati.servlet;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.melati.Melati;
import org.melati.MelatiConfig;
import org.melati.util.MelatiException;
import org.melati.util.MelatiLocale;
import org.melati.util.StringUtils;
import org.melati.util.MelatiWriter;
public abstract class ConfigServlet extends HttpServlet {
// the melati
protected MelatiConfig melatiConfig;
/**
* Inititialise Melati
* @param ServletConfig
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
melatiConfig = melatiConfig();
} catch (MelatiException e) {
// log it to system.err as ServletExceptions go to the
// servlet runner log (eg jserv.log), and don't have a stack trace!
e.printStackTrace(System.err);
throw new ServletException(e.toString ());
}
}
/**
* Handles GET
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGetPostRequest(request, response);
}
/**
* Handle a POST
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGetPostRequest(request, response);
}
/**
* Process the request.
*/
private void doGetPostRequest(final HttpServletRequest request,
final HttpServletResponse response)
throws IOException {
try {
Melati melati = melatiConfig.getMelati(request, response);
try {
MelatiContext melatiContext = melatiContext(melati);
melati.setContext(melatiContext);
doConfiguredRequest(melati);
// send the output to the client
melati.write();
}
catch (Exception f) {
error(melati,f);
}
}
catch (Exception e) {
// log it
e.printStackTrace(System.err);
}
}
/**
* Send an error message
*/
- public void error(Melati melati, Exception e ) throws IOException {
+ public void error(Melati melati, Throwable e ) throws IOException {
// has it been trapped already, if so, we don't need to relog it here
if (! (e instanceof TrappedException)) {
// log it
e.printStackTrace(System.err);
// and put it on the page
melati.getResponse().setContentType ("text/html");
MelatiWriter mw = melati.getWriter();
// get rid of anything that has been written so far
mw.reset();
PrintWriter out = mw.getPrintWriter();
out.println("<html><head><title>Melati Error</title></head>");
out.println("<body><h2>Melati Error</h2>");
out.println("<p>An error has occured in the application");
out.println("that runs this website, please contact <a href='mailto:");
out.println(getSysAdminEmail() + "'>" + getSysAdminName() + "</a>");
out.println(", with the information given below.</p>");
out.println("<h4><font color=red><pre>" );
e.printStackTrace(out);
out.println("</pre></font></h4></body></html>");
melati.write();
}
}
/*
* Please override these settings.
*/
public String getSysAdminName () {
return "nobody";
}
public String getSysAdminEmail () {
return "[email protected]";
}
protected MelatiContext melatiContext(Melati melati)
throws PathInfoException {
MelatiContext it = new MelatiContext();
String[] parts = melati.getPathInfoParts();
if (parts.length > 0)
it.method = StringUtils.nulled(parts[parts.length - 1]);
return it;
}
/**
* To override any setting from MelatiServlet.properties,
* simply override this method and return a vaild MelatiConfig.
*
* eg to use a different AccessHandler from the default:
*
* <PRE>
* protected MelatiConfig melatiConfig() throws MelatiException {
* MelatiConfig config = super.melatiConfig();
* config.setAccessHandler(new YourAccessHandler());
* return config;
* }
* </PRE>
*
*/
protected MelatiConfig melatiConfig() throws MelatiException {
return new MelatiConfig();
}
/**
* Override this method to build up your output
* @param melati
*/
protected abstract void doConfiguredRequest (Melati melati)
throws Exception;
}
| true | true | public void error(Melati melati, Exception e ) throws IOException {
// has it been trapped already, if so, we don't need to relog it here
if (! (e instanceof TrappedException)) {
// log it
e.printStackTrace(System.err);
// and put it on the page
melati.getResponse().setContentType ("text/html");
MelatiWriter mw = melati.getWriter();
// get rid of anything that has been written so far
mw.reset();
PrintWriter out = mw.getPrintWriter();
out.println("<html><head><title>Melati Error</title></head>");
out.println("<body><h2>Melati Error</h2>");
out.println("<p>An error has occured in the application");
out.println("that runs this website, please contact <a href='mailto:");
out.println(getSysAdminEmail() + "'>" + getSysAdminName() + "</a>");
out.println(", with the information given below.</p>");
out.println("<h4><font color=red><pre>" );
e.printStackTrace(out);
out.println("</pre></font></h4></body></html>");
melati.write();
}
}
| public void error(Melati melati, Throwable e ) throws IOException {
// has it been trapped already, if so, we don't need to relog it here
if (! (e instanceof TrappedException)) {
// log it
e.printStackTrace(System.err);
// and put it on the page
melati.getResponse().setContentType ("text/html");
MelatiWriter mw = melati.getWriter();
// get rid of anything that has been written so far
mw.reset();
PrintWriter out = mw.getPrintWriter();
out.println("<html><head><title>Melati Error</title></head>");
out.println("<body><h2>Melati Error</h2>");
out.println("<p>An error has occured in the application");
out.println("that runs this website, please contact <a href='mailto:");
out.println(getSysAdminEmail() + "'>" + getSysAdminName() + "</a>");
out.println(", with the information given below.</p>");
out.println("<h4><font color=red><pre>" );
e.printStackTrace(out);
out.println("</pre></font></h4></body></html>");
melati.write();
}
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/domain/GeoCoordinates.java b/GAE/src/org/waterforpeople/mapping/domain/GeoCoordinates.java
index 31c2a4ba5..ad2a23228 100644
--- a/GAE/src/org/waterforpeople/mapping/domain/GeoCoordinates.java
+++ b/GAE/src/org/waterforpeople/mapping/domain/GeoCoordinates.java
@@ -1,56 +1,56 @@
package org.waterforpeople.mapping.domain;
public class GeoCoordinates {
private Double latitude;
private Double longitude;
private Double altitude;
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getAltitude() {
return altitude;
}
public void setAltitude(Double altitude) {
this.altitude = altitude;
}
public GeoCoordinates extractGeoCoordinate(String line) {
if (line != null && line.trim().length() > 0
- && !line.trim().equals("||")) {
+ && !line.trim().equals("||") && !line.startsWith("||")) {
String[] coordinates = line.split("\\|");
if (coordinates.length > 1) {
setLatitude(new Double(coordinates[0]));
setLongitude(new Double(coordinates[1]));
}
if (coordinates.length > 2) {
setAltitude(new Double(coordinates[2]));
}
}
return this;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("GeoCoordinates:");
sb.append("\n--Latitude: " + this.latitude);
sb.append("\n--Longitude: " + this.longitude);
sb.append("\n--Altitude: " + this.altitude);
return sb.toString();
}
}
| true | true | public GeoCoordinates extractGeoCoordinate(String line) {
if (line != null && line.trim().length() > 0
&& !line.trim().equals("||")) {
String[] coordinates = line.split("\\|");
if (coordinates.length > 1) {
setLatitude(new Double(coordinates[0]));
setLongitude(new Double(coordinates[1]));
}
if (coordinates.length > 2) {
setAltitude(new Double(coordinates[2]));
}
}
return this;
}
| public GeoCoordinates extractGeoCoordinate(String line) {
if (line != null && line.trim().length() > 0
&& !line.trim().equals("||") && !line.startsWith("||")) {
String[] coordinates = line.split("\\|");
if (coordinates.length > 1) {
setLatitude(new Double(coordinates[0]));
setLongitude(new Double(coordinates[1]));
}
if (coordinates.length > 2) {
setAltitude(new Double(coordinates[2]));
}
}
return this;
}
|
diff --git a/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/FeatureExecutableFactory.java b/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/FeatureExecutableFactory.java
index 5a540cabf..9a1c1e62e 100644
--- a/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/FeatureExecutableFactory.java
+++ b/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/FeatureExecutableFactory.java
@@ -1,116 +1,118 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.update.internal.core;
import java.io.*;
import java.net.*;
import org.eclipse.core.runtime.*;
import org.eclipse.update.core.*;
import org.eclipse.update.core.model.*;
/**
* FeatureFactory for Executable Features
*/
public class FeatureExecutableFactory extends BaseFeatureFactory {
/*
* @see IFeatureFactory#createFeature(URL,ISite,IProgressMonitor)
*/
public IFeature createFeature(URL url, ISite site, IProgressMonitor monitor) throws CoreException {
TargetFeature feature = null;
InputStream featureStream = null;
if (monitor == null)
monitor = new NullProgressMonitor();
if (url == null)
return createFeature(site);
// the URL should point to a directory
url = validate(url);
try {
IFeatureContentProvider contentProvider = new FeatureExecutableContentProvider(url);
- // PERF: Do not create FeatureContentConsumer
- //IFeatureContentConsumer contentConsumer =new FeatureExecutableContentConsumer();
+// // PERF: Do not create FeatureContentConsumer
+// bug 79893
+ IFeatureContentConsumer contentConsumer =new FeatureExecutableContentConsumer();
URL nonResolvedURL = contentProvider.getFeatureManifestReference(null).asURL();
URL resolvedURL = URLEncoder.encode(nonResolvedURL);
featureStream = UpdateCore.getPlugin().get(resolvedURL).getInputStream();
feature = (TargetFeature) this.parseFeature(featureStream);
monitor.worked(1);
feature.setSite(site);
feature.setFeatureContentProvider(contentProvider);
- // PERF: FeatureContentConsumer
- //feature.setContentConsumer(contentConsumer);
+// // PERF: FeatureContentConsumer
+// bug 79893
+ feature.setContentConsumer(contentConsumer);
feature.resolve(url, url);
feature.markReadOnly();
} catch (CoreException e) {
throw e;
} catch (Exception e) {
throw Utilities.newCoreException(Policy.bind("FeatureFactory.CreatingError", url.toExternalForm()), e); //$NON-NLS-1$
} finally {
try {
if (featureStream != null)
featureStream.close();
} catch (IOException e) {
}
}
return feature;
}
/*
* @see FeatureModelFactory#createFeatureModel()
*/
public FeatureModel createFeatureModel() {
return new TargetFeature();
}
/*
* Creates an empty feature on the site
*/
private IFeature createFeature(ISite site) throws CoreException {
TargetFeature feature = null;
IFeatureContentProvider contentProvider = new FeatureExecutableContentProvider(null);
IFeatureContentConsumer contentConsumer = new FeatureExecutableContentConsumer();
feature = (TargetFeature) createFeatureModel();
feature.setSite(site);
feature.setFeatureContentProvider(contentProvider);
feature.setContentConsumer(contentConsumer);
// do not mark read only yet...
return feature;
}
/*
* validates a URL as a directory URL
*/
private URL validate(URL url) throws CoreException {
if (url == null)
throw Utilities.newCoreException(Policy.bind("FeatureExecutableFactory.NullURL"), null); //$NON-NLS-1$
if (!(url.getFile().endsWith("/") || url.getFile().endsWith(File.separator) || url.getFile().endsWith(Feature.FEATURE_XML))) { //$NON-NLS-1$
try {
String path = url.getFile() + "/"; //$NON-NLS-1$
url = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
} catch (MalformedURLException e) {
throw Utilities.newCoreException(Policy.bind("FeatureExecutableFactory.CannotCreateURL", url.toExternalForm()), e); //$NON-NLS-1$
}
}
return url;
}
}
| false | true | public IFeature createFeature(URL url, ISite site, IProgressMonitor monitor) throws CoreException {
TargetFeature feature = null;
InputStream featureStream = null;
if (monitor == null)
monitor = new NullProgressMonitor();
if (url == null)
return createFeature(site);
// the URL should point to a directory
url = validate(url);
try {
IFeatureContentProvider contentProvider = new FeatureExecutableContentProvider(url);
// PERF: Do not create FeatureContentConsumer
//IFeatureContentConsumer contentConsumer =new FeatureExecutableContentConsumer();
URL nonResolvedURL = contentProvider.getFeatureManifestReference(null).asURL();
URL resolvedURL = URLEncoder.encode(nonResolvedURL);
featureStream = UpdateCore.getPlugin().get(resolvedURL).getInputStream();
feature = (TargetFeature) this.parseFeature(featureStream);
monitor.worked(1);
feature.setSite(site);
feature.setFeatureContentProvider(contentProvider);
// PERF: FeatureContentConsumer
//feature.setContentConsumer(contentConsumer);
feature.resolve(url, url);
feature.markReadOnly();
} catch (CoreException e) {
throw e;
} catch (Exception e) {
throw Utilities.newCoreException(Policy.bind("FeatureFactory.CreatingError", url.toExternalForm()), e); //$NON-NLS-1$
} finally {
try {
if (featureStream != null)
featureStream.close();
} catch (IOException e) {
}
}
return feature;
}
| public IFeature createFeature(URL url, ISite site, IProgressMonitor monitor) throws CoreException {
TargetFeature feature = null;
InputStream featureStream = null;
if (monitor == null)
monitor = new NullProgressMonitor();
if (url == null)
return createFeature(site);
// the URL should point to a directory
url = validate(url);
try {
IFeatureContentProvider contentProvider = new FeatureExecutableContentProvider(url);
// // PERF: Do not create FeatureContentConsumer
// bug 79893
IFeatureContentConsumer contentConsumer =new FeatureExecutableContentConsumer();
URL nonResolvedURL = contentProvider.getFeatureManifestReference(null).asURL();
URL resolvedURL = URLEncoder.encode(nonResolvedURL);
featureStream = UpdateCore.getPlugin().get(resolvedURL).getInputStream();
feature = (TargetFeature) this.parseFeature(featureStream);
monitor.worked(1);
feature.setSite(site);
feature.setFeatureContentProvider(contentProvider);
// // PERF: FeatureContentConsumer
// bug 79893
feature.setContentConsumer(contentConsumer);
feature.resolve(url, url);
feature.markReadOnly();
} catch (CoreException e) {
throw e;
} catch (Exception e) {
throw Utilities.newCoreException(Policy.bind("FeatureFactory.CreatingError", url.toExternalForm()), e); //$NON-NLS-1$
} finally {
try {
if (featureStream != null)
featureStream.close();
} catch (IOException e) {
}
}
return feature;
}
|
diff --git a/app/controllers/NScontroller.java b/app/controllers/NScontroller.java
index 150db9a..f74f9a1 100644
--- a/app/controllers/NScontroller.java
+++ b/app/controllers/NScontroller.java
@@ -1,314 +1,316 @@
package controllers;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import models.ComboboxOpts;
import models.Constants;
import models.IAjob;
import models.NSjob;
import org.codehaus.jackson.JsonNode;
import play.Logger;
import play.data.Form;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;
import tools.Utils;
import views.html.errorpage;
import views.html.ns.nsform;
import views.html.ns.nssummary;
public class NScontroller extends Controller {
final static Form<NSjob> nsForm = form(NSjob.class);
public static Result initNSform() {
Form<NSjob> newform = nsForm.fill(new NSjob());
return ok(nsform.render(newform, "", ""));
}
public static Result redirectPreloadedNSform(String jobid) {
IAjob iajob = IAcontroller.getJobFromJsonFile(jobid);
Form<NSjob> newform = nsForm.fill(new NSjob());
return ok(nsform.render(newform, iajob.jobid, iajob.jsonSelectedForNS));
}
public static Result initPreloadedNSform() {
// Get form
Form<NSjob> filledForm = nsForm.bindFromRequest();
NSjob job = filledForm.get();
// Logger.info("sJOB ID:"+job.jobid);
// Logger.info("selected for NS JSON:"+job.jsonSelectedForNS);
IAjob iajob = IAcontroller.getJobFromJsonFile(job.jobid);
iajob.jsonSelectedForNS = job.jsonSelectedForNS;
IAcontroller.writeJsonJobToFile(iajob, job.jobid);
return redirect("/preloaded-normalizationscoring/" + job.jobid);
}
public static Result submit() {
// Get form
Form<NSjob> filledForm = nsForm.bindFromRequest();
// Logger.info(filledForm.data().toString());
// Process submission
long submissionStartTime = new Date().getTime(); // start time
// Get job
NSjob job = filledForm.get();
job.linkageGenes = job.linkageGenes.replaceAll("\n|\r", ",");
job.linkageGenes = job.linkageGenes.replaceAll("\\s", "");
Logger.debug("LINKAGE GENES = " + job.linkageGenes);
Map<String, File> plateFilesMap = new HashMap<String, File>();
// Get file(s) uploaded
MultipartFormData body = request().body().asMultipartFormData();
// Check if we have an array definition file
FilePart arrayDefCustomFile = body.getFile("arrayDefCustomFile");
// Logger.error(body.toString());
// Logger.info("JOBid = "+job.jobid);
if (job.jobid == null | job.jobid.isEmpty()) {
// Logger.info("Files uploaded, populating plate file map:");
List<FilePart> plateFiles = body.getFiles();
for (FilePart fp : plateFiles) {
// File f = fp.getFile();
// Logger.info("--> "+f.getPath() + "\t"+f.exists());
plateFilesMap.put(fp.getFilename(), fp.getFile());
}
} else {
// Logger.info("Files preloaded from IA, populating plate file map:");
IAjob iajob = IAcontroller.getJobFromJsonFile(job.jobid);
// Logger.info("selectedForNS = "+iajob.jsonSelectedForNS);
String[] preloadedList = Json.fromJson(Json.parse(iajob.jsonSelectedForNS), String[].class);
for (String fileName : preloadedList) {
File file = new File(
Utils.joinPath(Constants.JOB_OUTPUT_DIR, job.jobid, "ia", "output_files", fileName));
// Logger.info("\t"+fileName+" -> " + file.getPath());
plateFilesMap.put(fileName, file);
}
}
// Generate
List<String> adList = ComboboxOpts.arrayDef();
StringBuilder adfiles = new StringBuilder();
String summaryAD = "Not applied";
if (job.doArrayDef) {
// Custom file -ERROR HERE FILE NOT UPLOADING
if (adList.indexOf(job.arrayDefPredefined) == adList.size() - 1) {
// Logger.info("Found array definition file");
// Remove extra non plate files
plateFilesMap.remove(arrayDefCustomFile.getFilename());
adfiles.append(arrayDefCustomFile.getFile().getPath());
summaryAD = "Custom upload: " + arrayDefCustomFile.getFilename();
}
// Predefined array def
else if (job.selectedArrayDefPlate != null) {
String arrayDefDir = Constants.ARRAY_DEF_PATH + "/" + job.arrayDefPredefined;
summaryAD = job.arrayDefPredefined + " (";
List<String> adPlatesList = ComboboxOpts.arrayDefPlates(job.arrayDefPredefined);
if (adPlatesList.indexOf(job.selectedArrayDefPlate) == 0) {
// All plates
for (int i = 1; i < adPlatesList.size(); i++) {
adfiles.append(Utils.joinPath(arrayDefDir, adPlatesList.get(i)));
if (i < adPlatesList.size() - 1) {
adfiles.append(':');
}
}
summaryAD += "All plates";
} else {
// One plate
adfiles.append(Utils.joinPath(arrayDefDir, job.selectedArrayDefPlate));
summaryAD += job.selectedArrayDefPlate;
}
summaryAD += ")";
}
}
// Make directories for output
if (job.jobid.isEmpty() || job.jobid == null) {
job.jobid = UUID.randomUUID().toString();
// Logger.info("Generated new UUID: "+job.jobid);
}
File outputDir = new File(Utils.joinPath(Constants.JOB_OUTPUT_DIR, job.jobid));
File nsDir = new File(Utils.joinPath(outputDir.getPath(), "ns"));
File outputFilesDir = new File(Utils.joinPath(nsDir.getPath(), "output_files"));
File inputFilesDir = new File(Utils.joinPath(nsDir.getPath(), "input_files"));
// Remove any ns directory if it exists
if (nsDir.exists()) {
nsDir.delete();
}
outputDir.mkdir();
nsDir.mkdir();
outputFilesDir.mkdir();
inputFilesDir.mkdir();
StringBuilder inputfiles = new StringBuilder();
StringBuilder savenames = new StringBuilder();
List<String> savenamesList = new ArrayList<String>();
for (Entry<String, File> e : plateFilesMap.entrySet()) {
inputfiles.append(e.getValue().getPath() + ":");
savenames.append(e.getKey() + ":");
savenamesList.add(e.getKey());
}
String ninputfiles = inputfiles.substring(0, inputfiles.lastIndexOf(":"));
String nsavenames = savenames.substring(0, savenames.lastIndexOf(":"));
if (!job.doLinkage)
job.linkageCutoff = "-1";
// Prepare arguments
List<String> c = new ArrayList<String>();
c.add("Rscript");
c.add(Constants.RSCRIPT_PATH);
c.add("--inputfiles");
c.add(ninputfiles);
c.add("--savenames");
c.add(nsavenames);
c.add("--outputdir");
c.add(outputFilesDir.getPath());
c.add("--replicates");
c.add(job.replicates.toString());
c.add("--linkagecutoff");
c.add(job.linkageCutoff.toString());
c.add("--linkagegenes");
c.add(job.linkageGenes.toString());
c.add("--wd");
c.add(Constants.RSCRIPT_DIR);
if (!adfiles.toString().isEmpty()) {
c.add("--adfiles");
c.add(adfiles.toString());
c.add("--adname");
c.add(summaryAD);
}
if (job.doScoring) {
c.add("--score");
// c.add("--sfunction"); c.add(job.scoringFunction);
c.add("--sfunction");
c.add("1");
}
// Logger.info("#####"+c );
String zipFilePath = nsDir.getPath() + "normalizationscoring-sgatools-" + job.jobid + ".zip";
StringBuilder shell_output = new StringBuilder();
StringBuilder shell_output_error = new StringBuilder();
try {
// Try execute and read
Process p = Runtime.getRuntime().exec(c.toArray(new String[0]));
// Read in output returned from shell
// #########FOR DEBUG ONLY######
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
shell_output.append(line + "\n");
}
// Read in error input stream (if we have some error)
BufferedReader in_error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line_error;
while ((line_error = in_error.readLine()) != null) {
shell_output_error.append(line_error + "\n");
}
in_error.close();
// #############################
Logger.debug(shell_output.toString());
- Logger.error(shell_output_error.toString());
+ if (!shell_output_error.toString().isEmpty()) {
+ Logger.error(shell_output_error.toString());
+ }
// Zip files
Zipper.zipDir(zipFilePath, outputFilesDir.getPath());
} catch (Exception e) {
Logger.error(shell_output.toString());
Logger.error("===============================");
Logger.error(shell_output_error.toString());
// Fatal error
filledForm
.reject("plateFiles",
"Fatal error, no output files were produced. If this problem persists, please contact the developers with your input files");
return badRequest(nsform.render(filledForm, "", ""));
}
// Record time elapsed
long submissionEndTime = new Date().getTime(); // end time
long milliseconds = submissionEndTime - submissionStartTime; // check
// different
int seconds = (int) (milliseconds / 1000) % 60;
int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
Map<String, String> outputFilesMap = new HashMap<String, String>();
for (File of : outputFilesDir.listFiles()) {
if (!of.getName().startsWith("combined") && !of.getName().startsWith("README")
&& !of.getName().startsWith("scores"))
outputFilesMap.put(of.getName(), of.getPath());
}
// Save some objects
job.timeElapsed = minutes + " mins " + seconds + " secs";
job.outputFilesMap = outputFilesMap;
job.summaryAD = summaryAD;
// Save bound data to file
job.plateFilesMap = plateFilesMap;
job.downloadZipPath = zipFilePath.replace(Constants.BASE_PUBLIC_DIR, "");
writeJsonJobToFile(job, job.jobid);
// Direct to summary page
return redirect("/normalizationscoring/" + job.jobid);
}
public static Result showJob(String jobid) {
NSjob nsJob = NScontroller.getJobFromJsonFile(jobid);
if (nsJob == null) {
return ok(errorpage.render(
"The job you have requested was not found, please check to make your job id is correct", "404"));
}
return ok(nssummary.render(nsJob));
}
public static NSjob getJobFromJsonFile(String jobid) {
try {
String jsonString = Help.readFile(Utils.joinPath(Constants.JOB_OUTPUT_DIR, jobid, "ns", jobid + ".json"));
NSjob nsJob = Json.fromJson(Json.parse(jsonString), NSjob.class);
return nsJob;
} catch (Exception e) {
Logger.error(e.getMessage());
return null;
}
}
public static boolean writeJsonJobToFile(NSjob job, String jobid) {
try {
JsonNode jn = Json.toJson(job);
Help.writeFile(jn.toString(), Utils.joinPath(Constants.JOB_OUTPUT_DIR, jobid, "ns", jobid + ".json"));
return true;
} catch (Exception e) {
return false;
}
}
}
| true | true | public static Result submit() {
// Get form
Form<NSjob> filledForm = nsForm.bindFromRequest();
// Logger.info(filledForm.data().toString());
// Process submission
long submissionStartTime = new Date().getTime(); // start time
// Get job
NSjob job = filledForm.get();
job.linkageGenes = job.linkageGenes.replaceAll("\n|\r", ",");
job.linkageGenes = job.linkageGenes.replaceAll("\\s", "");
Logger.debug("LINKAGE GENES = " + job.linkageGenes);
Map<String, File> plateFilesMap = new HashMap<String, File>();
// Get file(s) uploaded
MultipartFormData body = request().body().asMultipartFormData();
// Check if we have an array definition file
FilePart arrayDefCustomFile = body.getFile("arrayDefCustomFile");
// Logger.error(body.toString());
// Logger.info("JOBid = "+job.jobid);
if (job.jobid == null | job.jobid.isEmpty()) {
// Logger.info("Files uploaded, populating plate file map:");
List<FilePart> plateFiles = body.getFiles();
for (FilePart fp : plateFiles) {
// File f = fp.getFile();
// Logger.info("--> "+f.getPath() + "\t"+f.exists());
plateFilesMap.put(fp.getFilename(), fp.getFile());
}
} else {
// Logger.info("Files preloaded from IA, populating plate file map:");
IAjob iajob = IAcontroller.getJobFromJsonFile(job.jobid);
// Logger.info("selectedForNS = "+iajob.jsonSelectedForNS);
String[] preloadedList = Json.fromJson(Json.parse(iajob.jsonSelectedForNS), String[].class);
for (String fileName : preloadedList) {
File file = new File(
Utils.joinPath(Constants.JOB_OUTPUT_DIR, job.jobid, "ia", "output_files", fileName));
// Logger.info("\t"+fileName+" -> " + file.getPath());
plateFilesMap.put(fileName, file);
}
}
// Generate
List<String> adList = ComboboxOpts.arrayDef();
StringBuilder adfiles = new StringBuilder();
String summaryAD = "Not applied";
if (job.doArrayDef) {
// Custom file -ERROR HERE FILE NOT UPLOADING
if (adList.indexOf(job.arrayDefPredefined) == adList.size() - 1) {
// Logger.info("Found array definition file");
// Remove extra non plate files
plateFilesMap.remove(arrayDefCustomFile.getFilename());
adfiles.append(arrayDefCustomFile.getFile().getPath());
summaryAD = "Custom upload: " + arrayDefCustomFile.getFilename();
}
// Predefined array def
else if (job.selectedArrayDefPlate != null) {
String arrayDefDir = Constants.ARRAY_DEF_PATH + "/" + job.arrayDefPredefined;
summaryAD = job.arrayDefPredefined + " (";
List<String> adPlatesList = ComboboxOpts.arrayDefPlates(job.arrayDefPredefined);
if (adPlatesList.indexOf(job.selectedArrayDefPlate) == 0) {
// All plates
for (int i = 1; i < adPlatesList.size(); i++) {
adfiles.append(Utils.joinPath(arrayDefDir, adPlatesList.get(i)));
if (i < adPlatesList.size() - 1) {
adfiles.append(':');
}
}
summaryAD += "All plates";
} else {
// One plate
adfiles.append(Utils.joinPath(arrayDefDir, job.selectedArrayDefPlate));
summaryAD += job.selectedArrayDefPlate;
}
summaryAD += ")";
}
}
// Make directories for output
if (job.jobid.isEmpty() || job.jobid == null) {
job.jobid = UUID.randomUUID().toString();
// Logger.info("Generated new UUID: "+job.jobid);
}
File outputDir = new File(Utils.joinPath(Constants.JOB_OUTPUT_DIR, job.jobid));
File nsDir = new File(Utils.joinPath(outputDir.getPath(), "ns"));
File outputFilesDir = new File(Utils.joinPath(nsDir.getPath(), "output_files"));
File inputFilesDir = new File(Utils.joinPath(nsDir.getPath(), "input_files"));
// Remove any ns directory if it exists
if (nsDir.exists()) {
nsDir.delete();
}
outputDir.mkdir();
nsDir.mkdir();
outputFilesDir.mkdir();
inputFilesDir.mkdir();
StringBuilder inputfiles = new StringBuilder();
StringBuilder savenames = new StringBuilder();
List<String> savenamesList = new ArrayList<String>();
for (Entry<String, File> e : plateFilesMap.entrySet()) {
inputfiles.append(e.getValue().getPath() + ":");
savenames.append(e.getKey() + ":");
savenamesList.add(e.getKey());
}
String ninputfiles = inputfiles.substring(0, inputfiles.lastIndexOf(":"));
String nsavenames = savenames.substring(0, savenames.lastIndexOf(":"));
if (!job.doLinkage)
job.linkageCutoff = "-1";
// Prepare arguments
List<String> c = new ArrayList<String>();
c.add("Rscript");
c.add(Constants.RSCRIPT_PATH);
c.add("--inputfiles");
c.add(ninputfiles);
c.add("--savenames");
c.add(nsavenames);
c.add("--outputdir");
c.add(outputFilesDir.getPath());
c.add("--replicates");
c.add(job.replicates.toString());
c.add("--linkagecutoff");
c.add(job.linkageCutoff.toString());
c.add("--linkagegenes");
c.add(job.linkageGenes.toString());
c.add("--wd");
c.add(Constants.RSCRIPT_DIR);
if (!adfiles.toString().isEmpty()) {
c.add("--adfiles");
c.add(adfiles.toString());
c.add("--adname");
c.add(summaryAD);
}
if (job.doScoring) {
c.add("--score");
// c.add("--sfunction"); c.add(job.scoringFunction);
c.add("--sfunction");
c.add("1");
}
// Logger.info("#####"+c );
String zipFilePath = nsDir.getPath() + "normalizationscoring-sgatools-" + job.jobid + ".zip";
StringBuilder shell_output = new StringBuilder();
StringBuilder shell_output_error = new StringBuilder();
try {
// Try execute and read
Process p = Runtime.getRuntime().exec(c.toArray(new String[0]));
// Read in output returned from shell
// #########FOR DEBUG ONLY######
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
shell_output.append(line + "\n");
}
// Read in error input stream (if we have some error)
BufferedReader in_error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line_error;
while ((line_error = in_error.readLine()) != null) {
shell_output_error.append(line_error + "\n");
}
in_error.close();
// #############################
Logger.debug(shell_output.toString());
Logger.error(shell_output_error.toString());
// Zip files
Zipper.zipDir(zipFilePath, outputFilesDir.getPath());
} catch (Exception e) {
Logger.error(shell_output.toString());
Logger.error("===============================");
Logger.error(shell_output_error.toString());
// Fatal error
filledForm
.reject("plateFiles",
"Fatal error, no output files were produced. If this problem persists, please contact the developers with your input files");
return badRequest(nsform.render(filledForm, "", ""));
}
// Record time elapsed
long submissionEndTime = new Date().getTime(); // end time
long milliseconds = submissionEndTime - submissionStartTime; // check
// different
int seconds = (int) (milliseconds / 1000) % 60;
int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
Map<String, String> outputFilesMap = new HashMap<String, String>();
for (File of : outputFilesDir.listFiles()) {
if (!of.getName().startsWith("combined") && !of.getName().startsWith("README")
&& !of.getName().startsWith("scores"))
outputFilesMap.put(of.getName(), of.getPath());
}
// Save some objects
job.timeElapsed = minutes + " mins " + seconds + " secs";
job.outputFilesMap = outputFilesMap;
job.summaryAD = summaryAD;
// Save bound data to file
job.plateFilesMap = plateFilesMap;
job.downloadZipPath = zipFilePath.replace(Constants.BASE_PUBLIC_DIR, "");
writeJsonJobToFile(job, job.jobid);
// Direct to summary page
return redirect("/normalizationscoring/" + job.jobid);
}
| public static Result submit() {
// Get form
Form<NSjob> filledForm = nsForm.bindFromRequest();
// Logger.info(filledForm.data().toString());
// Process submission
long submissionStartTime = new Date().getTime(); // start time
// Get job
NSjob job = filledForm.get();
job.linkageGenes = job.linkageGenes.replaceAll("\n|\r", ",");
job.linkageGenes = job.linkageGenes.replaceAll("\\s", "");
Logger.debug("LINKAGE GENES = " + job.linkageGenes);
Map<String, File> plateFilesMap = new HashMap<String, File>();
// Get file(s) uploaded
MultipartFormData body = request().body().asMultipartFormData();
// Check if we have an array definition file
FilePart arrayDefCustomFile = body.getFile("arrayDefCustomFile");
// Logger.error(body.toString());
// Logger.info("JOBid = "+job.jobid);
if (job.jobid == null | job.jobid.isEmpty()) {
// Logger.info("Files uploaded, populating plate file map:");
List<FilePart> plateFiles = body.getFiles();
for (FilePart fp : plateFiles) {
// File f = fp.getFile();
// Logger.info("--> "+f.getPath() + "\t"+f.exists());
plateFilesMap.put(fp.getFilename(), fp.getFile());
}
} else {
// Logger.info("Files preloaded from IA, populating plate file map:");
IAjob iajob = IAcontroller.getJobFromJsonFile(job.jobid);
// Logger.info("selectedForNS = "+iajob.jsonSelectedForNS);
String[] preloadedList = Json.fromJson(Json.parse(iajob.jsonSelectedForNS), String[].class);
for (String fileName : preloadedList) {
File file = new File(
Utils.joinPath(Constants.JOB_OUTPUT_DIR, job.jobid, "ia", "output_files", fileName));
// Logger.info("\t"+fileName+" -> " + file.getPath());
plateFilesMap.put(fileName, file);
}
}
// Generate
List<String> adList = ComboboxOpts.arrayDef();
StringBuilder adfiles = new StringBuilder();
String summaryAD = "Not applied";
if (job.doArrayDef) {
// Custom file -ERROR HERE FILE NOT UPLOADING
if (adList.indexOf(job.arrayDefPredefined) == adList.size() - 1) {
// Logger.info("Found array definition file");
// Remove extra non plate files
plateFilesMap.remove(arrayDefCustomFile.getFilename());
adfiles.append(arrayDefCustomFile.getFile().getPath());
summaryAD = "Custom upload: " + arrayDefCustomFile.getFilename();
}
// Predefined array def
else if (job.selectedArrayDefPlate != null) {
String arrayDefDir = Constants.ARRAY_DEF_PATH + "/" + job.arrayDefPredefined;
summaryAD = job.arrayDefPredefined + " (";
List<String> adPlatesList = ComboboxOpts.arrayDefPlates(job.arrayDefPredefined);
if (adPlatesList.indexOf(job.selectedArrayDefPlate) == 0) {
// All plates
for (int i = 1; i < adPlatesList.size(); i++) {
adfiles.append(Utils.joinPath(arrayDefDir, adPlatesList.get(i)));
if (i < adPlatesList.size() - 1) {
adfiles.append(':');
}
}
summaryAD += "All plates";
} else {
// One plate
adfiles.append(Utils.joinPath(arrayDefDir, job.selectedArrayDefPlate));
summaryAD += job.selectedArrayDefPlate;
}
summaryAD += ")";
}
}
// Make directories for output
if (job.jobid.isEmpty() || job.jobid == null) {
job.jobid = UUID.randomUUID().toString();
// Logger.info("Generated new UUID: "+job.jobid);
}
File outputDir = new File(Utils.joinPath(Constants.JOB_OUTPUT_DIR, job.jobid));
File nsDir = new File(Utils.joinPath(outputDir.getPath(), "ns"));
File outputFilesDir = new File(Utils.joinPath(nsDir.getPath(), "output_files"));
File inputFilesDir = new File(Utils.joinPath(nsDir.getPath(), "input_files"));
// Remove any ns directory if it exists
if (nsDir.exists()) {
nsDir.delete();
}
outputDir.mkdir();
nsDir.mkdir();
outputFilesDir.mkdir();
inputFilesDir.mkdir();
StringBuilder inputfiles = new StringBuilder();
StringBuilder savenames = new StringBuilder();
List<String> savenamesList = new ArrayList<String>();
for (Entry<String, File> e : plateFilesMap.entrySet()) {
inputfiles.append(e.getValue().getPath() + ":");
savenames.append(e.getKey() + ":");
savenamesList.add(e.getKey());
}
String ninputfiles = inputfiles.substring(0, inputfiles.lastIndexOf(":"));
String nsavenames = savenames.substring(0, savenames.lastIndexOf(":"));
if (!job.doLinkage)
job.linkageCutoff = "-1";
// Prepare arguments
List<String> c = new ArrayList<String>();
c.add("Rscript");
c.add(Constants.RSCRIPT_PATH);
c.add("--inputfiles");
c.add(ninputfiles);
c.add("--savenames");
c.add(nsavenames);
c.add("--outputdir");
c.add(outputFilesDir.getPath());
c.add("--replicates");
c.add(job.replicates.toString());
c.add("--linkagecutoff");
c.add(job.linkageCutoff.toString());
c.add("--linkagegenes");
c.add(job.linkageGenes.toString());
c.add("--wd");
c.add(Constants.RSCRIPT_DIR);
if (!adfiles.toString().isEmpty()) {
c.add("--adfiles");
c.add(adfiles.toString());
c.add("--adname");
c.add(summaryAD);
}
if (job.doScoring) {
c.add("--score");
// c.add("--sfunction"); c.add(job.scoringFunction);
c.add("--sfunction");
c.add("1");
}
// Logger.info("#####"+c );
String zipFilePath = nsDir.getPath() + "normalizationscoring-sgatools-" + job.jobid + ".zip";
StringBuilder shell_output = new StringBuilder();
StringBuilder shell_output_error = new StringBuilder();
try {
// Try execute and read
Process p = Runtime.getRuntime().exec(c.toArray(new String[0]));
// Read in output returned from shell
// #########FOR DEBUG ONLY######
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
shell_output.append(line + "\n");
}
// Read in error input stream (if we have some error)
BufferedReader in_error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line_error;
while ((line_error = in_error.readLine()) != null) {
shell_output_error.append(line_error + "\n");
}
in_error.close();
// #############################
Logger.debug(shell_output.toString());
if (!shell_output_error.toString().isEmpty()) {
Logger.error(shell_output_error.toString());
}
// Zip files
Zipper.zipDir(zipFilePath, outputFilesDir.getPath());
} catch (Exception e) {
Logger.error(shell_output.toString());
Logger.error("===============================");
Logger.error(shell_output_error.toString());
// Fatal error
filledForm
.reject("plateFiles",
"Fatal error, no output files were produced. If this problem persists, please contact the developers with your input files");
return badRequest(nsform.render(filledForm, "", ""));
}
// Record time elapsed
long submissionEndTime = new Date().getTime(); // end time
long milliseconds = submissionEndTime - submissionStartTime; // check
// different
int seconds = (int) (milliseconds / 1000) % 60;
int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
Map<String, String> outputFilesMap = new HashMap<String, String>();
for (File of : outputFilesDir.listFiles()) {
if (!of.getName().startsWith("combined") && !of.getName().startsWith("README")
&& !of.getName().startsWith("scores"))
outputFilesMap.put(of.getName(), of.getPath());
}
// Save some objects
job.timeElapsed = minutes + " mins " + seconds + " secs";
job.outputFilesMap = outputFilesMap;
job.summaryAD = summaryAD;
// Save bound data to file
job.plateFilesMap = plateFilesMap;
job.downloadZipPath = zipFilePath.replace(Constants.BASE_PUBLIC_DIR, "");
writeJsonJobToFile(job, job.jobid);
// Direct to summary page
return redirect("/normalizationscoring/" + job.jobid);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.