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/spring-quartz/src/test/java/org/apache/archiva/redback/components/scheduler/JobOne.java b/spring-quartz/src/test/java/org/apache/archiva/redback/components/scheduler/JobOne.java
index 681d002..19de8a9 100644
--- a/spring-quartz/src/test/java/org/apache/archiva/redback/components/scheduler/JobOne.java
+++ b/spring-quartz/src/test/java/org/apache/archiva/redback/components/scheduler/JobOne.java
@@ -1,49 +1,48 @@
package org.apache.archiva.redback.components.scheduler;
/*
* 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.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
public class JobOne
implements Job
{
private Logger logger = LoggerFactory.getLogger( getClass() );
public JobOne()
{
}
public void execute( JobExecutionContext context )
throws JobExecutionException
{
logger.info(
- " --- Testing Scheduler Component\n --- " + context.getJobDetail().getDescription() + " executed.["
- + new Date() + "]" );
+ " --- Testing Scheduler Component --- {} executed.[{}]", context.getJobDetail().getDescription(), new Date() );
}
}
| true | true | public void execute( JobExecutionContext context )
throws JobExecutionException
{
logger.info(
" --- Testing Scheduler Component\n --- " + context.getJobDetail().getDescription() + " executed.["
+ new Date() + "]" );
}
| public void execute( JobExecutionContext context )
throws JobExecutionException
{
logger.info(
" --- Testing Scheduler Component --- {} executed.[{}]", context.getJobDetail().getDescription(), new Date() );
}
|
diff --git a/src/com/kremerk/commandprocessor/CommandServlet.java b/src/com/kremerk/commandprocessor/CommandServlet.java
index 0dca6e5..c417c2f 100644
--- a/src/com/kremerk/commandprocessor/CommandServlet.java
+++ b/src/com/kremerk/commandprocessor/CommandServlet.java
@@ -1,111 +1,112 @@
package com.kremerk.commandprocessor;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kremerk.commandprocessor.exception.CommandProcessorException;
import com.kremerk.commandprocessor.response.BinaryResponse;
import com.kremerk.commandprocessor.response.JsonResponse;
import com.kremerk.commandprocessor.response.Response;
import com.kremerk.commandprocessor.response.ResponseType;
public class CommandServlet extends HttpServlet {
public CommandServlet(CommandProcessor processor) {
this.cmdProcessor = processor;
}
/**
* The CRUDServlet expects to take a command and a series of parameters.
*
* <p>
* The url format is as follows:
*
* <P>
* http://server:port/cmd=MyCoolCommand¶m=1¶m=2¶m=blah
* http://server:port/CommandServletMapping/CommandSetName/CommandName/?param=1¶m=2¶m=blah
*
* <p>
* The implementation of the MyCoolCommand class will need to appropriately
* handle the params passed in in the given order.
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] commandParts = parseCommandParts(request);
String commandSetName = commandParts[0];
String commandName = commandParts[1];
- ResponseType rspType = ResponseType.getResponseTypeFromString(request.getParameter("type"));
+ String type = request.getParameter("type");
+ ResponseType rspType = ResponseType.getResponseTypeFromString(type);
String[] parameters = request.getParameterValues("param");
Response rsp = null;
try {
if (mockMode) {
cmdProcessor = new MockCommandProcessor(mockCommandRoot);
}
if(rspType == ResponseType.JSON) {
rsp = new JsonResponse(cmdProcessor.processCommand(commandSetName, commandName, parameters));
response.setContentType(rsp.getContentType());
response.getWriter().write((String) rsp.getResponse());
response.setStatus(HttpServletResponse.SC_OK);
}
else if(rspType == ResponseType.BINARY) {
rsp = new BinaryResponse(cmdProcessor.processBinaryCommand(commandSetName, commandName, parameters));
response.setContentType(rsp.getContentType());
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
out.write((byte[]) rsp.getResponse());
out.flush();
out.close();
}
else if(rspType == ResponseType.UNSUPPORTED){
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.format("Error executing command with type %s. Type %s is not supported.",rspType.getType(), rspType.getType()));
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.format("Error executing command with type %s. Type %s is not supported.",type, type));
}
else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Type must be supplied when calling a command");
}
} catch (CommandProcessorException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error executing command " + commandName);
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void setMockMode(boolean mockMode) {
this.mockMode = mockMode;
}
public boolean isMockMode() {
return mockMode;
}
public void setMockRoot(String rootDirectory, String commandRoot) {
mockCommandRoot = rootDirectory + File.separator + commandRoot;
}
public void setMockRoot(String commandRoot) {
setMockRoot(System.getProperty("user.dir"), commandRoot);
}
public String[] parseCommandParts(HttpServletRequest request) {
String path = request.getPathInfo();
path = path.replaceFirst("/", "");
return path.split("/");
}
private boolean mockMode = false;
private String mockCommandRoot;
private CommandProcessor cmdProcessor;
private static final long serialVersionUID = 8946402369349157361L;
}
| false | true | public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] commandParts = parseCommandParts(request);
String commandSetName = commandParts[0];
String commandName = commandParts[1];
ResponseType rspType = ResponseType.getResponseTypeFromString(request.getParameter("type"));
String[] parameters = request.getParameterValues("param");
Response rsp = null;
try {
if (mockMode) {
cmdProcessor = new MockCommandProcessor(mockCommandRoot);
}
if(rspType == ResponseType.JSON) {
rsp = new JsonResponse(cmdProcessor.processCommand(commandSetName, commandName, parameters));
response.setContentType(rsp.getContentType());
response.getWriter().write((String) rsp.getResponse());
response.setStatus(HttpServletResponse.SC_OK);
}
else if(rspType == ResponseType.BINARY) {
rsp = new BinaryResponse(cmdProcessor.processBinaryCommand(commandSetName, commandName, parameters));
response.setContentType(rsp.getContentType());
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
out.write((byte[]) rsp.getResponse());
out.flush();
out.close();
}
else if(rspType == ResponseType.UNSUPPORTED){
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.format("Error executing command with type %s. Type %s is not supported.",rspType.getType(), rspType.getType()));
}
else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Type must be supplied when calling a command");
}
} catch (CommandProcessorException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error executing command " + commandName);
return;
}
}
| public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] commandParts = parseCommandParts(request);
String commandSetName = commandParts[0];
String commandName = commandParts[1];
String type = request.getParameter("type");
ResponseType rspType = ResponseType.getResponseTypeFromString(type);
String[] parameters = request.getParameterValues("param");
Response rsp = null;
try {
if (mockMode) {
cmdProcessor = new MockCommandProcessor(mockCommandRoot);
}
if(rspType == ResponseType.JSON) {
rsp = new JsonResponse(cmdProcessor.processCommand(commandSetName, commandName, parameters));
response.setContentType(rsp.getContentType());
response.getWriter().write((String) rsp.getResponse());
response.setStatus(HttpServletResponse.SC_OK);
}
else if(rspType == ResponseType.BINARY) {
rsp = new BinaryResponse(cmdProcessor.processBinaryCommand(commandSetName, commandName, parameters));
response.setContentType(rsp.getContentType());
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
out.write((byte[]) rsp.getResponse());
out.flush();
out.close();
}
else if(rspType == ResponseType.UNSUPPORTED){
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.format("Error executing command with type %s. Type %s is not supported.",type, type));
}
else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Type must be supplied when calling a command");
}
} catch (CommandProcessorException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error executing command " + commandName);
return;
}
}
|
diff --git a/src/java/org/jivesoftware/sparkimpl/plugin/systray/SysTrayPlugin.java b/src/java/org/jivesoftware/sparkimpl/plugin/systray/SysTrayPlugin.java
index b12a529b..6778a183 100644
--- a/src/java/org/jivesoftware/sparkimpl/plugin/systray/SysTrayPlugin.java
+++ b/src/java/org/jivesoftware/sparkimpl/plugin/systray/SysTrayPlugin.java
@@ -1,334 +1,334 @@
package org.jivesoftware.sparkimpl.plugin.systray;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import org.jivesoftware.Spark;
import org.jivesoftware.resource.Default;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.MessageEventNotificationListener;
import org.jivesoftware.spark.NativeHandler;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.ui.PresenceListener;
import org.jivesoftware.spark.ui.status.CustomStatusItem;
import org.jivesoftware.spark.ui.status.StatusBar;
import org.jivesoftware.spark.ui.status.StatusItem;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;
public class SysTrayPlugin implements Plugin, NativeHandler, MessageEventNotificationListener {
private JPopupMenu popupMenu = new JPopupMenu();
private final JMenuItem openMenu = new JMenuItem(Res.getString("menuitem.open"));
private final JMenuItem minimizeMenu = new JMenuItem(Res.getString("menuitem.hide"));
private final JMenuItem exitMenu = new JMenuItem(Res.getString("menuitem.exit"));
private final JMenu statusMenu = new JMenu(Res.getString("menuitem.status"));
private final JMenuItem logoutMenu = new JMenuItem(Res.getString("menuitem.logout.no.status"));
private LocalPreferences pref = SettingsManager.getLocalPreferences();
private ImageIcon availableIcon;
private ImageIcon dndIcon;
private ImageIcon awayIcon;
private ImageIcon newMessageIcon;
private ImageIcon typingIcon;
private TrayIcon trayIcon;
public boolean canShutDown() {
return true;
}
public void initialize() {
SystemTray tray = SystemTray.getSystemTray();
SparkManager.getNativeManager().addNativeHandler(this);
SparkManager.getMessageEventManager().addMessageEventNotificationListener(this);
newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY);
typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY);
if (SystemTray.isSupported()) {
availableIcon = Default.getImageIcon(Default.TRAY_IMAGE);
if (availableIcon == null) {
availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE);
}
awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY);
dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND);
popupMenu.add(openMenu);
openMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
SparkManager.getMainWindow().setVisible(true);
SparkManager.getMainWindow().toFront();
}
});
popupMenu.add(minimizeMenu);
minimizeMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
SparkManager.getMainWindow().setVisible(false);
}
});
popupMenu.addSeparator();
addStatusMessages();
popupMenu.add(statusMenu);
statusMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
}
});
if (Spark.isWindows()) {
popupMenu.add(logoutMenu);
logoutMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
SparkManager.getMainWindow().logout(false);
}
});
}
// Exit Menu
exitMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
SparkManager.getMainWindow().shutdown();
}
});
popupMenu.add(exitMenu);
SparkManager.getSessionManager().addPresenceListener(new
PresenceListener() {
public void presenceChanged(Presence presence) {
if (presence.getMode() == Presence.Mode.available) {
trayIcon.setImage(availableIcon.getImage());
} else if (presence.getMode() == Presence.Mode.away) {
trayIcon.setImage(awayIcon.getImage());
} else if (presence.getMode() == Presence.Mode.dnd) {
trayIcon.setImage(dndIcon.getImage());
} else {
trayIcon.setImage(availableIcon.getImage());
}
}
});
try {
- trayIcon = new TrayIcon(availableIcon.getImage(), "Spark", null);
+ trayIcon = new TrayIcon(availableIcon.getImage(), Default.APPLICATION_NAME, null);
trayIcon.setImageAutoSize(true);
trayIcon.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent event) {
if (event.getButton() == MouseEvent.BUTTON1
&& event.getClickCount() == 1) {
if (SparkManager.getMainWindow().isVisible()) {
SparkManager.getMainWindow().setVisible(false);
} else {
SparkManager.getMainWindow().setVisible(true);
SparkManager.getMainWindow().toFront();
}
} else if (event.getButton() == MouseEvent.BUTTON1) {
SparkManager.getMainWindow().toFront();
// SparkManager.getMainWindow().requestFocus();
} else if (event.getButton() == MouseEvent.BUTTON3) {
popupMenu.setLocation(event.getX(), event.getY());
popupMenu.setInvoker(popupMenu);
popupMenu.setVisible(true);
}
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
});
tray.add(trayIcon);
} catch (Exception e) {
// Not Supported
}
}
}
public void addStatusMessages() {
StatusBar statusBar = SparkManager.getWorkspace().getStatusBar();
for (Object o : statusBar.getStatusList()) {
final StatusItem statusItem = (StatusItem) o;
final AbstractAction action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
StatusBar statusBar = SparkManager.getWorkspace()
.getStatusBar();
SparkManager.getSessionManager().changePresence(
statusItem.getPresence());
statusBar.setStatus(statusItem.getText());
}
};
action.putValue(Action.NAME, statusItem.getText());
action.putValue(Action.SMALL_ICON, statusItem.getIcon());
boolean hasChildren = false;
for (Object aCustom : SparkManager.getWorkspace().getStatusBar()
.getCustomStatusList()) {
final CustomStatusItem cItem = (CustomStatusItem) aCustom;
String type = cItem.getType();
if (type.equals(statusItem.getText())) {
hasChildren = true;
}
}
if (!hasChildren) {
JMenuItem status = new JMenuItem(action);
statusMenu.add(status);
} else {
final JMenu status = new JMenu(action);
statusMenu.add(status);
status.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
action.actionPerformed(null);
popupMenu.setVisible(false);
}
});
for (Object aCustom : SparkManager.getWorkspace()
.getStatusBar().getCustomStatusList()) {
final CustomStatusItem customItem = (CustomStatusItem) aCustom;
String type = customItem.getType();
if (type.equals(statusItem.getText())) {
AbstractAction customAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
StatusBar statusBar = SparkManager
.getWorkspace().getStatusBar();
Presence oldPresence = statusItem.getPresence();
Presence presence = StatusBar
.copyPresence(oldPresence);
presence.setStatus(customItem.getStatus());
presence.setPriority(customItem.getPriority());
SparkManager.getSessionManager()
.changePresence(presence);
statusBar.setStatus(statusItem.getName()
+ " - " + customItem.getStatus());
}
};
customAction.putValue(Action.NAME, customItem.getStatus());
customAction.putValue(Action.SMALL_ICON, statusItem.getIcon());
JMenuItem menuItem = new JMenuItem(customAction);
status.add(menuItem);
}
}
}
}
}
public void shutdown() {
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
tray.remove(trayIcon);
}
}
public void uninstall() {
}
// Info on new Messages
@Override
public void flashWindow(Window window) {
if (pref.isSystemTrayNotificationEnabled())
{
trayIcon.setImage(newMessageIcon.getImage());
}
}
@Override
public void flashWindowStopWhenFocused(Window window) {
trayIcon.setImage(availableIcon.getImage());
}
@Override
public boolean handleNotification() {
return true;
}
@Override
public void stopFlashing(Window window) {
trayIcon.setImage(availableIcon.getImage());
}
// For Typing
@Override
public void cancelledNotification(String from, String packetID) {
trayIcon.setImage(availableIcon.getImage());
}
@Override
public void composingNotification(String from, String packetID) {
if (pref.isTypingNotificationShown()) {
trayIcon.setImage(typingIcon.getImage());
}
}
@Override
public void deliveredNotification(String from, String packetID) {
// Nothing
}
@Override
public void displayedNotification(String from, String packetID) {
// Nothing
}
@Override
public void offlineNotification(String from, String packetID) {
// Nothing
}
}
| true | true | public void initialize() {
SystemTray tray = SystemTray.getSystemTray();
SparkManager.getNativeManager().addNativeHandler(this);
SparkManager.getMessageEventManager().addMessageEventNotificationListener(this);
newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY);
typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY);
if (SystemTray.isSupported()) {
availableIcon = Default.getImageIcon(Default.TRAY_IMAGE);
if (availableIcon == null) {
availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE);
}
awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY);
dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND);
popupMenu.add(openMenu);
openMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
SparkManager.getMainWindow().setVisible(true);
SparkManager.getMainWindow().toFront();
}
});
popupMenu.add(minimizeMenu);
minimizeMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
SparkManager.getMainWindow().setVisible(false);
}
});
popupMenu.addSeparator();
addStatusMessages();
popupMenu.add(statusMenu);
statusMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
}
});
if (Spark.isWindows()) {
popupMenu.add(logoutMenu);
logoutMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
SparkManager.getMainWindow().logout(false);
}
});
}
// Exit Menu
exitMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
SparkManager.getMainWindow().shutdown();
}
});
popupMenu.add(exitMenu);
SparkManager.getSessionManager().addPresenceListener(new
PresenceListener() {
public void presenceChanged(Presence presence) {
if (presence.getMode() == Presence.Mode.available) {
trayIcon.setImage(availableIcon.getImage());
} else if (presence.getMode() == Presence.Mode.away) {
trayIcon.setImage(awayIcon.getImage());
} else if (presence.getMode() == Presence.Mode.dnd) {
trayIcon.setImage(dndIcon.getImage());
} else {
trayIcon.setImage(availableIcon.getImage());
}
}
});
try {
trayIcon = new TrayIcon(availableIcon.getImage(), "Spark", null);
trayIcon.setImageAutoSize(true);
trayIcon.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent event) {
if (event.getButton() == MouseEvent.BUTTON1
&& event.getClickCount() == 1) {
if (SparkManager.getMainWindow().isVisible()) {
SparkManager.getMainWindow().setVisible(false);
} else {
SparkManager.getMainWindow().setVisible(true);
SparkManager.getMainWindow().toFront();
}
} else if (event.getButton() == MouseEvent.BUTTON1) {
SparkManager.getMainWindow().toFront();
// SparkManager.getMainWindow().requestFocus();
} else if (event.getButton() == MouseEvent.BUTTON3) {
popupMenu.setLocation(event.getX(), event.getY());
popupMenu.setInvoker(popupMenu);
popupMenu.setVisible(true);
}
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
});
tray.add(trayIcon);
} catch (Exception e) {
// Not Supported
}
}
}
| public void initialize() {
SystemTray tray = SystemTray.getSystemTray();
SparkManager.getNativeManager().addNativeHandler(this);
SparkManager.getMessageEventManager().addMessageEventNotificationListener(this);
newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY);
typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY);
if (SystemTray.isSupported()) {
availableIcon = Default.getImageIcon(Default.TRAY_IMAGE);
if (availableIcon == null) {
availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE);
}
awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY);
dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND);
popupMenu.add(openMenu);
openMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
SparkManager.getMainWindow().setVisible(true);
SparkManager.getMainWindow().toFront();
}
});
popupMenu.add(minimizeMenu);
minimizeMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
SparkManager.getMainWindow().setVisible(false);
}
});
popupMenu.addSeparator();
addStatusMessages();
popupMenu.add(statusMenu);
statusMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event) {
}
});
if (Spark.isWindows()) {
popupMenu.add(logoutMenu);
logoutMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
SparkManager.getMainWindow().logout(false);
}
});
}
// Exit Menu
exitMenu.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
SparkManager.getMainWindow().shutdown();
}
});
popupMenu.add(exitMenu);
SparkManager.getSessionManager().addPresenceListener(new
PresenceListener() {
public void presenceChanged(Presence presence) {
if (presence.getMode() == Presence.Mode.available) {
trayIcon.setImage(availableIcon.getImage());
} else if (presence.getMode() == Presence.Mode.away) {
trayIcon.setImage(awayIcon.getImage());
} else if (presence.getMode() == Presence.Mode.dnd) {
trayIcon.setImage(dndIcon.getImage());
} else {
trayIcon.setImage(availableIcon.getImage());
}
}
});
try {
trayIcon = new TrayIcon(availableIcon.getImage(), Default.APPLICATION_NAME, null);
trayIcon.setImageAutoSize(true);
trayIcon.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent event) {
if (event.getButton() == MouseEvent.BUTTON1
&& event.getClickCount() == 1) {
if (SparkManager.getMainWindow().isVisible()) {
SparkManager.getMainWindow().setVisible(false);
} else {
SparkManager.getMainWindow().setVisible(true);
SparkManager.getMainWindow().toFront();
}
} else if (event.getButton() == MouseEvent.BUTTON1) {
SparkManager.getMainWindow().toFront();
// SparkManager.getMainWindow().requestFocus();
} else if (event.getButton() == MouseEvent.BUTTON3) {
popupMenu.setLocation(event.getX(), event.getY());
popupMenu.setInvoker(popupMenu);
popupMenu.setVisible(true);
}
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
});
tray.add(trayIcon);
} catch (Exception e) {
// Not Supported
}
}
}
|
diff --git a/driver-core/src/main/java/com/datastax/driver/core/Connection.java b/driver-core/src/main/java/com/datastax/driver/core/Connection.java
index 481974bb1..17c3b9642 100644
--- a/driver-core/src/main/java/com/datastax/driver/core/Connection.java
+++ b/driver-core/src/main/java/com/datastax/driver/core/Connection.java
@@ -1,621 +1,622 @@
/*
* Copyright (C) 2012 DataStax Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.driver.core;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Uninterruptibles;
import com.datastax.driver.core.exceptions.AuthenticationException;
import com.datastax.driver.core.exceptions.DriverInternalError;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.transport.*;
import org.apache.cassandra.transport.messages.*;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// For LoggingHandler
//import org.jboss.netty.handler.logging.LoggingHandler;
//import org.jboss.netty.logging.InternalLogLevel;
/**
* A connection to a Cassandra Node.
*/
class Connection extends org.apache.cassandra.transport.Connection
{
public static final int MAX_STREAM_PER_CONNECTION = 128;
private static final Logger logger = LoggerFactory.getLogger(Connection.class);
// TODO: that doesn't belong here
private static final String CQL_VERSION = "3.0.0";
private static final org.apache.cassandra.transport.Connection.Tracker EMPTY_TRACKER = new org.apache.cassandra.transport.Connection.Tracker() {
@Override
public void addConnection(Channel ch, org.apache.cassandra.transport.Connection connection) {}
@Override
public void closeAll() {}
};
public final InetAddress address;
private final String name;
private final Channel channel;
private final Factory factory;
private final Dispatcher dispatcher = new Dispatcher();
// Used by connnection pooling to count how many requests are "in flight" on that connection.
public final AtomicInteger inFlight = new AtomicInteger(0);
private final AtomicInteger writer = new AtomicInteger(0);
private volatile boolean isClosed;
private volatile String keyspace;
private volatile boolean isDefunct;
private volatile ConnectionException exception;
/**
* Create a new connection to a Cassandra node.
*
* The connection is open and initialized by the constructor.
*
* @throws ConnectionException if the connection attempts fails or is
* refused by the server.
*/
private Connection(String name, InetAddress address, Factory factory) throws ConnectionException, InterruptedException {
super(EMPTY_TRACKER);
this.address = address;
this.factory = factory;
this.name = name;
ClientBootstrap bootstrap = factory.newBootstrap();
bootstrap.setPipelineFactory(new PipelineFactory(this));
ChannelFuture future = bootstrap.connect(new InetSocketAddress(address, factory.getPort()));
writer.incrementAndGet();
try {
// Wait until the connection attempt succeeds or fails.
this.channel = future.awaitUninterruptibly().getChannel();
this.factory.allChannels.add(this.channel);
if (!future.isSuccess())
{
if (logger.isDebugEnabled())
logger.debug(String.format("[%s] Error connecting to %s%s", name, address, extractMessage(future.getCause())));
throw new TransportException(address, "Cannot connect", future.getCause());
}
} finally {
writer.decrementAndGet();
}
logger.trace("[{}] Connection opened successfully", name);
initializeTransport();
logger.trace("[{}] Transport initialized and ready", name);
}
private static String extractMessage(Throwable t) {
if (t == null || t.getMessage().isEmpty())
return "";
return " (" + t.getMessage() + ")";
}
private void initializeTransport() throws ConnectionException, InterruptedException {
// TODO: we will need to get fancy about handling protocol version at
// some point, but keep it simple for now.
- Map<String, String> options = ImmutableMap.of(StartupMessage.CQL_VERSION, CQL_VERSION);
+ ImmutableMap.Builder<String, String> options = new ImmutableMap.Builder<String, String>();
+ options.put(StartupMessage.CQL_VERSION, CQL_VERSION);
ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
if (compression != ProtocolOptions.Compression.NONE)
{
options.put(StartupMessage.COMPRESSION, compression.toString());
setCompressor(compression.compressor());
}
- StartupMessage startup = new StartupMessage(options);
+ StartupMessage startup = new StartupMessage(options.build());
try {
Message.Response response = write(startup).get();
switch (response.type) {
case READY:
break;
case ERROR:
throw defunct(new TransportException(address, String.format("Error initializing connection: %s", ((ErrorMessage)response).error.getMessage())));
case AUTHENTICATE:
CredentialsMessage creds = new CredentialsMessage();
creds.credentials.putAll(factory.authProvider.getAuthInfo(address));
Message.Response authResponse = write(creds).get();
switch (authResponse.type) {
case READY:
break;
case ERROR:
throw new AuthenticationException(address, (((ErrorMessage)authResponse).error).getMessage());
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)));
}
break;
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
}
} catch (BusyConnectionException e) {
throw new DriverInternalError("Newly created connection should not be busy");
} catch (ExecutionException e) {
throw defunct(new ConnectionException(address, "Unexpected error during transport initialization", e.getCause()));
}
}
public boolean isDefunct() {
return isDefunct;
}
public ConnectionException lastException() {
return exception;
}
ConnectionException defunct(ConnectionException e) {
if (logger.isDebugEnabled())
logger.debug("Defuncting connection to " + address, e);
exception = e;
isDefunct = true;
dispatcher.errorOutAllHandler(e);
return e;
}
public String keyspace() {
return keyspace;
}
public void setKeyspace(String keyspace) throws ConnectionException {
if (keyspace == null)
return;
if (this.keyspace != null && this.keyspace.equals(keyspace))
return;
try {
logger.trace("[{}] Setting keyspace {}", name, keyspace);
Message.Response response = Uninterruptibles.getUninterruptibly(write(new QueryMessage("USE \"" + keyspace + "\"", ConsistencyLevel.DEFAULT_CASSANDRA_CL)));
switch (response.type) {
case RESULT:
this.keyspace = keyspace;
break;
default:
// The code set the keyspace only when a successful 'use'
// has been perform, so there shouldn't be any error here.
// It can happen however that the node we're connecting to
// is not up on the schema yet. In that case, defuncting
// the connection is not a bad choice.
defunct(new ConnectionException(address, String.format("Problem while setting keyspace, got %s as response", response)));
break;
}
} catch (ConnectionException e) {
throw defunct(e);
} catch (BusyConnectionException e) {
logger.error("Tried to set the keyspace on busy connection. This should not happen but is not critical");
} catch (ExecutionException e) {
throw defunct(new ConnectionException(address, "Error while setting keyspace", e));
}
}
/**
* Write a request on this connection.
*
* @param request the request to send
* @return a future on the server response
*
* @throws ConnectionException if the connection is closed
* @throws TransportException if an I/O error while sending the request
*/
public Future write(Message.Request request) throws ConnectionException, BusyConnectionException {
Future future = new Future(request);
write(future);
return future;
}
public void write(ResponseCallback callback) throws ConnectionException, BusyConnectionException {
Message.Request request = callback.request();
if (isDefunct)
throw new ConnectionException(address, "Write attempt on defunct connection");
if (isClosed)
throw new ConnectionException(address, "Connection has been closed");
request.attach(this);
ResponseHandler handler = new ResponseHandler(dispatcher, callback);
dispatcher.add(handler);
request.setStreamId(handler.streamId);
logger.trace("[{}] writing request {}", name, request);
writer.incrementAndGet();
channel.write(request).addListener(writeHandler(request, handler));
}
private ChannelFutureListener writeHandler(final Message.Request request, final ResponseHandler handler) {
return new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture writeFuture) {
writer.decrementAndGet();
if (!writeFuture.isSuccess()) {
logger.debug("[{}] Error writing request {}", name, request);
// Remove this handler from the dispatcher so it don't get notified of the error
// twice (we will fail that method already)
dispatcher.removeHandler(handler.streamId);
ConnectionException ce;
if (writeFuture.getCause() instanceof java.nio.channels.ClosedChannelException) {
ce = new TransportException(address, "Error writing: Closed channel");
} else {
ce = new TransportException(address, "Error writing", writeFuture.getCause());
}
handler.callback.onException(Connection.this, defunct(ce));
} else {
logger.trace("[{}] request sent successfully", name);
}
}
};
}
public void close() {
try {
close(0, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public boolean close(long timeout, TimeUnit unit) throws InterruptedException {
if (isClosed)
return true;
// Note: there is no guarantee only one thread will reach that point, but executing this
// method multiple time is harmless. If the latter change, we'll have to CAS isClosed to
// make sure this gets executed only once.
logger.trace("[{}] closing connection", name);
// Make sure all new writes are rejected
isClosed = true;
long start = System.nanoTime();
if (!isDefunct) {
// Busy waiting, we just wait for request to be fully written, shouldn't take long
while (writer.get() > 0 && Cluster.timeSince(start, unit) < timeout)
Uninterruptibles.sleepUninterruptibly(1, unit);
}
return channel.close().await(timeout - Cluster.timeSince(start, unit), unit);
// Note: we must not call releaseExternalResources on the bootstrap, because this shutdown the executors, which are shared
}
public boolean isClosed() {
return isClosed;
}
@Override
public String toString() {
return String.format("Connection[%s, inFlight=%d, closed=%b]", name, inFlight.get(), isClosed);
}
// Cruft needed because we reuse server side classes, but we don't care about it
public void validateNewMessage(Message.Type type) {};
public void applyStateTransition(Message.Type requestType, Message.Type responseType) {};
public ClientState clientState() { return null; };
public static class Factory {
private final ExecutorService bossExecutor = Executors.newCachedThreadPool();
private final ExecutorService workerExecutor = Executors.newCachedThreadPool();
private final ChannelFactory channelFactory = new NioClientSocketChannelFactory(bossExecutor, workerExecutor);
private final ChannelGroup allChannels = new DefaultChannelGroup();
private final ConcurrentMap<Host, AtomicInteger> idGenerators = new ConcurrentHashMap<Host, AtomicInteger>();
public final DefaultResponseHandler defaultHandler;
public final Configuration configuration;
public final AuthInfoProvider authProvider;
private volatile boolean isShutdown;
public Factory(Cluster.Manager manager, AuthInfoProvider authProvider) {
this(manager, manager.configuration, authProvider);
}
private Factory(DefaultResponseHandler defaultHandler, Configuration configuration, AuthInfoProvider authProvider) {
this.defaultHandler = defaultHandler;
this.configuration = configuration;
this.authProvider = authProvider;
}
public int getPort() {
return configuration.getProtocolOptions().getPort();
}
/**
* Opens a new connection to the node this factory points to.
*
* @return the newly created (and initialized) connection.
*
* @throws ConnectionException if connection attempt fails.
*/
public Connection open(Host host) throws ConnectionException, InterruptedException {
InetAddress address = host.getAddress();
if (isShutdown)
throw new ConnectionException(address, "Connection factory is shut down");
String name = address.toString() + "-" + getIdGenerator(host).getAndIncrement();
return new Connection(name, address, this);
}
private AtomicInteger getIdGenerator(Host host) {
AtomicInteger g = idGenerators.get(host);
if (g == null) {
g = new AtomicInteger(1);
AtomicInteger old = idGenerators.putIfAbsent(host, g);
if (old != null)
g = old;
}
return g;
}
private ClientBootstrap newBootstrap() {
ClientBootstrap b = new ClientBootstrap(channelFactory);
SocketOptions options = configuration.getSocketOptions();
b.setOption("connectTimeoutMillis", options.getConnectTimeoutMillis());
Boolean keepAlive = options.getKeepAlive();
if (keepAlive != null)
b.setOption("keepAlive", keepAlive);
Boolean reuseAddress = options.getReuseAddress();
if (reuseAddress != null)
b.setOption("reuseAddress", reuseAddress);
Integer soLinger = options.getSoLinger();
if (soLinger != null)
b.setOption("soLinger", soLinger);
Boolean tcpNoDelay = options.getTcpNoDelay();
if (tcpNoDelay != null)
b.setOption("tcpNoDelay", tcpNoDelay);
Integer receiveBufferSize = options.getReceiveBufferSize();
if (receiveBufferSize != null)
b.setOption("receiveBufferSize", receiveBufferSize);
Integer sendBufferSize = options.getSendBufferSize();
if (sendBufferSize != null)
b.setOption("sendBufferSize", sendBufferSize);
return b;
}
public boolean shutdown(long timeout, TimeUnit unit) throws InterruptedException {
// Make sure we skip creating connection from now on.
isShutdown = true;
long start = System.nanoTime();
ChannelGroupFuture future = allChannels.close();
channelFactory.releaseExternalResources();
return future.await(timeout, unit)
&& bossExecutor.awaitTermination(timeout - Cluster.timeSince(start, unit), unit)
&& workerExecutor.awaitTermination(timeout - Cluster.timeSince(start, unit), unit);
}
}
private class Dispatcher extends SimpleChannelUpstreamHandler {
public final StreamIdGenerator streamIdHandler = new StreamIdGenerator();
private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>();
public void add(ResponseHandler handler) {
ResponseHandler old = pending.put(handler.streamId, handler);
assert old == null;
}
public void removeHandler(int streamId) {
pending.remove(streamId);
streamIdHandler.release(streamId);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
if (!(e.getMessage() instanceof Message.Response)) {
logger.error("[{}] Received unexpected message: {}", name, e.getMessage());
defunct(new TransportException(address, "Unexpected message received: " + e.getMessage()));
} else {
Message.Response response = (Message.Response)e.getMessage();
int streamId = response.getStreamId();
logger.trace("[{}] received: {}", name, e.getMessage());
if (streamId < 0) {
factory.defaultHandler.handle(response);
return;
}
ResponseHandler handler = pending.remove(streamId);
streamIdHandler.release(streamId);
if (handler == null) {
// Note: this is a bug, either us or cassandra. So log it, but I'm not sure it's worth breaking
// the connection for that.
logger.error("[{}] No handler set for stream {} (this is a bug, either of this driver or of Cassandra, you should report it)", name, streamId);
return;
}
handler.callback.onSet(Connection.this, response);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
if (logger.isTraceEnabled())
logger.trace(String.format("[%s] connection error", name), e.getCause());
// Ignore exception while writing, this will be handled by write() directly
if (writer.get() > 0)
return;
defunct(new TransportException(address, "Unexpected exception triggered", e.getCause()));
}
public void errorOutAllHandler(ConnectionException ce) {
Iterator<ResponseHandler> iter = pending.values().iterator();
while (iter.hasNext())
{
iter.next().callback.onException(Connection.this, ce);
iter.remove();
}
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
{
// If we've closed the channel server side then we don't really want to defunct the connection, but
// if there is remaining thread waiting on us, we still want to wake them up
if (isClosed)
errorOutAllHandler(new TransportException(address, "Channel has been closed"));
else
defunct(new TransportException(address, "Channel has been closed"));
}
}
static class Future extends SimpleFuture<Message.Response> implements RequestHandler.Callback {
private final Message.Request request;
private volatile InetAddress address;
public Future(Message.Request request) {
this.request = request;
}
@Override
public Message.Request request() {
return request;
}
@Override
public void onSet(Connection connection, Message.Response response, ExecutionInfo info) {
onSet(connection, response);
}
@Override
public void onSet(Connection connection, Message.Response response) {
this.address = connection.address;
super.set(response);
}
@Override
public void onException(Connection connection, Exception exception) {
super.setException(exception);
}
public InetAddress getAddress() {
return address;
}
}
interface ResponseCallback {
public Message.Request request();
public void onSet(Connection connection, Message.Response response);
public void onException(Connection connection, Exception exception);
}
private static class ResponseHandler {
public final int streamId;
public final ResponseCallback callback;
public ResponseHandler(Dispatcher dispatcher, ResponseCallback callback) throws BusyConnectionException {
this.streamId = dispatcher.streamIdHandler.next();
this.callback = callback;
}
}
public interface DefaultResponseHandler {
public void handle(Message.Response response);
}
private static class PipelineFactory implements ChannelPipelineFactory {
// Stateless handlers
private static final Message.ProtocolDecoder messageDecoder = new Message.ProtocolDecoder();
private static final Message.ProtocolEncoder messageEncoder = new Message.ProtocolEncoder();
private static final Frame.Decompressor frameDecompressor = new Frame.Decompressor();
private static final Frame.Compressor frameCompressor = new Frame.Compressor();
private static final Frame.Encoder frameEncoder = new Frame.Encoder();
// One more fallout of using server side classes; not a big deal
private static final org.apache.cassandra.transport.Connection.Tracker tracker;
static {
tracker = new org.apache.cassandra.transport.Connection.Tracker() {
@Override
public void addConnection(Channel ch, org.apache.cassandra.transport.Connection connection) {}
@Override
public void closeAll() {}
};
}
private final Connection connection;
private final org.apache.cassandra.transport.Connection.Factory cfactory;
public PipelineFactory(final Connection connection) {
this.connection = connection;
this.cfactory = new org.apache.cassandra.transport.Connection.Factory() {
@Override
public Connection newConnection(org.apache.cassandra.transport.Connection.Tracker tracker) {
return connection;
}
};
}
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
//pipeline.addLast("debug", new LoggingHandler(InternalLogLevel.INFO));
pipeline.addLast("frameDecoder", new Frame.Decoder(tracker, cfactory));
pipeline.addLast("frameEncoder", frameEncoder);
pipeline.addLast("frameDecompressor", frameDecompressor);
pipeline.addLast("frameCompressor", frameCompressor);
pipeline.addLast("messageDecoder", messageDecoder);
pipeline.addLast("messageEncoder", messageEncoder);
pipeline.addLast("dispatcher", connection.dispatcher);
return pipeline;
}
}
}
| false | true | private void initializeTransport() throws ConnectionException, InterruptedException {
// TODO: we will need to get fancy about handling protocol version at
// some point, but keep it simple for now.
Map<String, String> options = ImmutableMap.of(StartupMessage.CQL_VERSION, CQL_VERSION);
ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
if (compression != ProtocolOptions.Compression.NONE)
{
options.put(StartupMessage.COMPRESSION, compression.toString());
setCompressor(compression.compressor());
}
StartupMessage startup = new StartupMessage(options);
try {
Message.Response response = write(startup).get();
switch (response.type) {
case READY:
break;
case ERROR:
throw defunct(new TransportException(address, String.format("Error initializing connection: %s", ((ErrorMessage)response).error.getMessage())));
case AUTHENTICATE:
CredentialsMessage creds = new CredentialsMessage();
creds.credentials.putAll(factory.authProvider.getAuthInfo(address));
Message.Response authResponse = write(creds).get();
switch (authResponse.type) {
case READY:
break;
case ERROR:
throw new AuthenticationException(address, (((ErrorMessage)authResponse).error).getMessage());
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)));
}
break;
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
}
} catch (BusyConnectionException e) {
throw new DriverInternalError("Newly created connection should not be busy");
} catch (ExecutionException e) {
throw defunct(new ConnectionException(address, "Unexpected error during transport initialization", e.getCause()));
}
}
| private void initializeTransport() throws ConnectionException, InterruptedException {
// TODO: we will need to get fancy about handling protocol version at
// some point, but keep it simple for now.
ImmutableMap.Builder<String, String> options = new ImmutableMap.Builder<String, String>();
options.put(StartupMessage.CQL_VERSION, CQL_VERSION);
ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
if (compression != ProtocolOptions.Compression.NONE)
{
options.put(StartupMessage.COMPRESSION, compression.toString());
setCompressor(compression.compressor());
}
StartupMessage startup = new StartupMessage(options.build());
try {
Message.Response response = write(startup).get();
switch (response.type) {
case READY:
break;
case ERROR:
throw defunct(new TransportException(address, String.format("Error initializing connection: %s", ((ErrorMessage)response).error.getMessage())));
case AUTHENTICATE:
CredentialsMessage creds = new CredentialsMessage();
creds.credentials.putAll(factory.authProvider.getAuthInfo(address));
Message.Response authResponse = write(creds).get();
switch (authResponse.type) {
case READY:
break;
case ERROR:
throw new AuthenticationException(address, (((ErrorMessage)authResponse).error).getMessage());
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)));
}
break;
default:
throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
}
} catch (BusyConnectionException e) {
throw new DriverInternalError("Newly created connection should not be busy");
} catch (ExecutionException e) {
throw defunct(new ConnectionException(address, "Unexpected error during transport initialization", e.getCause()));
}
}
|
diff --git a/app/controllers/StreamRulesController.java b/app/controllers/StreamRulesController.java
index 70c37b4a..5130ef14 100644
--- a/app/controllers/StreamRulesController.java
+++ b/app/controllers/StreamRulesController.java
@@ -1,110 +1,108 @@
package controllers;
import com.google.gson.Gson;
import com.google.inject.Inject;
import lib.APIException;
import lib.ApiClient;
import lib.BreadcrumbList;
import models.Stream;
import models.StreamRule;
import models.StreamRuleService;
import models.StreamService;
import models.api.requests.streams.CreateStreamRuleRequest;
import models.api.responses.streams.CreateStreamRuleResponse;
import play.data.Form;
import play.mvc.Result;
import java.io.IOException;
/**
* @author Dennis Oelkers <[email protected]>
*/
public class StreamRulesController extends AuthenticatedController {
private static final Form<CreateStreamRuleRequest> createStreamRuleForm = Form.form(CreateStreamRuleRequest.class);
@Inject
private StreamService streamService;
@Inject
private StreamRuleService streamRuleService;
public Result index(String streamId) {
Stream stream;
try {
stream = streamService.get(streamId);
} catch (APIException e) {
String message = "Could not fetch stream rules. We expect HTTP 200, but got a HTTP " + e.getHttpCode() + ".";
return status(504, views.html.errors.error.render(message, e, request()));
} catch (IOException e) {
return status(504, views.html.errors.error.render(ApiClient.ERROR_MSG_IO, e, request()));
}
return ok(views.html.streamrules.index.render(currentUser(), stream, stream.getStreamRules(), standardBreadcrumbs(stream)));
}
public Result create(String streamId) {
Form<CreateStreamRuleRequest> form = createStreamRuleForm.bindFromRequest();
CreateStreamRuleResponse response = null;
try {
CreateStreamRuleRequest csrr = form.get();
response = streamRuleService.create(streamId, csrr);
/*if (request().accepts("application/json"))
return created(new Gson().toJson(response)).as("application/json");
else {*/
StreamRule streamRule = streamRuleService.get(streamId, response.streamrule_id);
return created(views.html.partials.streamrules.list_item.render(streamRule));
//}
} catch (APIException e) {
String message = "Could not create stream rule. We expected HTTP 201, but got a HTTP " + e.getHttpCode() + ".";
return status(504, message);
} catch (IOException e) {
return status(504, e.toString());
}
}
public Result update(String streamId, String streamRuleId) {
Form<CreateStreamRuleRequest> form = createStreamRuleForm.bindFromRequest();
CreateStreamRuleResponse response = null;
try {
CreateStreamRuleRequest csrr = form.get();
response = streamRuleService.update(streamId, streamRuleId, csrr);
- System.out.println(request().accepts("application/json"));
/*if (request().accepts("application/json"))
return created(new Gson().toJson(response)).as("application/json");
else {*/
StreamRule streamRule = streamRuleService.get(streamId, response.streamrule_id);
return created(views.html.partials.streamrules.list_item.render(streamRule));
//}
} catch (APIException e) {
String message = "Could not create stream rule. We expected HTTP 200, but got a HTTP " + e.getHttpCode() + ".";
- System.out.println(message);
return status(504, message);
} catch (IOException e) {
return status(504, e.toString());
}
}
public Result delete(String streamId, String streamRuleId){
try {
streamRuleService.delete(streamId, streamRuleId);
} catch (APIException e) {
String message = "Could not delete stream rule. We expect HTTP 204, but got a HTTP " + e.getHttpCode() + ".";
return status(504, views.html.errors.error.render(message, e, request()));
} catch (IOException e) {
return status(504, views.html.errors.error.render(ApiClient.ERROR_MSG_IO, e, request()));
}
return ok();
}
private static BreadcrumbList standardBreadcrumbs(Stream stream) {
BreadcrumbList bc = new BreadcrumbList();
bc.addCrumb("All Streams", routes.StreamsController.index());
bc.addCrumb("Stream: " + stream.getTitle(), null);
return bc;
}
}
| false | true | public Result create(String streamId) {
Form<CreateStreamRuleRequest> form = createStreamRuleForm.bindFromRequest();
CreateStreamRuleResponse response = null;
try {
CreateStreamRuleRequest csrr = form.get();
response = streamRuleService.create(streamId, csrr);
/*if (request().accepts("application/json"))
return created(new Gson().toJson(response)).as("application/json");
else {*/
StreamRule streamRule = streamRuleService.get(streamId, response.streamrule_id);
return created(views.html.partials.streamrules.list_item.render(streamRule));
//}
} catch (APIException e) {
String message = "Could not create stream rule. We expected HTTP 201, but got a HTTP " + e.getHttpCode() + ".";
return status(504, message);
} catch (IOException e) {
return status(504, e.toString());
}
}
public Result update(String streamId, String streamRuleId) {
Form<CreateStreamRuleRequest> form = createStreamRuleForm.bindFromRequest();
CreateStreamRuleResponse response = null;
try {
CreateStreamRuleRequest csrr = form.get();
response = streamRuleService.update(streamId, streamRuleId, csrr);
System.out.println(request().accepts("application/json"));
/*if (request().accepts("application/json"))
return created(new Gson().toJson(response)).as("application/json");
else {*/
StreamRule streamRule = streamRuleService.get(streamId, response.streamrule_id);
return created(views.html.partials.streamrules.list_item.render(streamRule));
//}
} catch (APIException e) {
String message = "Could not create stream rule. We expected HTTP 200, but got a HTTP " + e.getHttpCode() + ".";
System.out.println(message);
return status(504, message);
} catch (IOException e) {
return status(504, e.toString());
}
}
public Result delete(String streamId, String streamRuleId){
try {
streamRuleService.delete(streamId, streamRuleId);
} catch (APIException e) {
String message = "Could not delete stream rule. We expect HTTP 204, but got a HTTP " + e.getHttpCode() + ".";
return status(504, views.html.errors.error.render(message, e, request()));
} catch (IOException e) {
return status(504, views.html.errors.error.render(ApiClient.ERROR_MSG_IO, e, request()));
}
return ok();
}
private static BreadcrumbList standardBreadcrumbs(Stream stream) {
BreadcrumbList bc = new BreadcrumbList();
bc.addCrumb("All Streams", routes.StreamsController.index());
bc.addCrumb("Stream: " + stream.getTitle(), null);
return bc;
}
}
| public Result create(String streamId) {
Form<CreateStreamRuleRequest> form = createStreamRuleForm.bindFromRequest();
CreateStreamRuleResponse response = null;
try {
CreateStreamRuleRequest csrr = form.get();
response = streamRuleService.create(streamId, csrr);
/*if (request().accepts("application/json"))
return created(new Gson().toJson(response)).as("application/json");
else {*/
StreamRule streamRule = streamRuleService.get(streamId, response.streamrule_id);
return created(views.html.partials.streamrules.list_item.render(streamRule));
//}
} catch (APIException e) {
String message = "Could not create stream rule. We expected HTTP 201, but got a HTTP " + e.getHttpCode() + ".";
return status(504, message);
} catch (IOException e) {
return status(504, e.toString());
}
}
public Result update(String streamId, String streamRuleId) {
Form<CreateStreamRuleRequest> form = createStreamRuleForm.bindFromRequest();
CreateStreamRuleResponse response = null;
try {
CreateStreamRuleRequest csrr = form.get();
response = streamRuleService.update(streamId, streamRuleId, csrr);
/*if (request().accepts("application/json"))
return created(new Gson().toJson(response)).as("application/json");
else {*/
StreamRule streamRule = streamRuleService.get(streamId, response.streamrule_id);
return created(views.html.partials.streamrules.list_item.render(streamRule));
//}
} catch (APIException e) {
String message = "Could not create stream rule. We expected HTTP 200, but got a HTTP " + e.getHttpCode() + ".";
return status(504, message);
} catch (IOException e) {
return status(504, e.toString());
}
}
public Result delete(String streamId, String streamRuleId){
try {
streamRuleService.delete(streamId, streamRuleId);
} catch (APIException e) {
String message = "Could not delete stream rule. We expect HTTP 204, but got a HTTP " + e.getHttpCode() + ".";
return status(504, views.html.errors.error.render(message, e, request()));
} catch (IOException e) {
return status(504, views.html.errors.error.render(ApiClient.ERROR_MSG_IO, e, request()));
}
return ok();
}
private static BreadcrumbList standardBreadcrumbs(Stream stream) {
BreadcrumbList bc = new BreadcrumbList();
bc.addCrumb("All Streams", routes.StreamsController.index());
bc.addCrumb("Stream: " + stream.getTitle(), null);
return bc;
}
}
|
diff --git a/utils/src/main/java/org/apache/ode/utils/LoggingInterceptor.java b/utils/src/main/java/org/apache/ode/utils/LoggingInterceptor.java
index 5aed0aacb..1368f7c85 100644
--- a/utils/src/main/java/org/apache/ode/utils/LoggingInterceptor.java
+++ b/utils/src/main/java/org/apache/ode/utils/LoggingInterceptor.java
@@ -1,161 +1,161 @@
package org.apache.ode.utils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
public class LoggingInterceptor<T> implements InvocationHandler {
private static final Set<String> PARAMSTYPES = new HashSet<String>();
static {
PARAMSTYPES.add("setArray");
PARAMSTYPES.add("setBigDecimal");
PARAMSTYPES.add("setBoolean");
PARAMSTYPES.add("setByte");
PARAMSTYPES.add("setBytes");
PARAMSTYPES.add("setDate");
PARAMSTYPES.add("setDouble");
PARAMSTYPES.add("setFloat");
PARAMSTYPES.add("setInt");
PARAMSTYPES.add("setLong");
PARAMSTYPES.add("setObject");
PARAMSTYPES.add("setRef");
PARAMSTYPES.add("setShort");
PARAMSTYPES.add("setString");
PARAMSTYPES.add("setTime");
PARAMSTYPES.add("setTimestamp");
PARAMSTYPES.add("setURL");
}
private Log _log;
private T _delegate;
private TreeMap<String, Object> _paramsByName = new TreeMap<String, Object>();
private TreeMap<Integer, Object> _paramsByIdx = new TreeMap<Integer, Object>();
public LoggingInterceptor(T delegate, Log log) {
_log = log;
_delegate = delegate;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
try {
if (method.getDeclaringClass() == DataSource.class
&& "getConnection".equals(method.getName())) {
Connection conn = (Connection)method.invoke(_delegate, args);
print("getConnection (tx=" + conn.getTransactionIsolation() + ")");
return Proxy.newProxyInstance(_delegate.getClass().getClassLoader(),
new Class[] {Connection.class}, new LoggingInterceptor<Connection>(conn, _log));
} else if (method.getDeclaringClass() == Connection.class
&& Statement.class.isAssignableFrom(method.getReturnType())) {
Statement stmt = (Statement)method.invoke(_delegate, args);
print(method, args);
return Proxy.newProxyInstance(_delegate.getClass().getClassLoader(),
new Class[] {method.getReturnType()}, new LoggingInterceptor<Statement>(stmt, _log));
} else {
print(method, args);
return method.invoke(_delegate, args);
}
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
private void print(Method method, Object[] args) {
if (shouldPrint()) {
// JDBC Connection
- if ("prepareStmt".equals(method.getName())) {
+ if ("prepareStatement".equals(method.getName())) {
print("prepareStmt: " + args[0]);
if (((String)args[0]).indexOf("ODE_SCOPE") > 0) {
for (StackTraceElement traceElement : Thread.currentThread().getStackTrace()) {
print(traceElement.toString());
}
}
} else if ("prepareCall".equals(method.getName())) {
print("prepareCall: " + args[0]);
} else if ("close".equals(method.getName())) {
print("close()");
} else if ("commit".equals(method.getName())) {
print("commit()");
} else if ("rollback".equals(method.getName())) {
print("rollback()");
} else if ("setTransactionIsolation".equals(method.getName())) {
print("Set isolation level to " + args[0]);
}
// JDBC Statement
else if (method.getName().startsWith("execute")) {
print(method.getName() + ", " + getParams());
} else if ("clearParameters".equals(method.getName())) {
_paramsByIdx.clear();
_paramsByName.clear();
} else if ("setNull".equals(method.getName())) {
if (String.class.isAssignableFrom(args[0].getClass())) {
_paramsByName.put((String)args[0], null);
} else if (Integer.class.isAssignableFrom(args[0].getClass())) {
_paramsByIdx.put((Integer)args[0], null);
}
} else if (PARAMSTYPES.contains(method.getName())){
if (String.class.isAssignableFrom(args[0].getClass())) {
_paramsByName.put((String)args[0], args[1]);
} else if (Integer.class.isAssignableFrom(args[0].getClass())) {
_paramsByIdx.put((Integer)args[0], args[1]);
}
}
}
}
private String getParams() {
if (_paramsByIdx.size() > 0 || _paramsByName.size() > 0) {
StringBuffer buf = new StringBuffer();
buf.append("bound ");
for (Map.Entry<Integer, Object> entry : _paramsByIdx.entrySet()) {
try {
buf.append("(").append(entry.getKey()).append(",").append(entry.getValue()).append(") ");
} catch (Throwable e) {
// We don't want to mess with the connection just for logging
return "[e]";
}
}
for (Map.Entry<String, Object> entry : _paramsByName.entrySet()) {
try {
buf.append("(").append(entry.getKey()).append(",").append(entry.getValue()).append(") ");
} catch (Throwable e) {
// We don't want to mess with the connection just for logging
return "[e]";
}
}
return buf.toString();
}
return "w/o params";
}
private boolean shouldPrint() {
if (_log != null)
return _log.isDebugEnabled();
else return true;
}
private void print(String str) {
if (_log != null)
_log.debug(str);
else System.out.println(str);
}
public static DataSource createLoggingDS(DataSource ds, Log log) {
return (DataSource)Proxy.newProxyInstance(ds.getClass().getClassLoader(),
new Class[] {DataSource.class}, new LoggingInterceptor<DataSource>(ds,log));
}
}
| true | true | private void print(Method method, Object[] args) {
if (shouldPrint()) {
// JDBC Connection
if ("prepareStmt".equals(method.getName())) {
print("prepareStmt: " + args[0]);
if (((String)args[0]).indexOf("ODE_SCOPE") > 0) {
for (StackTraceElement traceElement : Thread.currentThread().getStackTrace()) {
print(traceElement.toString());
}
}
} else if ("prepareCall".equals(method.getName())) {
print("prepareCall: " + args[0]);
} else if ("close".equals(method.getName())) {
print("close()");
} else if ("commit".equals(method.getName())) {
print("commit()");
} else if ("rollback".equals(method.getName())) {
print("rollback()");
} else if ("setTransactionIsolation".equals(method.getName())) {
print("Set isolation level to " + args[0]);
}
// JDBC Statement
else if (method.getName().startsWith("execute")) {
print(method.getName() + ", " + getParams());
} else if ("clearParameters".equals(method.getName())) {
_paramsByIdx.clear();
_paramsByName.clear();
} else if ("setNull".equals(method.getName())) {
if (String.class.isAssignableFrom(args[0].getClass())) {
_paramsByName.put((String)args[0], null);
} else if (Integer.class.isAssignableFrom(args[0].getClass())) {
_paramsByIdx.put((Integer)args[0], null);
}
} else if (PARAMSTYPES.contains(method.getName())){
if (String.class.isAssignableFrom(args[0].getClass())) {
_paramsByName.put((String)args[0], args[1]);
} else if (Integer.class.isAssignableFrom(args[0].getClass())) {
_paramsByIdx.put((Integer)args[0], args[1]);
}
}
}
}
| private void print(Method method, Object[] args) {
if (shouldPrint()) {
// JDBC Connection
if ("prepareStatement".equals(method.getName())) {
print("prepareStmt: " + args[0]);
if (((String)args[0]).indexOf("ODE_SCOPE") > 0) {
for (StackTraceElement traceElement : Thread.currentThread().getStackTrace()) {
print(traceElement.toString());
}
}
} else if ("prepareCall".equals(method.getName())) {
print("prepareCall: " + args[0]);
} else if ("close".equals(method.getName())) {
print("close()");
} else if ("commit".equals(method.getName())) {
print("commit()");
} else if ("rollback".equals(method.getName())) {
print("rollback()");
} else if ("setTransactionIsolation".equals(method.getName())) {
print("Set isolation level to " + args[0]);
}
// JDBC Statement
else if (method.getName().startsWith("execute")) {
print(method.getName() + ", " + getParams());
} else if ("clearParameters".equals(method.getName())) {
_paramsByIdx.clear();
_paramsByName.clear();
} else if ("setNull".equals(method.getName())) {
if (String.class.isAssignableFrom(args[0].getClass())) {
_paramsByName.put((String)args[0], null);
} else if (Integer.class.isAssignableFrom(args[0].getClass())) {
_paramsByIdx.put((Integer)args[0], null);
}
} else if (PARAMSTYPES.contains(method.getName())){
if (String.class.isAssignableFrom(args[0].getClass())) {
_paramsByName.put((String)args[0], args[1]);
} else if (Integer.class.isAssignableFrom(args[0].getClass())) {
_paramsByIdx.put((Integer)args[0], args[1]);
}
}
}
}
|
diff --git a/platform/android/src/org/geometerplus/zlibrary/ui/android/library/BugReportActivity.java b/platform/android/src/org/geometerplus/zlibrary/ui/android/library/BugReportActivity.java
index 1bd7c34c..a14a6b21 100644
--- a/platform/android/src/org/geometerplus/zlibrary/ui/android/library/BugReportActivity.java
+++ b/platform/android/src/org/geometerplus/zlibrary/ui/android/library/BugReportActivity.java
@@ -1,68 +1,74 @@
/*
* Copyright (C) 2007-2009 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.ui.android.library;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.text.method.ScrollingMovementMethod;
import android.graphics.Typeface;
import org.geometerplus.zlibrary.ui.android.R;
public class BugReportActivity extends Activity {
static final String STACKTRACE = "fbreader.stacktrace";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bug_report_view);
final String stackTrace = getIntent().getStringExtra(STACKTRACE);
final TextView reportTextView = (TextView)findViewById(R.id.report_text);
reportTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
reportTextView.setClickable(false);
reportTextView.setLongClickable(false);
- reportTextView.append("FBReader has been crached, sorry. You can help to fix this bug by sending the report below to FBReader developers. The report will be sent by e-mail. Thank you in advance!\n\n");
+ String v = null;
+ try {
+ v = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
+ } catch (Exception e) {
+ }
+ final String versionName = (v != null) ? v : "?.?.?";
+ reportTextView.append("FBReader " + versionName + " has been crached, sorry. You can help to fix this bug by sending the report below to FBReader developers. The report will be sent by e-mail. Thank you in advance!\n\n");
reportTextView.append(stackTrace);
findViewById(R.id.send_report).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
sendIntent.putExtra(Intent.EXTRA_TEXT, stackTrace);
- sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + android.R.styleable.AndroidManifest_versionName + " exception report");
+ sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + versionName + " exception report");
sendIntent.setType("message/rfc822");
startActivity(sendIntent);
finish();
}
}
);
findViewById(R.id.cancel_report).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
finish();
}
}
);
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bug_report_view);
final String stackTrace = getIntent().getStringExtra(STACKTRACE);
final TextView reportTextView = (TextView)findViewById(R.id.report_text);
reportTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
reportTextView.setClickable(false);
reportTextView.setLongClickable(false);
reportTextView.append("FBReader has been crached, sorry. You can help to fix this bug by sending the report below to FBReader developers. The report will be sent by e-mail. Thank you in advance!\n\n");
reportTextView.append(stackTrace);
findViewById(R.id.send_report).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
sendIntent.putExtra(Intent.EXTRA_TEXT, stackTrace);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + android.R.styleable.AndroidManifest_versionName + " exception report");
sendIntent.setType("message/rfc822");
startActivity(sendIntent);
finish();
}
}
);
findViewById(R.id.cancel_report).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
finish();
}
}
);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bug_report_view);
final String stackTrace = getIntent().getStringExtra(STACKTRACE);
final TextView reportTextView = (TextView)findViewById(R.id.report_text);
reportTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
reportTextView.setClickable(false);
reportTextView.setLongClickable(false);
String v = null;
try {
v = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (Exception e) {
}
final String versionName = (v != null) ? v : "?.?.?";
reportTextView.append("FBReader " + versionName + " has been crached, sorry. You can help to fix this bug by sending the report below to FBReader developers. The report will be sent by e-mail. Thank you in advance!\n\n");
reportTextView.append(stackTrace);
findViewById(R.id.send_report).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
sendIntent.putExtra(Intent.EXTRA_TEXT, stackTrace);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + versionName + " exception report");
sendIntent.setType("message/rfc822");
startActivity(sendIntent);
finish();
}
}
);
findViewById(R.id.cancel_report).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
finish();
}
}
);
}
|
diff --git a/src/com/android/browser/PhoneUi.java b/src/com/android/browser/PhoneUi.java
index 1bc0f772..ee5ca408 100644
--- a/src/com/android/browser/PhoneUi.java
+++ b/src/com/android/browser/PhoneUi.java
@@ -1,595 +1,597 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.android.browser.UrlInputView.StateListener;
/**
* Ui for regular phone screen sizes
*/
public class PhoneUi extends BaseUi {
private static final String LOGTAG = "PhoneUi";
private static final int MSG_INIT_NAVSCREEN = 100;
private PieControlPhone mPieControl;
private NavScreen mNavScreen;
private AnimScreen mAnimScreen;
private NavigationBarPhone mNavigationBar;
private int mActionBarHeight;
boolean mExtendedMenuOpen;
boolean mOptionsMenuOpen;
boolean mAnimating;
/**
* @param browser
* @param controller
*/
public PhoneUi(Activity browser, UiController controller) {
super(browser, controller);
setUseQuickControls(BrowserSettings.getInstance().useQuickControls());
mNavigationBar = (NavigationBarPhone) mTitleBar.getNavigationBar();
TypedValue heightValue = new TypedValue();
browser.getTheme().resolveAttribute(
com.android.internal.R.attr.actionBarSize, heightValue, true);
mActionBarHeight = TypedValue.complexToDimensionPixelSize(heightValue.data,
browser.getResources().getDisplayMetrics());
}
@Override
public void onDestroy() {
hideTitleBar();
}
@Override
public void editUrl(boolean clearInput) {
if (mUseQuickControls) {
mTitleBar.setShowProgressOnly(false);
}
super.editUrl(clearInput);
}
@Override
public boolean onBackKey() {
if (showingNavScreen()) {
mNavScreen.close(mUiController.getTabControl().getCurrentPosition());
return true;
}
return super.onBackKey();
}
private boolean showingNavScreen() {
return mNavScreen != null && mNavScreen.getVisibility() == View.VISIBLE;
}
@Override
public boolean dispatchKey(int code, KeyEvent event) {
return false;
}
@Override
public void onProgressChanged(Tab tab) {
if (tab.inForeground()) {
int progress = tab.getLoadProgress();
mTitleBar.setProgress(progress);
if (progress == 100) {
if (!mOptionsMenuOpen || !mExtendedMenuOpen) {
suggestHideTitleBar();
if (mUseQuickControls) {
mTitleBar.setShowProgressOnly(false);
}
}
} else {
if (!mOptionsMenuOpen || mExtendedMenuOpen) {
if (mUseQuickControls && !mTitleBar.isEditingUrl()) {
mTitleBar.setShowProgressOnly(true);
setTitleGravity(Gravity.TOP);
}
showTitleBar();
}
}
}
if (mNavScreen == null && getTitleBar().getHeight() > 0) {
mHandler.sendEmptyMessage(MSG_INIT_NAVSCREEN);
}
}
@Override
protected void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == MSG_INIT_NAVSCREEN) {
if (mNavScreen == null) {
mNavScreen = new NavScreen(mActivity, mUiController, this);
mCustomViewContainer.addView(mNavScreen, COVER_SCREEN_PARAMS);
mNavScreen.setVisibility(View.GONE);
}
if (mAnimScreen == null) {
mAnimScreen = new AnimScreen(mActivity);
// initialize bitmaps
mAnimScreen.set(getTitleBar(), getWebView());
}
}
}
@Override
public void setActiveTab(final Tab tab) {
mTitleBar.cancelTitleBarAnimation(true);
mTitleBar.setSkipTitleBarAnimations(true);
super.setActiveTab(tab);
BrowserWebView view = (BrowserWebView) tab.getWebView();
// TabControl.setCurrentTab has been called before this,
// so the tab is guaranteed to have a webview
if (view == null) {
Log.e(LOGTAG, "active tab with no webview detected");
return;
}
// Request focus on the top window.
if (mUseQuickControls) {
mPieControl.forceToTop(mContentView);
} else {
// check if title bar is already attached by animation
if (mTitleBar.getParent() == null) {
view.setEmbeddedTitleBar(mTitleBar);
}
}
if (tab.isInVoiceSearchMode()) {
showVoiceTitleBar(tab.getVoiceDisplayTitle(), tab.getVoiceSearchResults());
} else {
revertVoiceTitleBar(tab);
}
// update nav bar state
mNavigationBar.onStateChanged(StateListener.STATE_NORMAL);
updateLockIconToLatest(tab);
tab.getTopWindow().requestFocus();
mTitleBar.setSkipTitleBarAnimations(false);
}
// menu handling callbacks
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
updateMenuState(mActiveTab, menu);
return true;
}
@Override
public void updateMenuState(Tab tab, Menu menu) {
MenuItem bm = menu.findItem(R.id.bookmarks_menu_id);
if (bm != null) {
bm.setVisible(!showingNavScreen());
}
MenuItem abm = menu.findItem(R.id.add_bookmark_menu_id);
if (abm != null) {
abm.setVisible((tab != null) && !tab.isSnapshot() && !showingNavScreen());
}
MenuItem info = menu.findItem(R.id.page_info_menu_id);
if (info != null) {
info.setVisible(false);
}
MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
if (newtab != null && !mUseQuickControls) {
newtab.setVisible(false);
}
MenuItem incognito = menu.findItem(R.id.incognito_menu_id);
if (incognito != null) {
incognito.setVisible(showingNavScreen() || mUseQuickControls);
}
if (showingNavScreen()) {
menu.setGroupVisible(R.id.LIVE_MENU, false);
menu.setGroupVisible(R.id.SNAPSHOT_MENU, false);
menu.setGroupVisible(R.id.NAV_MENU, false);
menu.setGroupVisible(R.id.COMBO_MENU, true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (showingNavScreen()
&& (item.getItemId() != R.id.history_menu_id)
&& (item.getItemId() != R.id.snapshots_menu_id)) {
hideNavScreen(mUiController.getTabControl().getCurrentPosition(), false);
}
return false;
}
@Override
public void onContextMenuCreated(Menu menu) {
hideTitleBar();
}
@Override
public void onContextMenuClosed(Menu menu, boolean inLoad) {
if (inLoad) {
showTitleBar();
}
}
// action mode callbacks
@Override
public void onActionModeStarted(ActionMode mode) {
if (!isEditingUrl()) {
hideTitleBar();
} else {
mTitleBar.animate().translationY(mActionBarHeight);
}
}
@Override
public void onActionModeFinished(boolean inLoad) {
mTitleBar.animate().translationY(0);
if (inLoad) {
if (mUseQuickControls) {
mTitleBar.setShowProgressOnly(true);
}
showTitleBar();
}
}
@Override
protected void setTitleGravity(int gravity) {
if (mUseQuickControls) {
FrameLayout.LayoutParams lp =
(FrameLayout.LayoutParams) mTitleBar.getLayoutParams();
lp.gravity = gravity;
mTitleBar.setLayoutParams(lp);
} else {
super.setTitleGravity(gravity);
}
}
@Override
public void setUseQuickControls(boolean useQuickControls) {
mUseQuickControls = useQuickControls;
mTitleBar.setUseQuickControls(mUseQuickControls);
if (useQuickControls) {
mPieControl = new PieControlPhone(mActivity, mUiController, this);
mPieControl.attachToContainer(mContentView);
WebView web = getWebView();
if (web != null) {
web.setEmbeddedTitleBar(null);
}
} else {
if (mPieControl != null) {
mPieControl.removeFromContainer(mContentView);
}
WebView web = getWebView();
if (web != null) {
// make sure we can re-parent titlebar
if ((mTitleBar != null) && (mTitleBar.getParent() != null)) {
((ViewGroup) mTitleBar.getParent()).removeView(mTitleBar);
}
web.setEmbeddedTitleBar(mTitleBar);
}
setTitleGravity(Gravity.NO_GRAVITY);
}
updateUrlBarAutoShowManagerTarget();
}
@Override
public boolean isWebShowing() {
return super.isWebShowing() && !showingNavScreen();
}
@Override
public void showWeb(boolean animate) {
super.showWeb(animate);
hideNavScreen(mUiController.getTabControl().getCurrentPosition(), animate);
}
void showNavScreen() {
mUiController.setBlockEvents(true);
if (mNavScreen == null) {
mNavScreen = new NavScreen(mActivity, mUiController, this);
mCustomViewContainer.addView(mNavScreen, COVER_SCREEN_PARAMS);
} else {
mNavScreen.setVisibility(View.VISIBLE);
mNavScreen.setAlpha(1f);
mNavScreen.refreshAdapter();
}
mActiveTab.capture();
if (mAnimScreen == null) {
mAnimScreen = new AnimScreen(mActivity);
} else {
mAnimScreen.mMain.setAlpha(1f);
mAnimScreen.mTitle.setAlpha(1f);
mAnimScreen.setScaleFactor(1f);
}
mAnimScreen.set(getTitleBar(), getWebView());
if (mAnimScreen.mMain.getParent() == null) {
mCustomViewContainer.addView(mAnimScreen.mMain, COVER_SCREEN_PARAMS);
}
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
mAnimScreen.mMain.layout(0, 0, mContentView.getWidth(),
mContentView.getHeight());
int fromLeft = 0;
int fromTop = getTitleBar().getHeight();
int fromRight = mContentView.getWidth();
int fromBottom = mContentView.getHeight();
int width = mActivity.getResources().getDimensionPixelSize(R.dimen.nav_tab_width);
int height = mActivity.getResources().getDimensionPixelSize(R.dimen.nav_tab_height);
int ntth = mActivity.getResources().getDimensionPixelSize(R.dimen.nav_tab_titleheight);
int toLeft = (mContentView.getWidth() - width) / 2;
int toTop = ((fromBottom - (ntth + height)) / 2 + ntth);
int toRight = toLeft + width;
int toBottom = toTop + height;
float scaleFactor = width / (float) mContentView.getWidth();
detachTab(mActiveTab);
mContentView.setVisibility(View.GONE);
AnimatorSet set1 = new AnimatorSet();
AnimatorSet inanim = new AnimatorSet();
ObjectAnimator tx = ObjectAnimator.ofInt(mAnimScreen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator ty = ObjectAnimator.ofInt(mAnimScreen.mContent, "top",
fromTop, toTop);
ObjectAnimator tr = ObjectAnimator.ofInt(mAnimScreen.mContent, "right",
fromRight, toRight);
ObjectAnimator tb = ObjectAnimator.ofInt(mAnimScreen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator title = ObjectAnimator.ofFloat(mAnimScreen.mTitle, "alpha",
1f, 0f);
ObjectAnimator sx = ObjectAnimator.ofFloat(mAnimScreen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator blend1 = ObjectAnimator.ofFloat(mAnimScreen.mMain,
"alpha", 1f, 0f);
blend1.setDuration(100);
inanim.playTogether(tx, ty, tr, tb, sx, title);
inanim.setDuration(200);
set1.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(mAnimScreen.mMain);
finishAnimationIn();
mUiController.setBlockEvents(false);
}
});
set1.playSequentially(inanim, blend1);
set1.start();
}
private void finishAnimationIn() {
if (showingNavScreen()) {
// notify accessibility manager about the screen change
mNavScreen.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
mTabControl.setOnThumbnailUpdatedListener(mNavScreen);
}
}
void hideNavScreen(int position, boolean animate) {
if (!showingNavScreen()) return;
final Tab tab = mUiController.getTabControl().getTab(position);
if ((tab == null) || !animate) {
if (tab != null) {
setActiveTab(tab);
} else if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
NavTabView tabview = (NavTabView) mNavScreen.getTabView(position);
if (tabview == null) {
if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
mUiController.setBlockEvents(true);
mUiController.setActiveTab(tab);
mContentView.setVisibility(View.VISIBLE);
if (mAnimScreen == null) {
mAnimScreen = new AnimScreen(mActivity);
}
mAnimScreen.set(tab.getScreenshot());
- mCustomViewContainer.addView(mAnimScreen.mMain, COVER_SCREEN_PARAMS);
+ if (mAnimScreen.mMain.getParent() == null) {
+ mCustomViewContainer.addView(mAnimScreen.mMain, COVER_SCREEN_PARAMS);
+ }
mAnimScreen.mMain.layout(0, 0, mContentView.getWidth(),
mContentView.getHeight());
mNavScreen.mScroller.finishScroller();
ImageView target = tabview.mImage;
int toLeft = 0;
int toTop = (tab.getWebView() != null) ? tab.getWebView().getVisibleTitleHeight() : 0;
int toRight = mContentView.getWidth();
int width = target.getDrawable().getIntrinsicWidth();
int height = target.getDrawable().getIntrinsicHeight();
int fromLeft = tabview.getLeft() + target.getLeft() - mNavScreen.mScroller.getScrollX();
int fromTop = tabview.getTop() + target.getTop() - mNavScreen.mScroller.getScrollY();
int fromRight = fromLeft + width;
int fromBottom = fromTop + height;
float scaleFactor = mContentView.getWidth() / (float) width;
int toBottom = toTop + (int) (height * scaleFactor);
mAnimScreen.mContent.setLeft(fromLeft);
mAnimScreen.mContent.setTop(fromTop);
mAnimScreen.mContent.setRight(fromRight);
mAnimScreen.mContent.setBottom(fromBottom);
mAnimScreen.setScaleFactor(1f);
AnimatorSet set1 = new AnimatorSet();
ObjectAnimator fade2 = ObjectAnimator.ofFloat(mAnimScreen.mMain, "alpha", 0f, 1f);
ObjectAnimator fade1 = ObjectAnimator.ofFloat(mNavScreen, "alpha", 1f, 0f);
set1.playTogether(fade1, fade2);
set1.setDuration(100);
AnimatorSet set2 = new AnimatorSet();
ObjectAnimator l = ObjectAnimator.ofInt(mAnimScreen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator t = ObjectAnimator.ofInt(mAnimScreen.mContent, "top",
fromTop, toTop);
ObjectAnimator r = ObjectAnimator.ofInt(mAnimScreen.mContent, "right",
fromRight, toRight);
ObjectAnimator b = ObjectAnimator.ofInt(mAnimScreen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator scale = ObjectAnimator.ofFloat(mAnimScreen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
otheralpha.setDuration(100);
set2.playTogether(l, t, r, b, scale);
set2.setDuration(200);
AnimatorSet combo = new AnimatorSet();
combo.playSequentially(set1, set2, otheralpha);
combo.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(mAnimScreen.mMain);
finishAnimateOut();
mUiController.setBlockEvents(false);
}
});
combo.start();
}
private void finishAnimateOut() {
mTabControl.setOnThumbnailUpdatedListener(null);
mNavScreen.setVisibility(View.GONE);
mCustomViewContainer.setAlpha(1f);
mCustomViewContainer.setVisibility(View.GONE);
}
@Override
public boolean needsRestoreAllTabs() {
return false;
}
public void toggleNavScreen() {
if (!showingNavScreen()) {
showNavScreen();
} else {
hideNavScreen(mUiController.getTabControl().getCurrentPosition(), false);
}
}
@Override
public boolean shouldCaptureThumbnails() {
return true;
}
static class AnimScreen {
private View mMain;
private ImageView mTitle;
private ImageView mContent;
private float mScale;
private Bitmap mTitleBarBitmap;
private Bitmap mContentBitmap;
public AnimScreen(Context ctx) {
mMain = LayoutInflater.from(ctx).inflate(R.layout.anim_screen,
null);
mTitle = (ImageView) mMain.findViewById(R.id.title);
mContent = (ImageView) mMain.findViewById(R.id.content);
mContent.setScaleType(ImageView.ScaleType.MATRIX);
mContent.setImageMatrix(new Matrix());
mScale = 1.0f;
setScaleFactor(getScaleFactor());
}
public void set(TitleBar tbar, WebView web) {
if (tbar == null || web == null) {
return;
}
if (tbar.getWidth() > 0 && tbar.getEmbeddedHeight() > 0) {
if (mTitleBarBitmap == null
|| mTitleBarBitmap.getWidth() != tbar.getWidth()
|| mTitleBarBitmap.getHeight() != tbar.getEmbeddedHeight()) {
mTitleBarBitmap = safeCreateBitmap(tbar.getWidth(),
tbar.getEmbeddedHeight());
}
if (mTitleBarBitmap != null) {
Canvas c = new Canvas(mTitleBarBitmap);
tbar.draw(c);
c.setBitmap(null);
}
} else {
mTitleBarBitmap = null;
}
mTitle.setImageBitmap(mTitleBarBitmap);
mTitle.setVisibility(View.VISIBLE);
int h = web.getHeight() - tbar.getEmbeddedHeight();
if (mContentBitmap == null
|| mContentBitmap.getWidth() != web.getWidth()
|| mContentBitmap.getHeight() != h) {
mContentBitmap = safeCreateBitmap(web.getWidth(), h);
}
if (mContentBitmap != null) {
Canvas c = new Canvas(mContentBitmap);
int tx = web.getScrollX();
int ty = web.getScrollY();
c.translate(-tx, -ty - tbar.getEmbeddedHeight());
web.draw(c);
c.setBitmap(null);
}
mContent.setImageBitmap(mContentBitmap);
}
private Bitmap safeCreateBitmap(int width, int height) {
if (width <= 0 || height <= 0) {
Log.w(LOGTAG, "safeCreateBitmap failed! width: " + width
+ ", height: " + height);
return null;
}
return Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
}
public void set(Bitmap image) {
mTitle.setVisibility(View.GONE);
mContent.setImageBitmap(image);
}
private void setScaleFactor(float sf) {
mScale = sf;
Matrix m = new Matrix();
m.postScale(sf,sf);
mContent.setImageMatrix(m);
}
private float getScaleFactor() {
return mScale;
}
}
}
| true | true | void hideNavScreen(int position, boolean animate) {
if (!showingNavScreen()) return;
final Tab tab = mUiController.getTabControl().getTab(position);
if ((tab == null) || !animate) {
if (tab != null) {
setActiveTab(tab);
} else if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
NavTabView tabview = (NavTabView) mNavScreen.getTabView(position);
if (tabview == null) {
if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
mUiController.setBlockEvents(true);
mUiController.setActiveTab(tab);
mContentView.setVisibility(View.VISIBLE);
if (mAnimScreen == null) {
mAnimScreen = new AnimScreen(mActivity);
}
mAnimScreen.set(tab.getScreenshot());
mCustomViewContainer.addView(mAnimScreen.mMain, COVER_SCREEN_PARAMS);
mAnimScreen.mMain.layout(0, 0, mContentView.getWidth(),
mContentView.getHeight());
mNavScreen.mScroller.finishScroller();
ImageView target = tabview.mImage;
int toLeft = 0;
int toTop = (tab.getWebView() != null) ? tab.getWebView().getVisibleTitleHeight() : 0;
int toRight = mContentView.getWidth();
int width = target.getDrawable().getIntrinsicWidth();
int height = target.getDrawable().getIntrinsicHeight();
int fromLeft = tabview.getLeft() + target.getLeft() - mNavScreen.mScroller.getScrollX();
int fromTop = tabview.getTop() + target.getTop() - mNavScreen.mScroller.getScrollY();
int fromRight = fromLeft + width;
int fromBottom = fromTop + height;
float scaleFactor = mContentView.getWidth() / (float) width;
int toBottom = toTop + (int) (height * scaleFactor);
mAnimScreen.mContent.setLeft(fromLeft);
mAnimScreen.mContent.setTop(fromTop);
mAnimScreen.mContent.setRight(fromRight);
mAnimScreen.mContent.setBottom(fromBottom);
mAnimScreen.setScaleFactor(1f);
AnimatorSet set1 = new AnimatorSet();
ObjectAnimator fade2 = ObjectAnimator.ofFloat(mAnimScreen.mMain, "alpha", 0f, 1f);
ObjectAnimator fade1 = ObjectAnimator.ofFloat(mNavScreen, "alpha", 1f, 0f);
set1.playTogether(fade1, fade2);
set1.setDuration(100);
AnimatorSet set2 = new AnimatorSet();
ObjectAnimator l = ObjectAnimator.ofInt(mAnimScreen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator t = ObjectAnimator.ofInt(mAnimScreen.mContent, "top",
fromTop, toTop);
ObjectAnimator r = ObjectAnimator.ofInt(mAnimScreen.mContent, "right",
fromRight, toRight);
ObjectAnimator b = ObjectAnimator.ofInt(mAnimScreen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator scale = ObjectAnimator.ofFloat(mAnimScreen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
otheralpha.setDuration(100);
set2.playTogether(l, t, r, b, scale);
set2.setDuration(200);
AnimatorSet combo = new AnimatorSet();
combo.playSequentially(set1, set2, otheralpha);
combo.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(mAnimScreen.mMain);
finishAnimateOut();
mUiController.setBlockEvents(false);
}
});
combo.start();
}
| void hideNavScreen(int position, boolean animate) {
if (!showingNavScreen()) return;
final Tab tab = mUiController.getTabControl().getTab(position);
if ((tab == null) || !animate) {
if (tab != null) {
setActiveTab(tab);
} else if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
NavTabView tabview = (NavTabView) mNavScreen.getTabView(position);
if (tabview == null) {
if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
mUiController.setBlockEvents(true);
mUiController.setActiveTab(tab);
mContentView.setVisibility(View.VISIBLE);
if (mAnimScreen == null) {
mAnimScreen = new AnimScreen(mActivity);
}
mAnimScreen.set(tab.getScreenshot());
if (mAnimScreen.mMain.getParent() == null) {
mCustomViewContainer.addView(mAnimScreen.mMain, COVER_SCREEN_PARAMS);
}
mAnimScreen.mMain.layout(0, 0, mContentView.getWidth(),
mContentView.getHeight());
mNavScreen.mScroller.finishScroller();
ImageView target = tabview.mImage;
int toLeft = 0;
int toTop = (tab.getWebView() != null) ? tab.getWebView().getVisibleTitleHeight() : 0;
int toRight = mContentView.getWidth();
int width = target.getDrawable().getIntrinsicWidth();
int height = target.getDrawable().getIntrinsicHeight();
int fromLeft = tabview.getLeft() + target.getLeft() - mNavScreen.mScroller.getScrollX();
int fromTop = tabview.getTop() + target.getTop() - mNavScreen.mScroller.getScrollY();
int fromRight = fromLeft + width;
int fromBottom = fromTop + height;
float scaleFactor = mContentView.getWidth() / (float) width;
int toBottom = toTop + (int) (height * scaleFactor);
mAnimScreen.mContent.setLeft(fromLeft);
mAnimScreen.mContent.setTop(fromTop);
mAnimScreen.mContent.setRight(fromRight);
mAnimScreen.mContent.setBottom(fromBottom);
mAnimScreen.setScaleFactor(1f);
AnimatorSet set1 = new AnimatorSet();
ObjectAnimator fade2 = ObjectAnimator.ofFloat(mAnimScreen.mMain, "alpha", 0f, 1f);
ObjectAnimator fade1 = ObjectAnimator.ofFloat(mNavScreen, "alpha", 1f, 0f);
set1.playTogether(fade1, fade2);
set1.setDuration(100);
AnimatorSet set2 = new AnimatorSet();
ObjectAnimator l = ObjectAnimator.ofInt(mAnimScreen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator t = ObjectAnimator.ofInt(mAnimScreen.mContent, "top",
fromTop, toTop);
ObjectAnimator r = ObjectAnimator.ofInt(mAnimScreen.mContent, "right",
fromRight, toRight);
ObjectAnimator b = ObjectAnimator.ofInt(mAnimScreen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator scale = ObjectAnimator.ofFloat(mAnimScreen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
otheralpha.setDuration(100);
set2.playTogether(l, t, r, b, scale);
set2.setDuration(200);
AnimatorSet combo = new AnimatorSet();
combo.playSequentially(set1, set2, otheralpha);
combo.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(mAnimScreen.mMain);
finishAnimateOut();
mUiController.setBlockEvents(false);
}
});
combo.start();
}
|
diff --git a/freemind/freemind/main/FreeMind.java b/freemind/freemind/main/FreeMind.java
index 7124747..3f313ec 100644
--- a/freemind/freemind/main/FreeMind.java
+++ b/freemind/freemind/main/FreeMind.java
@@ -1,1355 +1,1356 @@
/*FreeMind - A Program for creating and viewing Mindmaps
*Copyright (C) 2000-2006 Joerg Mueller, Daniel Polansky, Christian Foltin and others.
*See COPYING for Details
*
*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.
*/
/*$Id: FreeMind.java,v 1.32.14.28.2.147 2011/01/09 21:03:13 christianfoltin Exp $*/
package freemind.main;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import freemind.controller.Controller;
import freemind.controller.LastStateStorageManagement;
import freemind.controller.MenuBar;
import freemind.controller.actions.generated.instance.MindmapLastStateStorage;
import freemind.modes.ModeController;
import freemind.preferences.FreemindPropertyListener;
import freemind.view.MapModule;
import freemind.view.mindmapview.MapView;
public class FreeMind extends JFrame implements FreeMindMain {
public static final String LOG_FILE_NAME = "log";
private static final String PORT_FILE = "portFile";
private static final String FREE_MIND_PROGRESS_LOAD_MAPS = "FreeMind.progress.loadMaps";
private static final String SPLIT_PANE_POSITION = "split_pane_position";
private static final String SPLIT_PANE_LAST_POSITION = "split_pane_last_position";
public static final String RESOURCE_LOOKANDFEEL = "lookandfeel";
public static final String RESOURCES_SELECTION_METHOD = "selection_method";
public static final String RESOURCES_NODE_STYLE = "standardnodestyle";
public static final String RESOURCES_ROOT_NODE_STYLE = "standardrootnodestyle";
public static final String RESOURCES_NODE_TEXT_COLOR = "standardnodetextcolor";
public static final String RESOURCES_SELECTED_NODE_COLOR = "standardselectednodecolor";
public static final String RESOURCES_SELECTED_NODE_RECTANGLE_COLOR = "standardselectednoderectanglecolor";
public static final String RESOURCE_DRAW_RECTANGLE_FOR_SELECTION = "standarddrawrectangleforselection";
public static final String RESOURCES_EDGE_COLOR = "standardedgecolor";
public static final String RESOURCES_EDGE_STYLE = "standardedgestyle";
public static final String RESOURCES_CLOUD_COLOR = "standardcloudcolor";
public static final String RESOURCES_LINK_COLOR = "standardlinkcolor";
public static final String RESOURCES_BACKGROUND_COLOR = "standardbackgroundcolor";
public static final String RESOURCE_PRINT_ON_WHITE_BACKGROUND = "printonwhitebackground";
public static final String RESOURCES_WHEEL_VELOCITY = "wheel_velocity";
public static final String RESOURCES_USE_TABBED_PANE = "use_tabbed_pane";
public static final String RESOURCES_USE_SPLIT_PANE = "use_split_pane";
public static final String RESOURCES_DELETE_NODES_WITHOUT_QUESTION = "delete_nodes_without_question";
public static final String RESOURCES_RELOAD_FILES_WITHOUT_QUESTION = "reload_files_without_question";
private Logger logger = null;
protected static final VersionInformation VERSION = new VersionInformation("1.0.0 Beta 6");
public static final String XML_VERSION = "1.0.0";
public static final String RESOURCES_REMIND_USE_RICH_TEXT_IN_NEW_LONG_NODES = "remind_use_rich_text_in_new_long_nodes";
public static final String RESOURCES_EXECUTE_SCRIPTS_WITHOUT_ASKING = "resources_execute_scripts_without_asking";
public static final String RESOURCES_EXECUTE_SCRIPTS_WITHOUT_FILE_RESTRICTION = "resources_execute_scripts_without_file_restriction";
public static final String RESOURCES_EXECUTE_SCRIPTS_WITHOUT_NETWORK_RESTRICTION = "resources_execute_scripts_without_network_restriction";
public static final String RESOURCES_EXECUTE_SCRIPTS_WITHOUT_EXEC_RESTRICTION = "resources_execute_scripts_without_exec_restriction";
public static final String RESOURCES_SCRIPT_USER_KEY_NAME_FOR_SIGNING = "resources_script_user_key_name_for_signing";
public static final String RESOURCES_CONVERT_TO_CURRENT_VERSION = "resources_convert_to_current_version";
public static final String RESOURCES_CUT_NODES_WITHOUT_QUESTION = "resources_cut_nodes_without_question";
public static final String RESOURCES_DON_T_SHOW_NOTE_ICONS = "resources_don_t_show_note_icons";
public static final String RESOURCES_REMOVE_NOTES_WITHOUT_QUESTION = "resources_remove_notes_without_question";
public static final String RESOURCES_SAVE_FOLDING_STATE = "resources_save_folding_state";
public static final String RESOURCES_SIGNED_SCRIPT_ARE_TRUSTED = "resources_signed_script_are_trusted";
public static final String RESOURCES_USE_DEFAULT_FONT_FOR_NOTES_TOO = "resources_use_default_font_for_notes_too";
public static final String RESOURCES_USE_MARGIN_TOP_ZERO_FOR_NOTES = "resources_use_margin_top_zero_for_notes";
public static final String RESOURCES_DON_T_SHOW_CLONE_ICONS = "resources_don_t_show_clone_icons";
public static final String RESOURCES_DON_T_OPEN_PORT = "resources_don_t_open_port";
// public static final String defaultPropsURL = "freemind.properties";
// public static Properties defaultProps;
public static Properties props;
private static Properties defProps;
private MenuBar menuBar;
private JLabel status;
private Map filetypes; // Hopefully obsolete. Used to store applications
// used to open different file types
private File autoPropertiesFile;
private File patternsFile;
Controller controller;// the one and only controller
private FreeMindCommon mFreeMindCommon;
private static FileHandler mFileHandler;
private static boolean mFileHandlerError = false;
private JScrollPane mScrollPane = null;
private JSplitPane mSplitPane;
private JComponent mContentComponent = null;
private JTabbedPane mTabbedPane = null;
private ImageIcon mWindowIcon;
private boolean mStartupDone = false;
private List mStartupDoneListeners = new Vector();
private EditServer mEditServer = null;
private Vector mLoggerList = new Vector();
public static final String KEYSTROKE_MOVE_MAP_LEFT = "keystroke_MoveMapLeft";
public static final String KEYSTROKE_MOVE_MAP_RIGHT = "keystroke_MoveMapRight";
public static final String KEYSTROKE_PREVIOUS_MAP = "keystroke_previousMap";
public static final String KEYSTROKE_NEXT_MAP = "keystroke_nextMap";
public static final String RESOURCES_SEARCH_IN_NOTES_TOO = "resources_search_in_notes_too";
public static final String RESOURCES_DON_T_SHOW_NOTE_TOOLTIPS = "resources_don_t_show_note_tooltips";
public static final String RESOURCES_SEARCH_FOR_NODE_TEXT_WITHOUT_QUESTION = "resources_search_for_node_text_without_question";
private static LogFileLogHandler sLogFileHandler;
public FreeMind(Properties pDefaultPreferences,
Properties pUserPreferences, File pAutoPropertiesFile) {
super("FreeMind");
// Focus searcher
System.setSecurityManager(new FreeMindSecurityManager());
defProps = pDefaultPreferences;
props = pUserPreferences;
autoPropertiesFile = pAutoPropertiesFile;
if (logger == null) {
logger = getLogger(FreeMind.class.getName());
StringBuffer info = new StringBuffer();
info.append("freemind_version = ");
info.append(VERSION);
info.append("; freemind_xml_version = ");
info.append(XML_VERSION);
try {
String propsLoc = "version.properties";
URL versionUrl = this.getClass().getClassLoader()
.getResource(propsLoc);
Properties buildNumberPros = new Properties();
InputStream stream = versionUrl.openStream();
buildNumberPros.load(stream);
info.append("\nBuild: "
+ buildNumberPros.getProperty("build.number") + "\n");
stream.close();
} catch (Exception e) {
info.append("Problems reading build number file: " + e);
}
info.append("\njava_version = ");
info.append(System.getProperty("java.version"));
info.append("; os_name = ");
info.append(System.getProperty("os.name"));
info.append("; os_version = ");
info.append(System.getProperty("os.version"));
logger.info(info.toString());
}
mFreeMindCommon = new FreeMindCommon(this);
Resources.createInstance(this);
}
void init(FeedBack feedback) {
/* This is only for apple but does not harm for the others. */
System.setProperty("apple.laf.useScreenMenuBar", "true");
patternsFile = new File(getFreemindDirectory(),
getDefaultProperty("patternsfile"));
feedback.increase("FreeMind.progress.updateLookAndFeel");
updateLookAndFeel();
feedback.increase("FreeMind.progress.createController");
setIconImage(mWindowIcon.getImage());
// Layout everything
getContentPane().setLayout(new BorderLayout());
controller = new Controller(this);
controller.init();
feedback.increase("FreeMind.progress.settingPreferences");
// add a listener for the controller, resource bundle:
Controller.addPropertyChangeListener(new FreemindPropertyListener() {
public void propertyChanged(String propertyName, String newValue,
String oldValue) {
if (propertyName.equals(FreeMindCommon.RESOURCE_LANGUAGE)) {
// re-read resources:
mFreeMindCommon.clearLanguageResources();
getResources();
}
}
});
// fc, disabled with purpose (see java look and feel styleguides).
// http://java.sun.com/products/jlf/ed2/book/index.html
// // add a listener for the controller, look and feel:
// Controller.addPropertyChangeListener(new FreemindPropertyListener() {
//
// public void propertyChanged(String propertyName, String newValue,
// String oldValue) {
// if (propertyName.equals(RESOURCE_LOOKANDFEEL)) {
// updateLookAndFeel();
// }
// }
// });
controller.optionAntialiasAction
.changeAntialias(getProperty(FreeMindCommon.RESOURCE_ANTIALIAS));
feedback.increase("FreeMind.progress.propageteLookAndFeel");
SwingUtilities.updateComponentTreeUI(this); // Propagate LookAndFeel to
feedback.increase("FreeMind.progress.buildScreen");
setScreenBounds();
// JComponents
feedback.increase("FreeMind.progress.createInitialMode");
controller.createNewMode(getProperty("initial_mode"));
}// Constructor
/**
*
*/
private void updateLookAndFeel() {
// set Look&Feel
try {
String lookAndFeel = props.getProperty(RESOURCE_LOOKANDFEEL);
if (lookAndFeel.equals("windows")) {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} else if (lookAndFeel.equals("motif")) {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} else if (lookAndFeel.equals("mac")) {
// Only available on macOS
UIManager.setLookAndFeel("javax.swing.plaf.mac.MacLookAndFeel");
} else if (lookAndFeel.equals("metal")) {
UIManager
.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} else if (lookAndFeel.equals("gtk")) {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
} else if (lookAndFeel.equals("nothing")) {
} else if (lookAndFeel.indexOf('.') != -1) { // string contains a
// dot
UIManager.setLookAndFeel(lookAndFeel);
// we assume class name
} else {
// default.
logger.info("Default (System) Look & Feel: "
+ UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
}
} catch (Exception ex) {
System.err.println("Unable to set Look & Feel.");
}
mFreeMindCommon.loadUIProperties(defProps);
}
public boolean isApplet() {
return false;
}
public File getPatternsFile() {
return patternsFile;
}
public VersionInformation getFreemindVersion() {
return VERSION;
}
// maintain this methods to keep the last state/size of the window (PN)
public int getWinHeight() {
return getHeight();
}
public int getWinWidth() {
return getWidth();
}
public int getWinX() {
return getX();
}
public int getWinY() {
return getY();
}
public int getWinState() {
return getExtendedState();
}
public URL getResource(String name) {
return this.getClass().getClassLoader().getResource(name);
}
public String getProperty(String key) {
return props.getProperty(key);
}
public int getIntProperty(String key, int defaultValue) {
try {
return Integer.parseInt(getProperty(key));
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
public Properties getProperties() {
return props;
}
public void setProperty(String key, String value) {
props.setProperty(key, value);
}
public String getDefaultProperty(String key) {
return defProps.getProperty(key);
}
public void setDefaultProperty(String key, String value) {
defProps.setProperty(key, value);
}
public String getFreemindDirectory() {
return System.getProperty("user.home") + File.separator
+ getProperty("properties_folder");
}
public void saveProperties(boolean pIsShutdown) {
try {
OutputStream out = new FileOutputStream(autoPropertiesFile);
final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
out, "8859_1");
outputStreamWriter.write("#FreeMind ");
outputStreamWriter.write(VERSION.toString());
outputStreamWriter.write('\n');
outputStreamWriter.flush();
// auto.store(out,null);//to save as few props as possible.
props.store(out, null);
out.close();
} catch (Exception ex) {
}
getController().getFilterController().saveConditions();
if (pIsShutdown && mEditServer != null) {
mEditServer.stopServer();
}
}
public MapView getView() {
return controller.getView();
}
public Controller getController() {
return controller;
}
public void setView(MapView view) {
mScrollPane.setViewportView(view);
}
public MenuBar getFreeMindMenuBar() {
return menuBar;
}
public void out(String msg) {
// TODO: Automatically remove old messages after a certain time.
if (status != null) {
status.setText(msg);
// logger.info(msg);
}
}
public void err(String msg) {
if (status != null) {
status.setText(msg);
}
// logger.info(msg);
}
/**
* Open url in WWW browser. This method hides some differences between
* operating systems.
*/
public void openDocument(URL url) throws Exception {
// build string for default browser:
String correctedUrl = new String(url.toExternalForm());
if (url.getProtocol().equals("file")) {
correctedUrl = correctedUrl.replace('\\', '/').replaceAll(" ",
"%20");
// ^ This is more of a heuristic than a "logical" code
// and due to a java bug:
// http://forum.java.sun.com/thread.jsp?forum=31&thread=363990
}
// Originally, this method determined external application, with which
// the document
// should be opened. Which application should open which document type
// was
// configured in FreeMind properties file. As a result, FreeMind tried
// to solve the
// problem (of determining application for a file type), which should
// better be
// solved somewhere else. Indeed, on Windows, this problem is perfectly
// solved by
// Explorer. On KDE, this problem is solved by Konqueror default
// browser. In
// general, most WWW browsers have to solve this problem.
// As a result, the only thing we do here, is to open URL in WWW
// browser.
String osName = System.getProperty("os.name");
String urlString = url.toString();
- final File file = Tools.urlToFile(url);
if (osName.substring(0, 3).equals("Win")) {
String propertyString = new String(
"default_browser_command_windows");
if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) {
propertyString += "_9x";
} else {
propertyString += "_nt";
}
String browser_command = new String();
String command = new String();
// Here we introduce " around the parameter of explorer
// command. This is not because of possible spaces in this
// parameter - it is because of "=" character, which causes
// problems. My understanding of MSDOS is not so good, but at
// least I can say, that "=" is used in general for the purpose
// of variable assignment.
// String[] call = { browser_command, "\""+url.toString()+"\"" };
try {
// This is working fine on Windows 2000 and NT as well
// Below is a piece of code showing how to run executables
// directly
// without asking. However, we don't want to do that. Explorer
// will run
// executable, but ask before it actually runs it.
//
// Imagine you download a package of maps containing also nasty
// executable. Let's say there is a map "index.mm". This map
// contains a
// link to that nasty executable, but the name of the link
// appearing to the
// user does not indicate at all that clicking the link leads to
// execution
// of a programm. This executable is located on your local
// computer, so
// asking before executing remote executable does not solve the
// problem. You click the link and there you are running evil
// executable.
// build string for default browser:
// ask for property about browser: fc, 26.11.2003.
Object[] messageArguments = { urlString };
MessageFormat formatter = new MessageFormat(
getProperty(propertyString));
browser_command = formatter.format(messageArguments);
if (url.getProtocol().equals("file")) {
+ final File file = Tools.urlToFile(url);
if (!Tools.isBelowJava6()) {
Class desktopClass = Class.forName("java.awt.Desktop");
Method getDesktopMethod = desktopClass.getMethod(
"getDesktop", new Class[] {});
Object desktopObject = getDesktopMethod.invoke(null,
new Object[] {});
Method openMethod = desktopObject.getClass().getMethod(
"open", new Class[] { File.class });
openMethod.invoke(desktopObject, new Object[] { file });
return;
}
// command = "rundll32 url.dll,FileProtocolHandler "+
// Tools.urlGetFile(url);
// bug fix by Dan:
command = "cmd /C rundll32 url.dll,FileProtocolHandler "
+ urlString;
// see
// http://rsb.info.nih.gov/ij/developer/source/ij/plugin/BrowserLauncher.java.html
if (System.getProperty("os.name")
.startsWith("Windows 2000"))
command = "cmd /C rundll32 shell32.dll,ShellExec_RunDLL "
+ urlString;
} else if (urlString.startsWith("mailto:")) {
command = "cmd /C rundll32 url.dll,FileProtocolHandler "
+ urlString;
} else {
command = browser_command;
}
logger.info("Starting browser with " + command);
// Runtime.getRuntime().exec(command);
execWindows(command);
} catch (IOException x) {
controller
.errorMessage("Could not invoke browser.\n\nFreemind excecuted the following statement on a command line:\n\""
+ command
+ "\".\n\nYou may look at the user or default property called '"
+ propertyString + "'.");
System.err.println("Caught: " + x);
}
} else if (osName.startsWith("Mac OS")) {
// logger.info("Opening URL "+urlString);
String browser_command = new String();
try {
// ask for property about browser: fc, 26.11.2003.
Object[] messageArguments = { correctedUrl, urlString };
if ("file".equals(url.getProtocol())) {
// Bug in the apple's open function. For files, a pure
// filename must be given.
+ final File file = Tools.urlToFile(url);
String[] command = {
getProperty("default_browser_command_mac_open"),
"file:" + file.getAbsolutePath() };
logger.info("Starting command: "
+ Arrays.deepToString(command));
Runtime.getRuntime().exec(command, null, null);
} else {
MessageFormat formatter = new MessageFormat(
getProperty("default_browser_command_mac"));
browser_command = formatter.format(messageArguments);
logger.info("Starting command: " + browser_command);
Runtime.getRuntime().exec(browser_command);
}
} catch (IOException ex2) {
controller
.errorMessage("Could not invoke browser.\n\nFreemind excecuted the following statement on a command line:\n\""
+ browser_command
+ "\".\n\nYou may look at the user or default property called 'default_browser_command_mac'.");
System.err.println("Caught: " + ex2);
}
} else {
// There is no '"' character around url.toString (compare to Windows
// code
// above). Putting '"' around does not work on Linux - instead, the
// '"'
// becomes part of URL, which is malformed, as a result.
String browser_command = new String();
try {
// ask for property about browser: fc, 26.11.2003.
Object[] messageArguments = { correctedUrl, urlString };
MessageFormat formatter = new MessageFormat(
getProperty("default_browser_command_other_os"));
browser_command = formatter.format(messageArguments);
logger.info("Starting command: " + browser_command);
Runtime.getRuntime().exec(browser_command);
} catch (IOException ex2) {
controller
.errorMessage("Could not invoke browser.\n\nFreemind excecuted the following statement on a command line:\n\""
+ browser_command
+ "\".\n\nYou may look at the user or default property called 'default_browser_command_other_os'.");
System.err.println("Caught: " + ex2);
}
}
}
/**
* @param cmd
* precondition: the command can be split by spaces and the last
* argument is the only one that contains unicode chars.
* Moreover, we are under Windows. THIS METHOD DOESN'T SEEM TO
* WORK for UNICODE ARGUMENTS.
* @throws IOException
*/
private void execWindows(String pCommand) throws IOException {
// taken and adapted from
// http://stackoverflow.com/questions/1876507/java-runtime-exec-on-windows-fails-with-unicode-in-arguments
StringTokenizer st = new StringTokenizer(pCommand, " ");
String[] cmd = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
cmd[i++] = st.nextToken();
}
Map newEnv = new HashMap();
newEnv.putAll(System.getenv());
// exchange last argument by environment
String envName = "JENV_1";
newEnv.put(envName, cmd[cmd.length - 1]);
cmd[cmd.length - 1] = "%" + envName + "%";
logger.info("Starting command array "
+ Arrays.toString(cmd)
+ ", and env for "
+ envName
+ " = "
+ HtmlTools.unicodeToHTMLUnicodeEntity(
(String) newEnv.get(envName), true));
ProcessBuilder pb = new ProcessBuilder(cmd);
Map env = pb.environment();
env.putAll(newEnv);
final Process p = pb.start();
}
private String transpose(String input, char findChar, String replaceString) {
String res = new String();
for (int i = 0; i < input.length(); ++i) {
char d = input.charAt(i);
if (d == findChar)
res += replaceString;
else
res += d;
}
return res;
}
public void setWaitingCursor(boolean waiting) {
if (waiting) {
getRootPane().getGlassPane().setCursor(
Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
getRootPane().getGlassPane().setVisible(true);
} else {
getRootPane().getGlassPane().setCursor(
Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
getRootPane().getGlassPane().setVisible(false);
}
}
private String getProgramForFile(String type) {
if (filetypes == null) {
filetypes = new HashMap();
String raw = getProperty("filetypes");
if (raw == null || raw.equals("")) {
return "";
}
StringTokenizer tokens = new StringTokenizer(raw, ",");
while (tokens.hasMoreTokens()) {
StringTokenizer pair = new StringTokenizer(tokens.nextToken(),
":");
String key = pair.nextToken().trim().toLowerCase();
String value = pair.nextToken().trim();
filetypes.put(key, value);
}
}
return (String) filetypes.get(type.trim().toLowerCase());
}
/** Returns the ResourceBundle with the current language */
public ResourceBundle getResources() {
return mFreeMindCommon.getResources();
}
public String getResourceString(String resource) {
return mFreeMindCommon.getResourceString(resource);
}
public String getResourceString(String key, String pDefault) {
return mFreeMindCommon.getResourceString(key, pDefault);
}
public Logger getLogger(String forClass) {
Logger loggerForClass = java.util.logging.Logger.getLogger(forClass);
mLoggerList.add(loggerForClass);
if (mFileHandler == null && !mFileHandlerError) {
// initialize handlers using an old System.err:
final Logger parentLogger = loggerForClass.getParent();
final Handler[] handlers = parentLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
final Handler handler = handlers[i];
if (handler instanceof ConsoleHandler) {
parentLogger.removeHandler(handler);
}
}
try {
mFileHandler = new FileHandler(getFreemindDirectory()
+ File.separator + LOG_FILE_NAME, 1400000, 5, false);
mFileHandler.setFormatter(new StdFormatter());
mFileHandler.setLevel(Level.INFO);
parentLogger.addHandler(mFileHandler);
final ConsoleHandler stdConsoleHandler = new ConsoleHandler();
stdConsoleHandler.setFormatter(new StdFormatter());
stdConsoleHandler.setLevel(Level.WARNING);
parentLogger.addHandler(stdConsoleHandler);
sLogFileHandler = new LogFileLogHandler();
sLogFileHandler.setFormatter(new SimpleFormatter());
sLogFileHandler.setLevel(Level.INFO);
LoggingOutputStream los;
Logger logger = Logger.getLogger(StdFormatter.STDOUT.getName());
los = new LoggingOutputStream(logger, StdFormatter.STDOUT);
System.setOut(new PrintStream(los, true));
logger = Logger.getLogger(StdFormatter.STDERR.getName());
los = new LoggingOutputStream(logger, StdFormatter.STDERR);
System.setErr(new PrintStream(los, true));
} catch (Exception e) {
System.err.println("Error creating logging File Handler");
e.printStackTrace();
mFileHandlerError = true;
// to avoid infinite recursion.
// freemind.main.Resources.getInstance().logExecption(e);
}
}
if (sLogFileHandler != null) {
loggerForClass.addHandler(sLogFileHandler);
}
return loggerForClass;
}
public static void main(final String[] args,
Properties pDefaultPreferences, Properties pUserPreferences,
File pAutoPropertiesFile) {
final FreeMind frame = new FreeMind(pDefaultPreferences,
pUserPreferences, pAutoPropertiesFile);
IFreeMindSplash splash = null;
frame.checkForAnotherInstance(args);
frame.initServer();
final FeedBack feedBack;
// change here, if you don't like the splash
if (true) {
splash = new FreeMindSplashModern(frame);
splash.setVisible(true);
feedBack = splash.getFeedBack();
frame.mWindowIcon = splash.getWindowIcon();
} else {
feedBack = new FeedBack() {
int value = 0;
public int getActualValue() {
return value;
}
public void increase(String messageId) {
progress(getActualValue() + 1, messageId);
}
public void progress(int act, String messageId) {
frame.logger.info("Beginnig task:" + messageId);
}
public void setMaximumValue(int max) {
}
};
frame.mWindowIcon = new ImageIcon(
frame.getResource("images/FreeMindWindowIcon.png"));
}
feedBack.setMaximumValue(9 + frame.getMaximumNumberOfMapsToLoad(args));
frame.init(feedBack);
feedBack.increase("FreeMind.progress.startCreateController");
final ModeController ctrl = frame.createModeController(args);
feedBack.increase(FREE_MIND_PROGRESS_LOAD_MAPS);
// This could be improved.
frame.loadMaps(args, ctrl, feedBack);
Tools.waitForEventQueue();
feedBack.increase("FreeMind.progress.endStartup");
// focus fix after startup.
frame.addWindowFocusListener(new WindowFocusListener() {
public void windowLostFocus(WindowEvent e) {
}
public void windowGainedFocus(WindowEvent e) {
frame.getController().obtainFocusForSelected();
frame.removeWindowFocusListener(this);
}
});
frame.setVisible(true);
if (splash != null) {
splash.setVisible(false);
}
frame.fireStartupDone();
}
private void initServer() {
String portFile = getPortFile();
if (portFile == null) {
return;
}
mEditServer = new EditServer(portFile, this);
mEditServer.start();
}
private void checkForAnotherInstance(String[] pArgs) {
String portFile = getPortFile();
if (portFile == null) {
return;
}
// {{{ Try connecting to another running FreeMind instance
if (portFile != null && new File(portFile).exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(portFile));
String check = in.readLine();
if (!check.equals("b"))
throw new Exception("Wrong port file format");
int port = Integer.parseInt(in.readLine());
int key = Integer.parseInt(in.readLine());
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),
port);
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
out.writeInt(key);
String script;
// Put url to open here
script = Tools.arrayToUrls(pArgs);
out.writeUTF(script);
logger.info("Waiting for server");
// block until its closed
try {
socket.getInputStream().read();
} catch (Exception e) {
}
in.close();
out.close();
System.exit(0);
} catch (Exception e) {
// ok, this one seems to confuse newbies
// endlessly, so log it as NOTICE, not
// ERROR
logger.info("An error occurred"
+ " while connecting to the jEdit server instance.");
logger.info("This probably means that"
+ " jEdit crashed and/or exited abnormally");
logger.info("the last time it was run.");
logger.info("If you don't"
+ " know what this means, don't worry.");
logger.info("" + e);
}
}
}
/**
* @return null, if no port should be opened.
*/
private String getPortFile() {
if (mEditServer == null
&& Resources.getInstance().getBoolProperty(
RESOURCES_DON_T_OPEN_PORT)) {
return null;
}
return getFreemindDirectory() + File.separator + getProperty(PORT_FILE);
}
private void fireStartupDone() {
mStartupDone = true;
for (Iterator it = mStartupDoneListeners.iterator(); it.hasNext();) {
StartupDoneListener listener = (StartupDoneListener) it.next();
listener.startupDone();
}
}
private void setScreenBounds() {
// Create the MenuBar
menuBar = new MenuBar(controller);
setJMenuBar(menuBar);
// Create the scroll pane
mScrollPane = new MapView.ScrollPane();
if (Resources.getInstance().getBoolProperty("no_scrollbar")) {
mScrollPane
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
mScrollPane
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
} else {
mScrollPane
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
mScrollPane
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
status = new JLabel("!");
status.setPreferredSize(status.getPreferredSize());
status.setText("");
mContentComponent = mScrollPane;
boolean shouldUseTabbedPane = Resources.getInstance().getBoolProperty(
RESOURCES_USE_TABBED_PANE);
if (shouldUseTabbedPane) {
// tabbed panes eat control up. This is corrected here.
InputMap map;
map = (InputMap) UIManager.get("TabbedPane.ancestorInputMap");
KeyStroke keyStrokeCtrlUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP,
InputEvent.CTRL_DOWN_MASK);
map.remove(keyStrokeCtrlUp);
mTabbedPane = new JTabbedPane();
mTabbedPane.setFocusable(false);
controller.addTabbedPane(mTabbedPane);
getContentPane().add(mTabbedPane, BorderLayout.CENTER);
} else {
// don't use tabbed panes.
getContentPane().add(mContentComponent, BorderLayout.CENTER);
}
getContentPane().add(status, BorderLayout.SOUTH);
// Disable the default close button, instead use windowListener
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
controller.quit
.actionPerformed(new ActionEvent(this, 0, "quit"));
}
/*
* fc, 14.3.2008: Completely removed, as it damaged the focus if for
* example the note window was active.
*/
// public void windowActivated(WindowEvent e) {
// // This doesn't work the first time, it's called too early to
// // get Focus
// logger.info("windowActivated");
// if ((getView() != null) && (getView().getSelected() != null)) {
// getView().getSelected().requestFocus();
// }
// }
});
if (Tools.safeEquals(getProperty("toolbarVisible"), "false")) {
controller.setToolbarVisible(false);
}
if (Tools.safeEquals(getProperty("leftToolbarVisible"), "false")) {
controller.setLeftToolbarVisible(false);
}
// first define the final layout of the screen:
setFocusTraversalKeysEnabled(false);
pack();
// and now, determine size, position and state.
// set the default size (PN)
int win_width = getIntProperty("appwindow_width", 0);
int win_height = getIntProperty("appwindow_height", 0);
int win_x = getIntProperty("appwindow_x", 0);
int win_y = getIntProperty("appwindow_y", 0);
win_width = (win_width > 0) ? win_width : 640;
win_height = (win_height > 0) ? win_height : 440;
final Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
final Insets screenInsets = defaultToolkit
.getScreenInsets(getGraphicsConfiguration());
Dimension screenSize = defaultToolkit.getScreenSize();
final int screenWidth = screenSize.width - screenInsets.left
- screenInsets.right;
win_width = Math.min(win_width, screenWidth);
final int screenHeight = screenSize.height - screenInsets.top
- screenInsets.bottom;
win_height = Math.min(win_height, screenHeight);
win_x = Math.max(screenInsets.left, win_x);
win_x = Math.min(screenWidth + screenInsets.left - win_width, win_x);
win_y = Math.max(screenInsets.top, win_y);
win_y = Math.min(screenWidth + screenInsets.top - win_height, win_y);
setBounds(win_x, win_y, win_width, win_height);
// set the default state (normal/maximized) (PN)
// (note: this must be done later when partucular
// initalizations of the windows are ready,
// perhaps after setVisible is it enough... :-?
int win_state = Integer.parseInt(FreeMind.props.getProperty(
"appwindow_state", "0"));
win_state = ((win_state & ICONIFIED) != 0) ? NORMAL : win_state;
setExtendedState(win_state);
}
private ModeController createModeController(final String[] args) {
ModeController ctrl = controller.getModeController();
// try to load mac module:
try {
Class macClass = Class.forName("accessories.plugins.MacChanges");
// lazy programming. the mac class has exactly one
// constructor
// with a modeController.
macClass.getConstructors()[0].newInstance(new Object[] { this });
} catch (Exception e1) {
// freemind.main.Resources.getInstance().logExecption(e1);
}
return ctrl;
}
private int getMaximumNumberOfMapsToLoad(String[] args) {
LastStateStorageManagement management = getLastStateStorageManagement();
int[] values = { args.length, management.getLastOpenList().size(), 1 };
int ret = 0;
for (int i = 0; i < values.length; i++) {
ret = Math.max(ret, values[i]);
}
return ret;
}
private void loadMaps(final String[] args, ModeController pModeController,
FeedBack pFeedBack) {
boolean fileLoaded = false;
for (int i = 0; i < args.length; i++) {
// JOptionPane.showMessageDialog(null,i+":"+args[i]);
String fileArgument = args[i];
if (fileArgument.toLowerCase().endsWith(
freemind.main.FreeMindCommon.FREEMIND_FILE_EXTENSION)) {
if (!Tools.isAbsolutePath(fileArgument)) {
fileArgument = System.getProperty("user.dir")
+ System.getProperty("file.separator")
+ fileArgument;
}
// fin = ;
try {
pModeController.load(new File(fileArgument));
fileLoaded = true;
// logger.info("Attempting to load: " +
// args[i]);
} catch (Exception ex) {
System.err.println("File " + fileArgument
+ " not found error");
// System.exit(1);
}
}
pFeedBack.increase(FREE_MIND_PROGRESS_LOAD_MAPS);
}
if (!fileLoaded) {
fileLoaded = processLoadEventFromStartupPhase();
}
if (!fileLoaded
&& Tools.isPreferenceTrue(getProperty(FreeMindCommon.LOAD_LAST_MAPS_AND_LAYOUT))) {
int index = 0;
MapModule mapToFocus = null;
LastStateStorageManagement management = getLastStateStorageManagement();
for (Iterator it = management.getLastOpenList().iterator(); it
.hasNext();) {
MindmapLastStateStorage store = (MindmapLastStateStorage) it
.next();
String restorable = store.getRestorableName();
try {
if (controller.getLastOpenedList().open(restorable)) {
if (index == management.getLastFocussedTab()) {
mapToFocus = controller.getMapModule();
}
}
fileLoaded = true;
} catch (Exception e) {
freemind.main.Resources.getInstance().logException(e);
}
index++;
pFeedBack.increase(FREE_MIND_PROGRESS_LOAD_MAPS);
}
if (mapToFocus != null) {
controller.getMapModuleManager().changeToMapModule(
mapToFocus.getDisplayName());
}
}
if (!fileLoaded) {
String restoreable = getProperty(FreeMindCommon.ON_START_IF_NOT_SPECIFIED);
if (Tools
.isPreferenceTrue(getProperty(FreeMindCommon.LOAD_LAST_MAP))
&& restoreable != null && restoreable.length() > 0) {
try {
controller.getLastOpenedList().open(restoreable);
controller.getModeController().getView().moveToRoot();
fileLoaded = true;
pFeedBack.increase(FREE_MIND_PROGRESS_LOAD_MAPS);
} catch (Exception e) {
freemind.main.Resources.getInstance().logException(e);
out("An error occured on opening the file: " + restoreable
+ ".");
}
}
}
if (!fileLoaded
&& Tools.isPreferenceTrue(getProperty(FreeMindCommon.LOAD_NEW_MAP))) {
/*
* nothing loaded so far. Perhaps, we should display a new map...
* According to Summary: On first start FreeMind should show new map
* to newbies
* https://sourceforge.net/tracker/?func=detail&atid=107118
* &aid=1752516&group_id=7118
*/
pModeController.newMap();
pFeedBack.increase(FREE_MIND_PROGRESS_LOAD_MAPS);
}
}
private LastStateStorageManagement getLastStateStorageManagement() {
String lastStateMapXml = getProperty(FreeMindCommon.MINDMAP_LAST_STATE_MAP_STORAGE);
LastStateStorageManagement management = new LastStateStorageManagement(
lastStateMapXml);
return management;
}
/**
* Iterates over the load events from the startup phase
* <p>
* More than one file can be opened during startup. The filenames are stored
* in numbered properties, i.e.
* <ul>
* loadEventDuringStartup0=/Users/alex/Desktop/test1.mm
* loadEventDuringStartup1=/Users/alex/Desktop/test2.mm
* </ul>
*
* @return true if at least one file has been loaded
*/
private boolean processLoadEventFromStartupPhase() {
boolean atLeastOneFileHasBeenLoaded = false;
int count = 0;
while (true) {
String propertyKey = FreeMindCommon.LOAD_EVENT_DURING_STARTUP
+ count;
if (getProperty(propertyKey) == null) {
break;
} else {
if (processLoadEventFromStartupPhase(propertyKey))
atLeastOneFileHasBeenLoaded = true;
++count;
}
}
return atLeastOneFileHasBeenLoaded;
}
private boolean processLoadEventFromStartupPhase(String propertyKey) {
String filename = getProperty(propertyKey);
try {
if (logger.isLoggable(Level.INFO)) {
logger.info("Loading " + filename);
}
controller.getModeController().load(
Tools.fileToUrl(new File(filename)));
// remove temporary property because we do not want to store in a
// file and survive restart
getProperties().remove(propertyKey);
return true;
} catch (Exception e) {
freemind.main.Resources.getInstance().logException(e);
out("An error occured on opening the file: " + filename + ".");
return false;
}
}
/*
* (non-Javadoc)
*
* @see freemind.main.FreeMindMain#getJFrame()
*/
public JFrame getJFrame() {
return this;
}
public ClassLoader getFreeMindClassLoader() {
return mFreeMindCommon.getFreeMindClassLoader();
}
public String getFreemindBaseDir() {
return mFreeMindCommon.getFreemindBaseDir();
}
public String getAdjustableProperty(String label) {
return mFreeMindCommon.getAdjustableProperty(label);
}
public JSplitPane insertComponentIntoSplitPane(JComponent pMindMapComponent) {
if (mSplitPane != null) {
// already present:
return mSplitPane;
}
removeContentComponent();
mSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mScrollPane,
pMindMapComponent);
mSplitPane.setContinuousLayout(true);
mSplitPane.setOneTouchExpandable(false);
/*
* This means that the mind map area gets all the space that results
* from resizing the window.
*/
mSplitPane.setResizeWeight(1.0d);
// split panes eat F8 and F6. This is corrected here.
Tools.correctJSplitPaneKeyMap();
mContentComponent = mSplitPane;
setContentComponent();
// set divider position:
int splitPanePosition = getIntProperty(SPLIT_PANE_POSITION, -1);
int lastSplitPanePosition = getIntProperty(SPLIT_PANE_LAST_POSITION, -1);
if (splitPanePosition != -1 && lastSplitPanePosition != -1) {
mSplitPane.setDividerLocation(splitPanePosition);
mSplitPane.setLastDividerLocation(lastSplitPanePosition);
}
return mSplitPane;
}
public void removeSplitPane() {
if (mSplitPane != null) {
setProperty(SPLIT_PANE_POSITION,
"" + mSplitPane.getDividerLocation());
setProperty(SPLIT_PANE_LAST_POSITION,
"" + mSplitPane.getLastDividerLocation());
removeContentComponent();
mContentComponent = mScrollPane;
setContentComponent();
mSplitPane = null;
}
}
private void removeContentComponent() {
if (mTabbedPane != null) {
if (mTabbedPane.getSelectedIndex() >= 0) {
mTabbedPane.setComponentAt(mTabbedPane.getSelectedIndex(),
new JPanel());
}
} else {
getContentPane().remove(mContentComponent);
getRootPane().revalidate();
}
}
private void setContentComponent() {
if (mTabbedPane != null) {
if (mTabbedPane.getSelectedIndex() >= 0) {
mTabbedPane.setComponentAt(mTabbedPane.getSelectedIndex(),
mContentComponent);
}
} else {
getContentPane().add(mContentComponent, BorderLayout.CENTER);
getRootPane().revalidate();
}
}
public JScrollPane getScrollPane() {
return mScrollPane;
}
public JComponent getContentComponent() {
return mContentComponent;
}
public void registerStartupDoneListener(
StartupDoneListener pStartupDoneListener) {
if (!mStartupDone)
mStartupDoneListeners.add(pStartupDoneListener);
}
public List getLoggerList() {
return Collections.unmodifiableList(mLoggerList);
}
}
| false | true | public void openDocument(URL url) throws Exception {
// build string for default browser:
String correctedUrl = new String(url.toExternalForm());
if (url.getProtocol().equals("file")) {
correctedUrl = correctedUrl.replace('\\', '/').replaceAll(" ",
"%20");
// ^ This is more of a heuristic than a "logical" code
// and due to a java bug:
// http://forum.java.sun.com/thread.jsp?forum=31&thread=363990
}
// Originally, this method determined external application, with which
// the document
// should be opened. Which application should open which document type
// was
// configured in FreeMind properties file. As a result, FreeMind tried
// to solve the
// problem (of determining application for a file type), which should
// better be
// solved somewhere else. Indeed, on Windows, this problem is perfectly
// solved by
// Explorer. On KDE, this problem is solved by Konqueror default
// browser. In
// general, most WWW browsers have to solve this problem.
// As a result, the only thing we do here, is to open URL in WWW
// browser.
String osName = System.getProperty("os.name");
String urlString = url.toString();
final File file = Tools.urlToFile(url);
if (osName.substring(0, 3).equals("Win")) {
String propertyString = new String(
"default_browser_command_windows");
if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) {
propertyString += "_9x";
} else {
propertyString += "_nt";
}
String browser_command = new String();
String command = new String();
// Here we introduce " around the parameter of explorer
// command. This is not because of possible spaces in this
// parameter - it is because of "=" character, which causes
// problems. My understanding of MSDOS is not so good, but at
// least I can say, that "=" is used in general for the purpose
// of variable assignment.
// String[] call = { browser_command, "\""+url.toString()+"\"" };
try {
// This is working fine on Windows 2000 and NT as well
// Below is a piece of code showing how to run executables
// directly
// without asking. However, we don't want to do that. Explorer
// will run
// executable, but ask before it actually runs it.
//
// Imagine you download a package of maps containing also nasty
// executable. Let's say there is a map "index.mm". This map
// contains a
// link to that nasty executable, but the name of the link
// appearing to the
// user does not indicate at all that clicking the link leads to
// execution
// of a programm. This executable is located on your local
// computer, so
// asking before executing remote executable does not solve the
// problem. You click the link and there you are running evil
// executable.
// build string for default browser:
// ask for property about browser: fc, 26.11.2003.
Object[] messageArguments = { urlString };
MessageFormat formatter = new MessageFormat(
getProperty(propertyString));
browser_command = formatter.format(messageArguments);
if (url.getProtocol().equals("file")) {
if (!Tools.isBelowJava6()) {
Class desktopClass = Class.forName("java.awt.Desktop");
Method getDesktopMethod = desktopClass.getMethod(
"getDesktop", new Class[] {});
Object desktopObject = getDesktopMethod.invoke(null,
new Object[] {});
Method openMethod = desktopObject.getClass().getMethod(
"open", new Class[] { File.class });
openMethod.invoke(desktopObject, new Object[] { file });
return;
}
// command = "rundll32 url.dll,FileProtocolHandler "+
// Tools.urlGetFile(url);
// bug fix by Dan:
command = "cmd /C rundll32 url.dll,FileProtocolHandler "
+ urlString;
// see
// http://rsb.info.nih.gov/ij/developer/source/ij/plugin/BrowserLauncher.java.html
if (System.getProperty("os.name")
.startsWith("Windows 2000"))
command = "cmd /C rundll32 shell32.dll,ShellExec_RunDLL "
+ urlString;
} else if (urlString.startsWith("mailto:")) {
command = "cmd /C rundll32 url.dll,FileProtocolHandler "
+ urlString;
} else {
command = browser_command;
}
logger.info("Starting browser with " + command);
// Runtime.getRuntime().exec(command);
execWindows(command);
} catch (IOException x) {
controller
.errorMessage("Could not invoke browser.\n\nFreemind excecuted the following statement on a command line:\n\""
+ command
+ "\".\n\nYou may look at the user or default property called '"
+ propertyString + "'.");
System.err.println("Caught: " + x);
}
} else if (osName.startsWith("Mac OS")) {
// logger.info("Opening URL "+urlString);
String browser_command = new String();
try {
// ask for property about browser: fc, 26.11.2003.
Object[] messageArguments = { correctedUrl, urlString };
if ("file".equals(url.getProtocol())) {
// Bug in the apple's open function. For files, a pure
// filename must be given.
String[] command = {
getProperty("default_browser_command_mac_open"),
"file:" + file.getAbsolutePath() };
logger.info("Starting command: "
+ Arrays.deepToString(command));
Runtime.getRuntime().exec(command, null, null);
} else {
MessageFormat formatter = new MessageFormat(
getProperty("default_browser_command_mac"));
browser_command = formatter.format(messageArguments);
logger.info("Starting command: " + browser_command);
Runtime.getRuntime().exec(browser_command);
}
} catch (IOException ex2) {
controller
.errorMessage("Could not invoke browser.\n\nFreemind excecuted the following statement on a command line:\n\""
+ browser_command
+ "\".\n\nYou may look at the user or default property called 'default_browser_command_mac'.");
System.err.println("Caught: " + ex2);
}
} else {
// There is no '"' character around url.toString (compare to Windows
// code
// above). Putting '"' around does not work on Linux - instead, the
// '"'
// becomes part of URL, which is malformed, as a result.
String browser_command = new String();
try {
// ask for property about browser: fc, 26.11.2003.
Object[] messageArguments = { correctedUrl, urlString };
MessageFormat formatter = new MessageFormat(
getProperty("default_browser_command_other_os"));
browser_command = formatter.format(messageArguments);
logger.info("Starting command: " + browser_command);
Runtime.getRuntime().exec(browser_command);
} catch (IOException ex2) {
controller
.errorMessage("Could not invoke browser.\n\nFreemind excecuted the following statement on a command line:\n\""
+ browser_command
+ "\".\n\nYou may look at the user or default property called 'default_browser_command_other_os'.");
System.err.println("Caught: " + ex2);
}
}
}
| public void openDocument(URL url) throws Exception {
// build string for default browser:
String correctedUrl = new String(url.toExternalForm());
if (url.getProtocol().equals("file")) {
correctedUrl = correctedUrl.replace('\\', '/').replaceAll(" ",
"%20");
// ^ This is more of a heuristic than a "logical" code
// and due to a java bug:
// http://forum.java.sun.com/thread.jsp?forum=31&thread=363990
}
// Originally, this method determined external application, with which
// the document
// should be opened. Which application should open which document type
// was
// configured in FreeMind properties file. As a result, FreeMind tried
// to solve the
// problem (of determining application for a file type), which should
// better be
// solved somewhere else. Indeed, on Windows, this problem is perfectly
// solved by
// Explorer. On KDE, this problem is solved by Konqueror default
// browser. In
// general, most WWW browsers have to solve this problem.
// As a result, the only thing we do here, is to open URL in WWW
// browser.
String osName = System.getProperty("os.name");
String urlString = url.toString();
if (osName.substring(0, 3).equals("Win")) {
String propertyString = new String(
"default_browser_command_windows");
if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) {
propertyString += "_9x";
} else {
propertyString += "_nt";
}
String browser_command = new String();
String command = new String();
// Here we introduce " around the parameter of explorer
// command. This is not because of possible spaces in this
// parameter - it is because of "=" character, which causes
// problems. My understanding of MSDOS is not so good, but at
// least I can say, that "=" is used in general for the purpose
// of variable assignment.
// String[] call = { browser_command, "\""+url.toString()+"\"" };
try {
// This is working fine on Windows 2000 and NT as well
// Below is a piece of code showing how to run executables
// directly
// without asking. However, we don't want to do that. Explorer
// will run
// executable, but ask before it actually runs it.
//
// Imagine you download a package of maps containing also nasty
// executable. Let's say there is a map "index.mm". This map
// contains a
// link to that nasty executable, but the name of the link
// appearing to the
// user does not indicate at all that clicking the link leads to
// execution
// of a programm. This executable is located on your local
// computer, so
// asking before executing remote executable does not solve the
// problem. You click the link and there you are running evil
// executable.
// build string for default browser:
// ask for property about browser: fc, 26.11.2003.
Object[] messageArguments = { urlString };
MessageFormat formatter = new MessageFormat(
getProperty(propertyString));
browser_command = formatter.format(messageArguments);
if (url.getProtocol().equals("file")) {
final File file = Tools.urlToFile(url);
if (!Tools.isBelowJava6()) {
Class desktopClass = Class.forName("java.awt.Desktop");
Method getDesktopMethod = desktopClass.getMethod(
"getDesktop", new Class[] {});
Object desktopObject = getDesktopMethod.invoke(null,
new Object[] {});
Method openMethod = desktopObject.getClass().getMethod(
"open", new Class[] { File.class });
openMethod.invoke(desktopObject, new Object[] { file });
return;
}
// command = "rundll32 url.dll,FileProtocolHandler "+
// Tools.urlGetFile(url);
// bug fix by Dan:
command = "cmd /C rundll32 url.dll,FileProtocolHandler "
+ urlString;
// see
// http://rsb.info.nih.gov/ij/developer/source/ij/plugin/BrowserLauncher.java.html
if (System.getProperty("os.name")
.startsWith("Windows 2000"))
command = "cmd /C rundll32 shell32.dll,ShellExec_RunDLL "
+ urlString;
} else if (urlString.startsWith("mailto:")) {
command = "cmd /C rundll32 url.dll,FileProtocolHandler "
+ urlString;
} else {
command = browser_command;
}
logger.info("Starting browser with " + command);
// Runtime.getRuntime().exec(command);
execWindows(command);
} catch (IOException x) {
controller
.errorMessage("Could not invoke browser.\n\nFreemind excecuted the following statement on a command line:\n\""
+ command
+ "\".\n\nYou may look at the user or default property called '"
+ propertyString + "'.");
System.err.println("Caught: " + x);
}
} else if (osName.startsWith("Mac OS")) {
// logger.info("Opening URL "+urlString);
String browser_command = new String();
try {
// ask for property about browser: fc, 26.11.2003.
Object[] messageArguments = { correctedUrl, urlString };
if ("file".equals(url.getProtocol())) {
// Bug in the apple's open function. For files, a pure
// filename must be given.
final File file = Tools.urlToFile(url);
String[] command = {
getProperty("default_browser_command_mac_open"),
"file:" + file.getAbsolutePath() };
logger.info("Starting command: "
+ Arrays.deepToString(command));
Runtime.getRuntime().exec(command, null, null);
} else {
MessageFormat formatter = new MessageFormat(
getProperty("default_browser_command_mac"));
browser_command = formatter.format(messageArguments);
logger.info("Starting command: " + browser_command);
Runtime.getRuntime().exec(browser_command);
}
} catch (IOException ex2) {
controller
.errorMessage("Could not invoke browser.\n\nFreemind excecuted the following statement on a command line:\n\""
+ browser_command
+ "\".\n\nYou may look at the user or default property called 'default_browser_command_mac'.");
System.err.println("Caught: " + ex2);
}
} else {
// There is no '"' character around url.toString (compare to Windows
// code
// above). Putting '"' around does not work on Linux - instead, the
// '"'
// becomes part of URL, which is malformed, as a result.
String browser_command = new String();
try {
// ask for property about browser: fc, 26.11.2003.
Object[] messageArguments = { correctedUrl, urlString };
MessageFormat formatter = new MessageFormat(
getProperty("default_browser_command_other_os"));
browser_command = formatter.format(messageArguments);
logger.info("Starting command: " + browser_command);
Runtime.getRuntime().exec(browser_command);
} catch (IOException ex2) {
controller
.errorMessage("Could not invoke browser.\n\nFreemind excecuted the following statement on a command line:\n\""
+ browser_command
+ "\".\n\nYou may look at the user or default property called 'default_browser_command_other_os'.");
System.err.println("Caught: " + ex2);
}
}
}
|
diff --git a/modules/axiom-samples/src/test/java/org/apache/axiom/samples/FragmentsSample.java b/modules/axiom-samples/src/test/java/org/apache/axiom/samples/FragmentsSample.java
index 570b129b0..d6b86cb43 100644
--- a/modules/axiom-samples/src/test/java/org/apache/axiom/samples/FragmentsSample.java
+++ b/modules/axiom-samples/src/test/java/org/apache/axiom/samples/FragmentsSample.java
@@ -1,64 +1,64 @@
/*
* 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.axiom.samples;
import java.io.InputStream;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import junit.framework.TestCase;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMXMLBuilderFactory;
public class FragmentsSample extends TestCase {
// START SNIPPET: main
public void processFragments(InputStream in) throws XMLStreamException {
// Create an XMLStreamReader without building the object model
XMLStreamReader reader =
OMXMLBuilderFactory.createOMBuilder(in).getDocument().getXMLStreamReader(false);
while (reader.hasNext()) {
if (reader.getEventType() == XMLStreamReader.START_ELEMENT &&
reader.getName().equals(new QName("tag"))) {
// A matching START_ELEMENT event was found. Build a corresponding OMElement.
OMElement element =
OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement();
- // Make sure that all events belonging to the element are consumed so that
+ // Make sure that all events belonging to the element are consumed so
// that the XMLStreamReader points to a well defined location (namely the
// event immediately following the END_ELEMENT event).
element.build();
// Now process the element.
processFragment(element);
} else {
reader.next();
}
}
}
// END SNIPPET: main
public void processFragment(OMElement element) {
System.out.println(element.toString());
}
public void test() throws XMLStreamException {
processFragments(FragmentsSample.class.getResourceAsStream("fragments.xml"));
}
}
| true | true | public void processFragments(InputStream in) throws XMLStreamException {
// Create an XMLStreamReader without building the object model
XMLStreamReader reader =
OMXMLBuilderFactory.createOMBuilder(in).getDocument().getXMLStreamReader(false);
while (reader.hasNext()) {
if (reader.getEventType() == XMLStreamReader.START_ELEMENT &&
reader.getName().equals(new QName("tag"))) {
// A matching START_ELEMENT event was found. Build a corresponding OMElement.
OMElement element =
OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement();
// Make sure that all events belonging to the element are consumed so that
// that the XMLStreamReader points to a well defined location (namely the
// event immediately following the END_ELEMENT event).
element.build();
// Now process the element.
processFragment(element);
} else {
reader.next();
}
}
}
| public void processFragments(InputStream in) throws XMLStreamException {
// Create an XMLStreamReader without building the object model
XMLStreamReader reader =
OMXMLBuilderFactory.createOMBuilder(in).getDocument().getXMLStreamReader(false);
while (reader.hasNext()) {
if (reader.getEventType() == XMLStreamReader.START_ELEMENT &&
reader.getName().equals(new QName("tag"))) {
// A matching START_ELEMENT event was found. Build a corresponding OMElement.
OMElement element =
OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement();
// Make sure that all events belonging to the element are consumed so
// that the XMLStreamReader points to a well defined location (namely the
// event immediately following the END_ELEMENT event).
element.build();
// Now process the element.
processFragment(element);
} else {
reader.next();
}
}
}
|
diff --git a/debug/org.eclipse.ptp.debug.ui/src/org/eclipse/ptp/debug/ui/views/ParallelDebugViewEventHandler.java b/debug/org.eclipse.ptp.debug.ui/src/org/eclipse/ptp/debug/ui/views/ParallelDebugViewEventHandler.java
index ef9ddbfda..f971053f3 100644
--- a/debug/org.eclipse.ptp.debug.ui/src/org/eclipse/ptp/debug/ui/views/ParallelDebugViewEventHandler.java
+++ b/debug/org.eclipse.ptp.debug.ui/src/org/eclipse/ptp/debug/ui/views/ParallelDebugViewEventHandler.java
@@ -1,177 +1,177 @@
/*******************************************************************************
* Copyright (c) 2005 The Regents of the University of California.
* This material was produced under U.S. Government contract W-7405-ENG-36
* for Los Alamos National Laboratory, which is operated by the University
* of California for the U.S. Department of Energy. The U.S. Government has
* rights to use, reproduce, and distribute this software. NEITHER THE
* GOVERNMENT NOR THE UNIVERSITY MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* Additionally, 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
*
* LA-CC 04-115
*******************************************************************************/
package org.eclipse.ptp.debug.ui.views;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ptp.core.elements.IPJob;
import org.eclipse.ptp.core.elements.IPProcess;
import org.eclipse.ptp.debug.core.cdi.IPCDISession;
import org.eclipse.ptp.debug.core.events.IPDebugErrorInfo;
import org.eclipse.ptp.debug.core.events.IPDebugEvent;
import org.eclipse.ptp.debug.core.events.IPDebugInfo;
import org.eclipse.ptp.debug.core.events.IPDebugRegisterInfo;
import org.eclipse.ptp.debug.internal.ui.PDebugUIUtils;
import org.eclipse.ptp.debug.internal.ui.UIDebugManager;
import org.eclipse.ptp.debug.internal.ui.views.AbstractPDebugEventHandler;
import org.eclipse.ptp.debug.ui.PTPDebugUIPlugin;
import org.eclipse.ptp.ui.model.IElement;
import org.eclipse.ptp.ui.model.IElementHandler;
/**
* @author Clement chu
*/
public class ParallelDebugViewEventHandler extends AbstractPDebugEventHandler {
/**
* Constructs a new event handler on the given view
*
* @param view signals view
*/
public ParallelDebugViewEventHandler(ParallelDebugView view) {
super(view);
}
public ParallelDebugView getPView() {
return (ParallelDebugView)getView();
}
public void refresh(boolean all) {
getPView().refresh(all);
}
protected void doHandleDebugEvent(IPDebugEvent event, IProgressMonitor monitor) {
IPDebugInfo info = event.getInfo();
IPJob job = info.getJob();
switch(event.getKind()) {
case IPDebugEvent.CREATE:
switch (event.getDetail()) {
case IPDebugEvent.DEBUGGER:
PTPDebugUIPlugin.getUIDebugManager().defaultRegister((IPCDISession)event.getSource());
refresh();
break;
case IPDebugEvent.REGISTER:
boolean refresh = true;
if (info instanceof IPDebugRegisterInfo) {
refresh = ((IPDebugRegisterInfo)info).isRefresh();
}
int[] processes = info.getAllRegisteredProcesses().toArray();
if (refresh) {
IElementHandler elementHandler = getPView().getElementHandler(job.getID());
if (elementHandler != null) {
for (int j=0; j<processes.length; j++) {
IPProcess proc = job.getProcessByNumber(processes[j]);
IElement element = elementHandler.getSetRoot().get(proc.getID());
element.setRegistered(true);
elementHandler.addRegisterElement(element);
}
}
refresh();
}
if (processes.length > 0) {
getPView().focusOnDebugTarget(job, processes[0]);
}
break;
}
break;
case IPDebugEvent.TERMINATE:
switch (event.getDetail()) {
case IPDebugEvent.DEBUGGER:
refresh(true);
break;
case IPDebugEvent.REGISTER:
boolean refresh = true;
if (info instanceof IPDebugRegisterInfo) {
refresh = ((IPDebugRegisterInfo)info).isRefresh();
}
int[] processes = info.getAllUnregisteredProcesses().toArray();
if (refresh) {
IElementHandler elementHandler = getPView().getElementHandler(job.getID());
if (elementHandler != null) {
for (int j = 0; j < processes.length; j++) {
- //IPProcess proc = job.findProcessByTaskId(processes[j]);
- IElement element = elementHandler.getSetRoot().get(String.valueOf(processes[j]));
+ IPProcess proc = job.getProcessByNumber(processes[j]);
+ IElement element = elementHandler.getSetRoot().get(proc.getID());
element.setRegistered(false);
elementHandler.removeRegisterElement(element);
}
}
refresh();
}
break;
default:
/*
if (job.getID().equals(getPView().getCurrentID())) {
BitList tsource = (BitList) job.getAttribute(IAbstractDebugger.TERMINATED_PROC_KEY);
BitList ttarget = (BitList) job.getAttribute(IAbstractDebugger.SUSPENDED_PROC_KEY);
getPView().updateTerminateButton(tsource, ttarget);
}
*/
refresh(true);
break;
}
break;
case IPDebugEvent.RESUME:
((UIDebugManager) getPView().getUIManager()).updateVariableValue(false, info.getAllRegisteredProcesses());
case IPDebugEvent.SUSPEND:
if (job.getID().equals(getPView().getCurrentID())) {
//BitList ssource = (BitList)job.getAttribute(IAbstractDebugger.SUSPENDED_PROC_KEY);
//BitList starget = (BitList)job.getAttribute(IAbstractDebugger.TERMINATED_PROC_KEY);
//getPView().updateSuspendResumeButton(ssource, starget);
if (event.getKind() == IPDebugEvent.SUSPEND) {
getPView().updateStepReturnButton(info.getAllProcesses());
PTPDebugUIPlugin.getUIDebugManager().updateVariableValueOnSuspend(info.getAllProcesses());
}
}
getPView().updateAction();
refresh();
break;
case IPDebugEvent.CHANGE:
/*
int detail = event.getDetail();
if (detail == IPDebugEvent.EVALUATION || detail == IPDebugEvent.CONTENT) {
int[] diffTasks = info.getAllProcesses().toArray();
IElementHandler elementHandler = getPView().getElementHandler(job.getID());
for (int j=0; j<diffTasks.length; j++) {
IElement element = elementHandler.getSetRoot().get(String.valueOf(diffTasks[j]));
if (element instanceof DebugElement) {
if (detail == IPDebugEvent.EVALUATION) {
((DebugElement)element).setType(DebugElement.VALUE_DIFF);
}
else {
((DebugElement)element).resetType();
}
}
}
}
*/
refresh();
break;
case IPDebugEvent.ERROR:
final IPDebugErrorInfo errInfo = (IPDebugErrorInfo)info;
PTPDebugUIPlugin.getDisplay().asyncExec(new Runnable() {
public void run() {
String msg = "Error on tasks: "+ PDebugUIUtils.showBitList(errInfo.getAllProcesses()) + " - " + errInfo.getMsg();
IStatus status = new Status(IStatus.ERROR, PTPDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, msg, null);
PTPDebugUIPlugin.errorDialog("Error", status);
}
});
refresh(true);
break;
}
}
}
| true | true | protected void doHandleDebugEvent(IPDebugEvent event, IProgressMonitor monitor) {
IPDebugInfo info = event.getInfo();
IPJob job = info.getJob();
switch(event.getKind()) {
case IPDebugEvent.CREATE:
switch (event.getDetail()) {
case IPDebugEvent.DEBUGGER:
PTPDebugUIPlugin.getUIDebugManager().defaultRegister((IPCDISession)event.getSource());
refresh();
break;
case IPDebugEvent.REGISTER:
boolean refresh = true;
if (info instanceof IPDebugRegisterInfo) {
refresh = ((IPDebugRegisterInfo)info).isRefresh();
}
int[] processes = info.getAllRegisteredProcesses().toArray();
if (refresh) {
IElementHandler elementHandler = getPView().getElementHandler(job.getID());
if (elementHandler != null) {
for (int j=0; j<processes.length; j++) {
IPProcess proc = job.getProcessByNumber(processes[j]);
IElement element = elementHandler.getSetRoot().get(proc.getID());
element.setRegistered(true);
elementHandler.addRegisterElement(element);
}
}
refresh();
}
if (processes.length > 0) {
getPView().focusOnDebugTarget(job, processes[0]);
}
break;
}
break;
case IPDebugEvent.TERMINATE:
switch (event.getDetail()) {
case IPDebugEvent.DEBUGGER:
refresh(true);
break;
case IPDebugEvent.REGISTER:
boolean refresh = true;
if (info instanceof IPDebugRegisterInfo) {
refresh = ((IPDebugRegisterInfo)info).isRefresh();
}
int[] processes = info.getAllUnregisteredProcesses().toArray();
if (refresh) {
IElementHandler elementHandler = getPView().getElementHandler(job.getID());
if (elementHandler != null) {
for (int j = 0; j < processes.length; j++) {
//IPProcess proc = job.findProcessByTaskId(processes[j]);
IElement element = elementHandler.getSetRoot().get(String.valueOf(processes[j]));
element.setRegistered(false);
elementHandler.removeRegisterElement(element);
}
}
refresh();
}
break;
default:
/*
if (job.getID().equals(getPView().getCurrentID())) {
BitList tsource = (BitList) job.getAttribute(IAbstractDebugger.TERMINATED_PROC_KEY);
BitList ttarget = (BitList) job.getAttribute(IAbstractDebugger.SUSPENDED_PROC_KEY);
getPView().updateTerminateButton(tsource, ttarget);
}
*/
refresh(true);
break;
}
break;
case IPDebugEvent.RESUME:
((UIDebugManager) getPView().getUIManager()).updateVariableValue(false, info.getAllRegisteredProcesses());
case IPDebugEvent.SUSPEND:
if (job.getID().equals(getPView().getCurrentID())) {
//BitList ssource = (BitList)job.getAttribute(IAbstractDebugger.SUSPENDED_PROC_KEY);
//BitList starget = (BitList)job.getAttribute(IAbstractDebugger.TERMINATED_PROC_KEY);
//getPView().updateSuspendResumeButton(ssource, starget);
if (event.getKind() == IPDebugEvent.SUSPEND) {
getPView().updateStepReturnButton(info.getAllProcesses());
PTPDebugUIPlugin.getUIDebugManager().updateVariableValueOnSuspend(info.getAllProcesses());
}
}
getPView().updateAction();
refresh();
break;
case IPDebugEvent.CHANGE:
/*
int detail = event.getDetail();
if (detail == IPDebugEvent.EVALUATION || detail == IPDebugEvent.CONTENT) {
int[] diffTasks = info.getAllProcesses().toArray();
IElementHandler elementHandler = getPView().getElementHandler(job.getID());
for (int j=0; j<diffTasks.length; j++) {
IElement element = elementHandler.getSetRoot().get(String.valueOf(diffTasks[j]));
if (element instanceof DebugElement) {
if (detail == IPDebugEvent.EVALUATION) {
((DebugElement)element).setType(DebugElement.VALUE_DIFF);
}
else {
((DebugElement)element).resetType();
}
}
}
}
*/
refresh();
break;
case IPDebugEvent.ERROR:
final IPDebugErrorInfo errInfo = (IPDebugErrorInfo)info;
PTPDebugUIPlugin.getDisplay().asyncExec(new Runnable() {
public void run() {
String msg = "Error on tasks: "+ PDebugUIUtils.showBitList(errInfo.getAllProcesses()) + " - " + errInfo.getMsg();
IStatus status = new Status(IStatus.ERROR, PTPDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, msg, null);
PTPDebugUIPlugin.errorDialog("Error", status);
}
});
refresh(true);
break;
}
}
| protected void doHandleDebugEvent(IPDebugEvent event, IProgressMonitor monitor) {
IPDebugInfo info = event.getInfo();
IPJob job = info.getJob();
switch(event.getKind()) {
case IPDebugEvent.CREATE:
switch (event.getDetail()) {
case IPDebugEvent.DEBUGGER:
PTPDebugUIPlugin.getUIDebugManager().defaultRegister((IPCDISession)event.getSource());
refresh();
break;
case IPDebugEvent.REGISTER:
boolean refresh = true;
if (info instanceof IPDebugRegisterInfo) {
refresh = ((IPDebugRegisterInfo)info).isRefresh();
}
int[] processes = info.getAllRegisteredProcesses().toArray();
if (refresh) {
IElementHandler elementHandler = getPView().getElementHandler(job.getID());
if (elementHandler != null) {
for (int j=0; j<processes.length; j++) {
IPProcess proc = job.getProcessByNumber(processes[j]);
IElement element = elementHandler.getSetRoot().get(proc.getID());
element.setRegistered(true);
elementHandler.addRegisterElement(element);
}
}
refresh();
}
if (processes.length > 0) {
getPView().focusOnDebugTarget(job, processes[0]);
}
break;
}
break;
case IPDebugEvent.TERMINATE:
switch (event.getDetail()) {
case IPDebugEvent.DEBUGGER:
refresh(true);
break;
case IPDebugEvent.REGISTER:
boolean refresh = true;
if (info instanceof IPDebugRegisterInfo) {
refresh = ((IPDebugRegisterInfo)info).isRefresh();
}
int[] processes = info.getAllUnregisteredProcesses().toArray();
if (refresh) {
IElementHandler elementHandler = getPView().getElementHandler(job.getID());
if (elementHandler != null) {
for (int j = 0; j < processes.length; j++) {
IPProcess proc = job.getProcessByNumber(processes[j]);
IElement element = elementHandler.getSetRoot().get(proc.getID());
element.setRegistered(false);
elementHandler.removeRegisterElement(element);
}
}
refresh();
}
break;
default:
/*
if (job.getID().equals(getPView().getCurrentID())) {
BitList tsource = (BitList) job.getAttribute(IAbstractDebugger.TERMINATED_PROC_KEY);
BitList ttarget = (BitList) job.getAttribute(IAbstractDebugger.SUSPENDED_PROC_KEY);
getPView().updateTerminateButton(tsource, ttarget);
}
*/
refresh(true);
break;
}
break;
case IPDebugEvent.RESUME:
((UIDebugManager) getPView().getUIManager()).updateVariableValue(false, info.getAllRegisteredProcesses());
case IPDebugEvent.SUSPEND:
if (job.getID().equals(getPView().getCurrentID())) {
//BitList ssource = (BitList)job.getAttribute(IAbstractDebugger.SUSPENDED_PROC_KEY);
//BitList starget = (BitList)job.getAttribute(IAbstractDebugger.TERMINATED_PROC_KEY);
//getPView().updateSuspendResumeButton(ssource, starget);
if (event.getKind() == IPDebugEvent.SUSPEND) {
getPView().updateStepReturnButton(info.getAllProcesses());
PTPDebugUIPlugin.getUIDebugManager().updateVariableValueOnSuspend(info.getAllProcesses());
}
}
getPView().updateAction();
refresh();
break;
case IPDebugEvent.CHANGE:
/*
int detail = event.getDetail();
if (detail == IPDebugEvent.EVALUATION || detail == IPDebugEvent.CONTENT) {
int[] diffTasks = info.getAllProcesses().toArray();
IElementHandler elementHandler = getPView().getElementHandler(job.getID());
for (int j=0; j<diffTasks.length; j++) {
IElement element = elementHandler.getSetRoot().get(String.valueOf(diffTasks[j]));
if (element instanceof DebugElement) {
if (detail == IPDebugEvent.EVALUATION) {
((DebugElement)element).setType(DebugElement.VALUE_DIFF);
}
else {
((DebugElement)element).resetType();
}
}
}
}
*/
refresh();
break;
case IPDebugEvent.ERROR:
final IPDebugErrorInfo errInfo = (IPDebugErrorInfo)info;
PTPDebugUIPlugin.getDisplay().asyncExec(new Runnable() {
public void run() {
String msg = "Error on tasks: "+ PDebugUIUtils.showBitList(errInfo.getAllProcesses()) + " - " + errInfo.getMsg();
IStatus status = new Status(IStatus.ERROR, PTPDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, msg, null);
PTPDebugUIPlugin.errorDialog("Error", status);
}
});
refresh(true);
break;
}
}
|
diff --git a/src/model/XLBufferedReader.java b/src/model/XLBufferedReader.java
index 2bbcdba..786c31b 100755
--- a/src/model/XLBufferedReader.java
+++ b/src/model/XLBufferedReader.java
@@ -1,26 +1,26 @@
package model;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;
import util.XLException;
public class XLBufferedReader extends BufferedReader {
public XLBufferedReader(String name) throws FileNotFoundException {
super(new FileReader(name));
}
public void load(Map<String, Slot> map, SlotFactory slotFactory, Sheet sheet) {
try {
while (ready()) {
String string = readLine();
int i = string.indexOf('=');
- map.put(string.substring(0, i-1),slotFactory.build(string.substring(i+1),sheet));
+ map.put(string.substring(0, i),slotFactory.build(string.substring(i+1),sheet));
}
} catch (Exception e) {
throw new XLException(e.getMessage());
}
}
}
| true | true | public void load(Map<String, Slot> map, SlotFactory slotFactory, Sheet sheet) {
try {
while (ready()) {
String string = readLine();
int i = string.indexOf('=');
map.put(string.substring(0, i-1),slotFactory.build(string.substring(i+1),sheet));
}
} catch (Exception e) {
throw new XLException(e.getMessage());
}
}
| public void load(Map<String, Slot> map, SlotFactory slotFactory, Sheet sheet) {
try {
while (ready()) {
String string = readLine();
int i = string.indexOf('=');
map.put(string.substring(0, i),slotFactory.build(string.substring(i+1),sheet));
}
} catch (Exception e) {
throw new XLException(e.getMessage());
}
}
|
diff --git a/plugins/org.eclipse.sirius.editor/src-gen/org/eclipse/sirius/editor/properties/sections/description/estructuralfeaturecustomization/EStructuralFeatureCustomizationAppliedOnPropertySection.java b/plugins/org.eclipse.sirius.editor/src-gen/org/eclipse/sirius/editor/properties/sections/description/estructuralfeaturecustomization/EStructuralFeatureCustomizationAppliedOnPropertySection.java
index 30853ebfd..a386c5e82 100644
--- a/plugins/org.eclipse.sirius.editor/src-gen/org/eclipse/sirius/editor/properties/sections/description/estructuralfeaturecustomization/EStructuralFeatureCustomizationAppliedOnPropertySection.java
+++ b/plugins/org.eclipse.sirius.editor/src-gen/org/eclipse/sirius/editor/properties/sections/description/estructuralfeaturecustomization/EStructuralFeatureCustomizationAppliedOnPropertySection.java
@@ -1,195 +1,203 @@
/*******************************************************************************
* Copyright (c) 2007, 2014 THALES GLOBAL SERVICES.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.sirius.editor.properties.sections.description.estructuralfeaturecustomization;
// Start of user code imports
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.sirius.business.api.dialect.DialectManager;
import org.eclipse.sirius.common.tools.api.util.StringUtil;
import org.eclipse.sirius.editor.editorPlugin.SiriusEditor;
import org.eclipse.sirius.editor.properties.sections.common.AbstractEditorDialogPropertySection;
import org.eclipse.sirius.viewpoint.description.DescriptionPackage;
import org.eclipse.sirius.viewpoint.description.EAttributeCustomization;
import org.eclipse.sirius.viewpoint.description.EReferenceCustomization;
import org.eclipse.sirius.viewpoint.description.EStructuralFeatureCustomization;
import org.eclipse.sirius.viewpoint.description.style.BasicLabelStyleDescription;
import org.eclipse.sirius.viewpoint.description.style.LabelBorderStyleDescription;
import org.eclipse.sirius.viewpoint.description.style.StyleDescription;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
// End of user code imports
/**
* A section for the appliedOn property of a EStructuralFeatureCustomization
* object.
*/
public class EStructuralFeatureCustomizationAppliedOnPropertySection extends AbstractEditorDialogPropertySection {
/**
* @see org.eclipse.sirius.editor.properties.sections.AbstractEditorDialogPropertySection#getDefaultLabelText()
*/
protected String getDefaultLabelText() {
return "AppliedOn"; //$NON-NLS-1$
}
/**
* @see org.eclipse.sirius.editor.properties.sections.AbstractEditorDialogPropertySection#getLabelText()
*/
protected String getLabelText() {
String labelText;
labelText = super.getLabelText() + ":"; //$NON-NLS-1$
// Start of user code get label text
labelText = super.getLabelText() + "*:"; //$NON-NLS-1$
// End of user code get label text
return labelText;
}
/**
* @see org.eclipse.sirius.editor.properties.sections.AbstractEditorDialogPropertySection#getFeature()
*/
protected EReference getFeature() {
return DescriptionPackage.eINSTANCE.getEStructuralFeatureCustomization_AppliedOn();
}
/**
* @see org.eclipse.sirius.editor.properties.sections.AbstractEditorDialogPropertySection#getFeatureAsText()
*/
protected String getFeatureAsText() {
String string = new String();
if (eObject.eGet(getFeature()) != null) {
List<?> values = (List<?>) eObject.eGet(getFeature());
for (Iterator<?> iterator = values.iterator(); iterator.hasNext();) {
EObject eObj = (EObject) iterator.next();
string += getAdapterFactoryLabelProvider(eObj).getText(eObj);
if (iterator.hasNext())
string += ", ";
}
}
return string;
}
/**
* @see org.eclipse.sirius.editor.properties.sections.AbstractEditorDialogPropertySection#isEqual(java.util.List)
*/
protected boolean isEqual(List<?> newList) {
return newList.equals(eObject.eGet(getFeature()));
}
/**
* {@inheritDoc}
*/
public void createControls(Composite parent, TabbedPropertySheetPage tabbedPropertySheetPage) {
super.createControls(parent, tabbedPropertySheetPage);
text.setToolTipText("The style to customize.");
CLabel help = getWidgetFactory().createCLabel(composite, "");
FormData data = new FormData();
data.top = new FormAttachment(text, 0, SWT.TOP);
data.left = new FormAttachment(nameLabel);
help.setLayoutData(data);
help.setFont(SiriusEditor.getFontRegistry().get("description"));
help.setImage(getHelpIcon());
help.setToolTipText("The style to customize.");
// Start of user code create controls
nameLabel.setFont(SiriusEditor.getFontRegistry().get("required"));
// End of user code create controls
}
// Start of user code user operations
/**
* Overridden to limit the choice to {@link StyleDescription}s,
* {@link BasicLabelStyleDescription}s, {@link LabelBorderStyleDescription}s
* and {@link GaugeSectionDescription} owned by the current
* {@link DiagramDescription}.
*
* {@inheritDoc}
*/
@Override
protected List<?> getChoiceOfValues(List<?> currentValues) {
List<EObject> customizableElements = new ArrayList<EObject>();
for (Object choiceOfValue : super.getChoiceOfValues(currentValues)) {
if (choiceOfValue instanceof EObject) {
EObject choice = (EObject) choiceOfValue;
// Let the dialect tell us if they allow the customizations.
if (DialectManager.INSTANCE.allowsEStructuralFeatureCustomization(choice) && isConformToCustomization(choice)) {
customizableElements.add(choice);
}
}
}
return customizableElements;
}
private boolean isConformToCustomization(EObject choice) {
boolean isConform = false;
- // if the feature is null, let the user choose the value, the completion
- // will then help him to find the attribute name or the reference name
- // from the values.
+ // If the feature name (attribute name or reference name) is null or
+ // empty, let the user choose the value, the completion will then help
+ // him to find the attribute name or the reference name from the values.
// See
// org.eclipse.sirius.editor.tools.internal.assist.EAttributeCustomizationAttributeNameContentProposalProvider.bindCompletionProcessor(EAttributeCustomizationAttributeNamePropertySection,
// Text) and
// org.eclipse.sirius.editor.tools.internal.assist.EReferenceCustomizationReferenceNameContentProposalProvider.bindCompletionProcessor(EReferenceCustomizationReferenceNamePropertySection,
// Text)
if (eObject instanceof EAttributeCustomization) {
EAttributeCustomization eAttributeCustomization = (EAttributeCustomization) eObject;
- EStructuralFeature feature = getEStructuralFeature(choice.eClass(), eAttributeCustomization.getAttributeName());
- isConform = feature == null || feature instanceof EAttribute;
+ if (StringUtil.isEmpty(eAttributeCustomization.getAttributeName())) {
+ isConform = true;
+ } else {
+ EStructuralFeature feature = getEStructuralFeature(choice.eClass(), eAttributeCustomization.getAttributeName());
+ isConform = feature instanceof EAttribute;
+ }
} else if (eObject instanceof EReferenceCustomization) {
EReferenceCustomization eReferenceCustomization = (EReferenceCustomization) eObject;
- EStructuralFeature feature = getEStructuralFeature(choice.eClass(), eReferenceCustomization.getReferenceName());
- isConform = feature == null || feature instanceof EReference && checkValue((EReference) feature, eReferenceCustomization.getValue());
+ if (StringUtil.isEmpty(eReferenceCustomization.getReferenceName())) {
+ isConform = true;
+ } else {
+ EStructuralFeature feature = getEStructuralFeature(choice.eClass(), eReferenceCustomization.getReferenceName());
+ isConform = feature instanceof EReference && checkValue((EReference) feature, eReferenceCustomization.getValue());
+ }
}
return isConform;
}
private boolean checkValue(EReference ref, EObject value) {
EClass eType = ref.getEReferenceType();
return value != null && eType != null && eType.isSuperTypeOf(value.eClass());
}
private EStructuralFeature getEStructuralFeature(EClass eClass, String featureName) {
if (!StringUtil.isEmpty(featureName) && eClass != null) {
return eClass.getEStructuralFeature(featureName);
}
return null;
}
@Override
public void refresh() {
super.refresh();
updateReadOnlyStatus();
}
@Override
protected boolean shouldBeReadOnly() {
boolean shouldBeReadOnly = super.shouldBeReadOnly();
if (!shouldBeReadOnly) {
return ((EStructuralFeatureCustomization) eObject).isApplyOnAll();
}
return shouldBeReadOnly;
}
// End of user code user operations
}
| false | true | private boolean isConformToCustomization(EObject choice) {
boolean isConform = false;
// if the feature is null, let the user choose the value, the completion
// will then help him to find the attribute name or the reference name
// from the values.
// See
// org.eclipse.sirius.editor.tools.internal.assist.EAttributeCustomizationAttributeNameContentProposalProvider.bindCompletionProcessor(EAttributeCustomizationAttributeNamePropertySection,
// Text) and
// org.eclipse.sirius.editor.tools.internal.assist.EReferenceCustomizationReferenceNameContentProposalProvider.bindCompletionProcessor(EReferenceCustomizationReferenceNamePropertySection,
// Text)
if (eObject instanceof EAttributeCustomization) {
EAttributeCustomization eAttributeCustomization = (EAttributeCustomization) eObject;
EStructuralFeature feature = getEStructuralFeature(choice.eClass(), eAttributeCustomization.getAttributeName());
isConform = feature == null || feature instanceof EAttribute;
} else if (eObject instanceof EReferenceCustomization) {
EReferenceCustomization eReferenceCustomization = (EReferenceCustomization) eObject;
EStructuralFeature feature = getEStructuralFeature(choice.eClass(), eReferenceCustomization.getReferenceName());
isConform = feature == null || feature instanceof EReference && checkValue((EReference) feature, eReferenceCustomization.getValue());
}
return isConform;
}
| private boolean isConformToCustomization(EObject choice) {
boolean isConform = false;
// If the feature name (attribute name or reference name) is null or
// empty, let the user choose the value, the completion will then help
// him to find the attribute name or the reference name from the values.
// See
// org.eclipse.sirius.editor.tools.internal.assist.EAttributeCustomizationAttributeNameContentProposalProvider.bindCompletionProcessor(EAttributeCustomizationAttributeNamePropertySection,
// Text) and
// org.eclipse.sirius.editor.tools.internal.assist.EReferenceCustomizationReferenceNameContentProposalProvider.bindCompletionProcessor(EReferenceCustomizationReferenceNamePropertySection,
// Text)
if (eObject instanceof EAttributeCustomization) {
EAttributeCustomization eAttributeCustomization = (EAttributeCustomization) eObject;
if (StringUtil.isEmpty(eAttributeCustomization.getAttributeName())) {
isConform = true;
} else {
EStructuralFeature feature = getEStructuralFeature(choice.eClass(), eAttributeCustomization.getAttributeName());
isConform = feature instanceof EAttribute;
}
} else if (eObject instanceof EReferenceCustomization) {
EReferenceCustomization eReferenceCustomization = (EReferenceCustomization) eObject;
if (StringUtil.isEmpty(eReferenceCustomization.getReferenceName())) {
isConform = true;
} else {
EStructuralFeature feature = getEStructuralFeature(choice.eClass(), eReferenceCustomization.getReferenceName());
isConform = feature instanceof EReference && checkValue((EReference) feature, eReferenceCustomization.getValue());
}
}
return isConform;
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java
index 154b825fe..aff7be347 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java
@@ -1,332 +1,339 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;
import javax.annotation.PostConstruct;
import org.opentripplanner.routing.core.Edge;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.GraphVertex;
import org.opentripplanner.routing.core.TraverseOptions;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.EndpointVertex;
import org.opentripplanner.routing.edgetype.FreeEdge;
import org.opentripplanner.routing.edgetype.OutEdge;
import org.opentripplanner.routing.edgetype.PathwayEdge;
import org.opentripplanner.routing.edgetype.PlainStreetEdge;
import org.opentripplanner.routing.edgetype.StreetEdge;
import org.opentripplanner.routing.edgetype.StreetVertex;
import org.opentripplanner.routing.edgetype.TurnEdge;
import org.opentripplanner.routing.location.StreetLocation;
import org.opentripplanner.routing.services.StreetVertexIndexService;
import org.opentripplanner.routing.core.TransitStop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.index.SpatialIndex;
import com.vividsolutions.jts.index.strtree.STRtree;
import com.vividsolutions.jts.index.quadtree.Quadtree;
import com.vividsolutions.jts.linearref.LinearLocation;
import com.vividsolutions.jts.linearref.LocationIndexedLine;
/**
* Indexes all edges and transit vertices of the graph spatially. Has a variety of query methods used
* during network linking and trip planning.
*
* Creates a StreetLocation representing a location on a street that's not at an intersection,
* based on input latitude and longitude. Instantiating this class is expensive, because it creates
* a spatial index of all of the intersections in the graph.
*/
@Component
public class StreetVertexIndexServiceImpl implements StreetVertexIndexService {
private Graph graph;
private SpatialIndex edgeTree;
private STRtree transitStopTree;
private STRtree intersectionTree;
public static final double MAX_DISTANCE_FROM_STREET = 0.05;
private static final double DISTANCE_ERROR = 0.00005;
private static final double DIRECTION_ERROR = 0.05;
public StreetVertexIndexServiceImpl() {
}
public StreetVertexIndexServiceImpl(Graph graph) {
this.graph = graph;
}
public void setup_modifiable() {
edgeTree = new Quadtree();
postSetup();
}
@PostConstruct
public void setup() {
edgeTree = new STRtree();
postSetup();
((STRtree) edgeTree).build();
}
private void postSetup() {
transitStopTree = new STRtree();
intersectionTree = new STRtree();
for (GraphVertex gv : graph.getVertices()) {
Vertex v = gv.vertex;
for (Edge e : gv.getOutgoing()) {
if (e instanceof TurnEdge || e instanceof OutEdge || e instanceof PlainStreetEdge) {
if (e.getGeometry() == null) {
continue;
}
Envelope env = e.getGeometry().getEnvelopeInternal();
edgeTree.insert(env, e);
}
}
if (v instanceof TransitStop) {
// only index transit stops that (a) are entrances, or (b) have no associated
// entrances
TransitStop ts = (TransitStop) v;
if (!ts.isEntrance()) {
boolean hasEntrance = false;
for (Edge e : gv.getOutgoing()) {
if (e instanceof PathwayEdge) {
hasEntrance = true;
break;
}
}
if (hasEntrance) {
continue;
}
}
Envelope env = new Envelope(v.getCoordinate());
transitStopTree.insert(env, v);
}
if (v instanceof StreetVertex || v instanceof EndpointVertex) {
Envelope env = new Envelope(v.getCoordinate());
intersectionTree.insert(env, v);
}
}
transitStopTree.build();
}
/**
* Get all transit stops within a given distance of a coordinate
*
* @param distance in meters
*/
@SuppressWarnings("unchecked")
public List<Vertex> getLocalTransitStops(Coordinate c, double distance) {
Envelope env = new Envelope(c);
env.expandBy(DistanceLibrary.metersToDegrees(distance));
List<Vertex> nearby = transitStopTree.query(env);
List<Vertex> results = new ArrayList<Vertex>();
for (Vertex v : nearby) {
if (v.distance(c) <= distance) {
results.add(v);
}
}
return results;
}
/**
* Gets the closest vertex to a coordinate. If necessary,
* this vertex will be created by splitting nearby edges (non-permanently).
*/
public Vertex getClosestVertex(final Coordinate coordinate, TraverseOptions options) {
List<Vertex> vertices = getIntersectionAt(coordinate);
if (vertices != null && !vertices.isEmpty()) {
StreetLocation closest = new StreetLocation("corner " + Math.random(), coordinate, "");
for (Vertex v : vertices) {
Edge e = new FreeEdge(closest, v);
closest.getExtra().add(e);
e = new FreeEdge(v, closest);
closest.getExtra().add(e);
}
return closest;
}
Collection<Edge> edges = getClosestEdges(coordinate, options);
if (edges != null) {
Edge bestStreet = edges.iterator().next();
Geometry g = bestStreet.getGeometry();
LocationIndexedLine l = new LocationIndexedLine(g);
LinearLocation location = l.project(coordinate);
Coordinate nearestPoint = location.getCoordinate(g);
return StreetLocation.createStreetLocation(bestStreet.getName() + "_"
+ coordinate.toString(), bestStreet.getName(), edges, nearestPoint);
}
return null;
}
@Autowired
public void setGraph(Graph graph) {
this.graph = graph;
}
public Graph getGraph() {
return graph;
}
public void reified(StreetLocation vertex) {
for (Edge e : graph.getIncoming(vertex)) {
if ((e instanceof TurnEdge || e instanceof OutEdge) && e.getGeometry() != null)
edgeTree.insert(e.getGeometry().getEnvelopeInternal(), e);
}
for (Edge e : graph.getOutgoing(vertex)) {
if ((e instanceof TurnEdge || e instanceof OutEdge) && e.getGeometry() != null)
edgeTree.insert(e.getGeometry().getEnvelopeInternal(), e);
}
}
@SuppressWarnings("unchecked")
public Collection<Edge> getClosestEdges(Coordinate coordinate, TraverseOptions options) {
Envelope envelope = new Envelope(coordinate);
List<Edge> nearby = new LinkedList<Edge>();
int i = 0;
double envelopeGrowthRate = 0.0002;
GeometryFactory factory = new GeometryFactory();
Point p = factory.createPoint(coordinate);
- while (nearby.size() < 1 && i < 10) {
+ double bestDistance = Double.MAX_VALUE;
+ while (bestDistance > MAX_DISTANCE_FROM_STREET && i < 10) {
++i;
envelope.expandBy(envelopeGrowthRate);
envelopeGrowthRate *= 2;
/*
* It is presumed, that edges which are roughly the same distance from the examined
* coordinate in the same direction are parallel (coincident) edges.
*
* Parallel edges are needed to account for (oneway) streets with varying permissions,
* as well as the edge-based nature of the graph.
* i.e. using a C point on a oneway street a cyclist may go in one direction only, while
* a pedestrian should be able to go in any direction.
*/
- double bestDistance = Double.MAX_VALUE;
+ bestDistance = Double.MAX_VALUE;
Edge bestEdge = null;
nearby = edgeTree.query(envelope);
if (nearby != null) {
for (Edge e : nearby) {
if (e == null || e instanceof OutEdge)
continue;
Geometry g = e.getGeometry();
if (g != null) {
if (options != null && e instanceof StreetEdge) {
if (!((StreetEdge) e).canTraverse(options)) {
continue;
}
}
double distance = g.distance(p);
+ if (distance > envelope.getWidth() / 2) {
+ // Even if an edge is outside the query envelope, bounding boxes can
+ // still intersect. In this case, distance to the edge is greater
+ // than the query envelope size.
+ continue;
+ }
if (distance < bestDistance) {
bestDistance = distance;
bestEdge = e;
}
}
}
// find coincidence edges
if (bestDistance <= MAX_DISTANCE_FROM_STREET) {
LocationIndexedLine lil = new LocationIndexedLine(bestEdge.getGeometry());
LinearLocation location = lil.project(coordinate);
Coordinate nearestPointOnEdge = lil.extractPoint(location);
double xd = nearestPointOnEdge.x - coordinate.x;
double yd = nearestPointOnEdge.y - coordinate.y;
double edgeDirection = Math.atan2(yd, xd);
TreeMap<Double, Edge> parallel = new TreeMap<Double, Edge>();
for (Edge e : nearby) {
/* only include edges that this user can actually use */
if (e == null || e instanceof OutEdge) {
continue;
}
if (options != null && e instanceof StreetEdge) {
if (!((StreetEdge) e).canTraverse(options)) {
continue;
}
}
Geometry eg = e.getGeometry();
if (eg != null) {
double distance = eg.distance(p);
if (distance <= bestDistance + DISTANCE_ERROR) {
lil = new LocationIndexedLine(eg);
location = lil.project(coordinate);
nearestPointOnEdge = lil.extractPoint(location);
if (distance > bestDistance) {
/* ignore edges caught end-on unless they're the
* only choice */
Coordinate[] coordinates = eg.getCoordinates();
if (nearestPointOnEdge.equals(coordinates[0]) ||
nearestPointOnEdge.equals(coordinates[coordinates.length - 1])) {
continue;
}
}
/* compute direction from coordinate to edge */
xd = nearestPointOnEdge.x - coordinate.x;
yd = nearestPointOnEdge.y - coordinate.y;
double direction = Math.atan2(yd, xd);
if (Math.abs(direction - edgeDirection) < DIRECTION_ERROR) {
while (parallel.containsKey(distance)) {
distance += 0.00000001;
}
parallel.put(distance, e);
}
}
}
}
return parallel.values();
}
}
}
return null;
}
@SuppressWarnings("unchecked")
public List<Vertex> getIntersectionAt(Coordinate coordinate) {
Envelope envelope = new Envelope(coordinate);
envelope.expandBy(DISTANCE_ERROR * 2);
List<Vertex> nearby = intersectionTree.query(envelope);
List<Vertex> atIntersection = new ArrayList<Vertex>(nearby.size());
for (Vertex v: nearby) {
if (coordinate.distance(v.getCoordinate()) < DISTANCE_ERROR) {
atIntersection.add(v);
}
}
if (atIntersection.isEmpty()) {
return null;
}
return atIntersection;
}
}
| false | true | public Collection<Edge> getClosestEdges(Coordinate coordinate, TraverseOptions options) {
Envelope envelope = new Envelope(coordinate);
List<Edge> nearby = new LinkedList<Edge>();
int i = 0;
double envelopeGrowthRate = 0.0002;
GeometryFactory factory = new GeometryFactory();
Point p = factory.createPoint(coordinate);
while (nearby.size() < 1 && i < 10) {
++i;
envelope.expandBy(envelopeGrowthRate);
envelopeGrowthRate *= 2;
/*
* It is presumed, that edges which are roughly the same distance from the examined
* coordinate in the same direction are parallel (coincident) edges.
*
* Parallel edges are needed to account for (oneway) streets with varying permissions,
* as well as the edge-based nature of the graph.
* i.e. using a C point on a oneway street a cyclist may go in one direction only, while
* a pedestrian should be able to go in any direction.
*/
double bestDistance = Double.MAX_VALUE;
Edge bestEdge = null;
nearby = edgeTree.query(envelope);
if (nearby != null) {
for (Edge e : nearby) {
if (e == null || e instanceof OutEdge)
continue;
Geometry g = e.getGeometry();
if (g != null) {
if (options != null && e instanceof StreetEdge) {
if (!((StreetEdge) e).canTraverse(options)) {
continue;
}
}
double distance = g.distance(p);
if (distance < bestDistance) {
bestDistance = distance;
bestEdge = e;
}
}
}
// find coincidence edges
if (bestDistance <= MAX_DISTANCE_FROM_STREET) {
LocationIndexedLine lil = new LocationIndexedLine(bestEdge.getGeometry());
LinearLocation location = lil.project(coordinate);
Coordinate nearestPointOnEdge = lil.extractPoint(location);
double xd = nearestPointOnEdge.x - coordinate.x;
double yd = nearestPointOnEdge.y - coordinate.y;
double edgeDirection = Math.atan2(yd, xd);
TreeMap<Double, Edge> parallel = new TreeMap<Double, Edge>();
for (Edge e : nearby) {
/* only include edges that this user can actually use */
if (e == null || e instanceof OutEdge) {
continue;
}
if (options != null && e instanceof StreetEdge) {
if (!((StreetEdge) e).canTraverse(options)) {
continue;
}
}
Geometry eg = e.getGeometry();
if (eg != null) {
double distance = eg.distance(p);
if (distance <= bestDistance + DISTANCE_ERROR) {
lil = new LocationIndexedLine(eg);
location = lil.project(coordinate);
nearestPointOnEdge = lil.extractPoint(location);
if (distance > bestDistance) {
/* ignore edges caught end-on unless they're the
* only choice */
Coordinate[] coordinates = eg.getCoordinates();
if (nearestPointOnEdge.equals(coordinates[0]) ||
nearestPointOnEdge.equals(coordinates[coordinates.length - 1])) {
continue;
}
}
/* compute direction from coordinate to edge */
xd = nearestPointOnEdge.x - coordinate.x;
yd = nearestPointOnEdge.y - coordinate.y;
double direction = Math.atan2(yd, xd);
if (Math.abs(direction - edgeDirection) < DIRECTION_ERROR) {
while (parallel.containsKey(distance)) {
distance += 0.00000001;
}
parallel.put(distance, e);
}
}
}
}
return parallel.values();
}
}
}
return null;
}
| public Collection<Edge> getClosestEdges(Coordinate coordinate, TraverseOptions options) {
Envelope envelope = new Envelope(coordinate);
List<Edge> nearby = new LinkedList<Edge>();
int i = 0;
double envelopeGrowthRate = 0.0002;
GeometryFactory factory = new GeometryFactory();
Point p = factory.createPoint(coordinate);
double bestDistance = Double.MAX_VALUE;
while (bestDistance > MAX_DISTANCE_FROM_STREET && i < 10) {
++i;
envelope.expandBy(envelopeGrowthRate);
envelopeGrowthRate *= 2;
/*
* It is presumed, that edges which are roughly the same distance from the examined
* coordinate in the same direction are parallel (coincident) edges.
*
* Parallel edges are needed to account for (oneway) streets with varying permissions,
* as well as the edge-based nature of the graph.
* i.e. using a C point on a oneway street a cyclist may go in one direction only, while
* a pedestrian should be able to go in any direction.
*/
bestDistance = Double.MAX_VALUE;
Edge bestEdge = null;
nearby = edgeTree.query(envelope);
if (nearby != null) {
for (Edge e : nearby) {
if (e == null || e instanceof OutEdge)
continue;
Geometry g = e.getGeometry();
if (g != null) {
if (options != null && e instanceof StreetEdge) {
if (!((StreetEdge) e).canTraverse(options)) {
continue;
}
}
double distance = g.distance(p);
if (distance > envelope.getWidth() / 2) {
// Even if an edge is outside the query envelope, bounding boxes can
// still intersect. In this case, distance to the edge is greater
// than the query envelope size.
continue;
}
if (distance < bestDistance) {
bestDistance = distance;
bestEdge = e;
}
}
}
// find coincidence edges
if (bestDistance <= MAX_DISTANCE_FROM_STREET) {
LocationIndexedLine lil = new LocationIndexedLine(bestEdge.getGeometry());
LinearLocation location = lil.project(coordinate);
Coordinate nearestPointOnEdge = lil.extractPoint(location);
double xd = nearestPointOnEdge.x - coordinate.x;
double yd = nearestPointOnEdge.y - coordinate.y;
double edgeDirection = Math.atan2(yd, xd);
TreeMap<Double, Edge> parallel = new TreeMap<Double, Edge>();
for (Edge e : nearby) {
/* only include edges that this user can actually use */
if (e == null || e instanceof OutEdge) {
continue;
}
if (options != null && e instanceof StreetEdge) {
if (!((StreetEdge) e).canTraverse(options)) {
continue;
}
}
Geometry eg = e.getGeometry();
if (eg != null) {
double distance = eg.distance(p);
if (distance <= bestDistance + DISTANCE_ERROR) {
lil = new LocationIndexedLine(eg);
location = lil.project(coordinate);
nearestPointOnEdge = lil.extractPoint(location);
if (distance > bestDistance) {
/* ignore edges caught end-on unless they're the
* only choice */
Coordinate[] coordinates = eg.getCoordinates();
if (nearestPointOnEdge.equals(coordinates[0]) ||
nearestPointOnEdge.equals(coordinates[coordinates.length - 1])) {
continue;
}
}
/* compute direction from coordinate to edge */
xd = nearestPointOnEdge.x - coordinate.x;
yd = nearestPointOnEdge.y - coordinate.y;
double direction = Math.atan2(yd, xd);
if (Math.abs(direction - edgeDirection) < DIRECTION_ERROR) {
while (parallel.containsKey(distance)) {
distance += 0.00000001;
}
parallel.put(distance, e);
}
}
}
}
return parallel.values();
}
}
}
return null;
}
|
diff --git a/MPDroid/src/com/namelessdev/mpdroid/helpers/CoverAsyncHelper.java b/MPDroid/src/com/namelessdev/mpdroid/helpers/CoverAsyncHelper.java
index fc67f26d..8e503fe8 100644
--- a/MPDroid/src/com/namelessdev/mpdroid/helpers/CoverAsyncHelper.java
+++ b/MPDroid/src/com/namelessdev/mpdroid/helpers/CoverAsyncHelper.java
@@ -1,186 +1,192 @@
/*
* Copyright (C) 2010-2014 The MPDroid 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.namelessdev.mpdroid.helpers;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import com.namelessdev.mpdroid.MPDApplication;
import com.namelessdev.mpdroid.tools.Tools;
import org.a0z.mpd.AlbumInfo;
import org.a0z.mpd.MPD;
import java.util.Collection;
import java.util.LinkedList;
/**
* Download Covers Asynchronous with Messages
*
* @author Stefan Agner
* @version $Id: $
*/
public class CoverAsyncHelper extends Handler implements CoverDownloadListener {
public static final int EVENT_COVER_DOWNLOADED = 1;
public static final int EVENT_COVER_NOT_FOUND = 2;
public static final int EVENT_COVER_DOWNLOAD_STARTED = 3;
public static final int MAX_SIZE = 0;
private static final Message COVER_NOT_FOUND_MESSAGE;
static {
COVER_NOT_FOUND_MESSAGE = new Message();
COVER_NOT_FOUND_MESSAGE.what = EVENT_COVER_NOT_FOUND;
}
private MPDApplication app = null;
private SharedPreferences settings = null;
private int coverMaxSize = MAX_SIZE;
private int cachedCoverMaxSize = MAX_SIZE;
private Collection<CoverDownloadListener> coverDownloadListener;
public CoverAsyncHelper(MPDApplication app, SharedPreferences settings) {
this.app = app;
this.settings = settings;
coverDownloadListener = new LinkedList<CoverDownloadListener>();
}
public void addCoverDownloadListener(CoverDownloadListener listener) {
coverDownloadListener.add(listener);
}
private void displayCoverRetrieverName(CoverInfo coverInfo) {
try {
if (!coverInfo.getCoverRetriever().isCoverLocal()) {
String message = "\"" + coverInfo.getAlbum() + "\" cover found with "
+ coverInfo.getCoverRetriever().getName();
Tools.notifyUser(message, MPD.getApplicationContext());
}
} catch (Exception e) {
// Nothing to do
}
}
public void downloadCover(AlbumInfo albumInfo) {
downloadCover(albumInfo, false);
}
public void downloadCover(AlbumInfo albumInfo, boolean priority) {
final CoverInfo info = new CoverInfo(albumInfo);
info.setCoverMaxSize(coverMaxSize);
info.setCachedCoverMaxSize(cachedCoverMaxSize);
info.setPriority(priority);
info.setListener(this);
tagListenerCovers(albumInfo);
if (!albumInfo.isValid()) {
COVER_NOT_FOUND_MESSAGE.obj = info;
handleMessage(COVER_NOT_FOUND_MESSAGE);
} else {
CoverManager.getInstance(app, settings).addCoverRequest(info);
}
}
public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_COVER_DOWNLOADED:
CoverInfo coverInfo = (CoverInfo) msg.obj;
+ if (coverInfo.getCachedCoverMaxSize() < cachedCoverMaxSize ||
+ coverInfo.getCoverMaxSize() < coverMaxSize) {
+ // We've got the wrong size, get it again from the cache
+ downloadCover(coverInfo);
+ break;
+ }
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverDownloaded(coverInfo);
if (CoverManager.DEBUG)
displayCoverRetrieverName(coverInfo);
break;
case EVENT_COVER_NOT_FOUND:
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverNotFound((CoverInfo) msg.obj);
break;
case EVENT_COVER_DOWNLOAD_STARTED:
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverDownloadStarted((CoverInfo) msg.obj);
break;
default:
break;
}
}
@Override
public void onCoverDownloaded(CoverInfo cover) {
CoverAsyncHelper.this.obtainMessage(EVENT_COVER_DOWNLOADED, cover).sendToTarget();
}
@Override
public void onCoverDownloadStarted(CoverInfo cover) {
CoverAsyncHelper.this.obtainMessage(EVENT_COVER_DOWNLOAD_STARTED, cover).sendToTarget();
}
@Override
public void onCoverNotFound(CoverInfo cover) {
CoverAsyncHelper.this.obtainMessage(EVENT_COVER_NOT_FOUND, cover).sendToTarget();
}
public void removeCoverDownloadListener(CoverDownloadListener listener) {
coverDownloadListener.remove(listener);
}
/*
* If you want cached images to be read as a different size than the
* downloaded ones. If this equals MAX_SIZE, it will use the coverMaxSize
* (if not also MAX_SIZE) Example : useful for NowPlayingSmallFragment,
* where it's useless to read a big image, but since downloading one will
* fill the cache, download it at a bigger size.
*/
public void setCachedCoverMaxSize(int size) {
if (size < 0)
size = MAX_SIZE;
cachedCoverMaxSize = size;
}
public void setCoverMaxSize(int size) {
if (size < 0)
size = MAX_SIZE;
coverMaxSize = size;
}
public void setCoverMaxSizeFromScreen(Activity activity) {
final DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
setCoverMaxSize(Math.min(metrics.widthPixels, metrics.heightPixels));
}
public void setCoverRetrieversFromPreferences() {
CoverManager.getInstance(app, settings).setCoverRetrieversFromPreferences();
}
@Override
public void tagAlbumCover(AlbumInfo albumInfo) {
// Nothing to do
}
private void tagListenerCovers(AlbumInfo albumInfo) {
for (CoverDownloadListener listener : coverDownloadListener) {
listener.tagAlbumCover(albumInfo);
}
}
}
| true | true | public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_COVER_DOWNLOADED:
CoverInfo coverInfo = (CoverInfo) msg.obj;
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverDownloaded(coverInfo);
if (CoverManager.DEBUG)
displayCoverRetrieverName(coverInfo);
break;
case EVENT_COVER_NOT_FOUND:
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverNotFound((CoverInfo) msg.obj);
break;
case EVENT_COVER_DOWNLOAD_STARTED:
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverDownloadStarted((CoverInfo) msg.obj);
break;
default:
break;
}
}
| public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_COVER_DOWNLOADED:
CoverInfo coverInfo = (CoverInfo) msg.obj;
if (coverInfo.getCachedCoverMaxSize() < cachedCoverMaxSize ||
coverInfo.getCoverMaxSize() < coverMaxSize) {
// We've got the wrong size, get it again from the cache
downloadCover(coverInfo);
break;
}
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverDownloaded(coverInfo);
if (CoverManager.DEBUG)
displayCoverRetrieverName(coverInfo);
break;
case EVENT_COVER_NOT_FOUND:
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverNotFound((CoverInfo) msg.obj);
break;
case EVENT_COVER_DOWNLOAD_STARTED:
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverDownloadStarted((CoverInfo) msg.obj);
break;
default:
break;
}
}
|
diff --git a/javafx.source/src/org/netbeans/api/javafx/source/TreeUtilities.java b/javafx.source/src/org/netbeans/api/javafx/source/TreeUtilities.java
index 728b77b1..b9775011 100644
--- a/javafx.source/src/org/netbeans/api/javafx/source/TreeUtilities.java
+++ b/javafx.source/src/org/netbeans/api/javafx/source/TreeUtilities.java
@@ -1,399 +1,363 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.api.javafx.source;
import com.sun.javafx.api.tree.JavaFXTree;
import com.sun.javafx.api.tree.JavaFXTreePathScanner;
import com.sun.source.tree.*;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javafx.tree.JavafxPretty;
import java.io.IOException;
import java.io.StringWriter;
import org.netbeans.api.javafx.lexer.JFXTokenId;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.lexer.TokenSequence;
/**
*
* @author Jan Lahoda, Dusan Balek, Tomas Zezula
*/
public final class TreeUtilities {
private static final Logger logger = Logger.getLogger(TreeUtilities.class.getName());
private static final boolean LOGGABLE = logger.isLoggable(Level.FINE);
private final CompilationInfo info;
// private final CommentHandlerService handler;
/** Creates a new instance of CommentUtilities */
public TreeUtilities(final CompilationInfo info) {
assert info != null;
this.info = info;
// this.handler = CommentHandlerService.instance(info.impl.getJavacTask().getContext());
}
/**Checks whether the given tree represents a class.
*/
public boolean isClass(ClassTree tree) {
throw new UnsupportedOperationException();
}
/**Returns whether or not the given tree is synthetic - generated by the parser.
* Please note that this method does not check trees transitively - a child of a syntetic tree
* may be considered non-syntetic.
*
* @return true if the given tree is synthetic, false otherwise
* @throws NullPointerException if the given tree is null
*/
public boolean isSynthetic(TreePath path) throws NullPointerException {
if (path == null)
throw new NullPointerException();
while (path != null) {
if (isSynthetic(path.getCompilationUnit(), path.getLeaf()))
return true;
path = path.getParentPath();
}
return false;
}
private boolean isSynthetic(CompilationUnitTree cut, Tree leaf) throws NullPointerException {
JCTree tree = (JCTree) leaf;
if (tree.pos == (-1))
return true;
//check for synthetic superconstructor call:
if (leaf.getKind() == Kind.EXPRESSION_STATEMENT) {
ExpressionStatementTree est = (ExpressionStatementTree) leaf;
if (est.getExpression().getKind() == Kind.METHOD_INVOCATION) {
MethodInvocationTree mit = (MethodInvocationTree) est.getExpression();
if (mit.getMethodSelect().getKind() == Kind.IDENTIFIER) {
IdentifierTree it = (IdentifierTree) mit.getMethodSelect();
if ("super".equals(it.getName().toString())) {
SourcePositions sp = info.getTrees().getSourcePositions();
return sp.getEndPosition(cut, leaf) == (-1);
}
}
}
}
return false;
}
/**Returns list of comments attached to a given tree. Can return either
* preceding or trailing comments.
*
* @param tree for which comments should be returned
* @param preceding true if preceding comments should be returned, false if trailing comments should be returned.
* @return list of preceding/trailing comments attached to the given tree
*/
// public List<Comment> getComments(Tree tree, boolean preceding) {
// CommentSetImpl set = handler.getComments(tree);
//
// if (!set.areCommentsMapped()) {
// boolean assertsEnabled = false;
// boolean automap = true;
//
// assert assertsEnabled = true;
//
// if (assertsEnabled) {
// TreePath tp = TreePath.getPath(info.getCompilationUnit(), tree);
//
// if (tp == null) {
// Logger.getLogger(TreeUtilities.class.getName()).log(Level.WARNING, "Comment automap requested for Tree not from the root compilation info. Please, make sure to call GeneratorUtilities.importComments before Treeutilities.getComments. Tree: {0}", tree);
// Logger.getLogger(TreeUtilities.class.getName()).log(Level.WARNING, "Caller", new Exception());
// automap = false;
// }
// }
//
// if (automap) {
// try {
// TokenSequence<JFXTokenId> seq = ((SourceFileObject) info.getCompilationUnit().getSourceFile()).getTokenHierarchy().tokenSequence(JFXTokenId.language());
// new TranslateIdentifier(info, true, false, seq).translate(tree);
// } catch (IOException ex) {
// Exceptions.printStackTrace(ex);
// }
// }
// }
//
// List<Comment> comments = preceding ? set.getPrecedingComments() : set.getTrailingComments();
//
// return Collections.unmodifiableList(comments);
// }
public TreePath pathFor(int pos) {
return pathFor(new TreePath(info.getCompilationUnit()), pos);
}
/*XXX: dbalek
*/
public TreePath pathFor(TreePath path, int pos) {
return pathFor(path, pos, info.getTrees().getSourcePositions());
}
/*XXX: dbalek
*/
public TreePath pathFor(TreePath path, int pos, SourcePositions sourcePositions) {
if (info == null || path == null || sourcePositions == null)
throw new IllegalArgumentException();
class Result extends Error {
TreePath path;
Result(TreePath path) {
this.path = path;
}
}
class PathFinder extends JavaFXTreePathScanner<Void,Void> {
private int pos;
private SourcePositions sourcePositions;
private PathFinder(int pos, SourcePositions sourcePositions) {
this.pos = pos;
this.sourcePositions = sourcePositions;
}
public Void scan(Tree tree, Void p) {
if (tree != null) {
super.scan(tree, p);
long start = sourcePositions.getStartPosition(getCurrentPath().getCompilationUnit(), tree);
long end = sourcePositions.getEndPosition(getCurrentPath().getCompilationUnit(), tree);
if (start < pos && end >= pos) {
if (tree.getKind() == Tree.Kind.ERRONEOUS) {
tree.accept(this, p);
throw new Result(getCurrentPath());
}
throw new Result(new TreePath(getCurrentPath(), tree));
} else {
if ((start == -1) || (end == -1)) {
if (!isSynthetic(getCurrentPath().getCompilationUnit(), tree)) {
// here we might have a problem
if (LOGGABLE) {
logger.finest("SCAN: Cannot determine start and end for: " + treeToString(info, tree));
}
}
}
}
}
return null;
}
}
try {
new PathFinder(pos, sourcePositions).scan(path, null);
} catch (Result result) {
path = result.path;
}
if (path.getLeaf() == path.getCompilationUnit()) {
log("pathFor returning compilation unit for position: " + pos);
return path;
}
int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf());
int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf());
- while ((start == -1) || (end == -1)) {
+ while (start == -1 || pos < start || pos > end) {
if (LOGGABLE) {
logger.finer("pathFor moving to parent: " + treeToString(info, path.getLeaf()));
}
path = path.getParentPath();
if (LOGGABLE) {
logger.finer("pathFor moved to parent: " + treeToString(info, path.getLeaf()));
}
if (path.getLeaf() == path.getCompilationUnit()) {
break;
}
start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf());
end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf());
}
if (LOGGABLE) {
- logger.finer("pathFor before checking the tokens: " + treeToString(info, path.getLeaf()));
- }
- TokenSequence<JFXTokenId> tokenList = tokensFor(path.getLeaf(), sourcePositions);
- tokenList.moveEnd();
- if (tokenList.movePrevious() && tokenList.offset() < pos) {
- switch (tokenList.token().id()) {
- case GT:
- if (path.getLeaf().getKind() == Tree.Kind.MEMBER_SELECT || path.getLeaf().getKind() == Tree.Kind.CLASS || path.getLeaf().getKind() == Tree.Kind.GREATER_THAN)
- break;
- case RPAREN:
- if (path.getLeaf().getKind() == Tree.Kind.ENHANCED_FOR_LOOP || path.getLeaf().getKind() == Tree.Kind.FOR_LOOP ||
- path.getLeaf().getKind() == Tree.Kind.IF || path.getLeaf().getKind() == Tree.Kind.WHILE_LOOP ||
- path.getLeaf().getKind() == Tree.Kind.DO_WHILE_LOOP || path.getLeaf().getKind() == Tree.Kind.TYPE_CAST)
- break;
- case SEMI:
- if (path.getLeaf().getKind() == Tree.Kind.FOR_LOOP &&
- tokenList.offset() <= sourcePositions.getStartPosition(path.getCompilationUnit(), ((ForLoopTree)path.getLeaf()).getUpdate().get(0)))
- break;
- case RBRACE:
- path = path.getParentPath();
- switch (path.getLeaf().getKind()) {
- case CATCH:
- path = path.getParentPath();
- case METHOD:
- case FOR_LOOP:
- case ENHANCED_FOR_LOOP:
- case IF:
- case SYNCHRONIZED:
- case WHILE_LOOP:
- case TRY:
- path = path.getParentPath();
- }
- break;
- }
- }
- if (LOGGABLE) {
log("pathFor(pos: " + pos + ") returning: " + treeToString(info, path.getLeaf()));
}
return path;
}
/**Computes {@link Scope} for the given position.
*/
public Scope scopeFor(int pos) {
List<? extends StatementTree> stmts = null;
SourcePositions sourcePositions = info.getTrees().getSourcePositions();
TreePath path = pathFor(pos);
CompilationUnitTree root = path.getCompilationUnit();
switch (path.getLeaf().getKind()) {
case BLOCK:
stmts = ((BlockTree)path.getLeaf()).getStatements();
break;
case FOR_LOOP:
stmts = ((ForLoopTree)path.getLeaf()).getInitializer();
break;
case ENHANCED_FOR_LOOP:
stmts = Collections.singletonList(((EnhancedForLoopTree)path.getLeaf()).getStatement());
break;
case METHOD:
stmts = ((MethodTree)path.getLeaf()).getParameters();
break;
}
if (stmts != null) {
Tree tree = null;
for (StatementTree st : stmts) {
if (sourcePositions.getStartPosition(root, st) < pos)
tree = st;
}
if (tree != null)
path = new TreePath(path, tree);
}
Scope scope = info.getTrees().getScope(path);
if (path.getLeaf().getKind() == Tree.Kind.CLASS) {
TokenSequence<JFXTokenId> ts = info.getTokenHierarchy().tokenSequence(JFXTokenId.language());
ts.move(pos);
while(ts.movePrevious()) {
switch (ts.token().id()) {
case WS:
case LINE_COMMENT:
case COMMENT:
case DOC_COMMENT:
break;
default:
return scope;
}
}
}
return scope;
}
/**Returns tokens for a given tree.
*/
public TokenSequence<JFXTokenId> tokensFor(Tree tree) {
return tokensFor(tree, info.getTrees().getSourcePositions());
}
/**Returns tokens for a given tree. Uses specified {@link SourcePositions}.
*/
public TokenSequence<JFXTokenId> tokensFor(Tree tree, SourcePositions sourcePositions) {
int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), tree);
int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), tree);
if ((start == -1) || (end == -1)) {
throw new RuntimeException("RE Cannot determine start and end for: " + treeToString(info, tree));
}
TokenSequence<JFXTokenId> t = info.getTokenHierarchy().tokenSequence(JFXTokenId.language());
if (t == null) {
throw new RuntimeException("RE SDid not get a token sequence.");
}
return t.subSequence(start, end);
}
private static String treeToString(CompilationInfo info, Tree t) {
JavaFXTree.JavaFXKind k = null;
StringWriter s = new StringWriter();
try {
new JavafxPretty(s, false).printExpr((JCTree)t);
} catch (IOException e) {
throw new AssertionError(e);
}
if (t instanceof JavaFXTree && t.getKind() == Kind.OTHER) {
JavaFXTree jfxt = (JavaFXTree)t;
k = jfxt.getJavaFXKind();
}
String res = null;
if (k != null) {
res = k.toString();
} else {
res = String.valueOf(t.getKind());
}
SourcePositions pos = info.getTrees().getSourcePositions();
res = res + '[' + pos.getStartPosition(info.getCompilationUnit(), t) + ',' +
pos.getEndPosition(info.getCompilationUnit(), t) + "]:" + s.toString();
return res;
}
private static void log(String s) {
if (LOGGABLE) {
logger.fine(s);
}
}
}
| false | true | public TreePath pathFor(TreePath path, int pos, SourcePositions sourcePositions) {
if (info == null || path == null || sourcePositions == null)
throw new IllegalArgumentException();
class Result extends Error {
TreePath path;
Result(TreePath path) {
this.path = path;
}
}
class PathFinder extends JavaFXTreePathScanner<Void,Void> {
private int pos;
private SourcePositions sourcePositions;
private PathFinder(int pos, SourcePositions sourcePositions) {
this.pos = pos;
this.sourcePositions = sourcePositions;
}
public Void scan(Tree tree, Void p) {
if (tree != null) {
super.scan(tree, p);
long start = sourcePositions.getStartPosition(getCurrentPath().getCompilationUnit(), tree);
long end = sourcePositions.getEndPosition(getCurrentPath().getCompilationUnit(), tree);
if (start < pos && end >= pos) {
if (tree.getKind() == Tree.Kind.ERRONEOUS) {
tree.accept(this, p);
throw new Result(getCurrentPath());
}
throw new Result(new TreePath(getCurrentPath(), tree));
} else {
if ((start == -1) || (end == -1)) {
if (!isSynthetic(getCurrentPath().getCompilationUnit(), tree)) {
// here we might have a problem
if (LOGGABLE) {
logger.finest("SCAN: Cannot determine start and end for: " + treeToString(info, tree));
}
}
}
}
}
return null;
}
}
try {
new PathFinder(pos, sourcePositions).scan(path, null);
} catch (Result result) {
path = result.path;
}
if (path.getLeaf() == path.getCompilationUnit()) {
log("pathFor returning compilation unit for position: " + pos);
return path;
}
int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf());
int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf());
while ((start == -1) || (end == -1)) {
if (LOGGABLE) {
logger.finer("pathFor moving to parent: " + treeToString(info, path.getLeaf()));
}
path = path.getParentPath();
if (LOGGABLE) {
logger.finer("pathFor moved to parent: " + treeToString(info, path.getLeaf()));
}
if (path.getLeaf() == path.getCompilationUnit()) {
break;
}
start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf());
end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf());
}
if (LOGGABLE) {
logger.finer("pathFor before checking the tokens: " + treeToString(info, path.getLeaf()));
}
TokenSequence<JFXTokenId> tokenList = tokensFor(path.getLeaf(), sourcePositions);
tokenList.moveEnd();
if (tokenList.movePrevious() && tokenList.offset() < pos) {
switch (tokenList.token().id()) {
case GT:
if (path.getLeaf().getKind() == Tree.Kind.MEMBER_SELECT || path.getLeaf().getKind() == Tree.Kind.CLASS || path.getLeaf().getKind() == Tree.Kind.GREATER_THAN)
break;
case RPAREN:
if (path.getLeaf().getKind() == Tree.Kind.ENHANCED_FOR_LOOP || path.getLeaf().getKind() == Tree.Kind.FOR_LOOP ||
path.getLeaf().getKind() == Tree.Kind.IF || path.getLeaf().getKind() == Tree.Kind.WHILE_LOOP ||
path.getLeaf().getKind() == Tree.Kind.DO_WHILE_LOOP || path.getLeaf().getKind() == Tree.Kind.TYPE_CAST)
break;
case SEMI:
if (path.getLeaf().getKind() == Tree.Kind.FOR_LOOP &&
tokenList.offset() <= sourcePositions.getStartPosition(path.getCompilationUnit(), ((ForLoopTree)path.getLeaf()).getUpdate().get(0)))
break;
case RBRACE:
path = path.getParentPath();
switch (path.getLeaf().getKind()) {
case CATCH:
path = path.getParentPath();
case METHOD:
case FOR_LOOP:
case ENHANCED_FOR_LOOP:
case IF:
case SYNCHRONIZED:
case WHILE_LOOP:
case TRY:
path = path.getParentPath();
}
break;
}
}
if (LOGGABLE) {
log("pathFor(pos: " + pos + ") returning: " + treeToString(info, path.getLeaf()));
}
return path;
}
| public TreePath pathFor(TreePath path, int pos, SourcePositions sourcePositions) {
if (info == null || path == null || sourcePositions == null)
throw new IllegalArgumentException();
class Result extends Error {
TreePath path;
Result(TreePath path) {
this.path = path;
}
}
class PathFinder extends JavaFXTreePathScanner<Void,Void> {
private int pos;
private SourcePositions sourcePositions;
private PathFinder(int pos, SourcePositions sourcePositions) {
this.pos = pos;
this.sourcePositions = sourcePositions;
}
public Void scan(Tree tree, Void p) {
if (tree != null) {
super.scan(tree, p);
long start = sourcePositions.getStartPosition(getCurrentPath().getCompilationUnit(), tree);
long end = sourcePositions.getEndPosition(getCurrentPath().getCompilationUnit(), tree);
if (start < pos && end >= pos) {
if (tree.getKind() == Tree.Kind.ERRONEOUS) {
tree.accept(this, p);
throw new Result(getCurrentPath());
}
throw new Result(new TreePath(getCurrentPath(), tree));
} else {
if ((start == -1) || (end == -1)) {
if (!isSynthetic(getCurrentPath().getCompilationUnit(), tree)) {
// here we might have a problem
if (LOGGABLE) {
logger.finest("SCAN: Cannot determine start and end for: " + treeToString(info, tree));
}
}
}
}
}
return null;
}
}
try {
new PathFinder(pos, sourcePositions).scan(path, null);
} catch (Result result) {
path = result.path;
}
if (path.getLeaf() == path.getCompilationUnit()) {
log("pathFor returning compilation unit for position: " + pos);
return path;
}
int start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf());
int end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf());
while (start == -1 || pos < start || pos > end) {
if (LOGGABLE) {
logger.finer("pathFor moving to parent: " + treeToString(info, path.getLeaf()));
}
path = path.getParentPath();
if (LOGGABLE) {
logger.finer("pathFor moved to parent: " + treeToString(info, path.getLeaf()));
}
if (path.getLeaf() == path.getCompilationUnit()) {
break;
}
start = (int)sourcePositions.getStartPosition(info.getCompilationUnit(), path.getLeaf());
end = (int)sourcePositions.getEndPosition(info.getCompilationUnit(), path.getLeaf());
}
if (LOGGABLE) {
log("pathFor(pos: " + pos + ") returning: " + treeToString(info, path.getLeaf()));
}
return path;
}
|
diff --git a/agent/src/main/java/org/whitesource/teamcity/agent/WhitesourceLifeCycleListener.java b/agent/src/main/java/org/whitesource/teamcity/agent/WhitesourceLifeCycleListener.java
index 0a23dc0..2b1a16e 100644
--- a/agent/src/main/java/org/whitesource/teamcity/agent/WhitesourceLifeCycleListener.java
+++ b/agent/src/main/java/org/whitesource/teamcity/agent/WhitesourceLifeCycleListener.java
@@ -1,260 +1,260 @@
/**
* Copyright (C) 2012 White Source Ltd.
*
* 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.whitesource.teamcity.agent;
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.ExtensionHolder;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;
import org.whitesource.agent.api.dispatch.CheckPoliciesResult;
import org.whitesource.agent.api.dispatch.UpdateInventoryResult;
import org.whitesource.agent.api.model.AgentProjectInfo;
import org.whitesource.agent.api.model.DependencyInfo;
import org.whitesource.agent.client.WhitesourceService;
import org.whitesource.agent.client.WssServiceException;
import org.whitesource.agent.report.PolicyCheckReport;
import org.whitesource.teamcity.common.Constants;
import org.whitesource.teamcity.common.WssUtils;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author Edo.Shor
*/
public class WhitesourceLifeCycleListener extends AgentLifeCycleAdapter {
/* --- Static members --- */
private static final String LOG_COMPONENT = "LifeCycleListener";
private ExtensionHolder extensionHolder;
/* --- Constructors --- */
/**
* Constructor
*/
public WhitesourceLifeCycleListener(@NotNull final EventDispatcher<AgentLifeCycleListener> eventDispatcher,
@NotNull final ExtensionHolder extensionHolder) {
this.extensionHolder = extensionHolder;
eventDispatcher.addListener(this);
}
@Override
public void agentInitialized(@NotNull BuildAgent agent) {
super.agentInitialized(agent);
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "initialized"));
}
/* --- Interface implementation methods --- */
@Override
public void beforeRunnerStart(@NotNull BuildRunnerContext runner) {
super.beforeRunnerStart(runner);
if (shouldUpdate(runner)) {
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "before runner start "
+ runner.getBuild().getProjectName() + " type " + runner.getName()));
}
}
@Override
public void runnerFinished(@NotNull BuildRunnerContext runner, @NotNull BuildFinishedStatus status) {
super.runnerFinished(runner, status);
AgentRunningBuild build = runner.getBuild();
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "runner finished " + build.getProjectName() + " type " + runner.getName()));
if (!shouldUpdate(runner)) { return; } // no need to update white source...
final BuildProgressLogger buildLogger = build.getBuildLogger();
buildLogger.message("Updating White Source");
// make sure we have an organization token
Map<String, String> runnerParameters = runner.getRunnerParameters();
String orgToken = runnerParameters.get(Constants.RUNNER_OVERRIDE_ORGANIZATION_TOKEN);
if (StringUtil.isEmptyOrSpaces(orgToken)) {
orgToken = runnerParameters.get(Constants.RUNNER_ORGANIZATION_TOKEN);
}
if (StringUtil.isEmptyOrSpaces(orgToken)) {
stopBuildOnError((AgentRunningBuildEx) build,
new IllegalStateException("Empty organization token. Please make sure an organization token is defined for this runner"));
return;
}
// should we check policies first ?
boolean shouldCheckPolicies;
String overrideCheckPolicies = runnerParameters.get(Constants.RUNNER_OVERRIDE_CHECK_POLICIES);
if (StringUtils.isBlank(overrideCheckPolicies) ||
"global".equals(overrideCheckPolicies)) {
shouldCheckPolicies = Boolean.parseBoolean(runnerParameters.get(Constants.RUNNER_CHECK_POLICIES));
} else {
- shouldCheckPolicies = "enabled".equals(overrideCheckPolicies);
+ shouldCheckPolicies = "enable".equals(overrideCheckPolicies);
}
String product = runnerParameters.get(Constants.RUNNER_PRODUCT);
String productVersion = runnerParameters.get(Constants.RUNNER_PRODUCT_VERSION);
// collect OSS usage information
buildLogger.message("Collecting OSS usage information");
Collection<AgentProjectInfo> projectInfos;
if (WssUtils.isMavenRunType(runner.getRunType())) {
MavenOssInfoExtractor extractor = new MavenOssInfoExtractor(runner);
projectInfos = extractor.extract();
if (StringUtil.isEmptyOrSpaces(product)) {
product = extractor.getTopMostProjectName();
}
} else {
GenericOssInfoExtractor extractor = new GenericOssInfoExtractor(runner);
projectInfos = extractor.extract();
}
debugAgentProjectInfos(projectInfos);
// send to white source
if (CollectionUtils.isEmpty(projectInfos)) {
buildLogger.message("No open source information found.");
} else {
WhitesourceService service = createServiceClient(runner);
try{
if (shouldCheckPolicies) {
buildLogger.message("Checking policies");
CheckPoliciesResult result = service.checkPolicies(orgToken, product, productVersion, projectInfos);
policyCheckReport(runner, result);
if (result.hasRejections()) {
stopBuild((AgentRunningBuildEx) build, "Open source rejected by organization policies.");
} else {
buildLogger.message("All dependencies conform with open source policies.");
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} else {
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} catch (WssServiceException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (IOException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (RuntimeException e) {
Loggers.AGENT.error(WssUtils.logMsg(LOG_COMPONENT, "Runtime Error"), e);
stopBuildOnError((AgentRunningBuildEx) build, e);
} finally {
service.shutdown();
}
}
}
private void policyCheckReport(BuildRunnerContext runner, CheckPoliciesResult result) throws IOException {
AgentRunningBuild build = runner.getBuild();
PolicyCheckReport report = new PolicyCheckReport(result, build.getProjectName(), build.getBuildNumber());
File reportArchive = report.generate(build.getBuildTempDirectory(), true);
ArtifactsPublisher publisher = extensionHolder.getExtensions(ArtifactsPublisher.class).iterator().next();
Map<File, String> artifactsToPublish = new HashMap<File, String>();
artifactsToPublish.put(reportArchive, "");
publisher.publishFiles(artifactsToPublish);
}
/* --- Private methods --- */
private boolean shouldUpdate(BuildRunnerContext runner) {
String shouldUpdate = runner.getRunnerParameters().get(Constants.RUNNER_DO_UPDATE);
return !StringUtil.isEmptyOrSpaces(shouldUpdate) && Boolean.parseBoolean(shouldUpdate);
}
private WhitesourceService createServiceClient(BuildRunnerContext runner) {
Map<String, String> runnerParameters = runner.getRunnerParameters();
String serviceUrl = runnerParameters.get(Constants.RUNNER_SERVICE_URL);
WhitesourceService service = new WhitesourceService(Constants.AGENT_TYPE, Constants.AGENT_VERSION, serviceUrl);
String proxyHost = runnerParameters.get(Constants.RUNNER_PROXY_HOST);
if (!StringUtil.isEmptyOrSpaces(proxyHost)) {
int port = Integer.parseInt(runnerParameters.get(Constants.RUNNER_PROXY_PORT));
String username = runnerParameters.get(Constants.RUNNER_PROXY_USERNAME);
String password = runnerParameters.get(Constants.RUNNER_PROXY_PASSWORD);
service.getClient().setProxy(proxyHost, port, username, password);
}
return service;
}
private void sendUpdate(String orgToken, String product, String productVersion, Collection<AgentProjectInfo> projectInfos,
WhitesourceService service, BuildProgressLogger buildLogger)
throws WssServiceException {
buildLogger.message("Sending to White Source");
UpdateInventoryResult updateResult = service.update(orgToken, product, productVersion, projectInfos);
logUpdateResult(updateResult, buildLogger);
}
private void logUpdateResult(UpdateInventoryResult result, BuildProgressLogger logger) {
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "update success"));
logger.message("White Source update results: ");
logger.message("White Source organization: " + result.getOrganization());
logger.message(result.getCreatedProjects().size() + " Newly created projects:");
logger.message(StringUtil.join(result.getCreatedProjects(), ","));
logger.message(result.getUpdatedProjects().size() + " existing projects were updated:");
logger.message(StringUtil.join(result.getUpdatedProjects(), ","));
}
private void stopBuildOnError(AgentRunningBuildEx build, Exception e) {
Loggers.AGENT.warn(WssUtils.logMsg(LOG_COMPONENT, "Stopping build"), e);
BuildProgressLogger logger = build.getBuildLogger();
String errorMessage = e.getLocalizedMessage();
logger.buildFailureDescription(errorMessage);
logger.exception(e);
logger.flush();
build.stopBuild(errorMessage);
}
private void stopBuild(AgentRunningBuildEx build, String message) {
Loggers.AGENT.warn(WssUtils.logMsg(LOG_COMPONENT, "Stopping build: + message"));
BuildProgressLogger logger = build.getBuildLogger();
logger.buildFailureDescription(message);
logger.flush();
build.stopBuild(message);
}
private void debugAgentProjectInfos(Collection<AgentProjectInfo> projectInfos) {
final Logger log = Loggers.AGENT;
log.info("----------------- dumping projectInfos -----------------");
log.info("Total number of projects : " + projectInfos.size());
for (AgentProjectInfo projectInfo : projectInfos) {
log.info("Project coordiantes: " + projectInfo.getCoordinates());
log.info("Project parent coordiantes: " + projectInfo.getParentCoordinates());
Collection<DependencyInfo> dependencies = projectInfo.getDependencies();
log.info("total # of dependencies: " + dependencies.size());
for (DependencyInfo info : dependencies) {
log.info(info + " SHA-1: " + info.getSha1());
}
}
log.info("----------------- dump finished -----------------");
}
}
| true | true | public void runnerFinished(@NotNull BuildRunnerContext runner, @NotNull BuildFinishedStatus status) {
super.runnerFinished(runner, status);
AgentRunningBuild build = runner.getBuild();
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "runner finished " + build.getProjectName() + " type " + runner.getName()));
if (!shouldUpdate(runner)) { return; } // no need to update white source...
final BuildProgressLogger buildLogger = build.getBuildLogger();
buildLogger.message("Updating White Source");
// make sure we have an organization token
Map<String, String> runnerParameters = runner.getRunnerParameters();
String orgToken = runnerParameters.get(Constants.RUNNER_OVERRIDE_ORGANIZATION_TOKEN);
if (StringUtil.isEmptyOrSpaces(orgToken)) {
orgToken = runnerParameters.get(Constants.RUNNER_ORGANIZATION_TOKEN);
}
if (StringUtil.isEmptyOrSpaces(orgToken)) {
stopBuildOnError((AgentRunningBuildEx) build,
new IllegalStateException("Empty organization token. Please make sure an organization token is defined for this runner"));
return;
}
// should we check policies first ?
boolean shouldCheckPolicies;
String overrideCheckPolicies = runnerParameters.get(Constants.RUNNER_OVERRIDE_CHECK_POLICIES);
if (StringUtils.isBlank(overrideCheckPolicies) ||
"global".equals(overrideCheckPolicies)) {
shouldCheckPolicies = Boolean.parseBoolean(runnerParameters.get(Constants.RUNNER_CHECK_POLICIES));
} else {
shouldCheckPolicies = "enabled".equals(overrideCheckPolicies);
}
String product = runnerParameters.get(Constants.RUNNER_PRODUCT);
String productVersion = runnerParameters.get(Constants.RUNNER_PRODUCT_VERSION);
// collect OSS usage information
buildLogger.message("Collecting OSS usage information");
Collection<AgentProjectInfo> projectInfos;
if (WssUtils.isMavenRunType(runner.getRunType())) {
MavenOssInfoExtractor extractor = new MavenOssInfoExtractor(runner);
projectInfos = extractor.extract();
if (StringUtil.isEmptyOrSpaces(product)) {
product = extractor.getTopMostProjectName();
}
} else {
GenericOssInfoExtractor extractor = new GenericOssInfoExtractor(runner);
projectInfos = extractor.extract();
}
debugAgentProjectInfos(projectInfos);
// send to white source
if (CollectionUtils.isEmpty(projectInfos)) {
buildLogger.message("No open source information found.");
} else {
WhitesourceService service = createServiceClient(runner);
try{
if (shouldCheckPolicies) {
buildLogger.message("Checking policies");
CheckPoliciesResult result = service.checkPolicies(orgToken, product, productVersion, projectInfos);
policyCheckReport(runner, result);
if (result.hasRejections()) {
stopBuild((AgentRunningBuildEx) build, "Open source rejected by organization policies.");
} else {
buildLogger.message("All dependencies conform with open source policies.");
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} else {
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} catch (WssServiceException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (IOException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (RuntimeException e) {
Loggers.AGENT.error(WssUtils.logMsg(LOG_COMPONENT, "Runtime Error"), e);
stopBuildOnError((AgentRunningBuildEx) build, e);
} finally {
service.shutdown();
}
}
}
| public void runnerFinished(@NotNull BuildRunnerContext runner, @NotNull BuildFinishedStatus status) {
super.runnerFinished(runner, status);
AgentRunningBuild build = runner.getBuild();
Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "runner finished " + build.getProjectName() + " type " + runner.getName()));
if (!shouldUpdate(runner)) { return; } // no need to update white source...
final BuildProgressLogger buildLogger = build.getBuildLogger();
buildLogger.message("Updating White Source");
// make sure we have an organization token
Map<String, String> runnerParameters = runner.getRunnerParameters();
String orgToken = runnerParameters.get(Constants.RUNNER_OVERRIDE_ORGANIZATION_TOKEN);
if (StringUtil.isEmptyOrSpaces(orgToken)) {
orgToken = runnerParameters.get(Constants.RUNNER_ORGANIZATION_TOKEN);
}
if (StringUtil.isEmptyOrSpaces(orgToken)) {
stopBuildOnError((AgentRunningBuildEx) build,
new IllegalStateException("Empty organization token. Please make sure an organization token is defined for this runner"));
return;
}
// should we check policies first ?
boolean shouldCheckPolicies;
String overrideCheckPolicies = runnerParameters.get(Constants.RUNNER_OVERRIDE_CHECK_POLICIES);
if (StringUtils.isBlank(overrideCheckPolicies) ||
"global".equals(overrideCheckPolicies)) {
shouldCheckPolicies = Boolean.parseBoolean(runnerParameters.get(Constants.RUNNER_CHECK_POLICIES));
} else {
shouldCheckPolicies = "enable".equals(overrideCheckPolicies);
}
String product = runnerParameters.get(Constants.RUNNER_PRODUCT);
String productVersion = runnerParameters.get(Constants.RUNNER_PRODUCT_VERSION);
// collect OSS usage information
buildLogger.message("Collecting OSS usage information");
Collection<AgentProjectInfo> projectInfos;
if (WssUtils.isMavenRunType(runner.getRunType())) {
MavenOssInfoExtractor extractor = new MavenOssInfoExtractor(runner);
projectInfos = extractor.extract();
if (StringUtil.isEmptyOrSpaces(product)) {
product = extractor.getTopMostProjectName();
}
} else {
GenericOssInfoExtractor extractor = new GenericOssInfoExtractor(runner);
projectInfos = extractor.extract();
}
debugAgentProjectInfos(projectInfos);
// send to white source
if (CollectionUtils.isEmpty(projectInfos)) {
buildLogger.message("No open source information found.");
} else {
WhitesourceService service = createServiceClient(runner);
try{
if (shouldCheckPolicies) {
buildLogger.message("Checking policies");
CheckPoliciesResult result = service.checkPolicies(orgToken, product, productVersion, projectInfos);
policyCheckReport(runner, result);
if (result.hasRejections()) {
stopBuild((AgentRunningBuildEx) build, "Open source rejected by organization policies.");
} else {
buildLogger.message("All dependencies conform with open source policies.");
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} else {
sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
}
} catch (WssServiceException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (IOException e) {
stopBuildOnError((AgentRunningBuildEx) build, e);
} catch (RuntimeException e) {
Loggers.AGENT.error(WssUtils.logMsg(LOG_COMPONENT, "Runtime Error"), e);
stopBuildOnError((AgentRunningBuildEx) build, e);
} finally {
service.shutdown();
}
}
}
|
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
index 0b115945b..46b363c10 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
@@ -1,311 +1,312 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
* Group class for static methods to help with creation and getting of the binary dictionary
* file from the dictionary provider
*/
public final class BinaryDictionaryFileDumper {
private static final String TAG = BinaryDictionaryFileDumper.class.getSimpleName();
private static final boolean DEBUG = false;
/**
* The size of the temporary buffer to copy files.
*/
private static final int FILE_READ_BUFFER_SIZE = 1024;
// TODO: make the following data common with the native code
private static final byte[] MAGIC_NUMBER_VERSION_1 =
new byte[] { (byte)0x78, (byte)0xB1, (byte)0x00, (byte)0x00 };
private static final byte[] MAGIC_NUMBER_VERSION_2 =
new byte[] { (byte)0x9B, (byte)0xC1, (byte)0x3A, (byte)0xFE };
private static final String DICTIONARY_PROJECTION[] = { "id" };
public static final String QUERY_PARAMETER_MAY_PROMPT_USER = "mayPrompt";
public static final String QUERY_PARAMETER_TRUE = "true";
public static final String QUERY_PARAMETER_DELETE_RESULT = "result";
public static final String QUERY_PARAMETER_SUCCESS = "success";
public static final String QUERY_PARAMETER_FAILURE = "failure";
// Prevents this class to be accidentally instantiated.
private BinaryDictionaryFileDumper() {
}
/**
* Returns a URI builder pointing to the dictionary pack.
*
* This creates a URI builder able to build a URI pointing to the dictionary
* pack content provider for a specific dictionary id.
*/
private static Uri.Builder getProviderUriBuilder(final String path) {
return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
.authority(BinaryDictionary.DICTIONARY_PACK_AUTHORITY).appendPath(
path);
}
/**
* Queries a content provider for the list of word lists for a specific locale
* available to copy into Latin IME.
*/
private static List<WordListInfo> getWordListWordListInfos(final Locale locale,
final Context context, final boolean hasDefaultWordList) {
final ContentResolver resolver = context.getContentResolver();
final Uri.Builder builder = getProviderUriBuilder(locale.toString());
if (!hasDefaultWordList) {
builder.appendQueryParameter(QUERY_PARAMETER_MAY_PROMPT_USER, QUERY_PARAMETER_TRUE);
}
final Uri dictionaryPackUri = builder.build();
final Cursor c = resolver.query(dictionaryPackUri, DICTIONARY_PROJECTION, null, null, null);
if (null == c) return Collections.<WordListInfo>emptyList();
if (c.getCount() <= 0 || !c.moveToFirst()) {
c.close();
return Collections.<WordListInfo>emptyList();
}
try {
final List<WordListInfo> list = CollectionUtils.newArrayList();
do {
final String wordListId = c.getString(0);
final String wordListLocale = c.getString(1);
if (TextUtils.isEmpty(wordListId)) continue;
list.add(new WordListInfo(wordListId, wordListLocale));
} while (c.moveToNext());
c.close();
return list;
} catch (Exception e) {
// Just in case we hit a problem in communication with the dictionary pack.
// We don't want to die.
Log.e(TAG, "Exception communicating with the dictionary pack : " + e);
return Collections.<WordListInfo>emptyList();
}
}
/**
* Helper method to encapsulate exception handling.
*/
private static AssetFileDescriptor openAssetFileDescriptor(final ContentResolver resolver,
final Uri uri) {
try {
return resolver.openAssetFileDescriptor(uri, "r");
} catch (FileNotFoundException e) {
// I don't want to log the word list URI here for security concerns
Log.e(TAG, "Could not find a word list from the dictionary provider.");
return null;
}
}
/**
* Caches a word list the id of which is passed as an argument. This will write the file
* to the cache file name designated by its id and locale, overwriting it if already present
* and creating it (and its containing directory) if necessary.
*/
private static AssetFileAddress cacheWordList(final String id, final String locale,
final ContentResolver resolver, final Context context) {
final int COMPRESSED_CRYPTED_COMPRESSED = 0;
final int CRYPTED_COMPRESSED = 1;
final int COMPRESSED_CRYPTED = 2;
final int COMPRESSED_ONLY = 3;
final int CRYPTED_ONLY = 4;
final int NONE = 5;
final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED;
final int MODE_MAX = NONE;
final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id);
final String finalFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context);
final String tempFileName = finalFileName + ".tmp";
for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) {
InputStream originalSourceStream = null;
InputStream inputStream = null;
File outputFile = null;
FileOutputStream outputStream = null;
AssetFileDescriptor afd = null;
final Uri wordListUri = wordListUriBuilder.build();
try {
// Open input.
afd = openAssetFileDescriptor(resolver, wordListUri);
// If we can't open it at all, don't even try a number of times.
if (null == afd) return null;
originalSourceStream = afd.createInputStream();
// Open output.
outputFile = new File(tempFileName);
// Just to be sure, delete the file. This may fail silently, and return false: this
// is the right thing to do, as we just want to continue anyway.
outputFile.delete();
outputStream = new FileOutputStream(outputFile);
// Get the appropriate decryption method for this try
switch (mode) {
case COMPRESSED_CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(
originalSourceStream)));
break;
case CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(originalSourceStream));
break;
case COMPRESSED_CRYPTED:
inputStream = FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(originalSourceStream));
break;
case COMPRESSED_ONLY:
inputStream = FileTransforms.getUncompressedStream(originalSourceStream);
break;
case CRYPTED_ONLY:
inputStream = FileTransforms.getDecryptedStream(originalSourceStream);
break;
case NONE:
inputStream = originalSourceStream;
break;
}
checkMagicAndCopyFileTo(new BufferedInputStream(inputStream), outputStream);
outputStream.flush();
outputStream.close();
final File finalFile = new File(finalFileName);
+ finalFile.delete();
if (!outputFile.renameTo(finalFile)) {
throw new IOException("Can't move the file to its final name");
}
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_SUCCESS);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "Could not have the dictionary pack delete a word list");
}
BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, finalFile);
// Success! Close files (through the finally{} clause) and return.
return AssetFileAddress.makeFromFileName(finalFileName);
} catch (Exception e) {
if (DEBUG) {
Log.i(TAG, "Can't open word list in mode " + mode + " : " + e);
}
if (null != outputFile) {
// This may or may not fail. The file may not have been created if the
// exception was thrown before it could be. Hence, both failure and
// success are expected outcomes, so we don't check the return value.
outputFile.delete();
}
// Try the next method.
} finally {
// Ignore exceptions while closing files.
try {
// inputStream.close() will close afd, we should not call afd.close().
if (null != inputStream) inputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e);
}
try {
if (null != outputStream) outputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a file : " + e);
}
}
}
// We could not copy the file at all. This is very unexpected.
// I'd rather not print the word list ID to the log out of security concerns
Log.e(TAG, "Could not copy a word list. Will not be able to use it.");
// If we can't copy it we should warn the dictionary provider so that it can mark it
// as invalid.
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_FAILURE);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "In addition, we were unable to delete it.");
}
return null;
}
/**
* Queries a content provider for word list data for some locale and cache the returned files
*
* This will query a content provider for word list data for a given locale, and copy the
* files locally so that they can be mmap'ed. This may overwrite previously cached word lists
* with newer versions if a newer version is made available by the content provider.
* @returns the addresses of the word list files, or null if no data could be obtained.
* @throw FileNotFoundException if the provider returns non-existent data.
* @throw IOException if the provider-returned data could not be read.
*/
public static List<AssetFileAddress> cacheWordListsFromContentProvider(final Locale locale,
final Context context, final boolean hasDefaultWordList) {
final ContentResolver resolver = context.getContentResolver();
final List<WordListInfo> idList = getWordListWordListInfos(locale, context,
hasDefaultWordList);
final List<AssetFileAddress> fileAddressList = CollectionUtils.newArrayList();
for (WordListInfo id : idList) {
final AssetFileAddress afd = cacheWordList(id.mId, id.mLocale, resolver, context);
if (null != afd) {
fileAddressList.add(afd);
}
}
return fileAddressList;
}
/**
* Copies the data in an input stream to a target file if the magic number matches.
*
* If the magic number does not match the expected value, this method throws an
* IOException. Other usual conditions for IOException or FileNotFoundException
* also apply.
*
* @param input the stream to be copied.
* @param output an output stream to copy the data to.
*/
private static void checkMagicAndCopyFileTo(final BufferedInputStream input,
final FileOutputStream output) throws FileNotFoundException, IOException {
// Check the magic number
final int length = MAGIC_NUMBER_VERSION_2.length;
final byte[] magicNumberBuffer = new byte[length];
final int readMagicNumberSize = input.read(magicNumberBuffer, 0, length);
if (readMagicNumberSize < length) {
throw new IOException("Less bytes to read than the magic number length");
}
if (!Arrays.equals(MAGIC_NUMBER_VERSION_2, magicNumberBuffer)) {
if (!Arrays.equals(MAGIC_NUMBER_VERSION_1, magicNumberBuffer)) {
throw new IOException("Wrong magic number for downloaded file");
}
}
output.write(magicNumberBuffer);
// Actually copy the file
final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE];
for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer))
output.write(buffer, 0, readBytes);
input.close();
}
}
| true | true | private static AssetFileAddress cacheWordList(final String id, final String locale,
final ContentResolver resolver, final Context context) {
final int COMPRESSED_CRYPTED_COMPRESSED = 0;
final int CRYPTED_COMPRESSED = 1;
final int COMPRESSED_CRYPTED = 2;
final int COMPRESSED_ONLY = 3;
final int CRYPTED_ONLY = 4;
final int NONE = 5;
final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED;
final int MODE_MAX = NONE;
final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id);
final String finalFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context);
final String tempFileName = finalFileName + ".tmp";
for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) {
InputStream originalSourceStream = null;
InputStream inputStream = null;
File outputFile = null;
FileOutputStream outputStream = null;
AssetFileDescriptor afd = null;
final Uri wordListUri = wordListUriBuilder.build();
try {
// Open input.
afd = openAssetFileDescriptor(resolver, wordListUri);
// If we can't open it at all, don't even try a number of times.
if (null == afd) return null;
originalSourceStream = afd.createInputStream();
// Open output.
outputFile = new File(tempFileName);
// Just to be sure, delete the file. This may fail silently, and return false: this
// is the right thing to do, as we just want to continue anyway.
outputFile.delete();
outputStream = new FileOutputStream(outputFile);
// Get the appropriate decryption method for this try
switch (mode) {
case COMPRESSED_CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(
originalSourceStream)));
break;
case CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(originalSourceStream));
break;
case COMPRESSED_CRYPTED:
inputStream = FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(originalSourceStream));
break;
case COMPRESSED_ONLY:
inputStream = FileTransforms.getUncompressedStream(originalSourceStream);
break;
case CRYPTED_ONLY:
inputStream = FileTransforms.getDecryptedStream(originalSourceStream);
break;
case NONE:
inputStream = originalSourceStream;
break;
}
checkMagicAndCopyFileTo(new BufferedInputStream(inputStream), outputStream);
outputStream.flush();
outputStream.close();
final File finalFile = new File(finalFileName);
if (!outputFile.renameTo(finalFile)) {
throw new IOException("Can't move the file to its final name");
}
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_SUCCESS);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "Could not have the dictionary pack delete a word list");
}
BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, finalFile);
// Success! Close files (through the finally{} clause) and return.
return AssetFileAddress.makeFromFileName(finalFileName);
} catch (Exception e) {
if (DEBUG) {
Log.i(TAG, "Can't open word list in mode " + mode + " : " + e);
}
if (null != outputFile) {
// This may or may not fail. The file may not have been created if the
// exception was thrown before it could be. Hence, both failure and
// success are expected outcomes, so we don't check the return value.
outputFile.delete();
}
// Try the next method.
} finally {
// Ignore exceptions while closing files.
try {
// inputStream.close() will close afd, we should not call afd.close().
if (null != inputStream) inputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e);
}
try {
if (null != outputStream) outputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a file : " + e);
}
}
}
// We could not copy the file at all. This is very unexpected.
// I'd rather not print the word list ID to the log out of security concerns
Log.e(TAG, "Could not copy a word list. Will not be able to use it.");
// If we can't copy it we should warn the dictionary provider so that it can mark it
// as invalid.
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_FAILURE);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "In addition, we were unable to delete it.");
}
return null;
}
| private static AssetFileAddress cacheWordList(final String id, final String locale,
final ContentResolver resolver, final Context context) {
final int COMPRESSED_CRYPTED_COMPRESSED = 0;
final int CRYPTED_COMPRESSED = 1;
final int COMPRESSED_CRYPTED = 2;
final int COMPRESSED_ONLY = 3;
final int CRYPTED_ONLY = 4;
final int NONE = 5;
final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED;
final int MODE_MAX = NONE;
final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id);
final String finalFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context);
final String tempFileName = finalFileName + ".tmp";
for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) {
InputStream originalSourceStream = null;
InputStream inputStream = null;
File outputFile = null;
FileOutputStream outputStream = null;
AssetFileDescriptor afd = null;
final Uri wordListUri = wordListUriBuilder.build();
try {
// Open input.
afd = openAssetFileDescriptor(resolver, wordListUri);
// If we can't open it at all, don't even try a number of times.
if (null == afd) return null;
originalSourceStream = afd.createInputStream();
// Open output.
outputFile = new File(tempFileName);
// Just to be sure, delete the file. This may fail silently, and return false: this
// is the right thing to do, as we just want to continue anyway.
outputFile.delete();
outputStream = new FileOutputStream(outputFile);
// Get the appropriate decryption method for this try
switch (mode) {
case COMPRESSED_CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(
originalSourceStream)));
break;
case CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(originalSourceStream));
break;
case COMPRESSED_CRYPTED:
inputStream = FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(originalSourceStream));
break;
case COMPRESSED_ONLY:
inputStream = FileTransforms.getUncompressedStream(originalSourceStream);
break;
case CRYPTED_ONLY:
inputStream = FileTransforms.getDecryptedStream(originalSourceStream);
break;
case NONE:
inputStream = originalSourceStream;
break;
}
checkMagicAndCopyFileTo(new BufferedInputStream(inputStream), outputStream);
outputStream.flush();
outputStream.close();
final File finalFile = new File(finalFileName);
finalFile.delete();
if (!outputFile.renameTo(finalFile)) {
throw new IOException("Can't move the file to its final name");
}
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_SUCCESS);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "Could not have the dictionary pack delete a word list");
}
BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, finalFile);
// Success! Close files (through the finally{} clause) and return.
return AssetFileAddress.makeFromFileName(finalFileName);
} catch (Exception e) {
if (DEBUG) {
Log.i(TAG, "Can't open word list in mode " + mode + " : " + e);
}
if (null != outputFile) {
// This may or may not fail. The file may not have been created if the
// exception was thrown before it could be. Hence, both failure and
// success are expected outcomes, so we don't check the return value.
outputFile.delete();
}
// Try the next method.
} finally {
// Ignore exceptions while closing files.
try {
// inputStream.close() will close afd, we should not call afd.close().
if (null != inputStream) inputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e);
}
try {
if (null != outputStream) outputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a file : " + e);
}
}
}
// We could not copy the file at all. This is very unexpected.
// I'd rather not print the word list ID to the log out of security concerns
Log.e(TAG, "Could not copy a word list. Will not be able to use it.");
// If we can't copy it we should warn the dictionary provider so that it can mark it
// as invalid.
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_FAILURE);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "In addition, we were unable to delete it.");
}
return null;
}
|
diff --git a/mongo-firsthops/src/main/java/ch/x42/terye/ItemManager.java b/mongo-firsthops/src/main/java/ch/x42/terye/ItemManager.java
index a82301a..0f0a1cd 100644
--- a/mongo-firsthops/src/main/java/ch/x42/terye/ItemManager.java
+++ b/mongo-firsthops/src/main/java/ch/x42/terye/ItemManager.java
@@ -1,162 +1,164 @@
package ch.x42.terye;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
import javax.jcr.ItemExistsException;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import ch.x42.terye.persistence.ChangeLog;
import ch.x42.terye.persistence.ItemState;
import ch.x42.terye.persistence.ItemType;
import ch.x42.terye.persistence.NodeState;
import ch.x42.terye.persistence.PersistenceManager;
import ch.x42.terye.persistence.PropertyState;
public class ItemManager {
private PersistenceManager pm;
private ChangeLog log;
private NavigableMap<String, ItemImpl> cache = new TreeMap<String, ItemImpl>();
private Set<String> removed = new HashSet<String>();
protected ItemManager() throws RepositoryException {
pm = PersistenceManager.getInstance();
log = new ChangeLog();
}
/**
* Returns an item by looking up the cache and if not present fetching the
* item from the database.
*
* @param path canonical path
* @param type item type
* @return the item
* @throws PathNotFoundException when no item at that path exists or the
* types don't match
*/
public ItemImpl getItem(String path, ItemType type)
throws PathNotFoundException {
// check if the item has been loaded and removed in this session
if (removed.contains(path)) {
throw new PathNotFoundException();
}
// check if the item is cached
ItemImpl item = cache.get(path);
if (item != null) {
if (item.getState().getType().equals(type)) {
return item;
}
throw new PathNotFoundException();
}
// load item state from db
ItemState state = pm.load(path, type);
if (state == null) {
throw new PathNotFoundException();
}
- // instantiate item
+ // instantiate, cache and return item
if (type.equals(ItemType.NODE)) {
- return new NodeImpl(this, (NodeState) state);
+ item = new NodeImpl(this, (NodeState) state);
} else {
- return new PropertyImpl(this, (PropertyState) state);
+ item = new PropertyImpl(this, (PropertyState) state);
}
+ cache.put(path, item);
+ return item;
}
public NodeImpl getNode(String path) throws PathNotFoundException {
return (NodeImpl) getItem(path, ItemType.NODE);
}
public PropertyImpl getProperty(String path) throws PathNotFoundException {
return (PropertyImpl) getItem(path, ItemType.PROPERTY);
}
/**
* @param path canonical path
* @param parent canonical path to parent
*/
public NodeImpl createNode(String path, String parentPath)
throws PathNotFoundException, ItemExistsException {
if (nodeExists(path)) {
throw new ItemExistsException();
}
NodeState state = new NodeState(path, parentPath);
NodeImpl node = new NodeImpl(this, state);
cache.put(path, node);
removed.remove(path);
log.nodeAdded(node);
if (parentPath == null) {
// only the case for the root node
return node;
}
NodeImpl parent = getNode(parentPath);
parent.getState().getChildren().add(path);
log.nodeModified(parent);
return node;
}
/**
*
* @param path canonical path
* @param parentPath canonical path to parent
*/
public PropertyImpl createProperty(String path, String parentPath,
Object value) throws PathNotFoundException {
PropertyState state = new PropertyState(path, parentPath, value);
PropertyImpl property = new PropertyImpl(this, state);
cache.put(path, property);
removed.remove(path);
log.propertyAdded(property);
NodeImpl parent = getNode(parentPath);
parent.getState().getProperties().add(path);
log.nodeModified(parent);
return property;
}
/**
* @param path canonical path
*/
public void removeNode(String path) throws RepositoryException {
NodeImpl node = getNode(path);
removed.add(path);
// takes care of removing descendents from db
log.nodeRemoved(node);
// remove entry from parent's children
NodeImpl parent = (NodeImpl) node.getParent();
parent.getState().getChildren().remove(path);
log.nodeModified(parent);
// remove node and descendents from cache
Iterator<String> iterator = cache.tailMap(path, true).navigableKeySet()
.iterator();
boolean done = false;
while (iterator.hasNext() && !done) {
String key = iterator.next();
if (!key.startsWith(path)) {
done = true;
} else {
iterator.remove();
}
}
}
/**
* @param path canonical path
*/
public boolean nodeExists(String path) {
try {
getNode(path);
} catch (PathNotFoundException e) {
return false;
}
return true;
}
public void save() throws RepositoryException {
pm.persist(log);
}
}
| false | true | public ItemImpl getItem(String path, ItemType type)
throws PathNotFoundException {
// check if the item has been loaded and removed in this session
if (removed.contains(path)) {
throw new PathNotFoundException();
}
// check if the item is cached
ItemImpl item = cache.get(path);
if (item != null) {
if (item.getState().getType().equals(type)) {
return item;
}
throw new PathNotFoundException();
}
// load item state from db
ItemState state = pm.load(path, type);
if (state == null) {
throw new PathNotFoundException();
}
// instantiate item
if (type.equals(ItemType.NODE)) {
return new NodeImpl(this, (NodeState) state);
} else {
return new PropertyImpl(this, (PropertyState) state);
}
}
| public ItemImpl getItem(String path, ItemType type)
throws PathNotFoundException {
// check if the item has been loaded and removed in this session
if (removed.contains(path)) {
throw new PathNotFoundException();
}
// check if the item is cached
ItemImpl item = cache.get(path);
if (item != null) {
if (item.getState().getType().equals(type)) {
return item;
}
throw new PathNotFoundException();
}
// load item state from db
ItemState state = pm.load(path, type);
if (state == null) {
throw new PathNotFoundException();
}
// instantiate, cache and return item
if (type.equals(ItemType.NODE)) {
item = new NodeImpl(this, (NodeState) state);
} else {
item = new PropertyImpl(this, (PropertyState) state);
}
cache.put(path, item);
return item;
}
|
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/ExcelEmitter.java b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/ExcelEmitter.java
index 967126649..b017c7939 100644
--- a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/ExcelEmitter.java
+++ b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/ExcelEmitter.java
@@ -1,405 +1,406 @@
package org.eclipse.birt.report.engine.emitter.excel;
import java.awt.Color;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IHTMLActionHandler;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.RenderOption;
import org.eclipse.birt.report.engine.api.script.IReportContext;
import org.eclipse.birt.report.engine.content.IAutoTextContent;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IDataContent;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IHyperlinkAction;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.ILabelContent;
import org.eclipse.birt.report.engine.content.IListBandContent;
import org.eclipse.birt.report.engine.content.IListContent;
import org.eclipse.birt.report.engine.content.IPageContent;
import org.eclipse.birt.report.engine.content.IReportContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.content.ITextContent;
import org.eclipse.birt.report.engine.css.engine.value.DataFormatValue;
import org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter;
import org.eclipse.birt.report.engine.emitter.EmitterUtil;
import org.eclipse.birt.report.engine.emitter.IEmitterServices;
import org.eclipse.birt.report.engine.emitter.excel.layout.ColumnsInfo;
import org.eclipse.birt.report.engine.emitter.excel.layout.ContainerSizeInfo;
import org.eclipse.birt.report.engine.emitter.excel.layout.ExcelContext;
import org.eclipse.birt.report.engine.emitter.excel.layout.ExcelLayoutEngine;
import org.eclipse.birt.report.engine.emitter.excel.layout.LayoutUtil;
import org.eclipse.birt.report.engine.ir.DataItemDesign;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.engine.ir.MapDesign;
import org.eclipse.birt.report.engine.layout.pdf.util.HTML2Content;
import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil;
import org.eclipse.birt.report.engine.presentation.ContentEmitterVisitor;
import com.ibm.icu.util.TimeZone;
public class ExcelEmitter extends ContentEmitterAdapter
{
protected static Logger logger = Logger.getLogger( ExcelEmitter.class
.getName( ) );
protected IEmitterServices service = null;
protected ExcelLayoutEngine engine;
protected ExcelContext context;
/**
* List of bookmark names that have already been encountered
*/
protected Set<String> bookmarkNames;
public String getOutputFormat( )
{
return "xls";
}
public void initialize( IEmitterServices service ) throws EngineException
{
this.context = createContext( );
this.service = service;
context.initialize( service );
this.bookmarkNames = new HashSet<String>();
}
protected ExcelContext createContext( )
{
return new ExcelContext( );
}
public void start( IReportContent report )
{
context.setReport( report );
IStyle style = report.getRoot( ).getComputedStyle( );
engine = createLayoutEngine( context, new ContentEmitterVisitor( this ) );
engine.initalize( style );
}
protected ExcelLayoutEngine createLayoutEngine( ExcelContext context,
ContentEmitterVisitor contentVisitor )
{
return new ExcelLayoutEngine( context, contentVisitor );
}
public void startPage( IPageContent page ) throws BirtException
{
engine.startPage( page );
}
public void endPage( IPageContent page ) throws BirtException
{
engine.endPage( page );
}
public void startTable( ITableContent table )
{
engine.startTable( table );
}
public void startRow( IRowContent row )
{
engine.addRow( row.getComputedStyle( ) );
}
public void endRow( IRowContent row )
{
DimensionType height = row.getHeight( );
float rowHeight = ExcelUtil.convertDimensionType( height, 0,
context.getDpi( ) ) / 1000f;
engine.endRow( rowHeight );
}
public void startCell( ICellContent cell )
{
IStyle style = cell.getComputedStyle( );
engine.addCell( cell, cell.getColumn( ), cell.getColSpan( ), cell
.getRowSpan( ), style );
}
public void endCell( ICellContent cell )
{
engine.endCell( cell );
}
public void endTable( ITableContent table )
{
engine.endTable( table );
}
public void startList( IListContent list )
{
ContainerSizeInfo size = engine.getCurrentContainer( ).getSizeInfo( );
ColumnsInfo table = LayoutUtil.createTable( list, size.getWidth( ),
context.getDpi( ) );
engine.addTable( list, table, size );
if ( list.getChildren( ) == null )
{
HyperlinkDef link = parseHyperLink( list );
BookmarkDef bookmark = getBookmark( list );
float height = getContentHeight( list );
engine.addData( null, list.getComputedStyle( ),
link, bookmark, height );
}
}
public void startListBand( IListBandContent listBand )
{
engine.addCell( 0, 1, 1, listBand.getComputedStyle( ) );
}
public void endListBand( IListBandContent listBand )
{
engine.endContainer( );
}
public void endList( IListContent list )
{
engine.endTable( list );
}
public void startForeign( IForeignContent foreign ) throws BirtException
{
if ( IForeignContent.HTML_TYPE.equalsIgnoreCase( foreign.getRawType( ) ) )
{
HTML2Content.html2Content( foreign );
HyperlinkDef link = parseHyperLink(foreign);
engine.processForeign( foreign, link );
}
}
public void startText( ITextContent text )
{
HyperlinkDef url = parseHyperLink( text );
BookmarkDef bookmark = getBookmark( text );
float height = getContentHeight( text );
engine.addData( text.getText( ), text.getComputedStyle( ), url,
bookmark, height );
}
public void startData( IDataContent data )
{
addDataContent( data );
}
protected Data addDataContent( IDataContent data )
{
float height = getContentHeight( data );
HyperlinkDef url = parseHyperLink( data );
BookmarkDef bookmark = getBookmark( data );
Data excelData = null;
Object generateBy = data.getGenerateBy( );
IStyle style = data.getComputedStyle( );
DataFormatValue dataformat = style.getDataFormat( );
MapDesign map = null;
if ( generateBy instanceof DataItemDesign )
{
DataItemDesign design = (DataItemDesign) generateBy;
map = design.getMap( );
}
if ( map != null && map.getRuleCount( ) > 0
&& data.getLabelText( ) != null )
{
excelData = engine.addData( data.getText( ), style,
url, bookmark, height );
}
else
{
String locale = null;
int type = ExcelUtil.getType( data.getValue( ) );
if ( type == SheetData.STRING )
{
if ( dataformat != null )
{
locale = dataformat.getStringLocale( );
}
- excelData = engine.addData( data.getText( ), style, url,
+ String text = data.getValue( ) == null ? null : data.getText( );
+ excelData = engine.addData( text, style, url,
bookmark, locale, height );
}
else if ( type == Data.NUMBER )
{
if ( dataformat != null )
{
locale = dataformat.getNumberLocale( );
}
excelData = engine.addData( data.getValue( ), style, url,
bookmark, locale, height );
}
else
{
if ( dataformat != null )
{
locale = dataformat.getDateTimeLocale( );
}
excelData = engine.addDateTime( data, style, url, bookmark,
locale, height );
}
}
return excelData;
}
private float getContentHeight( IContent content )
{
return ExcelUtil.convertDimensionType( content.getHeight( ), 0,
context.getDpi( ) ) / 1000f;
}
public void startImage( IImageContent image )
{
if ( context.isIgnoreImage( ) )
{
return;
}
IStyle style = image.getComputedStyle( );
HyperlinkDef url = parseHyperLink( image );
BookmarkDef bookmark = getBookmark( image );
engine.addImageData( image, style, url, bookmark );
}
public void startLabel( ILabelContent label )
{
Object design = label.getGenerateBy( );
IContent container = label;
while ( design == null )
{
container = (IContent) container.getParent( );
design = ( (IContent) container ).getGenerateBy( );
}
HyperlinkDef url = parseHyperLink( label );
BookmarkDef bookmark = getBookmark( label );
// If the text is BR and it generated by foreign,
// ignore it
if ( !( "\n".equalsIgnoreCase( label.getText( ) ) && container instanceof IForeignContent ) )
{
float height = getContentHeight( label );
engine.addData( label.getText( ), label.getComputedStyle( ), url,
bookmark, height );
}
}
public void startAutoText( IAutoTextContent autoText )
{
HyperlinkDef link = parseHyperLink( autoText );
BookmarkDef bookmark = getBookmark( autoText );
float height = getContentHeight( autoText );
engine.addData( autoText.getText( ), autoText.getComputedStyle( ),
link, bookmark, height );
}
public void end( IReportContent report )
{
engine.end( report );
engine.endWriter( );
}
public HyperlinkDef parseHyperLink( IContent content )
{
HyperlinkDef hyperlink = null;
IHyperlinkAction linkAction = content.getHyperlinkAction( );
if ( linkAction != null )
{
String tooltip = linkAction.getTooltip( );
String bookmark = linkAction.getBookmark( );
IReportRunnable reportRunnable = service.getReportRunnable( );
IReportContext reportContext = service.getReportContext( );
IHTMLActionHandler actionHandler = (IHTMLActionHandler) service
.getOption( RenderOption.ACTION_HANDLER );
switch ( linkAction.getType( ) )
{
case IHyperlinkAction.ACTION_BOOKMARK :
hyperlink = new HyperlinkDef( bookmark,
IHyperlinkAction.ACTION_BOOKMARK, tooltip );
break;
case IHyperlinkAction.ACTION_HYPERLINK :
String url = EmitterUtil.getHyperlinkUrl( linkAction,
reportRunnable, actionHandler, reportContext );
hyperlink = new HyperlinkDef( url,
IHyperlinkAction.ACTION_HYPERLINK, tooltip );
break;
case IHyperlinkAction.ACTION_DRILLTHROUGH :
url = EmitterUtil.getHyperlinkUrl( linkAction,
reportRunnable, actionHandler, reportContext );
hyperlink = new HyperlinkDef( url,
IHyperlinkAction.ACTION_DRILLTHROUGH, tooltip );
break;
}
}
if ( hyperlink != null )
{
Color color = PropertyUtil.getColor( content.getStyle( )
.getProperty( IStyle.STYLE_COLOR ) );
hyperlink.setColor( color );
}
return hyperlink;
}
protected BookmarkDef getBookmark( IContent content )
{
String bookmarkName = content.getBookmark( );
if (bookmarkName == null)
return null;
// if bookmark was already found before, skip it
if ( bookmarkNames.contains( bookmarkName ))
{
return null;
}
BookmarkDef bookmark=new BookmarkDef( bookmarkName );
if ( !ExcelUtil.isValidBookmarkName( bookmarkName ) )
{
bookmark.setGeneratedName( engine
.getGenerateBookmark( bookmarkName ) );
}
bookmarkNames.add( bookmarkName );
// !( content.getBookmark( ).startsWith( "__TOC" ) ) )
// bookmark starting with "__TOC" is not OK?
return bookmark;
}
public TimeZone getTimeZone()
{
if ( service != null )
{
IReportContext reportContext = service.getReportContext( );
if ( reportContext != null )
{
return reportContext.getTimeZone( );
}
}
return TimeZone.getDefault( );
}
public void endContainer( IContainerContent container )
{
engine.removeContainerStyle( );
}
public void startContainer( IContainerContent container )
{
engine.addContainerStyle( container.getComputedStyle( ) );
}
}
| true | true | protected Data addDataContent( IDataContent data )
{
float height = getContentHeight( data );
HyperlinkDef url = parseHyperLink( data );
BookmarkDef bookmark = getBookmark( data );
Data excelData = null;
Object generateBy = data.getGenerateBy( );
IStyle style = data.getComputedStyle( );
DataFormatValue dataformat = style.getDataFormat( );
MapDesign map = null;
if ( generateBy instanceof DataItemDesign )
{
DataItemDesign design = (DataItemDesign) generateBy;
map = design.getMap( );
}
if ( map != null && map.getRuleCount( ) > 0
&& data.getLabelText( ) != null )
{
excelData = engine.addData( data.getText( ), style,
url, bookmark, height );
}
else
{
String locale = null;
int type = ExcelUtil.getType( data.getValue( ) );
if ( type == SheetData.STRING )
{
if ( dataformat != null )
{
locale = dataformat.getStringLocale( );
}
excelData = engine.addData( data.getText( ), style, url,
bookmark, locale, height );
}
else if ( type == Data.NUMBER )
{
if ( dataformat != null )
{
locale = dataformat.getNumberLocale( );
}
excelData = engine.addData( data.getValue( ), style, url,
bookmark, locale, height );
}
else
{
if ( dataformat != null )
{
locale = dataformat.getDateTimeLocale( );
}
excelData = engine.addDateTime( data, style, url, bookmark,
locale, height );
}
}
return excelData;
}
| protected Data addDataContent( IDataContent data )
{
float height = getContentHeight( data );
HyperlinkDef url = parseHyperLink( data );
BookmarkDef bookmark = getBookmark( data );
Data excelData = null;
Object generateBy = data.getGenerateBy( );
IStyle style = data.getComputedStyle( );
DataFormatValue dataformat = style.getDataFormat( );
MapDesign map = null;
if ( generateBy instanceof DataItemDesign )
{
DataItemDesign design = (DataItemDesign) generateBy;
map = design.getMap( );
}
if ( map != null && map.getRuleCount( ) > 0
&& data.getLabelText( ) != null )
{
excelData = engine.addData( data.getText( ), style,
url, bookmark, height );
}
else
{
String locale = null;
int type = ExcelUtil.getType( data.getValue( ) );
if ( type == SheetData.STRING )
{
if ( dataformat != null )
{
locale = dataformat.getStringLocale( );
}
String text = data.getValue( ) == null ? null : data.getText( );
excelData = engine.addData( text, style, url,
bookmark, locale, height );
}
else if ( type == Data.NUMBER )
{
if ( dataformat != null )
{
locale = dataformat.getNumberLocale( );
}
excelData = engine.addData( data.getValue( ), style, url,
bookmark, locale, height );
}
else
{
if ( dataformat != null )
{
locale = dataformat.getDateTimeLocale( );
}
excelData = engine.addDateTime( data, style, url, bookmark,
locale, height );
}
}
return excelData;
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/commands/core/PermissionCommand.java b/src/main/java/net/aufdemrand/denizen/scripts/commands/core/PermissionCommand.java
index 09da02394..8d82ede72 100644
--- a/src/main/java/net/aufdemrand/denizen/scripts/commands/core/PermissionCommand.java
+++ b/src/main/java/net/aufdemrand/denizen/scripts/commands/core/PermissionCommand.java
@@ -1,92 +1,92 @@
package net.aufdemrand.denizen.scripts.commands.core;
import net.aufdemrand.denizen.exceptions.CommandExecutionException;
import net.aufdemrand.denizen.exceptions.InvalidArgumentsException;
import net.aufdemrand.denizen.scripts.ScriptEntry;
import net.aufdemrand.denizen.scripts.commands.AbstractCommand;
import net.aufdemrand.denizen.utilities.arguments.aH;
import net.aufdemrand.denizen.utilities.arguments.aH.ArgumentType;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizen.utilities.depends.Depends;
import org.bukkit.entity.Player;
public class PermissionCommand extends AbstractCommand {
private enum Action {ADD, REMOVE}
@Override
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {
// Initialize fields
Action action = null;
Player player = scriptEntry.getPlayer();
String permission = null;
String group = null;
String world = null;
for (String arg : scriptEntry.getArguments()) {
if (aH.matchesArg("ADD, REMOVE", arg)) {
action = Action.valueOf(aH.getStringFrom(arg).toUpperCase());
} else if (aH.matchesValueArg("PLAYER", arg, ArgumentType.String)) {
player = aH.getPlayerFrom(arg);
} else if (aH.matchesValueArg("GROUP", arg, ArgumentType.String)) {
group = aH.getStringFrom(arg);
} else if (aH.matchesValueArg("WORLD", arg, ArgumentType.String)) {
group = aH.getStringFrom(arg);
} else permission = arg;
}
// Add objects that need to be passed to execute() to the scriptEntry
scriptEntry.addObject("action", action)
.addObject("player", player)
.addObject("permission", permission)
.addObject("group", group)
.addObject("world", world);
}
@Override
public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {
// Fetch objects
Action action = (Action) scriptEntry.getObject("action");
Player player = (Player) scriptEntry.getObject("player");
String permission = String.valueOf(scriptEntry.getObject("permission"));
String group = String.valueOf(scriptEntry.getObject("group"));
String world = String.valueOf(scriptEntry.getObject("world"));
// Report to dB
dB.report(getName(),
aH.debugObj("Action", action.toString())
+ aH.debugObj("Player", player.getName())
+ aH.debugObj("Permission", permission)
+ aH.debugObj("Group", group)
+ aH.debugObj("World", world));
switch (action) {
case ADD:
- if(group != null) {
+ if(group != null && !group.equals("null")) {
if(Depends.permissions.groupHas(world, group, permission)) {
dB.echoDebug("Group " + group + " already has permission " + permission);
} else Depends.permissions.groupAdd(world, group, permission);
} else {
if(Depends.permissions.has(player, permission)) {
dB.echoDebug("Player " + player.getName() + " already has permission " + permission);
} else Depends.permissions.playerAdd(player, permission);
}
return;
case REMOVE:
- if(group != null) {
+ if(group != null&& !group.equals("null")) {
if(!Depends.permissions.groupHas(world, group, permission)) {
dB.echoDebug("Group " + group + " does not have access to permission " + permission);
} else Depends.permissions.groupRemove(world, group, permission);
} else {
if(!Depends.permissions.has(player, permission)) {
dB.echoDebug("Player " + player.getName() + " does not have access to permission " + permission);
} else Depends.permissions.playerRemove(world, player.getName(), permission);
}
return;
}
}
}
| false | true | public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {
// Fetch objects
Action action = (Action) scriptEntry.getObject("action");
Player player = (Player) scriptEntry.getObject("player");
String permission = String.valueOf(scriptEntry.getObject("permission"));
String group = String.valueOf(scriptEntry.getObject("group"));
String world = String.valueOf(scriptEntry.getObject("world"));
// Report to dB
dB.report(getName(),
aH.debugObj("Action", action.toString())
+ aH.debugObj("Player", player.getName())
+ aH.debugObj("Permission", permission)
+ aH.debugObj("Group", group)
+ aH.debugObj("World", world));
switch (action) {
case ADD:
if(group != null) {
if(Depends.permissions.groupHas(world, group, permission)) {
dB.echoDebug("Group " + group + " already has permission " + permission);
} else Depends.permissions.groupAdd(world, group, permission);
} else {
if(Depends.permissions.has(player, permission)) {
dB.echoDebug("Player " + player.getName() + " already has permission " + permission);
} else Depends.permissions.playerAdd(player, permission);
}
return;
case REMOVE:
if(group != null) {
if(!Depends.permissions.groupHas(world, group, permission)) {
dB.echoDebug("Group " + group + " does not have access to permission " + permission);
} else Depends.permissions.groupRemove(world, group, permission);
} else {
if(!Depends.permissions.has(player, permission)) {
dB.echoDebug("Player " + player.getName() + " does not have access to permission " + permission);
} else Depends.permissions.playerRemove(world, player.getName(), permission);
}
return;
}
}
| public void execute(ScriptEntry scriptEntry) throws CommandExecutionException {
// Fetch objects
Action action = (Action) scriptEntry.getObject("action");
Player player = (Player) scriptEntry.getObject("player");
String permission = String.valueOf(scriptEntry.getObject("permission"));
String group = String.valueOf(scriptEntry.getObject("group"));
String world = String.valueOf(scriptEntry.getObject("world"));
// Report to dB
dB.report(getName(),
aH.debugObj("Action", action.toString())
+ aH.debugObj("Player", player.getName())
+ aH.debugObj("Permission", permission)
+ aH.debugObj("Group", group)
+ aH.debugObj("World", world));
switch (action) {
case ADD:
if(group != null && !group.equals("null")) {
if(Depends.permissions.groupHas(world, group, permission)) {
dB.echoDebug("Group " + group + " already has permission " + permission);
} else Depends.permissions.groupAdd(world, group, permission);
} else {
if(Depends.permissions.has(player, permission)) {
dB.echoDebug("Player " + player.getName() + " already has permission " + permission);
} else Depends.permissions.playerAdd(player, permission);
}
return;
case REMOVE:
if(group != null&& !group.equals("null")) {
if(!Depends.permissions.groupHas(world, group, permission)) {
dB.echoDebug("Group " + group + " does not have access to permission " + permission);
} else Depends.permissions.groupRemove(world, group, permission);
} else {
if(!Depends.permissions.has(player, permission)) {
dB.echoDebug("Player " + player.getName() + " does not have access to permission " + permission);
} else Depends.permissions.playerRemove(world, player.getName(), permission);
}
return;
}
}
|
diff --git a/libraries/libformula/test/org/pentaho/reporting/libraries/formula/util/FormulaUtilTest.java b/libraries/libformula/test/org/pentaho/reporting/libraries/formula/util/FormulaUtilTest.java
index a67178d5a..1459d7af3 100644
--- a/libraries/libformula/test/org/pentaho/reporting/libraries/formula/util/FormulaUtilTest.java
+++ b/libraries/libformula/test/org/pentaho/reporting/libraries/formula/util/FormulaUtilTest.java
@@ -1,53 +1,53 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2006 - 2013 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.libraries.formula.util;
import org.junit.Assert;
import org.junit.Test;
public class FormulaUtilTest
{
@Test
public void testFormulaContextExtraction()
{
Object[][] test = {
new Object[]{ "test:IF()", true, "test", "IF()"},
new Object[]{ "=IF()", true, "report", "IF()"},
new Object[]{ "report-IF()", false, null, null},
new Object[]{ "=IF(:)", true, "report", "IF(:)"},
new Object[]{ "test=:IF()", false, null, null},
new Object[]{ "test asd:IF()", false, null, null},
};
for (Object[] objects : test)
{
String v = (String) objects[0];
String[] strings = FormulaUtil.extractFormulaContext(v);
if (strings[0] == null)
{
Assert.assertFalse("Failure in " + v, (Boolean) objects[1]);
}
else
{
Assert.assertTrue("Failure in " + v, (Boolean) objects[1]);
- Assert.assertEquals("Failure in " + strings[0], objects[2]);
- Assert.assertEquals("Failure in " + strings[1], objects[3]);
+ Assert.assertEquals("Failure in " + v, strings[0], objects[2]);
+ Assert.assertEquals("Failure in "+ v, strings[1], objects[3]);
}
}
}
}
| true | true | public void testFormulaContextExtraction()
{
Object[][] test = {
new Object[]{ "test:IF()", true, "test", "IF()"},
new Object[]{ "=IF()", true, "report", "IF()"},
new Object[]{ "report-IF()", false, null, null},
new Object[]{ "=IF(:)", true, "report", "IF(:)"},
new Object[]{ "test=:IF()", false, null, null},
new Object[]{ "test asd:IF()", false, null, null},
};
for (Object[] objects : test)
{
String v = (String) objects[0];
String[] strings = FormulaUtil.extractFormulaContext(v);
if (strings[0] == null)
{
Assert.assertFalse("Failure in " + v, (Boolean) objects[1]);
}
else
{
Assert.assertTrue("Failure in " + v, (Boolean) objects[1]);
Assert.assertEquals("Failure in " + strings[0], objects[2]);
Assert.assertEquals("Failure in " + strings[1], objects[3]);
}
}
}
| public void testFormulaContextExtraction()
{
Object[][] test = {
new Object[]{ "test:IF()", true, "test", "IF()"},
new Object[]{ "=IF()", true, "report", "IF()"},
new Object[]{ "report-IF()", false, null, null},
new Object[]{ "=IF(:)", true, "report", "IF(:)"},
new Object[]{ "test=:IF()", false, null, null},
new Object[]{ "test asd:IF()", false, null, null},
};
for (Object[] objects : test)
{
String v = (String) objects[0];
String[] strings = FormulaUtil.extractFormulaContext(v);
if (strings[0] == null)
{
Assert.assertFalse("Failure in " + v, (Boolean) objects[1]);
}
else
{
Assert.assertTrue("Failure in " + v, (Boolean) objects[1]);
Assert.assertEquals("Failure in " + v, strings[0], objects[2]);
Assert.assertEquals("Failure in "+ v, strings[1], objects[3]);
}
}
}
|
diff --git a/src/com/android/mms/ui/MessageListItem.java b/src/com/android/mms/ui/MessageListItem.java
index ad768de4..fff71e5f 100644
--- a/src/com/android/mms/ui/MessageListItem.java
+++ b/src/com/android/mms/ui/MessageListItem.java
@@ -1,862 +1,865 @@
/*
* Copyright (C) 2008 Esmertec AG.
* 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.mms.ui;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.Profile;
import android.provider.Telephony.Sms;
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.LineHeightSpan;
import android.text.style.StyleSpan;
import android.text.style.TextAppearanceSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.mms.MmsApp;
import com.android.mms.R;
import com.android.mms.data.Contact;
import com.android.mms.data.WorkingMessage;
import com.android.mms.model.SlideModel;
import com.android.mms.model.SlideshowModel;
import com.android.mms.transaction.SmsReceiverService;
import com.android.mms.transaction.Transaction;
import com.android.mms.transaction.TransactionBundle;
import com.android.mms.transaction.TransactionService;
import com.android.mms.util.DownloadManager;
import com.android.mms.util.ItemLoadedCallback;
import com.android.mms.util.ThumbnailManager.ImageLoaded;
import com.google.android.mms.ContentType;
import com.google.android.mms.pdu.PduHeaders;
/**
* This class provides view of a message in the messages list.
*/
public class MessageListItem extends LinearLayout implements
SlideViewInterface, OnClickListener {
public static final String EXTRA_URLS = "com.android.mms.ExtraUrls";
private static final String TAG = "MessageListItem";
private static final boolean DEBUG = false;
private static final boolean DEBUG_DONT_LOAD_IMAGES = false;
static final int MSG_LIST_EDIT = 1;
static final int MSG_LIST_PLAY = 2;
static final int MSG_LIST_DETAILS = 3;
private View mMmsView;
private ImageView mImageView;
private ImageView mLockedIndicator;
private ImageView mDeliveredIndicator;
private ImageView mDetailsIndicator;
private ImageButton mSlideShowButton;
private TextView mBodyTextView;
private Button mDownloadButton;
private TextView mDownloadingLabel;
private Handler mHandler;
private MessageItem mMessageItem;
private String mDefaultCountryIso;
private TextView mDateView;
public View mMessageBlock;
private QuickContactDivot mAvatar;
static private Drawable sDefaultContactImage;
private Presenter mPresenter;
private int mPosition; // for debugging
private ImageLoadedCallback mImageLoadedCallback;
private boolean mMultiRecipients;
public MessageListItem(Context context) {
super(context);
mDefaultCountryIso = MmsApp.getApplication().getCurrentCountryIso();
if (sDefaultContactImage == null) {
sDefaultContactImage = context.getResources().getDrawable(R.drawable.ic_contact_picture);
}
}
public MessageListItem(Context context, AttributeSet attrs) {
super(context, attrs);
int color = mContext.getResources().getColor(R.color.timestamp_color);
mColorSpan = new ForegroundColorSpan(color);
mDefaultCountryIso = MmsApp.getApplication().getCurrentCountryIso();
if (sDefaultContactImage == null) {
sDefaultContactImage = context.getResources().getDrawable(R.drawable.ic_contact_picture);
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mBodyTextView = (TextView) findViewById(R.id.text_view);
mDateView = (TextView) findViewById(R.id.date_view);
mLockedIndicator = (ImageView) findViewById(R.id.locked_indicator);
mDeliveredIndicator = (ImageView) findViewById(R.id.delivered_indicator);
mDetailsIndicator = (ImageView) findViewById(R.id.details_indicator);
mAvatar = (QuickContactDivot) findViewById(R.id.avatar);
mMessageBlock = findViewById(R.id.message_block);
}
public void bind(MessageItem msgItem, boolean convHasMultiRecipients, int position) {
if (DEBUG) {
Log.v(TAG, "bind for item: " + position + " old: " +
(mMessageItem != null ? mMessageItem.toString() : "NULL" ) +
" new " + msgItem.toString());
}
boolean sameItem = mMessageItem != null && mMessageItem.mMsgId == msgItem.mMsgId;
mMessageItem = msgItem;
mPosition = position;
mMultiRecipients = convHasMultiRecipients;
setLongClickable(false);
setClickable(false); // let the list view handle clicks on the item normally. When
// clickable is true, clicks bypass the listview and go straight
// to this listitem. We always want the listview to handle the
// clicks first.
switch (msgItem.mMessageType) {
case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
bindNotifInd();
break;
default:
bindCommonMessage(sameItem);
break;
}
}
public void unbind() {
// Clear all references to the message item, which can contain attachments and other
// memory-intensive objects
if (mImageView != null) {
// Because #setOnClickListener may have set the listener to an object that has the
// message item in its closure.
mImageView.setOnClickListener(null);
}
if (mSlideShowButton != null) {
// Because #drawPlaybackButton sets the tag to mMessageItem
mSlideShowButton.setTag(null);
}
// leave the presenter in case it's needed when rebound to a different MessageItem.
if (mPresenter != null) {
mPresenter.cancelBackgroundLoading();
}
}
public MessageItem getMessageItem() {
return mMessageItem;
}
public void setMsgListItemHandler(Handler handler) {
mHandler = handler;
}
private void bindNotifInd() {
showMmsView(false);
String msgSizeText = mContext.getString(R.string.message_size_label)
+ String.valueOf((mMessageItem.mMessageSize + 1023) / 1024)
+ mContext.getString(R.string.kilobyte);
mBodyTextView.setText(formatMessage(mMessageItem, null,
mMessageItem.mSubject,
mMessageItem.mHighlight,
mMessageItem.mTextContentType));
mDateView.setText(buildTimestampLine(msgSizeText + " " + mMessageItem.mTimestamp));
switch (mMessageItem.getMmsDownloadStatus()) {
case DownloadManager.STATE_PRE_DOWNLOADING:
case DownloadManager.STATE_DOWNLOADING:
showDownloadingAttachment();
break;
case DownloadManager.STATE_UNKNOWN:
case DownloadManager.STATE_UNSTARTED:
DownloadManager downloadManager = DownloadManager.getInstance();
boolean autoDownload = downloadManager.isAuto();
boolean dataSuspended = (MmsApp.getApplication().getTelephonyManager()
.getDataState() == TelephonyManager.DATA_SUSPENDED);
// If we're going to automatically start downloading the mms attachment, then
// don't bother showing the download button for an instant before the actual
// download begins. Instead, show downloading as taking place.
if (autoDownload && !dataSuspended) {
showDownloadingAttachment();
break;
}
case DownloadManager.STATE_TRANSIENT_FAILURE:
case DownloadManager.STATE_PERMANENT_FAILURE:
default:
setLongClickable(true);
inflateDownloadControls();
mDownloadingLabel.setVisibility(View.GONE);
mDownloadButton.setVisibility(View.VISIBLE);
mDownloadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDownloadingLabel.setVisibility(View.VISIBLE);
mDownloadButton.setVisibility(View.GONE);
Intent intent = new Intent(mContext, TransactionService.class);
intent.putExtra(TransactionBundle.URI, mMessageItem.mMessageUri.toString());
intent.putExtra(TransactionBundle.TRANSACTION_TYPE,
Transaction.RETRIEVE_TRANSACTION);
mContext.startService(intent);
DownloadManager.getInstance().markState(
mMessageItem.mMessageUri, DownloadManager.STATE_PRE_DOWNLOADING);
}
});
break;
}
// Hide the indicators.
mLockedIndicator.setVisibility(View.GONE);
mDeliveredIndicator.setVisibility(View.GONE);
mDetailsIndicator.setVisibility(View.GONE);
updateAvatarView(mMessageItem.mAddress, false);
}
private String buildTimestampLine(String timestamp) {
if (!mMultiRecipients || mMessageItem.isMe() || TextUtils.isEmpty(mMessageItem.mContact)) {
// Never show "Me" for messages I sent.
return timestamp;
}
// This is a group conversation, show the sender's name on the same line as the timestamp.
return mContext.getString(R.string.message_timestamp_format, mMessageItem.mContact,
timestamp);
}
private void showDownloadingAttachment() {
inflateDownloadControls();
mDownloadingLabel.setVisibility(View.VISIBLE);
mDownloadButton.setVisibility(View.GONE);
}
private void updateAvatarView(String addr, boolean isSelf) {
Drawable avatarDrawable;
if (isSelf || !TextUtils.isEmpty(addr)) {
Contact contact = isSelf ? Contact.getMe(false) : Contact.get(addr, false);
avatarDrawable = contact.getAvatar(mContext, sDefaultContactImage);
if (isSelf) {
mAvatar.assignContactUri(Profile.CONTENT_URI);
} else {
if (contact.existsInDatabase()) {
mAvatar.assignContactUri(contact.getUri());
} else {
mAvatar.assignContactFromPhone(contact.getNumber(), true);
}
}
} else {
avatarDrawable = sDefaultContactImage;
}
mAvatar.setImageDrawable(avatarDrawable);
}
private void bindCommonMessage(final boolean sameItem) {
if (mDownloadButton != null) {
mDownloadButton.setVisibility(View.GONE);
mDownloadingLabel.setVisibility(View.GONE);
}
// Since the message text should be concatenated with the sender's
// address(or name), I have to display it here instead of
// displaying it by the Presenter.
mBodyTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
boolean haveLoadedPdu = mMessageItem.isSms() || mMessageItem.mSlideshow != null;
// Here we're avoiding reseting the avatar to the empty avatar when we're rebinding
// to the same item. This happens when there's a DB change which causes the message item
// cache in the MessageListAdapter to get cleared. When an mms MessageItem is newly
// created, it has no info in it except the message id. The info is eventually loaded
// and bindCommonMessage is called again (see onPduLoaded below). When we haven't loaded
// the pdu, we don't want to call updateAvatarView because it
// will set the avatar to the generic avatar then when this method is called again
// from onPduLoaded, it will reset to the real avatar. This test is to avoid that flash.
if (!sameItem || haveLoadedPdu) {
boolean isSelf = Sms.isOutgoingFolder(mMessageItem.mBoxId);
String addr = isSelf ? null : mMessageItem.mAddress;
updateAvatarView(addr, isSelf);
}
// Get and/or lazily set the formatted message from/on the
// MessageItem. Because the MessageItem instances come from a
// cache (currently of size ~50), the hit rate on avoiding the
// expensive formatMessage() call is very high.
CharSequence formattedMessage = mMessageItem.getCachedFormattedMessage();
if (formattedMessage == null) {
formattedMessage = formatMessage(mMessageItem,
mMessageItem.mBody,
mMessageItem.mSubject,
mMessageItem.mHighlight,
mMessageItem.mTextContentType);
mMessageItem.setCachedFormattedMessage(formattedMessage);
}
if (!sameItem || haveLoadedPdu) {
mBodyTextView.setText(formattedMessage);
}
// Debugging code to put the URI of the image attachment in the body of the list item.
if (DEBUG) {
String debugText = null;
if (mMessageItem.mSlideshow == null) {
debugText = "NULL slideshow";
} else {
SlideModel slide = mMessageItem.mSlideshow.get(0);
if (slide == null) {
debugText = "NULL first slide";
} else if (!slide.hasImage()) {
debugText = "Not an image";
} else {
debugText = slide.getImage().getUri().toString();
}
}
mBodyTextView.setText(mPosition + ": " + debugText);
}
// If we're in the process of sending a message (i.e. pending), then we show a "SENDING..."
// string in place of the timestamp.
if (!sameItem || haveLoadedPdu) {
boolean isCountingDown = mMessageItem.getCountDown() > 0 &&
MessagingPreferenceActivity.getMessageSendDelayDuration(mContext) > 0;
int sendingTextResId = isCountingDown
? R.string.sent_countdown : R.string.sending_message;
mDateView.setText(buildTimestampLine(mMessageItem.isSending() ?
mContext.getResources().getString(sendingTextResId) :
mMessageItem.mTimestamp));
}
if (mMessageItem.isSms()) {
showMmsView(false);
mMessageItem.setOnPduLoaded(null);
} else {
if (DEBUG) {
Log.v(TAG, "bindCommonMessage for item: " + mPosition + " " +
mMessageItem.toString() +
" mMessageItem.mAttachmentType: " + mMessageItem.mAttachmentType +
" sameItem: " + sameItem);
}
if (mMessageItem.mAttachmentType != WorkingMessage.TEXT) {
if (!sameItem) {
setImage(null, null);
}
setOnClickListener(mMessageItem);
drawPlaybackButton(mMessageItem);
} else {
showMmsView(false);
}
if (mMessageItem.mSlideshow == null) {
+ final int mCurrentAttachmentType = mMessageItem.mAttachmentType;
mMessageItem.setOnPduLoaded(new MessageItem.PduLoadedCallback() {
public void onPduLoaded(MessageItem messageItem) {
if (DEBUG) {
Log.v(TAG, "PduLoadedCallback in MessageListItem for item: " + mPosition +
" " + (mMessageItem == null ? "NULL" : mMessageItem.toString()) +
" passed in item: " +
(messageItem == null ? "NULL" : messageItem.toString()));
}
if (messageItem != null && mMessageItem != null &&
messageItem.getMessageId() == mMessageItem.getMessageId()) {
mMessageItem.setCachedFormattedMessage(null);
- bindCommonMessage(true);
+ boolean isStillSame =
+ mCurrentAttachmentType == messageItem.mAttachmentType;
+ bindCommonMessage(isStillSame);
}
}
});
} else {
if (mPresenter == null) {
mPresenter = PresenterFactory.getPresenter(
"MmsThumbnailPresenter", mContext,
this, mMessageItem.mSlideshow);
} else {
mPresenter.setModel(mMessageItem.mSlideshow);
mPresenter.setView(this);
}
if (mImageLoadedCallback == null) {
mImageLoadedCallback = new ImageLoadedCallback(this);
} else {
mImageLoadedCallback.reset(this);
}
mPresenter.present(mImageLoadedCallback);
}
}
drawRightStatusIndicator(mMessageItem);
requestLayout();
}
static private class ImageLoadedCallback implements ItemLoadedCallback<ImageLoaded> {
private long mMessageId;
private final MessageListItem mListItem;
public ImageLoadedCallback(MessageListItem listItem) {
mListItem = listItem;
mMessageId = listItem.getMessageItem().getMessageId();
}
public void reset(MessageListItem listItem) {
mMessageId = listItem.getMessageItem().getMessageId();
}
public void onItemLoaded(ImageLoaded imageLoaded, Throwable exception) {
if (DEBUG_DONT_LOAD_IMAGES) {
return;
}
// Make sure we're still pointing to the same message. The list item could have
// been recycled.
MessageItem msgItem = mListItem.mMessageItem;
if (msgItem != null && msgItem.getMessageId() == mMessageId) {
if (imageLoaded.mIsVideo) {
mListItem.setVideoThumbnail(null, imageLoaded.mBitmap);
} else {
mListItem.setImage(null, imageLoaded.mBitmap);
}
}
}
}
@Override
public void startAudio() {
// TODO Auto-generated method stub
}
@Override
public void startVideo() {
// TODO Auto-generated method stub
}
@Override
public void setAudio(Uri audio, String name, Map<String, ?> extras) {
// TODO Auto-generated method stub
}
@Override
public void setImage(String name, Bitmap bitmap) {
showMmsView(true);
try {
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(VISIBLE);
} catch (java.lang.OutOfMemoryError e) {
Log.e(TAG, "setImage: out of memory: ", e);
}
}
private void showMmsView(boolean visible) {
if (mMmsView == null) {
mMmsView = findViewById(R.id.mms_view);
// if mMmsView is still null here, that mean the mms section hasn't been inflated
if (visible && mMmsView == null) {
//inflate the mms view_stub
View mmsStub = findViewById(R.id.mms_layout_view_stub);
mmsStub.setVisibility(View.VISIBLE);
mMmsView = findViewById(R.id.mms_view);
}
}
if (mMmsView != null) {
if (mImageView == null) {
mImageView = (ImageView) findViewById(R.id.image_view);
}
if (mSlideShowButton == null) {
mSlideShowButton = (ImageButton) findViewById(R.id.play_slideshow_button);
}
mMmsView.setVisibility(visible ? View.VISIBLE : View.GONE);
mImageView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
private void inflateDownloadControls() {
if (mDownloadButton == null) {
//inflate the download controls
findViewById(R.id.mms_downloading_view_stub).setVisibility(VISIBLE);
mDownloadButton = (Button) findViewById(R.id.btn_download_msg);
mDownloadingLabel = (TextView) findViewById(R.id.label_downloading);
}
}
private LineHeightSpan mSpan = new LineHeightSpan() {
@Override
public void chooseHeight(CharSequence text, int start,
int end, int spanstartv, int v, FontMetricsInt fm) {
fm.ascent -= 10;
}
};
TextAppearanceSpan mTextSmallSpan =
new TextAppearanceSpan(mContext, android.R.style.TextAppearance_Small);
ForegroundColorSpan mColorSpan = null; // set in ctor
private CharSequence formatMessage(MessageItem msgItem, String body,
String subject, Pattern highlight,
String contentType) {
SpannableStringBuilder buf = new SpannableStringBuilder();
boolean hasSubject = !TextUtils.isEmpty(subject);
if (hasSubject) {
buf.append(mContext.getResources().getString(R.string.inline_subject, subject));
}
if (!TextUtils.isEmpty(body)) {
// Converts html to spannable if ContentType is "text/html".
if (contentType != null && ContentType.TEXT_HTML.equals(contentType)) {
buf.append("\n");
buf.append(Html.fromHtml(body));
} else {
if (hasSubject) {
buf.append(" - ");
}
buf.append(body);
}
}
if (highlight != null) {
Matcher m = highlight.matcher(buf.toString());
while (m.find()) {
buf.setSpan(new StyleSpan(Typeface.BOLD), m.start(), m.end(), 0);
}
}
return buf;
}
private void drawPlaybackButton(MessageItem msgItem) {
switch (msgItem.mAttachmentType) {
case WorkingMessage.SLIDESHOW:
case WorkingMessage.AUDIO:
case WorkingMessage.VIDEO:
// Show the 'Play' button and bind message info on it.
mSlideShowButton.setTag(msgItem);
// Set call-back for the 'Play' button.
mSlideShowButton.setOnClickListener(this);
mSlideShowButton.setVisibility(View.VISIBLE);
setLongClickable(true);
// When we show the mSlideShowButton, this list item's onItemClickListener doesn't
// get called. (It gets set in ComposeMessageActivity:
// mMsgListView.setOnItemClickListener) Here we explicitly set the item's
// onClickListener. It allows the item to respond to embedded html links and at the
// same time, allows the slide show play button to work.
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onMessageListItemClick();
}
});
break;
default:
mSlideShowButton.setVisibility(View.GONE);
break;
}
}
// OnClick Listener for the playback button
@Override
public void onClick(View v) {
sendMessage(mMessageItem, MSG_LIST_PLAY);
}
private void sendMessage(MessageItem messageItem, int message) {
if (mHandler != null) {
Message msg = Message.obtain(mHandler, message);
msg.obj = messageItem;
msg.sendToTarget(); // See ComposeMessageActivity.mMessageListItemHandler.handleMessage
}
}
public void onMessageListItemClick() {
if (mMessageItem != null && mMessageItem.isSending() && mMessageItem.isSms()) {
SmsReceiverService.cancelSendingMessage(mMessageItem.mMessageUri);
return;
}
// If the message is a failed one, clicking it should reload it in the compose view,
// regardless of whether it has links in it
if (mMessageItem != null &&
mMessageItem.isOutgoingMessage() &&
mMessageItem.isFailedMessage() ) {
// Assuming the current message is a failed one, reload it into the compose view so
// the user can resend it.
sendMessage(mMessageItem, MSG_LIST_EDIT);
return;
}
// Check for links. If none, do nothing; if 1, open it; if >1, ask user to pick one
final URLSpan[] spans = mBodyTextView.getUrls();
if (spans.length == 0) {
sendMessage(mMessageItem, MSG_LIST_DETAILS); // show the message details dialog
} else if (spans.length == 1) {
spans[0].onClick(mBodyTextView);
} else {
ArrayAdapter<URLSpan> adapter =
new ArrayAdapter<URLSpan>(mContext, android.R.layout.select_dialog_item, spans) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
try {
URLSpan span = getItem(position);
String url = span.getURL();
Uri uri = Uri.parse(url);
TextView tv = (TextView) v;
Drawable d = mContext.getPackageManager().getActivityIcon(
new Intent(Intent.ACTION_VIEW, uri));
if (d != null) {
d.setBounds(0, 0, d.getIntrinsicHeight(), d.getIntrinsicHeight());
tv.setCompoundDrawablePadding(10);
tv.setCompoundDrawables(d, null, null, null);
}
final String telPrefix = "tel:";
if (url.startsWith(telPrefix)) {
if ((mDefaultCountryIso == null) || mDefaultCountryIso.isEmpty()) {
url = url.substring(telPrefix.length());
}
else {
url = PhoneNumberUtils.formatNumber(
url.substring(telPrefix.length()), mDefaultCountryIso);
}
}
tv.setText(url);
} catch (android.content.pm.PackageManager.NameNotFoundException ex) {
// it's ok if we're unable to set the drawable for this view - the user
// can still use it
}
return v;
}
};
AlertDialog.Builder b = new AlertDialog.Builder(mContext);
DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() {
@Override
public final void onClick(DialogInterface dialog, int which) {
if (which >= 0) {
spans[which].onClick(mBodyTextView);
}
dialog.dismiss();
}
};
b.setTitle(R.string.select_link_title);
b.setCancelable(true);
b.setAdapter(adapter, click);
b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public final void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
b.show();
}
}
private void setOnClickListener(final MessageItem msgItem) {
switch(msgItem.mAttachmentType) {
case WorkingMessage.IMAGE:
case WorkingMessage.VIDEO:
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendMessage(msgItem, MSG_LIST_PLAY);
}
});
mImageView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return v.showContextMenu();
}
});
break;
default:
mImageView.setOnClickListener(null);
break;
}
}
private void drawRightStatusIndicator(MessageItem msgItem) {
// Locked icon
if (msgItem.mLocked) {
mLockedIndicator.setImageResource(R.drawable.ic_lock_message_sms);
mLockedIndicator.setVisibility(View.VISIBLE);
} else {
mLockedIndicator.setVisibility(View.GONE);
}
// Delivery icon - we can show a failed icon for both sms and mms, but for an actual
// delivery, we only show the icon for sms. We don't have the information here in mms to
// know whether the message has been delivered. For mms, msgItem.mDeliveryStatus set
// to MessageItem.DeliveryStatus.RECEIVED simply means the setting requesting a
// delivery report was turned on when the message was sent. Yes, it's confusing!
if ((msgItem.isOutgoingMessage() && msgItem.isFailedMessage()) ||
msgItem.mDeliveryStatus == MessageItem.DeliveryStatus.FAILED) {
mDeliveredIndicator.setImageResource(R.drawable.ic_list_alert_sms_failed);
mDeliveredIndicator.setVisibility(View.VISIBLE);
} else if (msgItem.isSms() &&
msgItem.mDeliveryStatus == MessageItem.DeliveryStatus.RECEIVED) {
mDeliveredIndicator.setImageResource(R.drawable.ic_sms_mms_delivered);
mDeliveredIndicator.setVisibility(View.VISIBLE);
} else {
mDeliveredIndicator.setVisibility(View.GONE);
}
// Message details icon - this icon is shown both for sms and mms messages. For mms,
// we show the icon if the read report or delivery report setting was set when the
// message was sent. Showing the icon tells the user there's more information
// by selecting the "View report" menu.
if (msgItem.mDeliveryStatus == MessageItem.DeliveryStatus.INFO || msgItem.mReadReport
|| (msgItem.isMms() &&
msgItem.mDeliveryStatus == MessageItem.DeliveryStatus.RECEIVED)) {
mDetailsIndicator.setImageResource(R.drawable.ic_sms_mms_details);
mDetailsIndicator.setVisibility(View.VISIBLE);
} else {
mDetailsIndicator.setVisibility(View.GONE);
}
}
@Override
public void setImageRegionFit(String fit) {
// TODO Auto-generated method stub
}
@Override
public void setImageVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void setText(String name, String text) {
// TODO Auto-generated method stub
}
@Override
public void setTextVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void setVideo(String name, Uri uri) {
}
@Override
public void setVideoThumbnail(String name, Bitmap bitmap) {
showMmsView(true);
try {
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(VISIBLE);
} catch (java.lang.OutOfMemoryError e) {
Log.e(TAG, "setVideo: out of memory: ", e);
}
}
@Override
public void setVideoVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void stopAudio() {
// TODO Auto-generated method stub
}
@Override
public void stopVideo() {
// TODO Auto-generated method stub
}
@Override
public void reset() {
}
@Override
public void setVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void pauseAudio() {
// TODO Auto-generated method stub
}
@Override
public void pauseVideo() {
// TODO Auto-generated method stub
}
@Override
public void seekAudio(int seekTo) {
// TODO Auto-generated method stub
}
@Override
public void seekVideo(int seekTo) {
// TODO Auto-generated method stub
}
public void updateDelayCountDown() {
if (mMessageItem.isSms() && mMessageItem.getCountDown() > 0 && mMessageItem.isSending()) {
String content = mContext.getResources().getQuantityString(
R.plurals.remaining_delay_time,
mMessageItem.getCountDown(), mMessageItem.getCountDown());
Spanned spanned = Html.fromHtml(buildTimestampLine(content));
mDateView.setText(spanned);
} else {
mDateView.setText(buildTimestampLine(mMessageItem.isSending()
? mContext.getResources().getString(R.string.sending_message)
: mMessageItem.mTimestamp));
}
}
}
| false | true | private void bindCommonMessage(final boolean sameItem) {
if (mDownloadButton != null) {
mDownloadButton.setVisibility(View.GONE);
mDownloadingLabel.setVisibility(View.GONE);
}
// Since the message text should be concatenated with the sender's
// address(or name), I have to display it here instead of
// displaying it by the Presenter.
mBodyTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
boolean haveLoadedPdu = mMessageItem.isSms() || mMessageItem.mSlideshow != null;
// Here we're avoiding reseting the avatar to the empty avatar when we're rebinding
// to the same item. This happens when there's a DB change which causes the message item
// cache in the MessageListAdapter to get cleared. When an mms MessageItem is newly
// created, it has no info in it except the message id. The info is eventually loaded
// and bindCommonMessage is called again (see onPduLoaded below). When we haven't loaded
// the pdu, we don't want to call updateAvatarView because it
// will set the avatar to the generic avatar then when this method is called again
// from onPduLoaded, it will reset to the real avatar. This test is to avoid that flash.
if (!sameItem || haveLoadedPdu) {
boolean isSelf = Sms.isOutgoingFolder(mMessageItem.mBoxId);
String addr = isSelf ? null : mMessageItem.mAddress;
updateAvatarView(addr, isSelf);
}
// Get and/or lazily set the formatted message from/on the
// MessageItem. Because the MessageItem instances come from a
// cache (currently of size ~50), the hit rate on avoiding the
// expensive formatMessage() call is very high.
CharSequence formattedMessage = mMessageItem.getCachedFormattedMessage();
if (formattedMessage == null) {
formattedMessage = formatMessage(mMessageItem,
mMessageItem.mBody,
mMessageItem.mSubject,
mMessageItem.mHighlight,
mMessageItem.mTextContentType);
mMessageItem.setCachedFormattedMessage(formattedMessage);
}
if (!sameItem || haveLoadedPdu) {
mBodyTextView.setText(formattedMessage);
}
// Debugging code to put the URI of the image attachment in the body of the list item.
if (DEBUG) {
String debugText = null;
if (mMessageItem.mSlideshow == null) {
debugText = "NULL slideshow";
} else {
SlideModel slide = mMessageItem.mSlideshow.get(0);
if (slide == null) {
debugText = "NULL first slide";
} else if (!slide.hasImage()) {
debugText = "Not an image";
} else {
debugText = slide.getImage().getUri().toString();
}
}
mBodyTextView.setText(mPosition + ": " + debugText);
}
// If we're in the process of sending a message (i.e. pending), then we show a "SENDING..."
// string in place of the timestamp.
if (!sameItem || haveLoadedPdu) {
boolean isCountingDown = mMessageItem.getCountDown() > 0 &&
MessagingPreferenceActivity.getMessageSendDelayDuration(mContext) > 0;
int sendingTextResId = isCountingDown
? R.string.sent_countdown : R.string.sending_message;
mDateView.setText(buildTimestampLine(mMessageItem.isSending() ?
mContext.getResources().getString(sendingTextResId) :
mMessageItem.mTimestamp));
}
if (mMessageItem.isSms()) {
showMmsView(false);
mMessageItem.setOnPduLoaded(null);
} else {
if (DEBUG) {
Log.v(TAG, "bindCommonMessage for item: " + mPosition + " " +
mMessageItem.toString() +
" mMessageItem.mAttachmentType: " + mMessageItem.mAttachmentType +
" sameItem: " + sameItem);
}
if (mMessageItem.mAttachmentType != WorkingMessage.TEXT) {
if (!sameItem) {
setImage(null, null);
}
setOnClickListener(mMessageItem);
drawPlaybackButton(mMessageItem);
} else {
showMmsView(false);
}
if (mMessageItem.mSlideshow == null) {
mMessageItem.setOnPduLoaded(new MessageItem.PduLoadedCallback() {
public void onPduLoaded(MessageItem messageItem) {
if (DEBUG) {
Log.v(TAG, "PduLoadedCallback in MessageListItem for item: " + mPosition +
" " + (mMessageItem == null ? "NULL" : mMessageItem.toString()) +
" passed in item: " +
(messageItem == null ? "NULL" : messageItem.toString()));
}
if (messageItem != null && mMessageItem != null &&
messageItem.getMessageId() == mMessageItem.getMessageId()) {
mMessageItem.setCachedFormattedMessage(null);
bindCommonMessage(true);
}
}
});
} else {
if (mPresenter == null) {
mPresenter = PresenterFactory.getPresenter(
"MmsThumbnailPresenter", mContext,
this, mMessageItem.mSlideshow);
} else {
mPresenter.setModel(mMessageItem.mSlideshow);
mPresenter.setView(this);
}
if (mImageLoadedCallback == null) {
mImageLoadedCallback = new ImageLoadedCallback(this);
} else {
mImageLoadedCallback.reset(this);
}
mPresenter.present(mImageLoadedCallback);
}
}
drawRightStatusIndicator(mMessageItem);
requestLayout();
}
| private void bindCommonMessage(final boolean sameItem) {
if (mDownloadButton != null) {
mDownloadButton.setVisibility(View.GONE);
mDownloadingLabel.setVisibility(View.GONE);
}
// Since the message text should be concatenated with the sender's
// address(or name), I have to display it here instead of
// displaying it by the Presenter.
mBodyTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
boolean haveLoadedPdu = mMessageItem.isSms() || mMessageItem.mSlideshow != null;
// Here we're avoiding reseting the avatar to the empty avatar when we're rebinding
// to the same item. This happens when there's a DB change which causes the message item
// cache in the MessageListAdapter to get cleared. When an mms MessageItem is newly
// created, it has no info in it except the message id. The info is eventually loaded
// and bindCommonMessage is called again (see onPduLoaded below). When we haven't loaded
// the pdu, we don't want to call updateAvatarView because it
// will set the avatar to the generic avatar then when this method is called again
// from onPduLoaded, it will reset to the real avatar. This test is to avoid that flash.
if (!sameItem || haveLoadedPdu) {
boolean isSelf = Sms.isOutgoingFolder(mMessageItem.mBoxId);
String addr = isSelf ? null : mMessageItem.mAddress;
updateAvatarView(addr, isSelf);
}
// Get and/or lazily set the formatted message from/on the
// MessageItem. Because the MessageItem instances come from a
// cache (currently of size ~50), the hit rate on avoiding the
// expensive formatMessage() call is very high.
CharSequence formattedMessage = mMessageItem.getCachedFormattedMessage();
if (formattedMessage == null) {
formattedMessage = formatMessage(mMessageItem,
mMessageItem.mBody,
mMessageItem.mSubject,
mMessageItem.mHighlight,
mMessageItem.mTextContentType);
mMessageItem.setCachedFormattedMessage(formattedMessage);
}
if (!sameItem || haveLoadedPdu) {
mBodyTextView.setText(formattedMessage);
}
// Debugging code to put the URI of the image attachment in the body of the list item.
if (DEBUG) {
String debugText = null;
if (mMessageItem.mSlideshow == null) {
debugText = "NULL slideshow";
} else {
SlideModel slide = mMessageItem.mSlideshow.get(0);
if (slide == null) {
debugText = "NULL first slide";
} else if (!slide.hasImage()) {
debugText = "Not an image";
} else {
debugText = slide.getImage().getUri().toString();
}
}
mBodyTextView.setText(mPosition + ": " + debugText);
}
// If we're in the process of sending a message (i.e. pending), then we show a "SENDING..."
// string in place of the timestamp.
if (!sameItem || haveLoadedPdu) {
boolean isCountingDown = mMessageItem.getCountDown() > 0 &&
MessagingPreferenceActivity.getMessageSendDelayDuration(mContext) > 0;
int sendingTextResId = isCountingDown
? R.string.sent_countdown : R.string.sending_message;
mDateView.setText(buildTimestampLine(mMessageItem.isSending() ?
mContext.getResources().getString(sendingTextResId) :
mMessageItem.mTimestamp));
}
if (mMessageItem.isSms()) {
showMmsView(false);
mMessageItem.setOnPduLoaded(null);
} else {
if (DEBUG) {
Log.v(TAG, "bindCommonMessage for item: " + mPosition + " " +
mMessageItem.toString() +
" mMessageItem.mAttachmentType: " + mMessageItem.mAttachmentType +
" sameItem: " + sameItem);
}
if (mMessageItem.mAttachmentType != WorkingMessage.TEXT) {
if (!sameItem) {
setImage(null, null);
}
setOnClickListener(mMessageItem);
drawPlaybackButton(mMessageItem);
} else {
showMmsView(false);
}
if (mMessageItem.mSlideshow == null) {
final int mCurrentAttachmentType = mMessageItem.mAttachmentType;
mMessageItem.setOnPduLoaded(new MessageItem.PduLoadedCallback() {
public void onPduLoaded(MessageItem messageItem) {
if (DEBUG) {
Log.v(TAG, "PduLoadedCallback in MessageListItem for item: " + mPosition +
" " + (mMessageItem == null ? "NULL" : mMessageItem.toString()) +
" passed in item: " +
(messageItem == null ? "NULL" : messageItem.toString()));
}
if (messageItem != null && mMessageItem != null &&
messageItem.getMessageId() == mMessageItem.getMessageId()) {
mMessageItem.setCachedFormattedMessage(null);
boolean isStillSame =
mCurrentAttachmentType == messageItem.mAttachmentType;
bindCommonMessage(isStillSame);
}
}
});
} else {
if (mPresenter == null) {
mPresenter = PresenterFactory.getPresenter(
"MmsThumbnailPresenter", mContext,
this, mMessageItem.mSlideshow);
} else {
mPresenter.setModel(mMessageItem.mSlideshow);
mPresenter.setView(this);
}
if (mImageLoadedCallback == null) {
mImageLoadedCallback = new ImageLoadedCallback(this);
} else {
mImageLoadedCallback.reset(this);
}
mPresenter.present(mImageLoadedCallback);
}
}
drawRightStatusIndicator(mMessageItem);
requestLayout();
}
|
diff --git a/src/com/joshondesign/treegui/modes/aminojava/Property.java b/src/com/joshondesign/treegui/modes/aminojava/Property.java
index 5b4a9df..6c20e17 100644
--- a/src/com/joshondesign/treegui/modes/aminojava/Property.java
+++ b/src/com/joshondesign/treegui/modes/aminojava/Property.java
@@ -1,327 +1,331 @@
package com.joshondesign.treegui.modes.aminojava;
import org.joshy.gfx.draw.FlatColor;
import org.joshy.gfx.node.control.ListModel;
import org.joshy.gfx.util.u;
public class Property {
private final String name;
private final Class type;
private Object value;
private boolean exported = true;
private String exportName;
private boolean visible = true;
private boolean bindable = false;
private boolean list;
private DynamicNode itemPrototype;
private String displayName;
private DynamicNode node;
private boolean compound = false;
private String masterProperty = null;
private boolean proxy;
public Property(String name, Class type, Object value) {
this.name = name;
this.type = type;
this.value = value;
}
public Property setExported(boolean exported) {
this.exported = exported;
return this;
}
public boolean isExported() {
return exported;
}
public String getName() {
return name;
}
public String encode() {
if(type == String.class) return (String)value;
if(type == Boolean.class) return ((Boolean)value).toString();
if(type == Boolean.TYPE) {
if(value == null) return Boolean.toString(false);
return ((Boolean)value).toString();
}
if(type == Double.class) {
if(value instanceof Integer) {
return ((Integer)value).toString();
}
return ((Double)value).toString();
}
if(type == Double.TYPE) {
if(value == null) return ""+0;
return Double.toString((Double)value);
}
if(type == Integer.class) {
if(value instanceof Integer) {
return ((Integer)value).toString();
}
return ((Double)value).toString();
}
+ if(type == Integer.TYPE) {
+ if(value == null) return ""+0;
+ return Integer.toString((Integer)value);
+ }
if(type == CharSequence.class) {
return ((CharSequence)value).toString();
}
if(type == FlatColor.class) {
return Integer.toHexString(((FlatColor)value).getRGBA());
}
if(type.isEnum()) {
Object[] vals = type.getEnumConstants();
return value.toString();
}
if(type == ListModel.class) {
if(value != null && value instanceof ListModel) {
ListModel model = (ListModel) value;
StringBuffer sb = new StringBuffer();
for(int i=0; i<model.size(); i++) {
sb.append(model.get(i)+",");
}
return sb.toString();
}
}
if(type == Class.class && value != null) {
return ((Class)value).getName();
}
- u.p("WARNING: returning null for the encoding of property " + getName());
+ u.p("WARNING: returning null for the encoding of property " + getName() + " with type " + getType());
return null;
}
public Class getType() {
return type;
}
public Property duplicate() {
Property p = new Property(this.name,this.type,this.value);
p.exportName = this.exportName;
p.setVisible(this.isVisible());
p.setExported(this.isExported());
p.setBindable(this.isBindable());
p.setList(this.isList());
p.setItemPrototype(this.getItemPrototype());
p.setDisplayName(this.displayName);
p.setCompound(this.isCompound());
p.setMasterProperty(this.getMasterProperty());
return p;
}
public double getDoubleValue() {
if(type == Double.class || type == Double.TYPE) {
if(value instanceof Double) {
return ((Double)value).doubleValue();
}
if(value instanceof Integer) {
return ((Integer)value).doubleValue();
}
}
return -9999;
}
public int getIntegerValue() {
if(type == Integer.class || type == Integer.TYPE) {
if(value instanceof Integer) {
return ((Integer)value).intValue();
}
if(value instanceof Integer) {
return ((Integer)value).intValue();
}
}
return -9999;
}
public String getStringValue() {
if(type == String.class) {
return ((String)value);
}
if(type == CharSequence.class) {
return ((CharSequence)value).toString();
}
return "ERROR";
}
public boolean getBooleanValue() {
if(type == Boolean.class || type == Boolean.TYPE) {
return ((Boolean)value);
}
return false;
}
public FlatColor getColorValue() {
return (FlatColor) value;
}
public void setDoubleValue(double value) {
this.value = new Double(value);
markChanged();
}
public void setIntegerValue(int value) {
this.value = new Integer(value);
markChanged();
}
private void markChanged() {
if(node != null) {
node.markPropertyChanged();
}
}
public Property setExportName(String exportName) {
this.exportName = exportName;
markChanged();
return this;
}
public String getExportName() {
return exportName;
}
public void setStringValue(String text) {
this.value = text;
markChanged();
}
public void setDoubleValue(String text) {
this.value = Double.parseDouble(text);
markChanged();
}
public void setIntegerValue(String text) {
this.value = Integer.parseInt(text);
markChanged();
}
public void setBooleanValue(boolean selected) {
this.value = new Boolean(selected);
markChanged();
}
public Property setVisible(boolean visible) {
this.visible = visible;
markChanged();
return this;
}
public boolean isVisible() {
return visible;
}
public void setEnumValue(Object o) {
this.value = o;
markChanged();
}
public void setColorValue(FlatColor value) {
this.value = value;
markChanged();
}
public Enum getEnumValue() {
return (Enum) this.value;
}
public Property setBindable(boolean bindable) {
this.bindable = bindable;
markChanged();
return this;
}
public boolean isBindable() {
return bindable;
}
public Property setList(boolean list) {
this.list = list;
markChanged();
return this;
}
public boolean isList() {
return list;
}
public Property setItemPrototype(DynamicNode itemPrototype) {
this.itemPrototype = itemPrototype;
markChanged();
return this;
}
public DynamicNode getItemPrototype() {
return itemPrototype;
}
public Property setDisplayName(String name) {
this.displayName = name;
markChanged();
return this;
}
public String getDisplayName() {
if(displayName != null) return displayName;
return getName();
}
public void setNode(DynamicNode node) {
this.node = node;
markChanged();
}
public DynamicNode getNode() {
return node;
}
public Object getRawValue() {
return value;
}
public void setRawValue(Object rawValue) {
this.value = rawValue;
}
public void setCompound(boolean compound) {
this.compound = compound;
}
public boolean isCompound() {
return compound;
}
public void setMasterProperty(String masterProperty) {
this.masterProperty = masterProperty;
}
public String getMasterProperty() {
return masterProperty;
}
@Override
public String toString() {
return "Property{" +
"name='" + name + '\'' +
", type=" + type +
", value=" + value +
", exported=" + exported +
", exportName='" + exportName + '\'' +
", visible=" + visible +
", bindable=" + bindable +
", list=" + list +
", itemPrototype=" + itemPrototype +
", displayName='" + displayName + '\'' +
", node=" + node +
", compound=" + compound +
", masterProperty='" + masterProperty + '\'' +
", proxy=" + proxy +
'}';
}
public void setProxy(boolean proxy) {
this.proxy = proxy;
}
public boolean isProxy() {
return proxy;
}
}
| false | true | public String encode() {
if(type == String.class) return (String)value;
if(type == Boolean.class) return ((Boolean)value).toString();
if(type == Boolean.TYPE) {
if(value == null) return Boolean.toString(false);
return ((Boolean)value).toString();
}
if(type == Double.class) {
if(value instanceof Integer) {
return ((Integer)value).toString();
}
return ((Double)value).toString();
}
if(type == Double.TYPE) {
if(value == null) return ""+0;
return Double.toString((Double)value);
}
if(type == Integer.class) {
if(value instanceof Integer) {
return ((Integer)value).toString();
}
return ((Double)value).toString();
}
if(type == CharSequence.class) {
return ((CharSequence)value).toString();
}
if(type == FlatColor.class) {
return Integer.toHexString(((FlatColor)value).getRGBA());
}
if(type.isEnum()) {
Object[] vals = type.getEnumConstants();
return value.toString();
}
if(type == ListModel.class) {
if(value != null && value instanceof ListModel) {
ListModel model = (ListModel) value;
StringBuffer sb = new StringBuffer();
for(int i=0; i<model.size(); i++) {
sb.append(model.get(i)+",");
}
return sb.toString();
}
}
if(type == Class.class && value != null) {
return ((Class)value).getName();
}
u.p("WARNING: returning null for the encoding of property " + getName());
return null;
}
| public String encode() {
if(type == String.class) return (String)value;
if(type == Boolean.class) return ((Boolean)value).toString();
if(type == Boolean.TYPE) {
if(value == null) return Boolean.toString(false);
return ((Boolean)value).toString();
}
if(type == Double.class) {
if(value instanceof Integer) {
return ((Integer)value).toString();
}
return ((Double)value).toString();
}
if(type == Double.TYPE) {
if(value == null) return ""+0;
return Double.toString((Double)value);
}
if(type == Integer.class) {
if(value instanceof Integer) {
return ((Integer)value).toString();
}
return ((Double)value).toString();
}
if(type == Integer.TYPE) {
if(value == null) return ""+0;
return Integer.toString((Integer)value);
}
if(type == CharSequence.class) {
return ((CharSequence)value).toString();
}
if(type == FlatColor.class) {
return Integer.toHexString(((FlatColor)value).getRGBA());
}
if(type.isEnum()) {
Object[] vals = type.getEnumConstants();
return value.toString();
}
if(type == ListModel.class) {
if(value != null && value instanceof ListModel) {
ListModel model = (ListModel) value;
StringBuffer sb = new StringBuffer();
for(int i=0; i<model.size(); i++) {
sb.append(model.get(i)+",");
}
return sb.toString();
}
}
if(type == Class.class && value != null) {
return ((Class)value).getName();
}
u.p("WARNING: returning null for the encoding of property " + getName() + " with type " + getType());
return null;
}
|
diff --git a/VSPLogin/src/vsp/VspWebServiceImpl.java b/VSPLogin/src/vsp/VspWebServiceImpl.java
index 1983e49..d2f7bf8 100644
--- a/VSPLogin/src/vsp/VspWebServiceImpl.java
+++ b/VSPLogin/src/vsp/VspWebServiceImpl.java
@@ -1,43 +1,44 @@
package vsp;
import java.util.Date;
import java.sql.*;
import javax.sql.*;
import javax.jws.*;
public class VspWebServiceImpl
{
public AccountData getAccountInfo(String userName)
{
AccountData data = new AccountData("[unavailable]", new Date());
- String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
+ String dbUrl = "jdbc:mysql://localhost:3306/vsp";
String dbClass = "com.mysql.jdbc.Driver";
String query = "SELECT email, signup FROM users WHERE user_name='" + userName + "'";
try
{
Class.forName(dbClass);
- Connection con = DriverManager.getConnection (dbUrl);
+ Connection con = DriverManager.getConnection (dbUrl, "tomcat", "tomcat");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
+ rs.first();
String email = rs.getString("email");
Date signup = rs.getDate("signup");
data = new AccountData(email, signup);
con.close();
} //end try
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
return data;
}
}
| false | true | public AccountData getAccountInfo(String userName)
{
AccountData data = new AccountData("[unavailable]", new Date());
String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
String dbClass = "com.mysql.jdbc.Driver";
String query = "SELECT email, signup FROM users WHERE user_name='" + userName + "'";
try
{
Class.forName(dbClass);
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
String email = rs.getString("email");
Date signup = rs.getDate("signup");
data = new AccountData(email, signup);
con.close();
} //end try
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
return data;
}
| public AccountData getAccountInfo(String userName)
{
AccountData data = new AccountData("[unavailable]", new Date());
String dbUrl = "jdbc:mysql://localhost:3306/vsp";
String dbClass = "com.mysql.jdbc.Driver";
String query = "SELECT email, signup FROM users WHERE user_name='" + userName + "'";
try
{
Class.forName(dbClass);
Connection con = DriverManager.getConnection (dbUrl, "tomcat", "tomcat");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.first();
String email = rs.getString("email");
Date signup = rs.getDate("signup");
data = new AccountData(email, signup);
con.close();
} //end try
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
return data;
}
|
diff --git a/XMLLibrarian.java b/XMLLibrarian.java
index 8fe544c..31ec231 100644
--- a/XMLLibrarian.java
+++ b/XMLLibrarian.java
@@ -1,829 +1,829 @@
package plugins.XMLLibrarian;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import freenet.client.FetchException;
import freenet.client.FetchResult;
import freenet.client.HighLevelSimpleClient;
import freenet.clients.http.filter.CommentException;
import freenet.clients.http.filter.FilterCallback;
import freenet.keys.FreenetURI;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginHTTP;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.PluginHTTPException;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.HTMLEncoder;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
/**
* XMLLibrarian is a modified version of the old librarian.
* It uses the Xml index files for searching.
* In addition to searching in a single index, XMLLibrarian allows searching in multiple
* indices at the same time.
* Folders containing set of indices can be created and any search on a folder searches the string in
* all the indices in the folder.
*
* The current configuration can be stored in an external file and reused later. The default file for the same
* is XMLLibrarian.xml.
*
*The index list of a particular folder can be saved in an external file and likewise imported from
*an existing file.
*XMLLibrarian assumes that the index to be used is present at DEFAULT_INDEX_SITE/index.xml .
* @author swatigoyal
*
*/
public class XMLLibrarian implements FredPlugin, FredPluginHTTP, FredPluginThreadless {
/**
* Gives the default index site displayed in the browser.
* <p>Change this parameter accordingly.
*
*/
public String DEFAULT_INDEX_SITE="SSK@F2r3VplAy6D0Z3odk0hqoHIHMTZfAZ2nx98AiF44pfY,alJs1GWselPGxkjlEY3KdhqLoIAG7Snq5qfUMhgJYeI,AQACAAE/testsite/";
//public String DEFAULT_INDEX_SITE="SSK@0yc3irwbhLYU1j3MdzGuwC6y1KboBHJ~1zIi8AN2XC0,5j9hrd2LLcew6ieoX1yC-hXRueSKziKYnRaD~aLnAYE,AQACAAE/testsite/";
private String configfile = "XMLLibrarian.xml";
private String DEFAULT_FILE = "index.xml";
boolean goon = true;
private PluginRespirator pr;
private static final String plugName = "XMLLibrarian";
private String word ;
private boolean processingWord ;
private boolean found_match ;
private HashMap uris;
private Vector fileuris;
private String prefix_match;
private int prefix;
private boolean test;
/**
* indexList contains the index folders
* each folder has a name and a list of indices added to that folder
*/
private HashMap indexList = new HashMap();
public void terminate() {
goon = false;
save(configfile);
}
public String handleHTTPPut(HTTPRequest request) throws PluginHTTPException {
return null;
}
public String handleHTTPPost(HTTPRequest request) throws PluginHTTPException {
return null;
}
private void appendDefaultPageStart(StringBuffer out, String stylesheet) {
out.append("<HTML><HEAD><TITLE>" + plugName + "</TITLE>");
if(stylesheet != null)
out.append("<link href=\""+stylesheet+"\" type=\"text/css\" rel=\"stylesheet\" />");
out.append("</HEAD><BODY>\n");
out.append("<CENTER><H1>" + plugName + "</H1><BR/><BR/><BR/>\n");
}
private void appendDefaultPageEnd(StringBuffer out) {
out.append("</CENTER></BODY></HTML>");
}
/**
* appendDefaultPostFields generates the main interface to the XMLLibrarian
* @param out
* @param search
* @param index
*/
public void appendDefaultPostFields(StringBuffer out, String search, String index) {
search = HTMLEncoder.encode(search);
index = HTMLEncoder.encode(index);
out.append("Search in the index or folder:<br/>");
out.append("<form method=\"GET\"><input type=\"text\" value=\"").append(search).append("\" name=\"search\" size=80/><br/><br/>");
out.append("<input type=\"radio\" name=\"choice\" value=\"index\">Index<br/>");
out.append("Using the index site(remember to give the site without index.xml):<br/>");
out.append("<input type=\"text\" name=\"index\" value=\"").append(index).append("\" size=80/><br/>");
out.append("<select name=\"folderList\">");
String[] words = (String[]) indexList.keySet().toArray(new String[indexList.size()]);
for(int i =0;i<words.length;i++)
{
out.append("<option value=\"").append(words[i]).append("\">").append(words[i]).append("</option");
}
out.append("<br/><input type=\"radio\" name=\"choice\" value=\"folder\"> Folder<br/>");
out.append("<input type=submit name=\"addToFolder\" value=\"Add to folder\" />");
out.append("<input type=submit name=\"newFolder\" value=\"New Folder\" />");
out.append("<input type=submit name=\"List\" value=\"List\" />");
out.append("<input type=submit name=\"help\" value=\"Help!\" />");
out.append("<input type=submit name = \"find\" value=\"Find!\"/>\n");
out.append("<form><input type=\"file\" name=\"datafile\" /> ");
out.append("<input type=submit name=\"Import\" value=\"Import From File\"/> ");
out.append("<form><input type=\"text\" name=\"datafile2\" /> ");
out.append("<input type=submit name=\"Export\" value=\"Export To File\"/> </form>");
out.append("<form><input type=\"file\" name=\"datafile3\" /> ");
out.append("<input type=submit name=\"Reload\" value=\"Load Configuration\"/> ");
out.append("<form><input type=\"file\" name=\"datafile4\" /> ");
out.append("<input type=submit name=\"Save\" value=\"Save Configuration\"/> ");
// index - key to index
// search - text to search for
}
/**
* Generates the interface to the XMLLibrarian and takes apropos action to an event.
*
* @param request
*/
public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException {
- // if(test) {reloadOld(configfile); test= false;}
+ if(test) {reloadOld(configfile); test= false;}
StringBuffer out = new StringBuffer();
String search = request.getParam("search");
String stylesheet = request.getParam("stylesheet", null);
String choice = request.getParam("choice");
if(stylesheet != null) {
FilterCallback cb = pr.makeFilterCallback(request.getPath());
try {
stylesheet = cb.processURI(stylesheet, "text/css");
} catch (CommentException e) {
return "Invalid stylesheet: "+e.getMessage();
}
}
String indexuri = request.getParam("index", DEFAULT_INDEX_SITE);
appendDefaultPageStart(out, stylesheet);
appendDefaultPostFields(out, search, indexuri);
appendDefaultPageEnd(out);
if(choice.equals("folder")){
if((request.getParam("find")).equals("Find!"))
{
String folder = request.getParam("folderList");
String[] indices = (String [])indexList.get(folder);
for(int i =0;i<indices.length;i++)
{try{
searchStr(out,search,indices[i],stylesheet);}
catch (Exception e){
Logger.error(this, "Search for "+search+" in folder "+folder+" failed "+e.toString(), e);
}
}
}
}
else if((request.getParam("newFolder")).equals("New Folder")){
out.append("<p>Name of the new Folder<br/>");
out.append("<form><input type=\"text\" name=\"newfolder\" size=80/> ");
out.append("<input type=submit value=\"Add\" name=\"addNew\" />");
}
else if((request.getParam("addNew")).equals("Add")){
try{
String newFolder = request.getParam("newfolder");
indexList.put(newFolder, new String[]{new String("0")});
out.append("New folder "+newFolder+" added. Kindly refresh the page<br/> ");
}
catch(Exception e){
Logger.error(this, "Could not add new folder "+e.toString(), e);
}
return out.toString();
}
else if((request.getParam("help")).equals("Help!")){
out.append("<h3>Find</h3>");
out.append("<p>Search for the queried word in either an index site or a selected folder of indices <br/>");
out.append("If searching in a folder of indices, select the appropriate folder and check the button for folder<br/>");
out.append("<h3>Add to folder</h3>");
out.append("<p>Add the current index site to selected folder<br/>");
out.append("<h3>New folder</h3>");
out.append("<p>Create a new folder. To see the added folder refresh the page<br/>");
out.append("<h3>List</h3>");
out.append("<p>List the indices in the current folder<br/>");
}
else if((request.getParam("addToFolder")).equals("Add to folder")){
String folder = request.getParam("folderList");
indexuri = request.getParam("index",DEFAULT_INDEX_SITE);
try{
String[] old = (String []) indexList.get(folder);
String firstIndex = old[0];
String[] indices;
if(firstIndex.equals(new String("0"))){
indices = new String[]{indexuri};
}
else{
indices = new String[old.length+1];
System.arraycopy(old, 0, indices, 0, old.length);
indices[old.length] = indexuri;
}
out.append("index site "+indexuri+" added to "+folder);
indexList.remove(folder);
indexList.put(folder, indices);
}
catch(Exception e){
Logger.error(this, "Index "+indexuri+" could not be added to folder "+folder+" "+e.toString(), e);
}
}
else if((request.getParam("List")).equals("List")){
String folder = request.getParam("folderList");
String[] indices = (String[]) indexList.get(folder);
for(int i = 0;i<indices.length;i++){
out.append("<p>\n<table class=\"librarian-result\" width=\"100%\" border=1><tr><td align=center bgcolor=\"#D0D0D0\" class=\"librarian-result-url\">\n");
out.append(" <A HREF=\"").append(indices[i]).append("\">").append(indices[i]).append("</A>");
out.append("</td></tr><tr><td align=left class=\"librarian-result-summary\">\n");
out.append("</td></tr></table>\n");
}
}
else if((request.getParam("Save")).equals("Save Configuration")){
try{
String file = request.getParam("datafile4");
if(file.equals("")) file = configfile;
save(out,file);
out.append("Saved Configuration");
}
catch(Exception e){
Logger.error(this, "Configuration could not be saved "+e.toString(), e);
}
}
else if(choice.equals("index")){
try{
searchStr(out,search,indexuri,stylesheet);}
catch(Exception e){
Logger.error(this, "Searchign for the word "+search+" in index "+indexuri+" failed "+e.toString(), e);
}
}
else if((request.getParam("Reload")).equals("Load Configuration")){
String file = request.getParam("datafile3");
reloadOld(file);
out.append("Loaded Configuration");
}
else if((request.getParam("Import")).equals("Import From File")){
String folder = request.getParam("folderList");
String file = request.getParam("datafile");
Vector indices=new Vector();
try{
BufferedReader inp = new BufferedReader(new FileReader(file));
String index = inp.readLine();
while(index != null){
indices.add(index);
out.append("index :"+index);
index = inp.readLine();
}
String[] old = (String []) indexList.get(folder);
String[] finalIndex;
if(old[0].equals("0"))
{
finalIndex = new String[indices.size()];
for(int i = 0;i<indices.size();i++){
finalIndex[i] = (String) indices.elementAt(i);
}
}
else{
finalIndex = new String[old.length + indices.size()];
System.arraycopy(old, 0, finalIndex, 0, old.length);
for(int i = 0;i<indices.size();i++){
finalIndex[old.length + i] = (String) indices.elementAt(i);
}
}
indexList.remove(folder);
indexList.put(folder, finalIndex);
inp.close();
}
catch(Exception e){}
}
else if((request.getParam("Export")).equals("Export To File")){
String folder = request.getParam("folderList");
String file = request.getParam("datafile2");
try{
FileWriter outp = new FileWriter(file,true);
String[] indices = ((String [])indexList.get(folder));
for(int i = 0;i<indices.length;i++){
outp.write(indices[i]+"\n");
}
outp.close();
}
catch(Exception e){Logger.error(this, "Could not write configuration to external file "+e.toString(),e );}
return out.toString();
}
return out.toString();
}
/**
* reloadOld exports an externally saved configuration
* @param configuration filename
*/
private void reloadOld(String config){
try{
File f = new File(config);
if(f.exists()){
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(config);
Element root = doc.getDocumentElement();
NodeList folders = root.getElementsByTagName("folder");
for(int i =0;i<folders.getLength();i++)
{
Attr folder = (Attr) ((folders.item(i)).getAttributes().getNamedItem("name"));
String folderName = folder.getValue();
NodeList indices = ((Element) folders.item(i)).getElementsByTagName("index");
String[] index = new String[indices.getLength()];
for(int j=0;j<indices.getLength();j++)
{
Attr indexj = (Attr) ((indices.item(j)).getAttributes().getNamedItem("key"));
index[j] = indexj.getValue();
}
indexList.put(folderName, index);
}}
}
catch(Exception e){ Logger.error(this, "Could not read configuration "+e.toString(), e);}
}
private void save(StringBuffer out, String file){
File outputFile = new File(file);
StreamResult resultStream;
resultStream = new StreamResult(outputFile);
Document xmlDoc = null;
DocumentBuilderFactory xmlFactory = null;
DocumentBuilder xmlBuilder = null;
DOMImplementation impl = null;
Element rootElement = null;
xmlFactory = DocumentBuilderFactory.newInstance();
try {
xmlBuilder = xmlFactory.newDocumentBuilder();
} catch(javax.xml.parsers.ParserConfigurationException e) {
Logger.error(this, "Spider: Error while initializing XML generator: "+e.toString());
//return out.toString();
}
impl = xmlBuilder.getDOMImplementation();
xmlDoc = impl.createDocument(null, "XMLLibrarian", null);
rootElement = xmlDoc.getDocumentElement();
String[] folders = (String[]) indexList.keySet().toArray(new String[indexList.size()]);
for(int i=0;i<folders.length;i++)
{
Element folder = xmlDoc.createElement("folder");
String folderName = folders[i];
folder.setAttribute("name", folderName);
String[] indices = (String[]) indexList.get(folderName);
for(int j =0;j<indices.length;j++)
{
Element index = xmlDoc.createElement("index");
index.setAttribute("key", indices[j]);
folder.appendChild(index);
}
rootElement.appendChild(folder);
}
DOMSource domSource = new DOMSource(xmlDoc);
TransformerFactory transformFactory = TransformerFactory.newInstance();
Transformer serializer;
try {
serializer = transformFactory.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT,"yes");
try {
serializer.transform(domSource, resultStream);
} catch(javax.xml.transform.TransformerException e) {
Logger.error(this, "Spider: Error while serializing XML (transform()): "+e.toString());
//return out.toString();
}
} catch(javax.xml.transform.TransformerConfigurationException e) {
Logger.error(this, "Spider: Error while serializing XML (transformFactory.newTransformer()): "+e.toString());
// return out.toString();
}
if(Logger.shouldLog(Logger.MINOR, this))
Logger.minor(this, "Spider: indexes regenerated.");
}
private void save(String file){
File outputFile = new File(file);
StreamResult resultStream;
resultStream = new StreamResult(outputFile);
Document xmlDoc = null;
DocumentBuilderFactory xmlFactory = null;
DocumentBuilder xmlBuilder = null;
DOMImplementation impl = null;
Element rootElement = null;
xmlFactory = DocumentBuilderFactory.newInstance();
try {
xmlBuilder = xmlFactory.newDocumentBuilder();
} catch(javax.xml.parsers.ParserConfigurationException e) {
Logger.error(this, "Spider: Error while initializing XML generator: "+e.toString());
//return out.toString();
}
impl = xmlBuilder.getDOMImplementation();
xmlDoc = impl.createDocument(null, "XMLLibrarian", null);
rootElement = xmlDoc.getDocumentElement();
String[] folders = (String[]) indexList.keySet().toArray(new String[indexList.size()]);
for(int i=0;i<folders.length;i++)
{
Element folder = xmlDoc.createElement("folder");
String folderName = folders[i];
folder.setAttribute("name", folderName);
String[] indices = (String[]) indexList.get(folderName);
for(int j =0;j<indices.length;j++)
{
Element index = xmlDoc.createElement("index");
index.setAttribute("key", indices[j]);
folder.appendChild(index);
}
rootElement.appendChild(folder);
}
DOMSource domSource = new DOMSource(xmlDoc);
TransformerFactory transformFactory = TransformerFactory.newInstance();
Transformer serializer;
try {
serializer = transformFactory.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT,"yes");
try {
serializer.transform(domSource, resultStream);
} catch(javax.xml.transform.TransformerException e) {
Logger.error(this, "Spider: Error while serializing XML (transform()): "+e.toString());
//return out.toString();
}
} catch(javax.xml.transform.TransformerConfigurationException e) {
Logger.error(this, "Spider: Error while serializing XML (transformFactory.newTransformer()): "+e.toString());
// return out.toString();
}
if(Logger.shouldLog(Logger.MINOR, this))
Logger.minor(this, "Spider: indexes regenerated.");
}
/**
* Searches for the string in the specified index. In case of a folder searches in all included indices
* @param out
* @param search - string to be searched
* @param indexuri
* @param stylesheet
*/
private void searchStr(StringBuffer out,String search,String indexuri,String stylesheet) throws Exception{
if (search.equals("")) {
return;
}
try {
out.append("<p><span class=\"librarian-searching-for-header\">Searching: </span><span class=\"librarian-searching-for-target\">").append(HTMLEncoder.encode(search)).append("</span></p>\n");
// Get search result
out.append("<p>Index Site: "+indexuri+"</p>");
String searchWords[] = search.split(" ");
// Return results in order.
LinkedHashSet hs = new LinkedHashSet();
Vector keyuris;
try{
for(int i = 0;i<searchWords.length;i++){
keyuris = getIndex(searchWords[i]);
if(i == 0){
synchronized(hs){
hs.clear();
if (keyuris != null) {
Iterator it = keyuris.iterator();
while (it.hasNext()){
hs.add(it.next());
}
}
}
}
else{
try{
synchronized(hs){
if(keyuris.size() > 0){
Iterator it = hs.iterator();
while(it.hasNext()){
URIWrapper uri = (URIWrapper) it.next();
if(!Contains(uri.URI,keyuris)) it.remove();
}
}
if(keyuris.size() == 0) hs.clear();
}
}
catch(Exception e){
e.getMessage();
}
}
}}
catch(Exception e){
out.append("could not complete search for "+search +"in "+indexuri+e.toString());
Logger.error(this, "could not complete search for "+search +"in "+indexuri+e.toString(), e);
}
// Output results
int results = 0;
out.append("<table class=\"librarian-results\"><tr>\n");
Iterator it = hs.iterator();
try{
while (it.hasNext()) {
URIWrapper o = (URIWrapper)it.next();
String showurl = o.URI;
String description = HTMLEncoder.encode(o.descr);
if(!description.equals("not available")){
description=description.replaceAll("(\n|<(b|B)(r|R)>)", "<br>");
description=description.replaceAll(" ", " ");
description=description.replaceAll("</?[a-zA-Z].*/?>", "");
}
showurl = HTMLEncoder.encode(showurl);
if (showurl.length() > 60)
showurl = showurl.substring(0,15) + "…" + showurl.replaceFirst("[^/]*/", "/");
String realurl = (o.URI.startsWith("/")?"":"/") + o.URI;
realurl = HTMLEncoder.encode(realurl);
out.append("<p>\n<table class=\"librarian-result\" width=\"100%\" border=1><tr><td align=center bgcolor=\"#D0D0D0\" class=\"librarian-result-url\">\n");
out.append(" <A HREF=\"").append(realurl).append("\" title=\"").append(o.URI).append("\">").append(showurl).append("</A>\n");
out.append("</td></tr><tr><td align=left class=\"librarian-result-summary\">\n");
out.append("</td></tr></table>\n");
results++;
}
}
catch(Exception e){
out.append("Could not display results for "+search+e.toString());
Logger.error(this, "Could not display search results for "+search+e.toString(), e);
}
out.append("</tr><table>\n");
out.append("<p><span class=\"librarian-summary-found-text\">Found: </span><span class=\"librarian-summary-found-number\">").append(results).append(" results</span></p>\n");
} catch (Exception e) {
// TODO Auto-generated catch block
Logger.error(this, "Could not complete search for "+search +"in "+indexuri+e.toString(), e);
e.printStackTrace();
}
}
private boolean Contains(String str, Vector keyuris){
if(keyuris.size() > 0){
for(int i = 0; i<keyuris.size();i++){
if(str.equals((((URIWrapper) (keyuris.elementAt(i))).URI))) return true;
}
return false;
}
else return false;
}
/*
* gets the index for the given word
*/
private Vector getIndex(String word) throws Exception{
String subIndex = searchStr(word);
Vector index = new Vector();
index = getEntry(word,subIndex);
return index;
}
/**
* Parses through the main index file which is given by DEFAULT_INDEX_SITE + DEFAULT_FILE, searching for the given search word.
* <p>
*/
public String searchStr(String str) throws Exception{
HighLevelSimpleClient hlsc = pr.getHLSimpleClient();
FreenetURI u = new FreenetURI(DEFAULT_INDEX_SITE + DEFAULT_FILE);
FetchResult res;
while(true) {
try {
res = hlsc.fetch(u);
break;
} catch (FetchException e) {
if(e.newURI != null) {
u = e.newURI;
continue;
} else throw e;
}
}
word = str;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(res.asBucket().getInputStream(), new LibrarianHandler() );
} catch (Throwable err) {
err.printStackTrace ();}
return prefix_match;
}
// public String search(String str,NodeList list) throws Exception
// {
// int prefix = str.length();
// for(int i = 0;i<list.getLength();i++){
// Element subIndex = (Element) list.item(i);
// String key = subIndex.getAttribute("key");
// if(key.equals(str)) return key;
// }
//
// return search(str.substring(0, prefix-1),list);
// }
private Vector getEntry(String str,String subIndex)throws Exception{
//search for the word in the given subIndex
fileuris = new Vector();
HighLevelSimpleClient hlsc = pr.getHLSimpleClient();
FreenetURI u = new FreenetURI(DEFAULT_INDEX_SITE + "index_"+subIndex+".xml");
FetchResult res;
while(true) {
try {
res = hlsc.fetch(u);
break;
} catch (FetchException e) {
if(e.newURI != null) {
u = e.newURI;
continue;
} else throw e;
}
}
word = str; //word to be searched
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(res.asBucket().getInputStream(), new LibrarianHandler() );
} catch (Throwable err) {
err.printStackTrace ();}
return fileuris;
}
/**
* Gets the key of the matched uri.
* @param id id of the uri which contains the searched word
* @return key of the uri
* @throws Exception
*/
public String getURI(String id) throws Exception
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(DEFAULT_FILE);
Element root = doc.getDocumentElement();
NodeList fileList = root.getElementsByTagName("file");
for(int i = 0;i<fileList.getLength();i++){
Element file = (Element) fileList.item(i);
String fileId = file.getAttribute("id");
if(fileId.equals(id)) return file.getAttribute("key");
}
return "not available";
}
public void runPlugin(PluginRespirator pr) {
this.pr = pr;
this.test = true;
}
private class URIWrapper implements Comparable {
public String URI;
public String descr;
public int compareTo(Object o) {
if (o instanceof URIWrapper)
return URI.compareTo(((URIWrapper)o).URI);
return -1;
}
}
/**
* Required for using SAX parser on XML indices
* @author swati
*
*/
public class LibrarianHandler extends DefaultHandler {
// now we need to adapt this to read subindexing
private Locator locator = null;
public LibrarianHandler() throws Exception{
}
public void setDocumentLocator(Locator value) {
locator = value;
}
public void endDocument() throws SAXException{}
public void startDocument () throws SAXException
{
found_match = false;
uris = new HashMap();
}
public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attrs) throws SAXException {
if (rawName == null) {
rawName = localName;
}
String elt_name = rawName;
if(elt_name.equals("prefix")){
prefix = Integer.parseInt(attrs.getValue("value"));
}
if(elt_name.equals("subIndex")){
try{
String md5 = MD5(word);
//here we need to match and see if any of the subindices match the required substring of the word.
for(int i=0;i<prefix;i++){
if((md5.substring(0,prefix-i)).equals(attrs.getValue("key"))){
prefix_match=md5.substring(0, prefix-i);
break;
}
}
}
catch(Exception e){Logger.error(this, "MD5 of the word could not be calculated "+e.toString(), e);}
}
if(elt_name.equals("files")) processingWord = false;
if(elt_name.equals("keywords")) processingWord = true;
if(elt_name.equals("word")){
try{
if((attrs.getValue("v")).equals(word)) found_match = true;
}catch(Exception e){Logger.error(this, "word key doesn't match"+e.toString(), e); }
}
if(elt_name.equals("file")){
if(processingWord == true && found_match == true){
URIWrapper uri = new URIWrapper();
uri.URI = (uris.get(attrs.getValue("id"))).toString();
uri.descr = "not available";
fileuris.add(uri);
}
else{
try{
String id = attrs.getValue("id");
String key = attrs.getValue("key");
uris.put(id,key);
String[] words = (String[]) uris.values().toArray(new String[uris.size()]);
}
catch(Exception e){Logger.error(this,"File id and key could not be retrieved. May be due to format clash",e);}
}
}
}
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
//this function will return the String representation of the MD5 hash for the input string
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}
}
| true | true | public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException {
// if(test) {reloadOld(configfile); test= false;}
StringBuffer out = new StringBuffer();
String search = request.getParam("search");
String stylesheet = request.getParam("stylesheet", null);
String choice = request.getParam("choice");
if(stylesheet != null) {
FilterCallback cb = pr.makeFilterCallback(request.getPath());
try {
stylesheet = cb.processURI(stylesheet, "text/css");
} catch (CommentException e) {
return "Invalid stylesheet: "+e.getMessage();
}
}
String indexuri = request.getParam("index", DEFAULT_INDEX_SITE);
appendDefaultPageStart(out, stylesheet);
appendDefaultPostFields(out, search, indexuri);
appendDefaultPageEnd(out);
if(choice.equals("folder")){
if((request.getParam("find")).equals("Find!"))
{
String folder = request.getParam("folderList");
String[] indices = (String [])indexList.get(folder);
for(int i =0;i<indices.length;i++)
{try{
searchStr(out,search,indices[i],stylesheet);}
catch (Exception e){
Logger.error(this, "Search for "+search+" in folder "+folder+" failed "+e.toString(), e);
}
}
}
}
else if((request.getParam("newFolder")).equals("New Folder")){
out.append("<p>Name of the new Folder<br/>");
out.append("<form><input type=\"text\" name=\"newfolder\" size=80/> ");
out.append("<input type=submit value=\"Add\" name=\"addNew\" />");
}
else if((request.getParam("addNew")).equals("Add")){
try{
String newFolder = request.getParam("newfolder");
indexList.put(newFolder, new String[]{new String("0")});
out.append("New folder "+newFolder+" added. Kindly refresh the page<br/> ");
}
catch(Exception e){
Logger.error(this, "Could not add new folder "+e.toString(), e);
}
return out.toString();
}
else if((request.getParam("help")).equals("Help!")){
out.append("<h3>Find</h3>");
out.append("<p>Search for the queried word in either an index site or a selected folder of indices <br/>");
out.append("If searching in a folder of indices, select the appropriate folder and check the button for folder<br/>");
out.append("<h3>Add to folder</h3>");
out.append("<p>Add the current index site to selected folder<br/>");
out.append("<h3>New folder</h3>");
out.append("<p>Create a new folder. To see the added folder refresh the page<br/>");
out.append("<h3>List</h3>");
out.append("<p>List the indices in the current folder<br/>");
}
else if((request.getParam("addToFolder")).equals("Add to folder")){
String folder = request.getParam("folderList");
indexuri = request.getParam("index",DEFAULT_INDEX_SITE);
try{
String[] old = (String []) indexList.get(folder);
String firstIndex = old[0];
String[] indices;
if(firstIndex.equals(new String("0"))){
indices = new String[]{indexuri};
}
else{
indices = new String[old.length+1];
System.arraycopy(old, 0, indices, 0, old.length);
indices[old.length] = indexuri;
}
out.append("index site "+indexuri+" added to "+folder);
indexList.remove(folder);
indexList.put(folder, indices);
}
catch(Exception e){
Logger.error(this, "Index "+indexuri+" could not be added to folder "+folder+" "+e.toString(), e);
}
}
else if((request.getParam("List")).equals("List")){
String folder = request.getParam("folderList");
String[] indices = (String[]) indexList.get(folder);
for(int i = 0;i<indices.length;i++){
out.append("<p>\n<table class=\"librarian-result\" width=\"100%\" border=1><tr><td align=center bgcolor=\"#D0D0D0\" class=\"librarian-result-url\">\n");
out.append(" <A HREF=\"").append(indices[i]).append("\">").append(indices[i]).append("</A>");
out.append("</td></tr><tr><td align=left class=\"librarian-result-summary\">\n");
out.append("</td></tr></table>\n");
}
}
else if((request.getParam("Save")).equals("Save Configuration")){
try{
String file = request.getParam("datafile4");
if(file.equals("")) file = configfile;
save(out,file);
out.append("Saved Configuration");
}
catch(Exception e){
Logger.error(this, "Configuration could not be saved "+e.toString(), e);
}
}
else if(choice.equals("index")){
try{
searchStr(out,search,indexuri,stylesheet);}
catch(Exception e){
Logger.error(this, "Searchign for the word "+search+" in index "+indexuri+" failed "+e.toString(), e);
}
}
else if((request.getParam("Reload")).equals("Load Configuration")){
String file = request.getParam("datafile3");
reloadOld(file);
out.append("Loaded Configuration");
}
else if((request.getParam("Import")).equals("Import From File")){
String folder = request.getParam("folderList");
String file = request.getParam("datafile");
Vector indices=new Vector();
try{
BufferedReader inp = new BufferedReader(new FileReader(file));
String index = inp.readLine();
while(index != null){
indices.add(index);
out.append("index :"+index);
index = inp.readLine();
}
String[] old = (String []) indexList.get(folder);
String[] finalIndex;
if(old[0].equals("0"))
{
finalIndex = new String[indices.size()];
for(int i = 0;i<indices.size();i++){
finalIndex[i] = (String) indices.elementAt(i);
}
}
else{
finalIndex = new String[old.length + indices.size()];
System.arraycopy(old, 0, finalIndex, 0, old.length);
for(int i = 0;i<indices.size();i++){
finalIndex[old.length + i] = (String) indices.elementAt(i);
}
}
indexList.remove(folder);
indexList.put(folder, finalIndex);
inp.close();
}
catch(Exception e){}
}
else if((request.getParam("Export")).equals("Export To File")){
String folder = request.getParam("folderList");
String file = request.getParam("datafile2");
try{
FileWriter outp = new FileWriter(file,true);
String[] indices = ((String [])indexList.get(folder));
for(int i = 0;i<indices.length;i++){
outp.write(indices[i]+"\n");
}
outp.close();
}
catch(Exception e){Logger.error(this, "Could not write configuration to external file "+e.toString(),e );}
return out.toString();
}
return out.toString();
}
| public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException {
if(test) {reloadOld(configfile); test= false;}
StringBuffer out = new StringBuffer();
String search = request.getParam("search");
String stylesheet = request.getParam("stylesheet", null);
String choice = request.getParam("choice");
if(stylesheet != null) {
FilterCallback cb = pr.makeFilterCallback(request.getPath());
try {
stylesheet = cb.processURI(stylesheet, "text/css");
} catch (CommentException e) {
return "Invalid stylesheet: "+e.getMessage();
}
}
String indexuri = request.getParam("index", DEFAULT_INDEX_SITE);
appendDefaultPageStart(out, stylesheet);
appendDefaultPostFields(out, search, indexuri);
appendDefaultPageEnd(out);
if(choice.equals("folder")){
if((request.getParam("find")).equals("Find!"))
{
String folder = request.getParam("folderList");
String[] indices = (String [])indexList.get(folder);
for(int i =0;i<indices.length;i++)
{try{
searchStr(out,search,indices[i],stylesheet);}
catch (Exception e){
Logger.error(this, "Search for "+search+" in folder "+folder+" failed "+e.toString(), e);
}
}
}
}
else if((request.getParam("newFolder")).equals("New Folder")){
out.append("<p>Name of the new Folder<br/>");
out.append("<form><input type=\"text\" name=\"newfolder\" size=80/> ");
out.append("<input type=submit value=\"Add\" name=\"addNew\" />");
}
else if((request.getParam("addNew")).equals("Add")){
try{
String newFolder = request.getParam("newfolder");
indexList.put(newFolder, new String[]{new String("0")});
out.append("New folder "+newFolder+" added. Kindly refresh the page<br/> ");
}
catch(Exception e){
Logger.error(this, "Could not add new folder "+e.toString(), e);
}
return out.toString();
}
else if((request.getParam("help")).equals("Help!")){
out.append("<h3>Find</h3>");
out.append("<p>Search for the queried word in either an index site or a selected folder of indices <br/>");
out.append("If searching in a folder of indices, select the appropriate folder and check the button for folder<br/>");
out.append("<h3>Add to folder</h3>");
out.append("<p>Add the current index site to selected folder<br/>");
out.append("<h3>New folder</h3>");
out.append("<p>Create a new folder. To see the added folder refresh the page<br/>");
out.append("<h3>List</h3>");
out.append("<p>List the indices in the current folder<br/>");
}
else if((request.getParam("addToFolder")).equals("Add to folder")){
String folder = request.getParam("folderList");
indexuri = request.getParam("index",DEFAULT_INDEX_SITE);
try{
String[] old = (String []) indexList.get(folder);
String firstIndex = old[0];
String[] indices;
if(firstIndex.equals(new String("0"))){
indices = new String[]{indexuri};
}
else{
indices = new String[old.length+1];
System.arraycopy(old, 0, indices, 0, old.length);
indices[old.length] = indexuri;
}
out.append("index site "+indexuri+" added to "+folder);
indexList.remove(folder);
indexList.put(folder, indices);
}
catch(Exception e){
Logger.error(this, "Index "+indexuri+" could not be added to folder "+folder+" "+e.toString(), e);
}
}
else if((request.getParam("List")).equals("List")){
String folder = request.getParam("folderList");
String[] indices = (String[]) indexList.get(folder);
for(int i = 0;i<indices.length;i++){
out.append("<p>\n<table class=\"librarian-result\" width=\"100%\" border=1><tr><td align=center bgcolor=\"#D0D0D0\" class=\"librarian-result-url\">\n");
out.append(" <A HREF=\"").append(indices[i]).append("\">").append(indices[i]).append("</A>");
out.append("</td></tr><tr><td align=left class=\"librarian-result-summary\">\n");
out.append("</td></tr></table>\n");
}
}
else if((request.getParam("Save")).equals("Save Configuration")){
try{
String file = request.getParam("datafile4");
if(file.equals("")) file = configfile;
save(out,file);
out.append("Saved Configuration");
}
catch(Exception e){
Logger.error(this, "Configuration could not be saved "+e.toString(), e);
}
}
else if(choice.equals("index")){
try{
searchStr(out,search,indexuri,stylesheet);}
catch(Exception e){
Logger.error(this, "Searchign for the word "+search+" in index "+indexuri+" failed "+e.toString(), e);
}
}
else if((request.getParam("Reload")).equals("Load Configuration")){
String file = request.getParam("datafile3");
reloadOld(file);
out.append("Loaded Configuration");
}
else if((request.getParam("Import")).equals("Import From File")){
String folder = request.getParam("folderList");
String file = request.getParam("datafile");
Vector indices=new Vector();
try{
BufferedReader inp = new BufferedReader(new FileReader(file));
String index = inp.readLine();
while(index != null){
indices.add(index);
out.append("index :"+index);
index = inp.readLine();
}
String[] old = (String []) indexList.get(folder);
String[] finalIndex;
if(old[0].equals("0"))
{
finalIndex = new String[indices.size()];
for(int i = 0;i<indices.size();i++){
finalIndex[i] = (String) indices.elementAt(i);
}
}
else{
finalIndex = new String[old.length + indices.size()];
System.arraycopy(old, 0, finalIndex, 0, old.length);
for(int i = 0;i<indices.size();i++){
finalIndex[old.length + i] = (String) indices.elementAt(i);
}
}
indexList.remove(folder);
indexList.put(folder, finalIndex);
inp.close();
}
catch(Exception e){}
}
else if((request.getParam("Export")).equals("Export To File")){
String folder = request.getParam("folderList");
String file = request.getParam("datafile2");
try{
FileWriter outp = new FileWriter(file,true);
String[] indices = ((String [])indexList.get(folder));
for(int i = 0;i<indices.length;i++){
outp.write(indices[i]+"\n");
}
outp.close();
}
catch(Exception e){Logger.error(this, "Could not write configuration to external file "+e.toString(),e );}
return out.toString();
}
return out.toString();
}
|
diff --git a/frost-wot/source/frost/gui/MessageFrame.java b/frost-wot/source/frost/gui/MessageFrame.java
index e7522428..72cda7c1 100644
--- a/frost-wot/source/frost/gui/MessageFrame.java
+++ b/frost-wot/source/frost/gui/MessageFrame.java
@@ -1,1596 +1,1597 @@
/*
MessageFrame.java / Frost
Copyright (C) 2001 Frost Project <jtcfrost.sourceforge.net>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.gui;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import org.joda.time.*;
import frost.*;
import frost.boards.*;
import frost.ext.*;
import frost.gui.model.*;
import frost.identities.*;
import frost.messages.*;
import frost.storage.perst.messages.*;
import frost.util.*;
import frost.util.gui.*;
import frost.util.gui.textpane.*;
import frost.util.gui.translation.*;
public class MessageFrame extends JFrame {
private static final Logger logger = Logger.getLogger(MessageFrame.class.getName());
private final Language language;
private final Listener listener = new Listener();
private boolean initialized = false;
private final Window parentWindow;
private Board board;
private String repliedMsgId;
private final SettingsClass frostSettings;
private MFAttachedBoardsTable boardsTable;
private MFAttachedFilesTable filesTable;
private MFAttachedBoardsTableModel boardsTableModel;
private MFAttachedFilesTableModel filesTableModel;
private JSplitPane messageSplitPane = null;
private JSplitPane attachmentsSplitPane = null;
private JScrollPane filesTableScrollPane;
private JScrollPane boardsTableScrollPane;
private JSkinnablePopupMenu attFilesPopupMenu;
private JSkinnablePopupMenu attBoardsPopupMenu;
private MessageBodyPopupMenu messageBodyPopupMenu;
private final JButton Bsend = new JButton(new ImageIcon(this.getClass().getResource("/data/send.gif")));
private final JButton Bcancel = new JButton(new ImageIcon(this.getClass().getResource("/data/remove.gif")));
private final JButton BattachFile = new JButton(new ImageIcon(this.getClass().getResource("/data/attachment.gif")));
private final JButton BattachBoard = new JButton(new ImageIcon(MainFrame.class.getResource("/data/attachmentBoard.gif")));
private final JCheckBox sign = new JCheckBox();
private final JCheckBox encrypt = new JCheckBox();
private JComboBox buddies;
private final JLabel Lboard = new JLabel();
private final JLabel Lfrom = new JLabel();
private final JLabel Lsubject = new JLabel();
private final JTextField TFboard = new JTextField(); // Board (To)
private final JTextField subjectTextField = new JTextField(); // Subject
private final JButton BchooseSmiley = new JButton(new ImageIcon(MainFrame.class.getResource("/data/togglesmileys.gif")));
private final AntialiasedTextArea messageTextArea = new AntialiasedTextArea(); // Text
private ImmutableArea headerArea = null;
// private TextHighlighter textHighlighter = null;
private String oldSender = null;
private String currentSignature = null;
private FrostMessageObject repliedMessage = null;
private JComboBox ownIdentitiesComboBox = null;
private static int openInstanceCount = 0;
public MessageFrame(final SettingsClass newSettings, final Window tparentWindow) {
super();
parentWindow = tparentWindow;
this.language = Language.getInstance();
frostSettings = newSettings;
incOpenInstanceCount();
final String fontName = frostSettings.getValue(SettingsClass.MESSAGE_BODY_FONT_NAME);
final int fontStyle = frostSettings.getIntValue(SettingsClass.MESSAGE_BODY_FONT_STYLE);
final int fontSize = frostSettings.getIntValue(SettingsClass.MESSAGE_BODY_FONT_SIZE);
Font tofFont = new Font(fontName, fontStyle, fontSize);
if (!tofFont.getFamily().equals(fontName)) {
logger.severe("The selected font was not found in your system\n"
+ "That selection will be changed to \"Monospaced\".");
frostSettings.setValue(SettingsClass.MESSAGE_BODY_FONT_NAME, "Monospaced");
tofFont = new Font("Monospaced", fontStyle, fontSize);
}
messageTextArea.setFont(tofFont);
messageTextArea.setAntiAliasEnabled(frostSettings.getBoolValue(SettingsClass.MESSAGE_BODY_ANTIALIAS));
final ImmutableAreasDocument messageDocument = new ImmutableAreasDocument();
headerArea = new ImmutableArea(messageDocument);
messageDocument.addImmutableArea(headerArea); // user must not change the header of the message
messageTextArea.setDocument(messageDocument);
// textHighlighter = new TextHighlighter(Color.LIGHT_GRAY);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
windowIsClosing(e);
}
@Override
public void windowClosed(final WindowEvent e) {
windowWasClosed(e);
}
});
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
private void windowIsClosing(final WindowEvent e) {
final String title = language.getString("MessageFrame.discardMessage.title");
final String text = language.getString("MessageFrame.discardMessage.text");
final int answer = JOptionPane.showConfirmDialog(
this,
text,
title,
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if( answer == JOptionPane.YES_OPTION ) {
dispose();
}
}
private void windowWasClosed(final WindowEvent e) {
decOpenInstanceCount();
}
private void attachBoards_actionPerformed(final ActionEvent e) {
// get and sort all boards
final List allBoards = MainFrame.getInstance().getTofTreeModel().getAllBoards();
if (allBoards.size() == 0) {
return;
}
Collections.sort(allBoards);
final BoardsChooser chooser = new BoardsChooser(this, allBoards);
chooser.setLocationRelativeTo(this);
final List chosenBoards = chooser.runDialog();
if (chosenBoards == null || chosenBoards.size() == 0) { // nothing chosed or cancelled
return;
}
for (int i = 0; i < chosenBoards.size(); i++) {
final Board chosedBoard = (Board) chosenBoards.get(i);
String privKey = chosedBoard.getPrivateKey();
if (privKey != null) {
final int answer =
JOptionPane.showConfirmDialog(this,
language.formatMessage("MessageFrame.attachBoard.sendPrivateKeyConfirmationDialog.body", chosedBoard.getName()),
language.getString("MessageFrame.attachBoard.sendPrivateKeyConfirmationDialog.title"),
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.NO_OPTION) {
privKey = null; // don't provide privkey
}
}
// build a new board because maybe privKey shouldn't be uploaded
final Board aNewBoard =
new Board(chosedBoard.getName(), chosedBoard.getPublicKey(), privKey, chosedBoard.getDescription());
final MFAttachedBoard ab = new MFAttachedBoard(aNewBoard);
boardsTableModel.addRow(ab);
}
positionDividers();
}
private void attachFile_actionPerformed(final ActionEvent e) {
final String lastUsedDirectory = frostSettings.getValue(SettingsClass.DIR_LAST_USED);
final JFileChooser fc = new JFileChooser(lastUsedDirectory);
fc.setDialogTitle(language.getString("MessageFrame.fileChooser.title"));
fc.setFileHidingEnabled(false);
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.setMultiSelectionEnabled(true);
final int returnVal = fc.showOpenDialog(MessageFrame.this);
if( returnVal == JFileChooser.APPROVE_OPTION ) {
final File[] selectedFiles = fc.getSelectedFiles();
for( final File element : selectedFiles ) {
// for convinience remember last used directory
frostSettings.setValue(SettingsClass.DIR_LAST_USED, element.getPath());
// collect all choosed files + files in all choosed directories
final ArrayList allFiles = FileAccess.getAllEntries(element, "");
for (int j = 0; j < allFiles.size(); j++) {
final File aFile = (File)allFiles.get(j);
if (aFile.isFile() && aFile.length() > 0) {
final MFAttachedFile af = new MFAttachedFile( aFile );
filesTableModel.addRow( af );
}
}
}
}
positionDividers();
}
private void cancel_actionPerformed(final ActionEvent e) {
dispose();
}
/**
* Finally called to start composing a message. Uses alternate editor if configured.
*/
private void composeMessage(
final Board newBoard,
final String newSubject,
final String inReplyTo,
String newText,
final boolean isReply,
final Identity recipient,
final LocalIdentity senderId, // if given compose encrypted reply
final FrostMessageObject msg) {
repliedMessage = msg;
if (isReply) {
newText += "\n\n";
}
if (frostSettings.getBoolValue("useAltEdit")) {
// build our transfer object that the parser will provide us in its callback
final TransferObject to = new TransferObject();
to.newBoard = newBoard;
to.newSubject = newSubject;
to.inReplyTo = inReplyTo;
to.newText = newText;
to.isReply = isReply;
to.recipient = recipient;
to.senderId = senderId;
// create a temporary editText that is show in alternate editor
// the editor will return only new text to us
final DateTime now = new DateTime(DateTimeZone.UTC);
final String date = DateFun.FORMAT_DATE_EXT.print(now)
+ " - "
+ DateFun.FORMAT_TIME_EXT.print(now);
final String fromLine = "----- (sender) ----- " + date + " -----";
final String editText = newText + fromLine + "\n\n";
final AltEdit ae = new AltEdit(newSubject, editText, MainFrame.getInstance(), to, this);
ae.start();
} else {
// invoke frame directly, no alternate editor
composeMessageContinued(newBoard, newSubject, inReplyTo, newText, null, isReply, recipient, senderId);
}
}
public void altEditCallback(final Object toObj, String newAltSubject, final String newAltText) {
final TransferObject to = (TransferObject)toObj;
if( newAltSubject == null ) {
newAltSubject = to.newSubject; // use original subject
}
composeMessageContinued(
to.newBoard,
newAltSubject,
to.inReplyTo,
to.newText,
newAltText,
to.isReply,
to.recipient,
to.senderId);
}
/**
* This method is either invoked by ComposeMessage OR by the callback of the AltEdit class.
*/
private void composeMessageContinued(
final Board newBoard,
final String newSubject,
final String inReplyTo,
String newText,
final String altEditText,
final boolean isReply,
final Identity recipient, // if given compose encrypted reply
final LocalIdentity senderId) // if given compose encrypted reply
{
headerArea.setEnabled(false);
board = newBoard;
repliedMsgId = inReplyTo; // maybe null
String from;
boolean isInitializedSigned;
if( senderId != null ) {
// encrypted reply!
from = senderId.getUniqueName();
isInitializedSigned = true;
} else {
// use remembered sender name, maybe per board
String userName = Core.frostSettings.getValue("userName."+board.getBoardFilename());
if( userName == null || userName.length() == 0 ) {
userName = Core.frostSettings.getValue(SettingsClass.LAST_USED_FROMNAME);
}
if( Core.getIdentities().isMySelf(userName) ) {
// isSigned
from = userName;
isInitializedSigned = true;
} else if( userName.indexOf("@") > 0 ) {
// invalid, only LocalIdentities are allowed to contain an @
from = "Anonymous";
isInitializedSigned = false;
} else {
from = userName;
isInitializedSigned = false;
}
}
oldSender = from;
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
initialize(newBoard, newSubject);
} catch (final Exception e) {
logger.log(Level.SEVERE, "Exception thrown in composeMessage(...)", e);
}
sign.setEnabled(false);
final ImageIcon signedIcon = new ImageIcon(this.getClass().getResource("/data/signed.gif"));
final ImageIcon unsignedIcon = new ImageIcon(this.getClass().getResource("/data/unsigned.gif"));
sign.setDisabledSelectedIcon(signedIcon);
sign.setDisabledIcon(unsignedIcon);
sign.setSelectedIcon(signedIcon);
sign.setIcon(unsignedIcon);
sign.addItemListener(new ItemListener() {
public void itemStateChanged(final ItemEvent e) {
updateSignToolTip();
}
});
// maybe prepare to reply to an encrypted message
if( recipient != null ) {
// set correct sender identity
for(int x=0; x < getOwnIdentitiesComboBox().getItemCount(); x++) {
final Object obj = getOwnIdentitiesComboBox().getItemAt(x);
if( obj instanceof LocalIdentity ) {
final LocalIdentity li = (LocalIdentity)obj;
if( senderId.getUniqueName().equals(li.getUniqueName()) ) {
getOwnIdentitiesComboBox().setSelectedIndex(x);
break;
}
}
}
getOwnIdentitiesComboBox().setEnabled(false);
// set and lock controls (after we set the identity, the itemlistener would reset the controls!)
sign.setSelected(true);
encrypt.setSelected(true);
buddies.removeAllItems();
buddies.addItem(recipient);
buddies.setSelectedItem(recipient);
// dont allow to disable signing/encryption
encrypt.setEnabled(false);
buddies.setEnabled(false);
} else {
if( isInitializedSigned ) {
// set saved sender identity
for(int x=0; x < getOwnIdentitiesComboBox().getItemCount(); x++) {
final Object obj = getOwnIdentitiesComboBox().getItemAt(x);
if( obj instanceof LocalIdentity ) {
final LocalIdentity li = (LocalIdentity)obj;
if( from.equals(li.getUniqueName()) ) {
getOwnIdentitiesComboBox().setSelectedIndex(x);
sign.setSelected(true);
getOwnIdentitiesComboBox().setEditable(false);
break;
}
}
}
} else {
// initialized unsigned/anonymous
getOwnIdentitiesComboBox().setSelectedIndex(0);
getOwnIdentitiesComboBox().getEditor().setItem(from);
sign.setSelected(false);
getOwnIdentitiesComboBox().setEditable(true);
}
if( sign.isSelected() && buddies.getItemCount() > 0 ) {
encrypt.setEnabled(true);
} else {
encrypt.setEnabled(false);
}
encrypt.setSelected(false);
buddies.setEnabled(false);
}
updateSignToolTip();
// prepare message text
final DateTime now = new DateTime(DateTimeZone.UTC);
final String date = DateFun.FORMAT_DATE_EXT.print(now)
+ " - "
+ DateFun.FORMAT_TIME_EXT.print(now);
final String fromLine = "----- " + from + " ----- " + date + " -----";
final int headerAreaStart = newText.length();// begin of non-modifiable area
newText += fromLine + "\n\n";
final int headerAreaEnd = newText.length() - 2; // end of non-modifiable area
if( altEditText != null ) {
newText += altEditText; // maybe append text entered in alternate editor
}
// later set cursor to this position in text
final int caretPos = newText.length();
// set sig if msg is marked as signed
currentSignature = null;
if( sign.isSelected() ) {
// maybe append a signature
final LocalIdentity li = (LocalIdentity)getOwnIdentitiesComboBox().getSelectedItem();
if( li.getSignature() != null ) {
currentSignature = "\n-- \n" + li.getSignature();
newText += currentSignature;
}
}
messageTextArea.setText(newText);
headerArea.setStartPos(headerAreaStart);
headerArea.setEndPos(headerAreaEnd);
headerArea.setEnabled(true);
// textHighlighter.highlight(messageTextArea, headerAreaStart, headerAreaEnd-headerAreaStart, true);
setVisible(true);
// reset the splitpanes
positionDividers();
// Properly positions the caret (AKA cursor)
messageTextArea.requestFocusInWindow();
messageTextArea.getCaret().setDot(caretPos);
messageTextArea.getCaret().setVisible(true);
}
public void composeNewMessage(final Board newBoard, final String newSubject, final String newText) {
composeMessage(newBoard, newSubject, null, newText, false, null, null, null);
}
public void composeReply(
final Board newBoard,
final String newSubject,
final String inReplyTo,
final String newText,
final FrostMessageObject msg) {
composeMessage(newBoard, newSubject, inReplyTo, newText, true, null, null, msg);
}
public void composeEncryptedReply(
final Board newBoard,
final String newSubject,
final String inReplyTo,
final String newText,
final Identity recipient,
final LocalIdentity senderId,
final FrostMessageObject msg) {
composeMessage(newBoard, newSubject, inReplyTo, newText, true, recipient, senderId, msg);
}
@Override
public void dispose() {
if (initialized) {
language.removeLanguageListener(listener);
initialized = false;
}
super.dispose();
}
private MessageBodyPopupMenu getMessageBodyPopupMenu() {
if (messageBodyPopupMenu == null) {
messageBodyPopupMenu = new MessageBodyPopupMenu(messageTextArea);
}
return messageBodyPopupMenu;
}
private void initialize(final Board targetBoard, final String subject) throws Exception {
if (!initialized) {
refreshLanguage();
language.addLanguageListener(listener);
final ImageIcon frameIcon = new ImageIcon(getClass().getResource("/data/newmessage.gif"));
setIconImage(frameIcon.getImage());
setResizable(true);
boardsTableModel = new MFAttachedBoardsTableModel();
boardsTable = new MFAttachedBoardsTable(boardsTableModel);
boardsTableScrollPane = new JScrollPane(boardsTable);
boardsTableScrollPane.setWheelScrollingEnabled(true);
boardsTable.addMouseListener(listener);
filesTableModel = new MFAttachedFilesTableModel();
filesTable = new MFAttachedFilesTable(filesTableModel);
filesTableScrollPane = new JScrollPane(filesTable);
filesTableScrollPane.setWheelScrollingEnabled(true);
filesTable.addMouseListener(listener);
// FIXME: option to show own identities in list, or to hide them
final List<Identity> budList = Core.getIdentities().getAllGOODIdentities();
Identity id = null;
if( repliedMessage != null ) {
id = repliedMessage.getFromIdentity();
}
if( budList.size() > 0 || id != null ) {
Collections.sort( budList, new BuddyComparator() );
if( id != null ) {
if( id.isGOOD() == true ) {
budList.remove(id); // remove before put to top of list
}
// add id to top of list in case the user enables 'encrypt'
budList.add(0, id);
}
buddies = new JComboBox(new Vector<Identity>(budList));
buddies.setSelectedItem(budList.get(0));
} else {
buddies = new JComboBox();
}
buddies.setMaximumSize(new Dimension(300, 25)); // dirty fix for overlength combobox on linux
final MiscToolkit toolkit = MiscToolkit.getInstance();
toolkit.configureButton(
Bsend,
"MessageFrame.toolbar.tooltip.sendMessage",
"/data/send_rollover.gif",
language);
toolkit.configureButton(
Bcancel,
"Common.cancel",
"/data/remove_rollover.gif",
language);
toolkit.configureButton(
BattachFile,
"MessageFrame.toolbar.tooltip.addFileAttachments",
"/data/attachment_rollover.gif",
language);
toolkit.configureButton(
BattachBoard,
"MessageFrame.toolbar.tooltip.addBoardAttachments",
"/data/attachmentBoard_rollover.gif",
language);
toolkit.configureButton(
BchooseSmiley,
"MessageFrame.toolbar.tooltip.chooseSmiley",
"/data/togglesmileys.gif",
language);
+ BchooseSmiley.setFocusable(false);
TFboard.setEditable(false);
TFboard.setText(targetBoard.getName());
new TextComponentClipboardMenu(TFboard, language);
new TextComponentClipboardMenu((TextComboBoxEditor)getOwnIdentitiesComboBox().getEditor(), language);
new TextComponentClipboardMenu(subjectTextField, language);
subjectTextField.setText(subject);
messageTextArea.setLineWrap(true);
messageTextArea.setWrapStyleWord(true);
messageTextArea.addMouseListener(listener);
sign.setOpaque(false);
encrypt.setOpaque(false);
//------------------------------------------------------------------------
// Actionlistener
//------------------------------------------------------------------------
Bsend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
send_actionPerformed(e);
}
});
Bcancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
cancel_actionPerformed(e);
}
});
BattachFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
attachFile_actionPerformed(e);
}
});
BattachBoard.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
attachBoards_actionPerformed(e);
}
});
encrypt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
encrypt_actionPerformed(e);
}
});
BchooseSmiley.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
chooseSmiley_actionPerformed(e);
}
});
//------------------------------------------------------------------------
// Append objects
//------------------------------------------------------------------------
final JPanel panelMain = new JPanel(new BorderLayout()); // Main Panel
final JPanel panelHeader = new JPanel(new BorderLayout()); // header (toolbar and textfields)
final JPanel panelTextfields = new JPanel(new GridBagLayout());
final JToolBar panelToolbar = new JToolBar(); // toolbar
panelToolbar.setRollover(true);
panelToolbar.setFloatable(false);
final JScrollPane bodyScrollPane = new JScrollPane(messageTextArea); // Textscrollpane
bodyScrollPane.setWheelScrollingEnabled(true);
bodyScrollPane.setMinimumSize(new Dimension(100, 50));
// FIXME: add a smiley chooser right beside the subject textfield!
// text fields
final GridBagConstraints constraints = new GridBagConstraints();
final Insets insets = new Insets(0, 3, 0, 3);
final Insets insets0 = new Insets(0, 0, 0, 0);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.WEST;
constraints.weighty = 0.0;
constraints.weightx = 0.0;
constraints.insets = insets;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(Lboard, constraints);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = 2;
constraints.insets = insets0;
constraints.weightx = 1.0;
panelTextfields.add(TFboard, constraints);
constraints.gridx = 0;
constraints.gridy++;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(Lfrom, constraints);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = 2;
constraints.insets = insets0;
constraints.weightx = 1.0;
panelTextfields.add(getOwnIdentitiesComboBox(), constraints);
constraints.gridx = 0;
constraints.gridy++;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(Lsubject, constraints);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = 1;
constraints.insets = insets0;
constraints.weightx = 1.0;
panelTextfields.add(subjectTextField, constraints);
constraints.gridx = 2;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(BchooseSmiley, constraints);
// toolbar
panelToolbar.add(Bsend);
panelToolbar.add(Bcancel);
panelToolbar.addSeparator();
panelToolbar.add(BattachFile);
panelToolbar.add(BattachBoard);
panelToolbar.addSeparator();
panelToolbar.add(sign);
panelToolbar.addSeparator();
panelToolbar.add(encrypt);
panelToolbar.add(buddies);
// panelButtons.add(addAttachedFilesToUploadTable);
final ScrollableBar panelButtonsScrollable = new ScrollableBar(panelToolbar);
panelHeader.add(panelButtonsScrollable, BorderLayout.PAGE_START);
// panelToolbar.add(panelButtons, BorderLayout.PAGE_START);
panelHeader.add(panelTextfields, BorderLayout.CENTER);
//Put everything together
attachmentsSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, filesTableScrollPane,
boardsTableScrollPane);
attachmentsSplitPane.setResizeWeight(0.5);
attachmentsSplitPane.setDividerSize(3);
attachmentsSplitPane.setDividerLocation(0.5);
messageSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, bodyScrollPane,
attachmentsSplitPane);
messageSplitPane.setDividerSize(0);
messageSplitPane.setDividerLocation(1.0);
messageSplitPane.setResizeWeight(1.0);
panelMain.add(panelHeader, BorderLayout.NORTH);
panelMain.add(messageSplitPane, BorderLayout.CENTER);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(panelMain, BorderLayout.CENTER);
initPopupMenu();
pack();
// window is now packed to needed size. Check if packed width is smaller than
// 75% of the parent frame and use the larger size.
// pack is needed to ensure that all dialog elements are shown (was problem on linux).
int width = getWidth();
if( width < (int)(parentWindow.getWidth() * 0.75) ) {
width = (int)(parentWindow.getWidth() * 0.75);
}
setSize( width, (int)(parentWindow.getHeight() * 0.75) ); // always set height to 75% of parent
setLocationRelativeTo(parentWindow);
initialized = true;
}
}
protected void initPopupMenu() {
attFilesPopupMenu = new JSkinnablePopupMenu();
attBoardsPopupMenu = new JSkinnablePopupMenu();
final JMenuItem removeFiles = new JMenuItem(language.getString("MessageFrame.attachmentTables.popupmenu.remove"));
final JMenuItem removeBoards = new JMenuItem(language.getString("MessageFrame.attachmentTables.popupmenu.remove"));
removeFiles.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
removeSelectedItemsFromTable(filesTable);
}
});
removeBoards.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
removeSelectedItemsFromTable(boardsTable);
}
});
attFilesPopupMenu.add( removeFiles );
attBoardsPopupMenu.add( removeBoards );
}
private void positionDividers() {
final int attachedFiles = filesTableModel.getRowCount();
final int attachedBoards = boardsTableModel.getRowCount();
if (attachedFiles == 0 && attachedBoards == 0) {
// Neither files nor boards
messageSplitPane.setBottomComponent(null);
messageSplitPane.setDividerSize(0);
return;
}
messageSplitPane.setDividerSize(3);
messageSplitPane.setDividerLocation(0.75);
if (attachedFiles != 0 && attachedBoards == 0) {
//Only files
messageSplitPane.setBottomComponent(filesTableScrollPane);
return;
}
if (attachedFiles == 0 && attachedBoards != 0) {
//Only boards
messageSplitPane.setBottomComponent(boardsTableScrollPane);
return;
}
if (attachedFiles != 0 && attachedBoards != 0) {
//Both files and boards
messageSplitPane.setBottomComponent(attachmentsSplitPane);
attachmentsSplitPane.setTopComponent(filesTableScrollPane);
attachmentsSplitPane.setBottomComponent(boardsTableScrollPane);
}
}
private void refreshLanguage() {
setTitle(language.getString("MessageFrame.createMessage.title"));
Bsend.setToolTipText(language.getString("MessageFrame.toolbar.tooltip.sendMessage"));
Bcancel.setToolTipText(language.getString("Common.cancel"));
BattachFile.setToolTipText(language.getString("MessageFrame.toolbar.tooltip.addFileAttachments"));
BattachBoard.setToolTipText(language.getString("MessageFrame.toolbar.tooltip.addBoardAttachments"));
encrypt.setText(language.getString("MessageFrame.toolbar.encryptFor"));
Lboard.setText(language.getString("MessageFrame.board") + ": ");
Lfrom.setText(language.getString("MessageFrame.from") + ": ");
Lsubject.setText(language.getString("MessageFrame.subject") + ": ");
updateSignToolTip();
}
private void updateSignToolTip() {
final boolean isSelected = sign.isSelected();
if( isSelected ) {
sign.setToolTipText(language.getString("MessagePane.toolbar.tooltip.isSigned"));
} else {
sign.setToolTipText(language.getString("MessagePane.toolbar.tooltip.isUnsigned"));
}
}
protected void removeSelectedItemsFromTable( final JTable tbl ) {
final SortedTableModel m = (SortedTableModel)tbl.getModel();
final int[] sel = tbl.getSelectedRows();
for(int x=sel.length-1; x>=0; x--)
{
m.removeRow(sel[x]);
}
positionDividers();
}
private void chooseSmiley_actionPerformed(final ActionEvent e) {
final SmileyChooserDialog dlg = new SmileyChooserDialog(this);
final int x = this.getX() + BchooseSmiley.getX();
final int y = this.getY() + BchooseSmiley.getY();
String chosedSmileyText = dlg.startDialog(x, y);
if( chosedSmileyText != null && chosedSmileyText.length() > 0 ) {
chosedSmileyText += " ";
// paste into document
try {
final Caret caret = messageTextArea.getCaret();
final int p0 = Math.min(caret.getDot(), caret.getMark());
final int p1 = Math.max(caret.getDot(), caret.getMark());
final Document document = messageTextArea.getDocument();
// FIXME: maybe check for a blank before insert of smiley text???
if (document instanceof PlainDocument) {
((PlainDocument) document).replace(p0, p1 - p0, chosedSmileyText, null);
} else {
if (p0 != p1) {
document.remove(p0, p1 - p0);
}
document.insertString(p0, chosedSmileyText, null);
}
} catch (final Throwable ble) {
logger.log(Level.SEVERE, "Problem while pasting text.", ble);
}
}
// finally set focus back to message window
messageTextArea.requestFocusInWindow();
}
private void send_actionPerformed(final ActionEvent e) {
LocalIdentity senderId = null;
String from;
if( getOwnIdentitiesComboBox().getSelectedItem() instanceof LocalIdentity ) {
senderId = (LocalIdentity)getOwnIdentitiesComboBox().getSelectedItem();
from = senderId.getUniqueName();
} else {
from = getOwnIdentitiesComboBox().getEditor().getItem().toString();
}
final String subject = subjectTextField.getText().trim();
subjectTextField.setText(subject); // if a pbl occurs show the subject we checked
final String text = messageTextArea.getText().trim();
if( subject.equals("No subject") ) {
final int n = JOptionPane.showConfirmDialog( this,
language.getString("MessageFrame.defaultSubjectWarning.text"),
language.getString("MessageFrame.defaultSubjectWarning.title"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if( n == JOptionPane.YES_OPTION ) {
return;
}
}
if( subject.length() == 0) {
JOptionPane.showMessageDialog( this,
language.getString("MessageFrame.noSubjectError.text"),
language.getString("MessageFrame.noSubjectError.title"),
JOptionPane.ERROR);
return;
}
if( from.length() == 0) {
JOptionPane.showMessageDialog( this,
language.getString("MessageFrame.noSenderError.text"),
language.getString("MessageFrame.noSenderError.title"),
JOptionPane.ERROR);
return;
}
final int maxTextLength = (60*1024);
final int msgSize = text.length() + subject.length() + from.length() + ((repliedMsgId!=null)?repliedMsgId.length():0);
if( msgSize > maxTextLength ) {
JOptionPane.showMessageDialog( this,
language.formatMessage("MessageFrame.textTooLargeError.text",
Integer.toString(text.length()),
Integer.toString(maxTextLength)),
language.getString("MessageFrame.textTooLargeError.title"),
JOptionPane.ERROR_MESSAGE);
return;
}
final int idLinePos = headerArea.getStartPos();
final int idLineLen = headerArea.getEndPos() - headerArea.getStartPos();
if( text.length() == headerArea.getEndPos() ) {
JOptionPane.showMessageDialog( this,
language.getString("MessageFrame.noContentError.text"),
language.getString("MessageFrame.noContentError.title"),
JOptionPane.ERROR_MESSAGE);
return;
}
// for convinience set last used user
if( from.indexOf("@") < 0 ) {
// only save anonymous usernames
frostSettings.setValue(SettingsClass.LAST_USED_FROMNAME, from);
}
frostSettings.setValue("userName."+board.getBoardFilename(), from);
final FrostUnsentMessageObject newMessage = new FrostUnsentMessageObject();
newMessage.setMessageId(Mixed.createUniqueId()); // new message, create a new unique msg id
newMessage.setInReplyTo(repliedMsgId);
newMessage.setBoard(board);
newMessage.setFromName(from);
newMessage.setSubject(subject);
newMessage.setContent(text);
newMessage.setIdLinePos(idLinePos);
newMessage.setIdLineLen(idLineLen);
// MessageUploadThread will set date + time !
// attach all files and boards the user chosed
if( filesTableModel.getRowCount() > 0 ) {
for(int x=0; x < filesTableModel.getRowCount(); x++) {
final MFAttachedFile af = (MFAttachedFile)filesTableModel.getRow(x);
final File aChosedFile = af.getFile();
final FileAttachment fa = new FileAttachment(aChosedFile);
newMessage.addAttachment(fa);
}
newMessage.setHasFileAttachments(true);
}
if( boardsTableModel.getRowCount() > 0 ) {
for(int x=0; x < boardsTableModel.getRowCount(); x++) {
final MFAttachedBoard ab = (MFAttachedBoard)boardsTableModel.getRow(x);
final Board aChosedBoard = ab.getBoardObject();
final BoardAttachment ba = new BoardAttachment(aChosedBoard);
newMessage.addAttachment(ba);
}
newMessage.setHasBoardAttachments(true);
}
Identity recipient = null;
if( encrypt.isSelected() ) {
recipient = (Identity)buddies.getSelectedItem();
if( recipient == null ) {
JOptionPane.showMessageDialog( this,
language.getString("MessageFrame.encryptErrorNoRecipient.body"),
language.getString("MessageFrame.encryptErrorNoRecipient.title"),
JOptionPane.ERROR);
return;
}
newMessage.setRecipientName(recipient.getUniqueName());
}
UnsentMessagesManager.addNewUnsentMessage(newMessage);
// // zip the xml file and check for maximum size
// File tmpFile = FileAccess.createTempFile("msgframe_", "_tmp");
// tmpFile.deleteOnExit();
// if( mo.saveToFile(tmpFile) == true ) {
// File zipFile = new File(tmpFile.getPath() + ".zipped");
// zipFile.delete(); // just in case it already exists
// zipFile.deleteOnExit(); // so that it is deleted when Frost exits
// FileAccess.writeZipFile(FileAccess.readByteArray(tmpFile), "entry", zipFile);
// long zipLen = zipFile.length();
// tmpFile.delete();
// zipFile.delete();
// if( zipLen > 30000 ) { // 30000 because data+metadata must be smaller than 32k
// JOptionPane.showMessageDialog( this,
// "The zipped message is too large ("+zipLen+" bytes, "+30000+" allowed)! Remove some text.",
// "Message text too large!",
// JOptionPane.ERROR_MESSAGE);
// return;
// }
// } else {
// JOptionPane.showMessageDialog( this,
// "Error verifying the resulting message size.",
// "Error",
// JOptionPane.ERROR_MESSAGE);
// return;
// }
// TODO: if user deletes the unsent msg then the replied state keeps (see below)
// We would have to set the replied state after the msg was successfully sent, because
// we can't remove the state later, maybe the msg was replied twice and we would remove
// the replied state from first reply...
// set isReplied to replied message
if( repliedMessage != null ) {
if( repliedMessage.isReplied() == false ) {
repliedMessage.setReplied(true);
final FrostMessageObject saveMsg = repliedMessage;
final Thread saver = new Thread() {
@Override
public void run() {
// save the changed isreplied state into the database
MessageStorage.inst().updateMessage(saveMsg);
}
};
saver.start();
}
}
setVisible(false);
dispose();
}
private void senderChanged(final LocalIdentity selectedId) {
boolean isSigned;
if( selectedId == null ) {
isSigned = false;
} else {
isSigned = true;
}
sign.setSelected(isSigned);
if (isSigned) {
if( buddies.getItemCount() > 0 ) {
encrypt.setEnabled(true);
if( encrypt.isSelected() ) {
buddies.setEnabled(true);
} else {
buddies.setEnabled(false);
}
}
removeSignatureFromText(currentSignature); // remove signature if existing
currentSignature = addSignatureToText(selectedId.getSignature()); // add new signature if not existing
} else {
encrypt.setSelected(false);
encrypt.setEnabled(false);
buddies.setEnabled(false);
removeSignatureFromText(currentSignature); // remove signature if existing
currentSignature = null;
}
}
private String addSignatureToText(final String sig) {
if( sig == null ) {
return null;
}
final String newSig = "\n-- \n" + sig;
if (!messageTextArea.getText().endsWith(newSig)) {
try {
messageTextArea.getDocument().insertString(messageTextArea.getText().length(), newSig, null);
} catch (final BadLocationException e1) {
logger.log(Level.SEVERE, "Error while updating the signature ", e1);
}
}
return newSig;
}
private void removeSignatureFromText(final String sig) {
if( sig == null ) {
return;
}
if (messageTextArea.getText().endsWith(sig)) {
try {
messageTextArea.getDocument().remove(messageTextArea.getText().length()-sig.length(), sig.length());
} catch (final BadLocationException e1) {
logger.log(Level.SEVERE, "Error while updating the signature ", e1);
}
}
}
private void encrypt_actionPerformed(final ActionEvent e) {
if( encrypt.isSelected() ) {
buddies.setEnabled(true);
} else {
buddies.setEnabled(false);
}
}
protected void updateHeaderArea(final String sender) {
if( !headerArea.isEnabled() ) {
return; // ignore updates
}
if( sender == null || oldSender == null || oldSender.equals(sender) ) {
return;
}
try {
// TODO: add grey background! highlighter mit headerArea um pos zu finden
headerArea.setEnabled(false);
messageTextArea.getDocument().remove(headerArea.getStartPos() + 6, oldSender.length());
messageTextArea.getDocument().insertString(headerArea.getStartPos() + 6, sender, null);
oldSender = sender;
headerArea.setEnabled(true);
// textHighlighter.highlight(messageTextArea, headerArea.getStartPos(), headerArea.getEndPos()-headerArea.getStartPos(), true);
} catch (final BadLocationException exception) {
logger.log(Level.SEVERE, "Error while updating the message header", exception);
}
// String s= messageTextArea.getText().substring(headerArea.getStartPos(), headerArea.getEndPos());
// System.out.println("DBG: "+headerArea.getStartPos()+" ; "+headerArea.getEndPos()+": '"+s+"'");
// DBG: 0 ; 77: '----- blubb2@xpDZ5ZfXK9wYiHB_hkVGRCwJl54 ----- 2006.10.13 - 18:20:12GMT -----'
// DBG: 39 ; 119: '----- wegdami t@plewLcBTHKmPwpWakJNpUdvWSR8 ----- 2006.10.13 - 18:20:12GMT -----'
}
class TextComboBoxEditor extends JTextField implements ComboBoxEditor {
boolean isSigned;
public TextComboBoxEditor() {
super();
}
public Component getEditorComponent() {
return this;
}
public void setItem(final Object arg0) {
if( arg0 instanceof LocalIdentity ) {
isSigned = true;
} else {
isSigned = false;
}
setText(arg0.toString());
}
public Object getItem() {
return getText();
}
public boolean isSigned() {
return isSigned;
}
}
private JComboBox getOwnIdentitiesComboBox() {
if( ownIdentitiesComboBox == null ) {
ownIdentitiesComboBox = new JComboBox();
ownIdentitiesComboBox.addItem("Anonymous");
// sort own unique names
final TreeMap<String,LocalIdentity> sortedIds = new TreeMap<String,LocalIdentity>();
for( final Object element : Core.getIdentities().getLocalIdentities() ) {
final LocalIdentity li = (LocalIdentity)element;
sortedIds.put(li.getUniqueName(), li);
}
for( final Object element : sortedIds.values() ) {
ownIdentitiesComboBox.addItem(element);
}
final TextComboBoxEditor editor = new TextComboBoxEditor();
editor.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(final DocumentEvent e) {
updateHeaderArea2();
}
public void insertUpdate(final DocumentEvent e) {
updateHeaderArea2();
}
public void removeUpdate(final DocumentEvent e) {
updateHeaderArea2();
}
private void updateHeaderArea2() {
final String sender = getOwnIdentitiesComboBox().getEditor().getItem().toString();
updateHeaderArea(sender);
}
});
final AbstractDocument doc = (AbstractDocument) editor.getDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(final DocumentFilter.FilterBypass fb, final int offset, String string,
final AttributeSet attr) throws BadLocationException
{
if (((TextComboBoxEditor)getOwnIdentitiesComboBox().getEditor()).isSigned() == false ) {
string = string.replaceAll("@","");
}
super.insertString(fb, offset, string, attr);
}
@Override
public void replace(final DocumentFilter.FilterBypass fb, final int offset, final int length, String string,
final AttributeSet attrs) throws BadLocationException
{
if (((TextComboBoxEditor)getOwnIdentitiesComboBox().getEditor()).isSigned() == false ) {
string = string.replaceAll("@","");
}
super.replace(fb, offset, length, string, attrs);
}
});
ownIdentitiesComboBox.setEditor(editor);
ownIdentitiesComboBox.setEditable(true);
// ownIdentitiesComboBox.getEditor().selectAll();
ownIdentitiesComboBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(final java.awt.event.ItemEvent e) {
if( e.getStateChange() == ItemEvent.DESELECTED ) {
return;
}
LocalIdentity selectedId = null;
if( ownIdentitiesComboBox.getSelectedIndex() == 0 ) {
ownIdentitiesComboBox.setEditable(true); // original anonymous
// ownIdentitiesComboBox.getEditor().selectAll();
} else if( ownIdentitiesComboBox.getSelectedIndex() < 0 ) {
ownIdentitiesComboBox.setEditable(true); // own value, anonymous
// ownIdentitiesComboBox.getEditor().selectAll();
} else {
ownIdentitiesComboBox.setEditable(false);
selectedId = (LocalIdentity) ownIdentitiesComboBox.getSelectedItem();
}
final String sender = getOwnIdentitiesComboBox().getSelectedItem().toString();
updateHeaderArea(sender);
senderChanged(selectedId);
}
});
}
return ownIdentitiesComboBox;
}
class BuddyComparator implements Comparator<Identity> {
public int compare(final Identity id1, final Identity id2) {
final String s1 = id1.getUniqueName();
final String s2 = id2.getUniqueName();
return s1.toLowerCase().compareTo( s2.toLowerCase() );
}
}
private class Listener implements MouseListener, LanguageListener {
protected void maybeShowPopup(final MouseEvent e) {
if (e.isPopupTrigger()) {
if (e.getSource() == boardsTable) {
attBoardsPopupMenu.show(boardsTable, e.getX(), e.getY());
}
if (e.getSource() == filesTable) {
attFilesPopupMenu.show(filesTable, e.getX(), e.getY());
}
if (e.getSource() == messageTextArea) {
getMessageBodyPopupMenu().show(messageTextArea, e.getX(), e.getY());
}
}
}
public void mouseClicked(final MouseEvent event) {}
public void mouseEntered(final MouseEvent event) {}
public void mouseExited(final MouseEvent event) {}
public void mousePressed(final MouseEvent event) {
maybeShowPopup(event);
}
public void mouseReleased(final MouseEvent event) {
maybeShowPopup(event);
}
public void languageChanged(final LanguageEvent event) {
refreshLanguage();
}
}
private class MessageBodyPopupMenu
extends JSkinnablePopupMenu
implements ActionListener, ClipboardOwner {
private Clipboard clipboard;
private final JTextComponent sourceTextComponent;
private final JMenuItem cutItem = new JMenuItem();
private final JMenuItem copyItem = new JMenuItem();
private final JMenuItem pasteItem = new JMenuItem();
private final JMenuItem cancelItem = new JMenuItem();
public MessageBodyPopupMenu(final JTextComponent sourceTextComponent) {
super();
this.sourceTextComponent = sourceTextComponent;
initialize();
}
public void actionPerformed(final ActionEvent e) {
if (e.getSource() == cutItem) {
cutSelectedText();
}
if (e.getSource() == copyItem) {
copySelectedText();
}
if (e.getSource() == pasteItem) {
pasteText();
}
}
private void copySelectedText() {
final StringSelection selection = new StringSelection(sourceTextComponent.getSelectedText());
clipboard.setContents(selection, this);
}
private void cutSelectedText() {
final StringSelection selection = new StringSelection(sourceTextComponent.getSelectedText());
clipboard.setContents(selection, this);
final int start = sourceTextComponent.getSelectionStart();
final int end = sourceTextComponent.getSelectionEnd();
try {
sourceTextComponent.getDocument().remove(start, end - start);
} catch (final BadLocationException ble) {
logger.log(Level.SEVERE, "Problem while cutting text.", ble);
}
}
private void pasteText() {
final Transferable clipboardContent = clipboard.getContents(this);
try {
final String text = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor);
final Caret caret = sourceTextComponent.getCaret();
final int p0 = Math.min(caret.getDot(), caret.getMark());
final int p1 = Math.max(caret.getDot(), caret.getMark());
final Document document = sourceTextComponent.getDocument();
if (document instanceof PlainDocument) {
((PlainDocument) document).replace(p0, p1 - p0, text, null);
} else {
if (p0 != p1) {
document.remove(p0, p1 - p0);
}
document.insertString(p0, text, null);
}
} catch (final IOException ioe) {
logger.log(Level.SEVERE, "Problem while pasting text.", ioe);
} catch (final UnsupportedFlavorException ufe) {
logger.log(Level.SEVERE, "Problem while pasting text.", ufe);
} catch (final BadLocationException ble) {
logger.log(Level.SEVERE, "Problem while pasting text.", ble);
}
}
private void initialize() {
refreshLanguage();
final Toolkit toolkit = Toolkit.getDefaultToolkit();
clipboard = toolkit.getSystemClipboard();
cutItem.addActionListener(this);
copyItem.addActionListener(this);
pasteItem.addActionListener(this);
add(cutItem);
add(copyItem);
add(pasteItem);
addSeparator();
add(cancelItem);
}
private void refreshLanguage() {
cutItem.setText(language.getString("Common.cut"));
copyItem.setText(language.getString("Common.copy"));
pasteItem.setText(language.getString("Common.paste"));
cancelItem.setText(language.getString("Common.cancel"));
}
public void lostOwnership(final Clipboard nclipboard, final Transferable contents) {}
@Override
public void show(final Component invoker, final int x, final int y) {
if (sourceTextComponent.getSelectedText() != null) {
cutItem.setEnabled(true);
copyItem.setEnabled(true);
} else {
cutItem.setEnabled(false);
copyItem.setEnabled(false);
}
final Transferable clipboardContent = clipboard.getContents(this);
if ((clipboardContent != null) &&
(clipboardContent.isDataFlavorSupported(DataFlavor.stringFlavor))) {
pasteItem.setEnabled(true);
} else {
pasteItem.setEnabled(false);
}
super.show(invoker, x, y);
}
}
private class MFAttachedBoard implements TableMember {
Board aBoard;
public MFAttachedBoard(final Board ab) {
aBoard = ab;
}
public int compareTo( final TableMember anOther, final int tableColumIndex ) {
final Comparable c1 = (Comparable)getValueAt(tableColumIndex);
final Comparable c2 = (Comparable)anOther.getValueAt(tableColumIndex);
return c1.compareTo( c2 );
}
public Board getBoardObject() {
return aBoard;
}
public Object getValueAt(final int column) {
switch (column) {
case 0 : return aBoard.getName();
case 1 : return (aBoard.getPublicKey() == null) ? "N/A" : aBoard.getPublicKey();
case 2 : return (aBoard.getPrivateKey() == null) ? "N/A" : aBoard.getPrivateKey();
case 3 : return (aBoard.getDescription() == null) ? "N/A" : aBoard.getDescription();
}
return "*ERR*";
}
}
private class MFAttachedBoardsTable extends SortedTable {
public MFAttachedBoardsTable(final MFAttachedBoardsTableModel m) {
super(m);
// set column sizes
final int[] widths = {250, 80, 80};
for (int i = 0; i < widths.length; i++) {
getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
}
// default for sort: sort by name ascending ?
sortedColumnIndex = 0;
sortedColumnAscending = true;
resortTable();
}
}
private class MFAttachedBoardsTableModel extends SortedTableModel {
protected final Class columnClasses[] = {
String.class,
String.class,
String.class,
String.class
};
protected final String columnNames[] = {
language.getString("MessageFrame.boardAttachmentTable.boardname"),
language.getString("MessageFrame.boardAttachmentTable.publicKey"),
language.getString("MessageFrame.boardAttachmentTable.privateKey"),
language.getString("MessageFrame.boardAttachmentTable.description")
};
public MFAttachedBoardsTableModel() {
super();
}
@Override
public Class getColumnClass(final int column) {
if( column >= 0 && column < columnClasses.length ) {
return columnClasses[column];
}
return null;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(final int column) {
if( column >= 0 && column < columnNames.length ) {
return columnNames[column];
}
return null;
}
@Override
public boolean isCellEditable(final int row, final int col) {
return false;
}
@Override
public void setValueAt(final Object aValue, final int row, final int column) {}
}
private class MFAttachedFile implements TableMember {
File aFile;
public MFAttachedFile(final File af) {
aFile = af;
}
public int compareTo( final TableMember anOther, final int tableColumIndex ) {
final Comparable c1 = (Comparable)getValueAt(tableColumIndex);
final Comparable c2 = (Comparable)anOther.getValueAt(tableColumIndex);
return c1.compareTo( c2 );
}
public File getFile() {
return aFile;
}
public Object getValueAt(final int column) {
switch(column) {
case 0: return aFile.getName();
case 1: return Long.toString(aFile.length());
}
return "*ERR*";
}
}
private class MFAttachedFilesTable extends SortedTable {
public MFAttachedFilesTable(final MFAttachedFilesTableModel m) {
super(m);
// set column sizes
final int[] widths = {250, 80};
for (int i = 0; i < widths.length; i++) {
getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
}
// default for sort: sort by name ascending ?
sortedColumnIndex = 0;
sortedColumnAscending = true;
resortTable();
}
}
private class MFAttachedFilesTableModel extends SortedTableModel {
protected final Class columnClasses[] = {
String.class,
String.class
};
protected final String columnNames[] = {
language.getString("MessageFrame.fileAttachmentTable.filename"),
language.getString("MessageFrame.fileAttachmentTable.size")
};
public MFAttachedFilesTableModel() {
super();
}
@Override
public Class getColumnClass(final int column) {
if( column >= 0 && column < columnClasses.length ) {
return columnClasses[column];
}
return null;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(final int column) {
if( column >= 0 && column < columnNames.length ) {
return columnNames[column];
}
return null;
}
@Override
public boolean isCellEditable(final int row, final int col) {
return false;
}
@Override
public void setValueAt(final Object aValue, final int row, final int column) {}
}
private class TransferObject {
public Board newBoard;
public String newSubject;
public String inReplyTo;
public String newText;
public boolean isReply;
public Identity recipient = null;;
public LocalIdentity senderId = null;
}
public static synchronized int getOpenInstanceCount() {
return openInstanceCount;
}
private static synchronized void incOpenInstanceCount() {
openInstanceCount++;
}
private static synchronized void decOpenInstanceCount() {
if( openInstanceCount > 0 ) { // paranoia
openInstanceCount--;
}
}
}
| true | true | private void initialize(final Board targetBoard, final String subject) throws Exception {
if (!initialized) {
refreshLanguage();
language.addLanguageListener(listener);
final ImageIcon frameIcon = new ImageIcon(getClass().getResource("/data/newmessage.gif"));
setIconImage(frameIcon.getImage());
setResizable(true);
boardsTableModel = new MFAttachedBoardsTableModel();
boardsTable = new MFAttachedBoardsTable(boardsTableModel);
boardsTableScrollPane = new JScrollPane(boardsTable);
boardsTableScrollPane.setWheelScrollingEnabled(true);
boardsTable.addMouseListener(listener);
filesTableModel = new MFAttachedFilesTableModel();
filesTable = new MFAttachedFilesTable(filesTableModel);
filesTableScrollPane = new JScrollPane(filesTable);
filesTableScrollPane.setWheelScrollingEnabled(true);
filesTable.addMouseListener(listener);
// FIXME: option to show own identities in list, or to hide them
final List<Identity> budList = Core.getIdentities().getAllGOODIdentities();
Identity id = null;
if( repliedMessage != null ) {
id = repliedMessage.getFromIdentity();
}
if( budList.size() > 0 || id != null ) {
Collections.sort( budList, new BuddyComparator() );
if( id != null ) {
if( id.isGOOD() == true ) {
budList.remove(id); // remove before put to top of list
}
// add id to top of list in case the user enables 'encrypt'
budList.add(0, id);
}
buddies = new JComboBox(new Vector<Identity>(budList));
buddies.setSelectedItem(budList.get(0));
} else {
buddies = new JComboBox();
}
buddies.setMaximumSize(new Dimension(300, 25)); // dirty fix for overlength combobox on linux
final MiscToolkit toolkit = MiscToolkit.getInstance();
toolkit.configureButton(
Bsend,
"MessageFrame.toolbar.tooltip.sendMessage",
"/data/send_rollover.gif",
language);
toolkit.configureButton(
Bcancel,
"Common.cancel",
"/data/remove_rollover.gif",
language);
toolkit.configureButton(
BattachFile,
"MessageFrame.toolbar.tooltip.addFileAttachments",
"/data/attachment_rollover.gif",
language);
toolkit.configureButton(
BattachBoard,
"MessageFrame.toolbar.tooltip.addBoardAttachments",
"/data/attachmentBoard_rollover.gif",
language);
toolkit.configureButton(
BchooseSmiley,
"MessageFrame.toolbar.tooltip.chooseSmiley",
"/data/togglesmileys.gif",
language);
TFboard.setEditable(false);
TFboard.setText(targetBoard.getName());
new TextComponentClipboardMenu(TFboard, language);
new TextComponentClipboardMenu((TextComboBoxEditor)getOwnIdentitiesComboBox().getEditor(), language);
new TextComponentClipboardMenu(subjectTextField, language);
subjectTextField.setText(subject);
messageTextArea.setLineWrap(true);
messageTextArea.setWrapStyleWord(true);
messageTextArea.addMouseListener(listener);
sign.setOpaque(false);
encrypt.setOpaque(false);
//------------------------------------------------------------------------
// Actionlistener
//------------------------------------------------------------------------
Bsend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
send_actionPerformed(e);
}
});
Bcancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
cancel_actionPerformed(e);
}
});
BattachFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
attachFile_actionPerformed(e);
}
});
BattachBoard.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
attachBoards_actionPerformed(e);
}
});
encrypt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
encrypt_actionPerformed(e);
}
});
BchooseSmiley.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
chooseSmiley_actionPerformed(e);
}
});
//------------------------------------------------------------------------
// Append objects
//------------------------------------------------------------------------
final JPanel panelMain = new JPanel(new BorderLayout()); // Main Panel
final JPanel panelHeader = new JPanel(new BorderLayout()); // header (toolbar and textfields)
final JPanel panelTextfields = new JPanel(new GridBagLayout());
final JToolBar panelToolbar = new JToolBar(); // toolbar
panelToolbar.setRollover(true);
panelToolbar.setFloatable(false);
final JScrollPane bodyScrollPane = new JScrollPane(messageTextArea); // Textscrollpane
bodyScrollPane.setWheelScrollingEnabled(true);
bodyScrollPane.setMinimumSize(new Dimension(100, 50));
// FIXME: add a smiley chooser right beside the subject textfield!
// text fields
final GridBagConstraints constraints = new GridBagConstraints();
final Insets insets = new Insets(0, 3, 0, 3);
final Insets insets0 = new Insets(0, 0, 0, 0);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.WEST;
constraints.weighty = 0.0;
constraints.weightx = 0.0;
constraints.insets = insets;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(Lboard, constraints);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = 2;
constraints.insets = insets0;
constraints.weightx = 1.0;
panelTextfields.add(TFboard, constraints);
constraints.gridx = 0;
constraints.gridy++;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(Lfrom, constraints);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = 2;
constraints.insets = insets0;
constraints.weightx = 1.0;
panelTextfields.add(getOwnIdentitiesComboBox(), constraints);
constraints.gridx = 0;
constraints.gridy++;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(Lsubject, constraints);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = 1;
constraints.insets = insets0;
constraints.weightx = 1.0;
panelTextfields.add(subjectTextField, constraints);
constraints.gridx = 2;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(BchooseSmiley, constraints);
// toolbar
panelToolbar.add(Bsend);
panelToolbar.add(Bcancel);
panelToolbar.addSeparator();
panelToolbar.add(BattachFile);
panelToolbar.add(BattachBoard);
panelToolbar.addSeparator();
panelToolbar.add(sign);
panelToolbar.addSeparator();
panelToolbar.add(encrypt);
panelToolbar.add(buddies);
// panelButtons.add(addAttachedFilesToUploadTable);
final ScrollableBar panelButtonsScrollable = new ScrollableBar(panelToolbar);
panelHeader.add(panelButtonsScrollable, BorderLayout.PAGE_START);
// panelToolbar.add(panelButtons, BorderLayout.PAGE_START);
panelHeader.add(panelTextfields, BorderLayout.CENTER);
//Put everything together
attachmentsSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, filesTableScrollPane,
boardsTableScrollPane);
attachmentsSplitPane.setResizeWeight(0.5);
attachmentsSplitPane.setDividerSize(3);
attachmentsSplitPane.setDividerLocation(0.5);
messageSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, bodyScrollPane,
attachmentsSplitPane);
messageSplitPane.setDividerSize(0);
messageSplitPane.setDividerLocation(1.0);
messageSplitPane.setResizeWeight(1.0);
panelMain.add(panelHeader, BorderLayout.NORTH);
panelMain.add(messageSplitPane, BorderLayout.CENTER);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(panelMain, BorderLayout.CENTER);
initPopupMenu();
pack();
// window is now packed to needed size. Check if packed width is smaller than
// 75% of the parent frame and use the larger size.
// pack is needed to ensure that all dialog elements are shown (was problem on linux).
int width = getWidth();
if( width < (int)(parentWindow.getWidth() * 0.75) ) {
width = (int)(parentWindow.getWidth() * 0.75);
}
setSize( width, (int)(parentWindow.getHeight() * 0.75) ); // always set height to 75% of parent
setLocationRelativeTo(parentWindow);
initialized = true;
}
}
| private void initialize(final Board targetBoard, final String subject) throws Exception {
if (!initialized) {
refreshLanguage();
language.addLanguageListener(listener);
final ImageIcon frameIcon = new ImageIcon(getClass().getResource("/data/newmessage.gif"));
setIconImage(frameIcon.getImage());
setResizable(true);
boardsTableModel = new MFAttachedBoardsTableModel();
boardsTable = new MFAttachedBoardsTable(boardsTableModel);
boardsTableScrollPane = new JScrollPane(boardsTable);
boardsTableScrollPane.setWheelScrollingEnabled(true);
boardsTable.addMouseListener(listener);
filesTableModel = new MFAttachedFilesTableModel();
filesTable = new MFAttachedFilesTable(filesTableModel);
filesTableScrollPane = new JScrollPane(filesTable);
filesTableScrollPane.setWheelScrollingEnabled(true);
filesTable.addMouseListener(listener);
// FIXME: option to show own identities in list, or to hide them
final List<Identity> budList = Core.getIdentities().getAllGOODIdentities();
Identity id = null;
if( repliedMessage != null ) {
id = repliedMessage.getFromIdentity();
}
if( budList.size() > 0 || id != null ) {
Collections.sort( budList, new BuddyComparator() );
if( id != null ) {
if( id.isGOOD() == true ) {
budList.remove(id); // remove before put to top of list
}
// add id to top of list in case the user enables 'encrypt'
budList.add(0, id);
}
buddies = new JComboBox(new Vector<Identity>(budList));
buddies.setSelectedItem(budList.get(0));
} else {
buddies = new JComboBox();
}
buddies.setMaximumSize(new Dimension(300, 25)); // dirty fix for overlength combobox on linux
final MiscToolkit toolkit = MiscToolkit.getInstance();
toolkit.configureButton(
Bsend,
"MessageFrame.toolbar.tooltip.sendMessage",
"/data/send_rollover.gif",
language);
toolkit.configureButton(
Bcancel,
"Common.cancel",
"/data/remove_rollover.gif",
language);
toolkit.configureButton(
BattachFile,
"MessageFrame.toolbar.tooltip.addFileAttachments",
"/data/attachment_rollover.gif",
language);
toolkit.configureButton(
BattachBoard,
"MessageFrame.toolbar.tooltip.addBoardAttachments",
"/data/attachmentBoard_rollover.gif",
language);
toolkit.configureButton(
BchooseSmiley,
"MessageFrame.toolbar.tooltip.chooseSmiley",
"/data/togglesmileys.gif",
language);
BchooseSmiley.setFocusable(false);
TFboard.setEditable(false);
TFboard.setText(targetBoard.getName());
new TextComponentClipboardMenu(TFboard, language);
new TextComponentClipboardMenu((TextComboBoxEditor)getOwnIdentitiesComboBox().getEditor(), language);
new TextComponentClipboardMenu(subjectTextField, language);
subjectTextField.setText(subject);
messageTextArea.setLineWrap(true);
messageTextArea.setWrapStyleWord(true);
messageTextArea.addMouseListener(listener);
sign.setOpaque(false);
encrypt.setOpaque(false);
//------------------------------------------------------------------------
// Actionlistener
//------------------------------------------------------------------------
Bsend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
send_actionPerformed(e);
}
});
Bcancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
cancel_actionPerformed(e);
}
});
BattachFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
attachFile_actionPerformed(e);
}
});
BattachBoard.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
attachBoards_actionPerformed(e);
}
});
encrypt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
encrypt_actionPerformed(e);
}
});
BchooseSmiley.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final ActionEvent e) {
chooseSmiley_actionPerformed(e);
}
});
//------------------------------------------------------------------------
// Append objects
//------------------------------------------------------------------------
final JPanel panelMain = new JPanel(new BorderLayout()); // Main Panel
final JPanel panelHeader = new JPanel(new BorderLayout()); // header (toolbar and textfields)
final JPanel panelTextfields = new JPanel(new GridBagLayout());
final JToolBar panelToolbar = new JToolBar(); // toolbar
panelToolbar.setRollover(true);
panelToolbar.setFloatable(false);
final JScrollPane bodyScrollPane = new JScrollPane(messageTextArea); // Textscrollpane
bodyScrollPane.setWheelScrollingEnabled(true);
bodyScrollPane.setMinimumSize(new Dimension(100, 50));
// FIXME: add a smiley chooser right beside the subject textfield!
// text fields
final GridBagConstraints constraints = new GridBagConstraints();
final Insets insets = new Insets(0, 3, 0, 3);
final Insets insets0 = new Insets(0, 0, 0, 0);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.WEST;
constraints.weighty = 0.0;
constraints.weightx = 0.0;
constraints.insets = insets;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(Lboard, constraints);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = 2;
constraints.insets = insets0;
constraints.weightx = 1.0;
panelTextfields.add(TFboard, constraints);
constraints.gridx = 0;
constraints.gridy++;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(Lfrom, constraints);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = 2;
constraints.insets = insets0;
constraints.weightx = 1.0;
panelTextfields.add(getOwnIdentitiesComboBox(), constraints);
constraints.gridx = 0;
constraints.gridy++;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(Lsubject, constraints);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = 1;
constraints.insets = insets0;
constraints.weightx = 1.0;
panelTextfields.add(subjectTextField, constraints);
constraints.gridx = 2;
constraints.fill = GridBagConstraints.NONE;
constraints.gridwidth = 1;
constraints.insets = insets;
constraints.weightx = 0.0;
panelTextfields.add(BchooseSmiley, constraints);
// toolbar
panelToolbar.add(Bsend);
panelToolbar.add(Bcancel);
panelToolbar.addSeparator();
panelToolbar.add(BattachFile);
panelToolbar.add(BattachBoard);
panelToolbar.addSeparator();
panelToolbar.add(sign);
panelToolbar.addSeparator();
panelToolbar.add(encrypt);
panelToolbar.add(buddies);
// panelButtons.add(addAttachedFilesToUploadTable);
final ScrollableBar panelButtonsScrollable = new ScrollableBar(panelToolbar);
panelHeader.add(panelButtonsScrollable, BorderLayout.PAGE_START);
// panelToolbar.add(panelButtons, BorderLayout.PAGE_START);
panelHeader.add(panelTextfields, BorderLayout.CENTER);
//Put everything together
attachmentsSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, filesTableScrollPane,
boardsTableScrollPane);
attachmentsSplitPane.setResizeWeight(0.5);
attachmentsSplitPane.setDividerSize(3);
attachmentsSplitPane.setDividerLocation(0.5);
messageSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, bodyScrollPane,
attachmentsSplitPane);
messageSplitPane.setDividerSize(0);
messageSplitPane.setDividerLocation(1.0);
messageSplitPane.setResizeWeight(1.0);
panelMain.add(panelHeader, BorderLayout.NORTH);
panelMain.add(messageSplitPane, BorderLayout.CENTER);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(panelMain, BorderLayout.CENTER);
initPopupMenu();
pack();
// window is now packed to needed size. Check if packed width is smaller than
// 75% of the parent frame and use the larger size.
// pack is needed to ensure that all dialog elements are shown (was problem on linux).
int width = getWidth();
if( width < (int)(parentWindow.getWidth() * 0.75) ) {
width = (int)(parentWindow.getWidth() * 0.75);
}
setSize( width, (int)(parentWindow.getHeight() * 0.75) ); // always set height to 75% of parent
setLocationRelativeTo(parentWindow);
initialized = true;
}
}
|
diff --git a/src/main/java/org/robovm/maven/plugin/AbstractRoboVMMojo.java b/src/main/java/org/robovm/maven/plugin/AbstractRoboVMMojo.java
index 7ecada8..1571b2d 100644
--- a/src/main/java/org/robovm/maven/plugin/AbstractRoboVMMojo.java
+++ b/src/main/java/org/robovm/maven/plugin/AbstractRoboVMMojo.java
@@ -1,538 +1,539 @@
/*
* Copyright (C) 2013 Trillian AB.
*
* 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.robovm.maven.plugin;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
import org.robovm.compiler.AppCompiler;
import org.robovm.compiler.config.Arch;
import org.robovm.compiler.config.Config;
import org.robovm.compiler.config.Config.TargetType;
import org.robovm.compiler.config.OS;
import org.robovm.compiler.log.Logger;
import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.resolution.ArtifactRequest;
import org.sonatype.aether.resolution.ArtifactResolutionException;
import org.sonatype.aether.resolution.ArtifactResult;
import org.sonatype.aether.util.artifact.DefaultArtifact;
/**
*/
public abstract class AbstractRoboVMMojo extends AbstractMojo {
public static final String ROBO_VM_VERSION = "0.0.3";
/**
* The maven project.
*
* @parameter expression="${project}"
* @required
*/
protected MavenProject project;
/**
* The entry point to Aether, i.e. the component doing all the work.
*
* @component
* @readonly
*/
private RepositorySystem repoSystem;
/**
* The current repository/network configuration of Maven.
*
* @parameter default-value="${repositorySystemSession}"
* @readonly
*/
private RepositorySystemSession repoSession;
/**
* The project's remote repositories to use for the resolution of plugins and their dependencies.
*
* @parameter default-value="${project.remotePluginRepositories}"
* @readonly
*/
private List<RemoteRepository> remoteRepos;
/**
* To look up Archiver/UnArchiver implementations
*
* @component
* @readonly
*/
private ArchiverManager archiverManager;
/**
* Base directory to extract RoboVM native distribution files into. The robovm-dist bundle will be downloaded from
* Maven and extracted into this directory. Note that each release of RoboVM is placed in a separate sub-directory
* with the version number as suffix.
*
* If not set, then the tar file is extracted into the local Maven repository where the tar file is downloaded to.
*
* @parameter
*/
protected File home;
/**
* The directory where LLVM is installed. If this is not set, then the plugin will default to using the local
* repository (i.e. .m2 directory) and LLVM will be downloaded and installed under
* org/robovm/robovm-dist/robovm-dist-{version}/unpack/llvm.
*/
protected File llvmHomeDir;
/**
* @parameter
*/
protected File propertiesFile;
/**
* @parameter
*/
protected File configFile;
/**
* The main class to run when the application is started.
*
* @parameter
* @required
*/
protected String mainClass;
/**
* The iOS SDK version level supported by this app when running on iOS.
*
* @parameter
*/
protected String iosSdkVersion;
/**
* The identity to sign the app as when building an iOS bundle for the app.
*
* @parameter
*/
protected String iosSignIdentity;
/**
* @parameter expression="${project.build.finalName}"
*/
protected String executableName;
/**
* @parameter
*/
protected File iosInfoPList;
/**
* @parameter
*/
protected File iosEntitlementsPList;
/**
* @parameter
*/
protected File iosResourceRulesPList;
/**
* @parameter
*/
protected String[] frameworks;
/**
* @parameter
*/
protected String[] libs;
/**
* @parameter
*/
protected File[] resources;
/**
* Specifies class patterns matching classes that must be linked in when compiling. By default the RoboVM compiler
* will link in all classes that are referenced, directly or indirectly, by the target main class. It will not,
* however, link in classes that are loaded only by reflection (e.g. via e.g. Class.forName()) so these must be
* manually specified by adding a specific 'root' value.
*
* @parameter
*/
protected String[] forceLinkClasses;
/**
* The directory that the RoboVM distributable for the project will be built to.
*
* @parameter expression="${project.build.directory}/robovm"
*/
protected File installDir;
/**
* @parameter
*/
protected boolean includeJFX;
private Logger roboVMLogger;
public Config buildArchive(OS os, Arch arch, TargetType targetType) throws MojoExecutionException, MojoFailureException {
getLog().info("Building RoboVM app for: " + os + " (" + arch + ")");
Config.Builder builder = new Config.Builder();
File robovmSrcDir = new File(project.getBasedir(), "src/main/robovm");
// load config base file if it exists (and properties)
if (propertiesFile != null) {
if (!propertiesFile.exists()) {
throw new MojoExecutionException("Invalid 'propertiesFile' specified for RoboVM compile: " + propertiesFile);
}
try {
getLog().debug("Including properties file in RoboVM compiler config: " + propertiesFile.getAbsolutePath());
builder.addProperties(propertiesFile);
} catch (IOException e) {
throw new MojoExecutionException("Failed to add properties file to RoboVM config: " + propertiesFile);
}
} else {
File file = new File(robovmSrcDir, "Info.plist");
if (file.exists()) {
getLog().debug("Using default properties file: " + file.getAbsolutePath());
builder.iosInfoPList(file);
}
}
if (configFile != null) {
if (!configFile.exists()) {
throw new MojoExecutionException("Invalid 'configFile' specified for RoboVM compile: " + configFile);
}
try {
getLog().debug("Loading config file for RoboVM compiler: " + configFile.getAbsolutePath());
builder.read(configFile);
} catch (Exception e) {
throw new MojoExecutionException("Failed to read RoboVM config file: " + configFile);
}
} else {
File file = new File(robovmSrcDir, "config.xml");
if (file.exists()) {
getLog().debug("Using default config file: " + file.getAbsolutePath());
builder.iosInfoPList(file);
}
}
// override other settings based on POM
File osDir = new File(installDir, os.name());
File archiveDir = new File(new File(osDir, arch.name()), "");
builder.home(new Config.Home(unpackRoboVMDist()))
.logger(getRoboVMLogger())
.mainClass(mainClass)
.executableName(executableName)
.tmpDir(archiveDir)
.targetType(targetType)
.skipInstall(true)
.os(os)
.arch(arch);
if (forceLinkClasses != null) {
for (String pattern : forceLinkClasses) {
getLog().debug("Including class pattern for linking: " + pattern);
builder.addForceLinkClass(pattern);
}
}
if (frameworks != null) {
for (String framework : frameworks) {
getLog().debug("Including framework: " + framework);
builder.addFramework(framework);
}
}
if (libs != null) {
for (String lib : libs) {
getLog().debug("Including lib: " + lib);
builder.addLib(lib);
}
}
if (iosSdkVersion != null) {
getLog().debug("Using explicit iOS SDK version: " + iosSdkVersion);
builder.iosSdkVersion(iosSdkVersion);
}
if (iosSignIdentity != null) {
getLog().debug("Using explicit iOS Signing identity: " + iosSignIdentity);
builder.iosSignIdentity(iosSignIdentity);
}
if (iosInfoPList != null) {
if (!iosInfoPList.exists()) {
throw new MojoExecutionException("Invalid 'iosInfoPList' specified for RoboVM compile: " + iosInfoPList);
}
getLog().debug("Using Info.plist input file: " + iosInfoPList.getAbsolutePath());
builder.iosInfoPList(iosInfoPList);
} else {
File file = new File(robovmSrcDir, "Info.plist");
if (file.exists()) {
getLog().debug("Using default Info.plist input file: " + file.getAbsolutePath());
builder.iosInfoPList(file);
}
}
if (iosEntitlementsPList != null) {
if (!iosEntitlementsPList.exists()) {
throw new MojoExecutionException("Invalid 'iosEntitlementsPList' specified for RoboVM compile: " + iosEntitlementsPList);
}
getLog().debug("Using Entitlements.plist input file: " + iosEntitlementsPList.getAbsolutePath());
builder.iosEntitlementsPList(iosEntitlementsPList);
} else {
File file = new File(robovmSrcDir, "Entitlements.plist");
if (file.exists()) {
getLog().debug("Using default Entitlements.plist input file: " + file.getAbsolutePath());
builder.iosEntitlementsPList(file);
}
}
if (iosResourceRulesPList != null) {
if (!iosResourceRulesPList.exists()) {
throw new MojoExecutionException("Invalid 'iosResourceRulesPList' specified for RoboVM compile: " + iosResourceRulesPList);
}
getLog().debug("Using ResourceRules.plist input file: " + iosResourceRulesPList.getAbsolutePath());
builder.iosResourceRulesPList(iosResourceRulesPList);
} else {
File file = new File(robovmSrcDir, "ResourceRules.plist");
if (file.exists()) {
getLog().debug("Using default ResourceRules.plist input file: " + file.getAbsolutePath());
builder.iosResourceRulesPList(file);
}
}
if (resources != null) {
for (File resource : resources) {
if (!resource.exists()) {
throw new MojoExecutionException("Invalid 'resource' directory specified for RoboVM compile: " + resource);
}
getLog().debug("Including resource directory: " + resource.getAbsolutePath());
builder.addResource(resource);
}
} else {
// check if default resource dir exists
File resource = new File(robovmSrcDir, "resources");
if (resource.exists()) {
getLog().debug("Using default resource directory: " + resource.getAbsolutePath());
builder.addResource(resource);
}
}
builder.clearClasspathEntries();
// add JavaFX if needed
if (includeJFX) {
getLog().info("Including JavaFX Runtime in build");
// add jfxrt.jar to classpath
File jfxJar = resolveJavaFXRuntimeArtifact();
getLog().debug("JavaFX runtime JAR found at: " + jfxJar);
builder.addClasspathEntry(jfxJar);
// include native files as resources
File iosNativesBaseDir = unpackJavaFXNativeIOSArtifact();
- builder.addLib(new File(iosNativesBaseDir, "libdecora-sse-armv7.a").getAbsolutePath());
- builder.addLib(new File(iosNativesBaseDir, "libglass-armv7.a").getAbsolutePath());
- builder.addLib(new File(iosNativesBaseDir, "libjavafx-font-armv7.a").getAbsolutePath());
- builder.addLib(new File(iosNativesBaseDir, "libjavafx-iio-armv7.a").getAbsolutePath());
- builder.addLib(new File(iosNativesBaseDir, "libprism-common-armv7.a").getAbsolutePath());
- builder.addLib(new File(iosNativesBaseDir, "libprism-es2-armv7.a").getAbsolutePath());
- builder.addLib(new File(iosNativesBaseDir, "libprism-sw-armv7.a").getAbsolutePath());
+// builder.addLib(new File(iosNativesBaseDir, "libdecora-sse-" + arch.getClangName() + ".a").getAbsolutePath());
+ builder.addLib(new File(iosNativesBaseDir, "libglass-" + arch.getClangName() + ".a").getAbsolutePath());
+ builder.addLib(new File(iosNativesBaseDir, "libjavafx-font-" + arch.getClangName() + ".a").getAbsolutePath());
+ builder.addLib(new File(iosNativesBaseDir, "libjavafx-iio-" + arch.getClangName() + ".a").getAbsolutePath());
+ builder.addLib(new File(iosNativesBaseDir, "libprism-common-" + arch.getClangName() + ".a").getAbsolutePath());
+ builder.addLib(new File(iosNativesBaseDir, "libprism-es2-" + arch.getClangName() + ".a").getAbsolutePath());
+// builder.addLib(new File(iosNativesBaseDir, "libprism-sw-" + arch.getClangName() + ".a").getAbsolutePath());
// add default 'roots' needed for JFX to work
builder.addForceLinkClass("com.sun.javafx.tk.quantum.QuantumToolkit");
builder.addForceLinkClass("com.sun.prism.es2.ES2Pipeline");
builder.addForceLinkClass("com.sun.prism.es2.IOSGLFactory");
builder.addForceLinkClass("com.sun.glass.ui.ios.**.*");
builder.addForceLinkClass("javafx.scene.CssStyleHelper");
builder.addForceLinkClass("com.sun.prism.shader.**.*");
builder.addForceLinkClass("com.sun.scenario.effect.impl.es2.ES2ShaderSource");
+ builder.addForceLinkClass("com.sun.javafx.font.coretext.CTFactory");
builder.addForceLinkClass("sun.util.logging.PlatformLogger");
// add default 'frameworks' needed for JFX to work
builder.addFramework("UIKit");
builder.addFramework("OpenGLES");
builder.addFramework("QuartzCore");
builder.addFramework("CoreGraphics");
builder.addFramework("CoreText");
builder.addFramework("ImageIO");
builder.addFramework("MobileCoreServices");
// todo do we need to exclude built-in JFX from JDK classpath?
}
// configure the runtime classpath
try {
for (Object object : project.getRuntimeClasspathElements()) {
String path = (String) object;
if (getLog().isDebugEnabled()) {
getLog().debug("Including classpath element for RoboVM app: " + path);
}
builder.addClasspathEntry(new File(path));
}
} catch (DependencyResolutionRequiredException e) {
throw new MojoExecutionException("Error resolving application classpath for RoboVM build", e);
}
// execute the RoboVM build
try {
Config config = builder.build();
AppCompiler compiler = new AppCompiler(config);
compiler.compile();
return config;
} catch (IOException e) {
throw new MojoExecutionException("Error building RoboVM executable for app", e);
}
}
protected File unpackRoboVMDist() throws MojoExecutionException {
File distTarFile = resolveRoboVMDistArtifact();
File unpackBaseDir;
if (home != null) {
unpackBaseDir = home;
} else {
// by default unpack into the local repo directory
unpackBaseDir = new File(distTarFile.getParent(), "unpacked");
}
File unpackedDir = new File(unpackBaseDir, "robovm-" + ROBO_VM_VERSION);
unpack(distTarFile, unpackBaseDir);
return unpackedDir;
}
protected File resolveRoboVMDistArtifact() throws MojoExecutionException {
return resolveArtifact("org.robovm:robovm-dist:tar.gz:nocompiler:" + ROBO_VM_VERSION);
}
protected File resolveJavaFXRuntimeArtifact() throws MojoExecutionException {
return resolveArtifact("net.java.openjfx:jfx-backport:8.7.1");
}
protected File unpackJavaFXNativeIOSArtifact() throws MojoExecutionException {
File jarFile = resolveJavaFXNativeArtifact();
// by default unpack into the local repo directory
File unpackBaseDir = new File(jarFile.getParent(), "unpacked");
unpack(jarFile, unpackBaseDir);
return unpackBaseDir;
}
protected File resolveJavaFXNativeArtifact() throws MojoExecutionException {
return resolveArtifact("net.java.openjfx:jfx-backport-ios-natives:8.7.1");
}
protected File resolveArtifact(String artifactLocator) throws MojoExecutionException {
ArtifactRequest request = new ArtifactRequest();
DefaultArtifact artifact = new DefaultArtifact(artifactLocator);
request.setArtifact(artifact);
request.setRepositories(remoteRepos);
getLog().debug("Resolving artifact " + artifact + " from " + remoteRepos);
ArtifactResult result;
try {
result = repoSystem.resolveArtifact(repoSession, request);
} catch (ArtifactResolutionException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
getLog().debug("Resolved artifact " + artifact + " to " + result.getArtifact().getFile()
+ " from " + result.getRepository());
return result.getArtifact().getFile();
}
protected void unpack(File archive, File targetDirectory) throws MojoExecutionException {
if (!targetDirectory.exists()) {
getLog().info("Extracting '" + archive + "' to: " + targetDirectory);
if (!targetDirectory.mkdirs()) {
throw new MojoExecutionException("Unable to create base directory to unpack into: " + targetDirectory);
}
try {
UnArchiver unArchiver = archiverManager.getUnArchiver(archive);
unArchiver.setSourceFile(archive);
unArchiver.setDestDirectory(targetDirectory);
unArchiver.extract();
} catch (NoSuchArchiverException e) {
throw new MojoExecutionException("Unable to unpack archive " + archive + " to " + targetDirectory, e);
}
getLog().debug("Archive '" + archive + "' unpacked to: " + targetDirectory);
} else {
getLog().debug("Archive '" + archive + "' was already unpacked in: " + targetDirectory);
}
}
protected Logger getRoboVMLogger() {
if (roboVMLogger == null) {
roboVMLogger = new Logger() {
public void debug(String s, Object... objects) {
getLog().debug(String.format(s, objects));
}
public void info(String s, Object... objects) {
getLog().info(String.format(s, objects));
}
public void warn(String s, Object... objects) {
getLog().warn(String.format(s, objects));
}
public void error(String s, Object... objects) {
getLog().error(String.format(s, objects));
}
};
}
return roboVMLogger;
}
}
| false | true | public Config buildArchive(OS os, Arch arch, TargetType targetType) throws MojoExecutionException, MojoFailureException {
getLog().info("Building RoboVM app for: " + os + " (" + arch + ")");
Config.Builder builder = new Config.Builder();
File robovmSrcDir = new File(project.getBasedir(), "src/main/robovm");
// load config base file if it exists (and properties)
if (propertiesFile != null) {
if (!propertiesFile.exists()) {
throw new MojoExecutionException("Invalid 'propertiesFile' specified for RoboVM compile: " + propertiesFile);
}
try {
getLog().debug("Including properties file in RoboVM compiler config: " + propertiesFile.getAbsolutePath());
builder.addProperties(propertiesFile);
} catch (IOException e) {
throw new MojoExecutionException("Failed to add properties file to RoboVM config: " + propertiesFile);
}
} else {
File file = new File(robovmSrcDir, "Info.plist");
if (file.exists()) {
getLog().debug("Using default properties file: " + file.getAbsolutePath());
builder.iosInfoPList(file);
}
}
if (configFile != null) {
if (!configFile.exists()) {
throw new MojoExecutionException("Invalid 'configFile' specified for RoboVM compile: " + configFile);
}
try {
getLog().debug("Loading config file for RoboVM compiler: " + configFile.getAbsolutePath());
builder.read(configFile);
} catch (Exception e) {
throw new MojoExecutionException("Failed to read RoboVM config file: " + configFile);
}
} else {
File file = new File(robovmSrcDir, "config.xml");
if (file.exists()) {
getLog().debug("Using default config file: " + file.getAbsolutePath());
builder.iosInfoPList(file);
}
}
// override other settings based on POM
File osDir = new File(installDir, os.name());
File archiveDir = new File(new File(osDir, arch.name()), "");
builder.home(new Config.Home(unpackRoboVMDist()))
.logger(getRoboVMLogger())
.mainClass(mainClass)
.executableName(executableName)
.tmpDir(archiveDir)
.targetType(targetType)
.skipInstall(true)
.os(os)
.arch(arch);
if (forceLinkClasses != null) {
for (String pattern : forceLinkClasses) {
getLog().debug("Including class pattern for linking: " + pattern);
builder.addForceLinkClass(pattern);
}
}
if (frameworks != null) {
for (String framework : frameworks) {
getLog().debug("Including framework: " + framework);
builder.addFramework(framework);
}
}
if (libs != null) {
for (String lib : libs) {
getLog().debug("Including lib: " + lib);
builder.addLib(lib);
}
}
if (iosSdkVersion != null) {
getLog().debug("Using explicit iOS SDK version: " + iosSdkVersion);
builder.iosSdkVersion(iosSdkVersion);
}
if (iosSignIdentity != null) {
getLog().debug("Using explicit iOS Signing identity: " + iosSignIdentity);
builder.iosSignIdentity(iosSignIdentity);
}
if (iosInfoPList != null) {
if (!iosInfoPList.exists()) {
throw new MojoExecutionException("Invalid 'iosInfoPList' specified for RoboVM compile: " + iosInfoPList);
}
getLog().debug("Using Info.plist input file: " + iosInfoPList.getAbsolutePath());
builder.iosInfoPList(iosInfoPList);
} else {
File file = new File(robovmSrcDir, "Info.plist");
if (file.exists()) {
getLog().debug("Using default Info.plist input file: " + file.getAbsolutePath());
builder.iosInfoPList(file);
}
}
if (iosEntitlementsPList != null) {
if (!iosEntitlementsPList.exists()) {
throw new MojoExecutionException("Invalid 'iosEntitlementsPList' specified for RoboVM compile: " + iosEntitlementsPList);
}
getLog().debug("Using Entitlements.plist input file: " + iosEntitlementsPList.getAbsolutePath());
builder.iosEntitlementsPList(iosEntitlementsPList);
} else {
File file = new File(robovmSrcDir, "Entitlements.plist");
if (file.exists()) {
getLog().debug("Using default Entitlements.plist input file: " + file.getAbsolutePath());
builder.iosEntitlementsPList(file);
}
}
if (iosResourceRulesPList != null) {
if (!iosResourceRulesPList.exists()) {
throw new MojoExecutionException("Invalid 'iosResourceRulesPList' specified for RoboVM compile: " + iosResourceRulesPList);
}
getLog().debug("Using ResourceRules.plist input file: " + iosResourceRulesPList.getAbsolutePath());
builder.iosResourceRulesPList(iosResourceRulesPList);
} else {
File file = new File(robovmSrcDir, "ResourceRules.plist");
if (file.exists()) {
getLog().debug("Using default ResourceRules.plist input file: " + file.getAbsolutePath());
builder.iosResourceRulesPList(file);
}
}
if (resources != null) {
for (File resource : resources) {
if (!resource.exists()) {
throw new MojoExecutionException("Invalid 'resource' directory specified for RoboVM compile: " + resource);
}
getLog().debug("Including resource directory: " + resource.getAbsolutePath());
builder.addResource(resource);
}
} else {
// check if default resource dir exists
File resource = new File(robovmSrcDir, "resources");
if (resource.exists()) {
getLog().debug("Using default resource directory: " + resource.getAbsolutePath());
builder.addResource(resource);
}
}
builder.clearClasspathEntries();
// add JavaFX if needed
if (includeJFX) {
getLog().info("Including JavaFX Runtime in build");
// add jfxrt.jar to classpath
File jfxJar = resolveJavaFXRuntimeArtifact();
getLog().debug("JavaFX runtime JAR found at: " + jfxJar);
builder.addClasspathEntry(jfxJar);
// include native files as resources
File iosNativesBaseDir = unpackJavaFXNativeIOSArtifact();
builder.addLib(new File(iosNativesBaseDir, "libdecora-sse-armv7.a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libglass-armv7.a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libjavafx-font-armv7.a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libjavafx-iio-armv7.a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libprism-common-armv7.a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libprism-es2-armv7.a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libprism-sw-armv7.a").getAbsolutePath());
// add default 'roots' needed for JFX to work
builder.addForceLinkClass("com.sun.javafx.tk.quantum.QuantumToolkit");
builder.addForceLinkClass("com.sun.prism.es2.ES2Pipeline");
builder.addForceLinkClass("com.sun.prism.es2.IOSGLFactory");
builder.addForceLinkClass("com.sun.glass.ui.ios.**.*");
builder.addForceLinkClass("javafx.scene.CssStyleHelper");
builder.addForceLinkClass("com.sun.prism.shader.**.*");
builder.addForceLinkClass("com.sun.scenario.effect.impl.es2.ES2ShaderSource");
builder.addForceLinkClass("sun.util.logging.PlatformLogger");
// add default 'frameworks' needed for JFX to work
builder.addFramework("UIKit");
builder.addFramework("OpenGLES");
builder.addFramework("QuartzCore");
builder.addFramework("CoreGraphics");
builder.addFramework("CoreText");
builder.addFramework("ImageIO");
builder.addFramework("MobileCoreServices");
// todo do we need to exclude built-in JFX from JDK classpath?
}
// configure the runtime classpath
try {
for (Object object : project.getRuntimeClasspathElements()) {
String path = (String) object;
if (getLog().isDebugEnabled()) {
getLog().debug("Including classpath element for RoboVM app: " + path);
}
builder.addClasspathEntry(new File(path));
}
} catch (DependencyResolutionRequiredException e) {
throw new MojoExecutionException("Error resolving application classpath for RoboVM build", e);
}
// execute the RoboVM build
try {
Config config = builder.build();
AppCompiler compiler = new AppCompiler(config);
compiler.compile();
return config;
} catch (IOException e) {
throw new MojoExecutionException("Error building RoboVM executable for app", e);
}
}
| public Config buildArchive(OS os, Arch arch, TargetType targetType) throws MojoExecutionException, MojoFailureException {
getLog().info("Building RoboVM app for: " + os + " (" + arch + ")");
Config.Builder builder = new Config.Builder();
File robovmSrcDir = new File(project.getBasedir(), "src/main/robovm");
// load config base file if it exists (and properties)
if (propertiesFile != null) {
if (!propertiesFile.exists()) {
throw new MojoExecutionException("Invalid 'propertiesFile' specified for RoboVM compile: " + propertiesFile);
}
try {
getLog().debug("Including properties file in RoboVM compiler config: " + propertiesFile.getAbsolutePath());
builder.addProperties(propertiesFile);
} catch (IOException e) {
throw new MojoExecutionException("Failed to add properties file to RoboVM config: " + propertiesFile);
}
} else {
File file = new File(robovmSrcDir, "Info.plist");
if (file.exists()) {
getLog().debug("Using default properties file: " + file.getAbsolutePath());
builder.iosInfoPList(file);
}
}
if (configFile != null) {
if (!configFile.exists()) {
throw new MojoExecutionException("Invalid 'configFile' specified for RoboVM compile: " + configFile);
}
try {
getLog().debug("Loading config file for RoboVM compiler: " + configFile.getAbsolutePath());
builder.read(configFile);
} catch (Exception e) {
throw new MojoExecutionException("Failed to read RoboVM config file: " + configFile);
}
} else {
File file = new File(robovmSrcDir, "config.xml");
if (file.exists()) {
getLog().debug("Using default config file: " + file.getAbsolutePath());
builder.iosInfoPList(file);
}
}
// override other settings based on POM
File osDir = new File(installDir, os.name());
File archiveDir = new File(new File(osDir, arch.name()), "");
builder.home(new Config.Home(unpackRoboVMDist()))
.logger(getRoboVMLogger())
.mainClass(mainClass)
.executableName(executableName)
.tmpDir(archiveDir)
.targetType(targetType)
.skipInstall(true)
.os(os)
.arch(arch);
if (forceLinkClasses != null) {
for (String pattern : forceLinkClasses) {
getLog().debug("Including class pattern for linking: " + pattern);
builder.addForceLinkClass(pattern);
}
}
if (frameworks != null) {
for (String framework : frameworks) {
getLog().debug("Including framework: " + framework);
builder.addFramework(framework);
}
}
if (libs != null) {
for (String lib : libs) {
getLog().debug("Including lib: " + lib);
builder.addLib(lib);
}
}
if (iosSdkVersion != null) {
getLog().debug("Using explicit iOS SDK version: " + iosSdkVersion);
builder.iosSdkVersion(iosSdkVersion);
}
if (iosSignIdentity != null) {
getLog().debug("Using explicit iOS Signing identity: " + iosSignIdentity);
builder.iosSignIdentity(iosSignIdentity);
}
if (iosInfoPList != null) {
if (!iosInfoPList.exists()) {
throw new MojoExecutionException("Invalid 'iosInfoPList' specified for RoboVM compile: " + iosInfoPList);
}
getLog().debug("Using Info.plist input file: " + iosInfoPList.getAbsolutePath());
builder.iosInfoPList(iosInfoPList);
} else {
File file = new File(robovmSrcDir, "Info.plist");
if (file.exists()) {
getLog().debug("Using default Info.plist input file: " + file.getAbsolutePath());
builder.iosInfoPList(file);
}
}
if (iosEntitlementsPList != null) {
if (!iosEntitlementsPList.exists()) {
throw new MojoExecutionException("Invalid 'iosEntitlementsPList' specified for RoboVM compile: " + iosEntitlementsPList);
}
getLog().debug("Using Entitlements.plist input file: " + iosEntitlementsPList.getAbsolutePath());
builder.iosEntitlementsPList(iosEntitlementsPList);
} else {
File file = new File(robovmSrcDir, "Entitlements.plist");
if (file.exists()) {
getLog().debug("Using default Entitlements.plist input file: " + file.getAbsolutePath());
builder.iosEntitlementsPList(file);
}
}
if (iosResourceRulesPList != null) {
if (!iosResourceRulesPList.exists()) {
throw new MojoExecutionException("Invalid 'iosResourceRulesPList' specified for RoboVM compile: " + iosResourceRulesPList);
}
getLog().debug("Using ResourceRules.plist input file: " + iosResourceRulesPList.getAbsolutePath());
builder.iosResourceRulesPList(iosResourceRulesPList);
} else {
File file = new File(robovmSrcDir, "ResourceRules.plist");
if (file.exists()) {
getLog().debug("Using default ResourceRules.plist input file: " + file.getAbsolutePath());
builder.iosResourceRulesPList(file);
}
}
if (resources != null) {
for (File resource : resources) {
if (!resource.exists()) {
throw new MojoExecutionException("Invalid 'resource' directory specified for RoboVM compile: " + resource);
}
getLog().debug("Including resource directory: " + resource.getAbsolutePath());
builder.addResource(resource);
}
} else {
// check if default resource dir exists
File resource = new File(robovmSrcDir, "resources");
if (resource.exists()) {
getLog().debug("Using default resource directory: " + resource.getAbsolutePath());
builder.addResource(resource);
}
}
builder.clearClasspathEntries();
// add JavaFX if needed
if (includeJFX) {
getLog().info("Including JavaFX Runtime in build");
// add jfxrt.jar to classpath
File jfxJar = resolveJavaFXRuntimeArtifact();
getLog().debug("JavaFX runtime JAR found at: " + jfxJar);
builder.addClasspathEntry(jfxJar);
// include native files as resources
File iosNativesBaseDir = unpackJavaFXNativeIOSArtifact();
// builder.addLib(new File(iosNativesBaseDir, "libdecora-sse-" + arch.getClangName() + ".a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libglass-" + arch.getClangName() + ".a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libjavafx-font-" + arch.getClangName() + ".a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libjavafx-iio-" + arch.getClangName() + ".a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libprism-common-" + arch.getClangName() + ".a").getAbsolutePath());
builder.addLib(new File(iosNativesBaseDir, "libprism-es2-" + arch.getClangName() + ".a").getAbsolutePath());
// builder.addLib(new File(iosNativesBaseDir, "libprism-sw-" + arch.getClangName() + ".a").getAbsolutePath());
// add default 'roots' needed for JFX to work
builder.addForceLinkClass("com.sun.javafx.tk.quantum.QuantumToolkit");
builder.addForceLinkClass("com.sun.prism.es2.ES2Pipeline");
builder.addForceLinkClass("com.sun.prism.es2.IOSGLFactory");
builder.addForceLinkClass("com.sun.glass.ui.ios.**.*");
builder.addForceLinkClass("javafx.scene.CssStyleHelper");
builder.addForceLinkClass("com.sun.prism.shader.**.*");
builder.addForceLinkClass("com.sun.scenario.effect.impl.es2.ES2ShaderSource");
builder.addForceLinkClass("com.sun.javafx.font.coretext.CTFactory");
builder.addForceLinkClass("sun.util.logging.PlatformLogger");
// add default 'frameworks' needed for JFX to work
builder.addFramework("UIKit");
builder.addFramework("OpenGLES");
builder.addFramework("QuartzCore");
builder.addFramework("CoreGraphics");
builder.addFramework("CoreText");
builder.addFramework("ImageIO");
builder.addFramework("MobileCoreServices");
// todo do we need to exclude built-in JFX from JDK classpath?
}
// configure the runtime classpath
try {
for (Object object : project.getRuntimeClasspathElements()) {
String path = (String) object;
if (getLog().isDebugEnabled()) {
getLog().debug("Including classpath element for RoboVM app: " + path);
}
builder.addClasspathEntry(new File(path));
}
} catch (DependencyResolutionRequiredException e) {
throw new MojoExecutionException("Error resolving application classpath for RoboVM build", e);
}
// execute the RoboVM build
try {
Config config = builder.build();
AppCompiler compiler = new AppCompiler(config);
compiler.compile();
return config;
} catch (IOException e) {
throw new MojoExecutionException("Error building RoboVM executable for app", e);
}
}
|
diff --git a/source/de/anomic/yacy/yacyVersion.java b/source/de/anomic/yacy/yacyVersion.java
index 45461f256..8534a513b 100644
--- a/source/de/anomic/yacy/yacyVersion.java
+++ b/source/de/anomic/yacy/yacyVersion.java
@@ -1,204 +1,200 @@
package de.anomic.yacy;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.anomic.search.Switchboard;
import de.anomic.yacy.logging.Log;
public class yacyVersion implements Comparator<yacyVersion>, Comparable<yacyVersion> {
public static final float YACY_SUPPORTS_PORT_FORWARDING = (float) 0.383;
public static final float YACY_SUPPORTS_GZIP_POST_REQUESTS_CHUNKED = (float) 0.58204761;
public static final float YACY_ACCEPTS_RANKING_TRANSMISSION = (float) 0.414;
public static final float YACY_HANDLES_COLLECTION_INDEX = (float) 0.486;
public static final float YACY_POVIDES_REMOTECRAWL_LISTS = (float) 0.550;
public static final float YACY_STANDARDREL_IS_PRO = (float) 0.557;
private static yacyVersion thisVersion = null;
/**
* information about latest release, retrieved by other peers release version,
* this value is overwritten when a peer with later version appears*/
public static double latestRelease = 0.1; //
private float releaseNr;
private String dateStamp;
private int svn;
private boolean mainRelease;
private String name;
/**
* parse a release file name
* <p>the have the following form:
* <ul>
* <li>yacy_dev_v${releaseVersion}_${DSTAMP}_${releaseNr}.tar.gz</li>
* <li>yacy_v${releaseVersion}_${DSTAMP}_${releaseNr}.tar.gz</li>
* </ul>
* i.e. yacy_v0.51_20070321_3501.tar.gz
* @param release
*/
public yacyVersion(String release) {
this.name = release;
if ((release == null) || (!((release.endsWith(".tar.gz") || (release.endsWith(".tar")))))) {
throw new RuntimeException("release file name '" + release + "' is not valid, no tar.gz");
}
// cut off tail
release = release.substring(0, release.length() - ((release.endsWith(".gz")) ? 7 : 4));
- if (release.startsWith("yacy_pro_v")) {
- release = release.substring(10);
- } else if (release.startsWith("yacy_emb_v")) {
- throw new RuntimeException("release file name '" + release + "' is not valid, no support for emb");
- } else if (release.startsWith("yacy_v")) {
+ if (release.startsWith("yacy_v")) {
release = release.substring(6);
} else {
throw new RuntimeException("release file name '" + release + "' is not valid, wrong prefix");
}
// now all release names have the form
// ${releaseVersion}_${DSTAMP}_${releaseNr}
final String[] comp = release.split("_"); // should be 3 parts
if (comp.length != 3) {
throw new RuntimeException("release file name '" + release + "' is not valid, 3 information parts expected");
}
try {
this.releaseNr = Float.parseFloat(comp[0]);
} catch (final NumberFormatException e) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[0] + "' should be a float number");
}
this.mainRelease = ((int) (this.getReleaseNr() * 100)) % 10 == 0;
//System.out.println("Release version " + this.releaseNr + " is " + ((this.mainRelease) ? "main" : "std"));
this.dateStamp = comp[1];
if (this.getDateStamp().length() != 8) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[1] + "' should be a 8-digit date string");
}
try {
this.svn = Integer.parseInt(comp[2]);
} catch (final NumberFormatException e) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[2] + "' should be a integer number");
}
// finished! we parsed a relase string
}
public static final yacyVersion thisVersion() {
// construct a virtual release name for this release
if (thisVersion == null) {
final Switchboard sb = Switchboard.getSwitchboard();
if (sb == null) return null;
thisVersion = new yacyVersion(
"yacy" +
"_v" + yacyBuildProperties.getVersion() + "_" +
yacyBuildProperties.getBuildDate() + "_" +
yacyBuildProperties.getSVNRevision() + ".tar.gz");
}
return thisVersion;
}
/**
* returns 0 if this object is equal to the obj, -1 if this is smaller
* than obj and 1 if this is greater than obj
*/
public int compareTo(final yacyVersion obj) {
return compare(this, obj);
}
/**
* compare-operator for two yacyVersion objects
* must be implemented to make it possible to put this object into
* a ordered structure, like TreeSet or TreeMap
*/
public int compare(final yacyVersion v0, final yacyVersion v1) {
return (Integer.valueOf(v0.getSvn())).compareTo(Integer.valueOf(v1.getSvn()));
}
public boolean equals(final Object obj) {
if(obj instanceof yacyVersion) {
final yacyVersion v = (yacyVersion) obj;
return (this.getSvn() == v.getSvn()) && (this.getName().equals(v.getName()));
}
return false;
}
public int hashCode() {
return this.getName().hashCode();
}
/**
* Converts combined version-string to a pretty string, e.g. "0.435/01818" or "dev/01818" (development version) or "dev/00000" (in case of wrong input)
*
* @param ver Combined version string matching regular expression: "\A(\d+\.\d{3})(\d{4}|\d{5})\z" <br>
* (i.e.: start of input, 1 or more digits in front of decimal point, decimal point followed by 3 digits as major version, 4 or 5 digits for SVN-Version, end of input)
* @return If the major version is < 0.11 - major version is separated from SVN-version by '/', e.g. "0.435/01818" <br>
* If the major version is >= 0.11 - major version is replaced by "dev" and separated SVN-version by '/', e.g."dev/01818" <br>
* "dev/00000" - If the input does not matcht the regular expression above
*/
public static String combined2prettyVersion(final String ver) {
return combined2prettyVersion(ver, "");
}
public static String combined2prettyVersion(final String ver, final String computerName) {
final Matcher matcher = Pattern.compile("\\A(\\d+\\.\\d{1,3})(\\d{0,5})\\z").matcher(ver);
if (!matcher.find()) {
Log.logWarning("STARTUP", "Peer '"+computerName+"': wrong format of version-string: '" + ver + "'. Using default string 'dev/00000' instead");
return "dev/00000";
}
final String mainversion = (Double.parseDouble(matcher.group(1)) < 0.11 ? "dev" : matcher.group(1));
String revision = matcher.group(2);
for(int i=revision.length();i<5;++i) revision += "0";
return mainversion+"/"+revision;
}
/**
* Combines the version of YaCy with the versionnumber from SVN to a
* combined version
*
* @param version Current given version.
* @param svn Current version given from SVN.
* @return String with the combined version.
*/
public static double versvn2combinedVersion(final double version, final int svn) {
return (Math.rint((version*100000000.0) + (svn))/100000000);
}
/**
* Timestamp of this version
* @return timestamp
*/
public String getDateStamp() {
return dateStamp;
}
/**
* SVN revision of release
* @return svn revision as integer
*/
public int getSvn() {
return svn;
}
/**
* Whether this is a stable main release or not
* @return
*/
public boolean isMainRelease() {
return mainRelease;
}
/**
* release number as float (e. g. 7.04)
* @return
*/
public float getReleaseNr() {
return releaseNr;
}
public String getName() {
return name;
}
}
| true | true | public yacyVersion(String release) {
this.name = release;
if ((release == null) || (!((release.endsWith(".tar.gz") || (release.endsWith(".tar")))))) {
throw new RuntimeException("release file name '" + release + "' is not valid, no tar.gz");
}
// cut off tail
release = release.substring(0, release.length() - ((release.endsWith(".gz")) ? 7 : 4));
if (release.startsWith("yacy_pro_v")) {
release = release.substring(10);
} else if (release.startsWith("yacy_emb_v")) {
throw new RuntimeException("release file name '" + release + "' is not valid, no support for emb");
} else if (release.startsWith("yacy_v")) {
release = release.substring(6);
} else {
throw new RuntimeException("release file name '" + release + "' is not valid, wrong prefix");
}
// now all release names have the form
// ${releaseVersion}_${DSTAMP}_${releaseNr}
final String[] comp = release.split("_"); // should be 3 parts
if (comp.length != 3) {
throw new RuntimeException("release file name '" + release + "' is not valid, 3 information parts expected");
}
try {
this.releaseNr = Float.parseFloat(comp[0]);
} catch (final NumberFormatException e) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[0] + "' should be a float number");
}
this.mainRelease = ((int) (this.getReleaseNr() * 100)) % 10 == 0;
//System.out.println("Release version " + this.releaseNr + " is " + ((this.mainRelease) ? "main" : "std"));
this.dateStamp = comp[1];
if (this.getDateStamp().length() != 8) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[1] + "' should be a 8-digit date string");
}
try {
this.svn = Integer.parseInt(comp[2]);
} catch (final NumberFormatException e) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[2] + "' should be a integer number");
}
// finished! we parsed a relase string
}
| public yacyVersion(String release) {
this.name = release;
if ((release == null) || (!((release.endsWith(".tar.gz") || (release.endsWith(".tar")))))) {
throw new RuntimeException("release file name '" + release + "' is not valid, no tar.gz");
}
// cut off tail
release = release.substring(0, release.length() - ((release.endsWith(".gz")) ? 7 : 4));
if (release.startsWith("yacy_v")) {
release = release.substring(6);
} else {
throw new RuntimeException("release file name '" + release + "' is not valid, wrong prefix");
}
// now all release names have the form
// ${releaseVersion}_${DSTAMP}_${releaseNr}
final String[] comp = release.split("_"); // should be 3 parts
if (comp.length != 3) {
throw new RuntimeException("release file name '" + release + "' is not valid, 3 information parts expected");
}
try {
this.releaseNr = Float.parseFloat(comp[0]);
} catch (final NumberFormatException e) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[0] + "' should be a float number");
}
this.mainRelease = ((int) (this.getReleaseNr() * 100)) % 10 == 0;
//System.out.println("Release version " + this.releaseNr + " is " + ((this.mainRelease) ? "main" : "std"));
this.dateStamp = comp[1];
if (this.getDateStamp().length() != 8) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[1] + "' should be a 8-digit date string");
}
try {
this.svn = Integer.parseInt(comp[2]);
} catch (final NumberFormatException e) {
throw new RuntimeException("release file name '" + release + "' is not valid, '" + comp[2] + "' should be a integer number");
}
// finished! we parsed a relase string
}
|
diff --git a/src/code_swarm.java b/src/code_swarm.java
index 1056322..c0bea5c 100644
--- a/src/code_swarm.java
+++ b/src/code_swarm.java
@@ -1,1495 +1,1499 @@
/**
* Copyright 2008 Michael Ogawa
*
* This file is part of code_swarm.
*
* code_swarm 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.
*
* code_swarm 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 code_swarm. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.vecmath.Vector2f;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import processing.core.PApplet;
import processing.core.PFont;
import processing.core.PImage;
/**
*
*
*/
public class code_swarm extends PApplet {
/** @remark needed for any serializable class */
public static final long serialVersionUID = 0;
// User-defined variables
int FRAME_RATE = 24;
long UPDATE_DELTA = -1;
String SPRITE_FILE = "particle.png";
String SCREENSHOT_FILE;
int background;
// Data storage
BlockingQueue<FileEvent> eventsQueue;
boolean isInputSorted = false;
protected static CopyOnWriteArrayList<FileNode> nodes;
protected static CopyOnWriteArrayList<Edge> edges;
protected static CopyOnWriteArrayList<PersonNode> people;
LinkedList<ColorBins> history;
boolean finishedLoading = false;
// Temporary variables
FileEvent currentEvent;
Date nextDate;
Date prevDate;
FileNode prevNode;
int maxTouches;
// Graphics objects
PFont font;
PFont boldFont;
PImage sprite;
// Graphics state variables
boolean looping = true;
boolean showHistogram = true;
boolean showDate = true;
boolean showLegend = false;
boolean showPopular = false;
boolean showEdges = false;
boolean showEngine = false;
boolean showHelp = false;
boolean takeSnapshots = false;
boolean showDebug = false;
boolean drawNamesSharp = false;
boolean drawNamesHalos = false;
boolean drawFilesSharp = false;
boolean drawFilesFuzzy = false;
boolean drawFilesJelly = false;
//used to ensure that input is sorted when we're told it is
long maximumDateSeenSoFar = 0;
// Color mapper
ColorAssigner colorAssigner;
int currentColor;
// Edge Length
protected static int EDGE_LEN = 25;
// Drawable object life decrement
private int EDGE_LIFE_INIT = 255;
private int FILE_LIFE_INIT = 255;
private int PERSON_LIFE_INIT = 255;
private int EDGE_LIFE_DECREMENT = -1;
private int FILE_LIFE_DECREMENT = -1;
private int PERSON_LIFE_DECREMENT = -1;
private float DEFAULT_NODE_SPEED = 7.0f;
private float DEFAULT_FILE_SPEED = 7.0f;
private float DEFAULT_PERSON_SPEED = 2.0f;
private float FILE_MASS = 1.0f;
private float PERSON_MASS = 10.0f;
private int HIGHLIGHT_PCT = 5;
// Physics engine configuration
String physicsEngineConfigDir;
String physicsEngineSelection;
LinkedList<peConfig> mPhysicsEngineChoices = new LinkedList<peConfig>();
PhysicsEngine mPhysicsEngine = null;
private boolean safeToToggle = false;
private boolean wantToToggle = false;
private boolean toggleDirection = false;
// Default Physics Engine (class) name
static final String PHYSICS_ENGINE_LEGACY = "PhysicsEngineLegacy";
// Formats the date string nicely
DateFormat formatter = DateFormat.getDateInstance();
protected static CodeSwarmConfig cfg;
private long lastDrawDuration = 0;
private String loadingMessage = "Reading input file";
protected static int width=0;
protected static int height=0;
private int maxFramesSaved;
protected int maxBackgroundThreads;
protected ExecutorService backgroundExecutor;
/**
* Used for utility functions
* current members:
* drawPoint: Pass coords and color
* drawLine: Pass coords and color
*/
public static Utils utils = null;
/**
* Initialization
*/
public void setup() {
utils = new Utils();
width=cfg.getPositiveIntProperty(CodeSwarmConfig.WIDTH_KEY,640);
height=cfg.getPositiveIntProperty(CodeSwarmConfig.HEIGHT_KEY,480);
if (cfg.getBooleanProperty(CodeSwarmConfig.USE_OPEN_GL, false)) {
size(width, height, OPENGL);
} else {
size(width, height);
}
int maxBackgroundThreads = cfg.getPositiveIntProperty(CodeSwarmConfig.MAX_THREADS_KEY, 8);
backgroundExecutor = new ThreadPoolExecutor(1, maxBackgroundThreads, Long.MAX_VALUE, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(4 * maxBackgroundThreads), new ThreadPoolExecutor.CallerRunsPolicy());
showLegend = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_LEGEND, false);
showHistogram = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_HISTORY, false);
showDate = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DATE, false);
showEdges = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_EDGES, false);
showDebug = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DEBUG, false);
takeSnapshots = cfg.getBooleanProperty(CodeSwarmConfig.TAKE_SNAPSHOTS_KEY,false);
drawNamesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_SHARP, true);
drawNamesHalos = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_HALOS, false);
drawFilesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_SHARP, false);
drawFilesFuzzy = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_FUZZY, true);
drawFilesJelly = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_JELLY, false);
background = cfg.getBackground().getRGB();
// Ensure we have sane values.
EDGE_LIFE_INIT = cfg.getPositiveIntProperty(CodeSwarmConfig.EDGE_LIFE_KEY,255);
FILE_LIFE_INIT = cfg.getPositiveIntProperty(CodeSwarmConfig.FILE_LIFE_KEY,255);
PERSON_LIFE_INIT = cfg.getPositiveIntProperty(CodeSwarmConfig.PERSON_LIFE_KEY,255);
UPDATE_DELTA = cfg.getIntProperty("testsets"/*CodeSwarmConfig.MSEC_PER_FRAME_KEY*/, -1);
/* enforce decrements < 0 */
EDGE_LIFE_DECREMENT = cfg.getNegativeIntProperty(CodeSwarmConfig.EDGE_DECREMENT_KEY,-2);
FILE_LIFE_DECREMENT = cfg.getNegativeIntProperty(CodeSwarmConfig.FILE_DECREMENT_KEY,-2);
PERSON_LIFE_DECREMENT = cfg.getNegativeIntProperty(CodeSwarmConfig.PERSON_DECREMENT_KEY,-1);
DEFAULT_NODE_SPEED = cfg.getFloatProperty(CodeSwarmConfig.NODE_SPEED_KEY, 7.0f);
DEFAULT_FILE_SPEED = cfg.getFloatProperty(CodeSwarmConfig.FILE_SPEED_KEY, DEFAULT_NODE_SPEED);
DEFAULT_PERSON_SPEED = cfg.getFloatProperty(CodeSwarmConfig.PERSON_SPEED_KEY, DEFAULT_NODE_SPEED);
FILE_MASS = cfg.getFloatProperty(CodeSwarmConfig.FILE_MASS_KEY,1.0f);
PERSON_MASS = cfg.getFloatProperty(CodeSwarmConfig.PERSON_MASS_KEY,1.0f);
HIGHLIGHT_PCT = cfg.getIntProperty(CodeSwarmConfig.HIGHLIGHT_PCT_KEY,5);
if (HIGHLIGHT_PCT < 0 || HIGHLIGHT_PCT > 100) {
HIGHLIGHT_PCT = 5;
}
UPDATE_DELTA = cfg.getIntProperty(CodeSwarmConfig.MSEC_PER_FRAME_KEY, -1);
if (UPDATE_DELTA == -1) {
int framesperday = cfg.getIntProperty(CodeSwarmConfig.FRAMES_PER_DAY_KEY, 4);
if (framesperday > 0) {
UPDATE_DELTA = (long) (86400000 / framesperday);
}
}
if (UPDATE_DELTA <= 0) {
// Default to 4 frames per day.
UPDATE_DELTA = 21600000;
}
isInputSorted = cfg.getBooleanProperty(CodeSwarmConfig.IS_INPUT_SORTED_KEY, false);
/**
* This section loads config files and calls the setup method for all physics engines.
*/
physicsEngineConfigDir = cfg.getStringProperty( CodeSwarmConfig.PHYSICS_ENGINE_CONF_DIR, "physics_engine");
File f = new File(physicsEngineConfigDir);
String[] configFiles = null;
if ( f.exists() && f.isDirectory() ) {
configFiles = f.list();
}
for (int i=0; configFiles != null && i<configFiles.length; i++) {
if (configFiles[i].endsWith(".config")) {
String ConfigPath = physicsEngineConfigDir + System.getProperty("file.separator") + configFiles[i];
CodeSwarmConfig physicsConfig = null;
try {
physicsConfig = new CodeSwarmConfig(ConfigPath);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
String ClassName = physicsConfig.getStringProperty("name", "__DEFAULT__");
if ( ! ClassName.equals("__DEFAULT__")) {
PhysicsEngine pe = getPhysicsEngine(ClassName);
pe.setup(physicsConfig);
peConfig pec = new peConfig(ClassName,pe);
mPhysicsEngineChoices.add(pec);
} else {
System.out.println("Skipping config file '" + ConfigPath + "'. Must specify class name via the 'name' parameter.");
System.exit(1);
}
}
}
if (mPhysicsEngineChoices.size() == 0) {
System.out.println("No physics engine config files found in '" + physicsEngineConfigDir + "'.");
System.exit(1);
}
// Physics engine configuration and instantiation
physicsEngineSelection = cfg.getStringProperty( CodeSwarmConfig.PHYSICS_ENGINE_SELECTION, PHYSICS_ENGINE_LEGACY );
for (peConfig p : mPhysicsEngineChoices) {
if (physicsEngineSelection.equals(p.name)) {
mPhysicsEngine = p.pe;
}
}
if (mPhysicsEngine == null) {
System.out.println("No physics engine matches your choice of '" + physicsEngineSelection + "'. Check '" + physicsEngineConfigDir + "' for options.");
System.exit(1);
}
smooth();
frameRate(FRAME_RATE);
// init data structures
nodes = new CopyOnWriteArrayList<FileNode>();
edges = new CopyOnWriteArrayList<Edge>();
people = new CopyOnWriteArrayList<PersonNode>();
history = new LinkedList<ColorBins>();
if (isInputSorted)
//If the input is sorted, we only need to store the next few events
eventsQueue = new ArrayBlockingQueue<FileEvent>(5000);
else
//Otherwise we need to store them all at once in a data structure that will sort them
eventsQueue = new PriorityBlockingQueue<FileEvent>();
// Init color map
initColors();
loadRepEvents(cfg.getStringProperty(CodeSwarmConfig.INPUT_FILE_KEY)); // event formatted (this is the standard)
while(!finishedLoading && eventsQueue.isEmpty());
+ if(eventsQueue.isEmpty()){
+ System.out.println("No events found in repository xml file.");
+ System.exit(1);
+ }
prevDate = eventsQueue.peek().date;
SCREENSHOT_FILE = cfg.getStringProperty(CodeSwarmConfig.SNAPSHOT_LOCATION_KEY);
EDGE_LEN = cfg.getPositiveIntProperty(CodeSwarmConfig.EDGE_LENGTH_KEY, 25);
maxFramesSaved = (int) Math.pow(10, SCREENSHOT_FILE.replaceAll("[^#]","").length());
// Create fonts
String fontName = cfg.getStringProperty(CodeSwarmConfig.FONT_KEY,"SansSerif");
Integer fontSize = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE, 10);
Integer fontSizeBold = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE_BOLD, 14);
font = createFont(fontName, fontSize);
boldFont = createFont(fontName + ".bold", fontSizeBold);
textFont(font);
String SPRITE_FILE = cfg.getStringProperty(CodeSwarmConfig.SPRITE_FILE_KEY);
// Create the file particle image
sprite = loadImage(SPRITE_FILE);
// Add translucency (using itself in this case)
sprite.mask(sprite);
}
/**
* Load a colormap
*/
public void initColors() {
colorAssigner = new ColorAssigner();
int i = 1;
String property;
while ((property = cfg.getColorAssignProperty(i)) != null) {
ColorTest ct = new ColorTest();
ct.loadProperty(property);
colorAssigner.addRule(ct);
i++;
}
// Load the default.
ColorTest ct = new ColorTest();
ct.loadProperty(CodeSwarmConfig.DEFAULT_COLOR_ASSIGN);
colorAssigner.addRule(ct);
}
/**
* Main loop
*/
public void draw() {
long start = System.currentTimeMillis();
background(background); // clear screen with background color
this.update(); // update state to next frame
// Draw edges (for debugging only)
if (showEdges) {
for (Edge edge : edges) {
edge.draw();
}
}
// Surround names with aura
// Then blur it
if (drawNamesHalos) {
drawPeopleNodesBlur();
}
// Then draw names again, but sharp
if (drawNamesSharp) {
drawPeopleNodesSharp();
}
// Draw file particles
for (FileNode node : nodes) {
node.draw();
}
textFont(font);
// Show the physics engine name
if (showEngine) {
drawEngine();
}
// help, legend and debug information are exclusive
if (showHelp) {
// help override legend and debug information
drawHelp();
}
else if (showDebug) {
// debug override legend information
drawDebugData();
}
else if (showLegend) {
// legend only if nothing "more important"
drawLegend();
}
if (showPopular) {
drawPopular();
}
if (showHistogram) {
drawHistory();
}
if (showDate) {
drawDate();
}
if (takeSnapshots) {
dumpFrame();
}
// Stop animation when we run out of data
if (finishedLoading && eventsQueue.isEmpty()) {
// noLoop();
backgroundExecutor.shutdown();
try {
backgroundExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) { /* Do nothing, just exit */}
exit();
}
long end = System.currentTimeMillis();
lastDrawDuration = end - start;
}
/**
* Surround names with aura
*/
public void drawPeopleNodesBlur() {
colorMode(HSB);
// First draw the name
for (PersonNode p : people) {
fill(hue(p.flavor), 64, 255, p.life);
p.draw();
}
// Then blur it
filter(BLUR, 3);
}
/**
* Draw person's name
*/
public void drawPeopleNodesSharp() {
colorMode(RGB);
for (int i = 0; i < people.size(); i++) {
PersonNode p = (PersonNode) people.get(i);
fill(lerpColor(p.flavor, color(255), 0.5f), max(p.life - 50, 0));
p.draw();
}
}
/**
* Draw date in lower-right corner
*/
public void drawDate() {
fill(255);
String dateText = formatter.format(prevDate);
textAlign(RIGHT, BASELINE);
textSize(font.size);
text(dateText, width - 1, height - textDescent());
}
/**
* Draw histogram in lower-left
*/
public void drawHistory() {
int counter = 0;
for (ColorBins cb : history) {
if (cb.num > 0) {
int color = cb.colorList[0];
int start = 0;
int end = 0;
for (int nextColor : cb.colorList) {
if (nextColor == color)
end++;
else {
stroke(color, 255);
rectMode(CORNERS);
rect(counter, height - start - 3, counter, height - end - 3);
start = end;
color = nextColor;
}
}
}
counter+=1;
}
}
/**
* Show the Loading screen.
*/
public void drawLoading() {
noStroke();
textFont(font, 20);
textAlign(LEFT, TOP);
fill(255, 200);
text(loadingMessage, 0, 0);
}
/**
* Show color codings
*/
public void drawLegend() {
noStroke();
textFont(font);
textAlign(LEFT, TOP);
fill(255, 200);
text("Legend:", 0, 0);
for (int i = 0; i < colorAssigner.tests.size(); i++) {
ColorTest t = colorAssigner.tests.get(i);
fill(t.c1, 200);
text(t.label, font.size, (i + 1) * font.size);
}
}
/**
* Show physics engine name
*/
public void drawEngine() {
fill(255);
textAlign(RIGHT, BASELINE);
textSize(10);
text(physicsEngineSelection, width-1, height - (textDescent() * 5));
}
/**
* Show short help on available commands
*/
public void drawHelp() {
int line = 0;
noStroke();
textFont(font);
textAlign(LEFT, TOP);
fill(255, 200);
text("Help on keyboard commands:", 0, 10*line++);
text("space bar : pause", 0, 10*line++);
text(" a : show name halos", 0, 10*line++);
text(" b : show debug", 0, 10*line++);
text(" d : show date", 0, 10*line++);
text(" e : show edges", 0, 10*line++);
text(" E : show physics engine name", 0, 10*line++);
text(" f : draw files fuzzy", 0, 10*line++);
text(" h : show histogram", 0, 10*line++);
text(" j : draw files jelly", 0, 10*line++);
text(" l : show legend", 0, 10*line++);
text(" p : show popular", 0, 10*line++);
text(" q : quit code_swarm", 0, 10*line++);
text(" s : draw names sharp", 0, 10*line++);
text(" S : draw files sharp", 0, 10*line++);
text(" minus : previous physics engine", 0, 10*line++);
text(" plus : next physics engine", 0, 10*line++);
text(" ? : show help", 0, 10*line++);
}
/**
* Show debug information about all drawable objects
*/
public void drawDebugData() {
noStroke();
textFont(font);
textAlign(LEFT, TOP);
fill(255, 200);
text("Nodes: " + nodes.size(), 0, 0);
text("People: " + people.size(), 0, 10);
text("Queue: " + eventsQueue.size(), 0, 20);
text("Last render time: " + lastDrawDuration, 0, 30);
}
/**
* TODO This could be made to look a lot better.
*/
public void drawPopular() {
CopyOnWriteArrayList <FileNode> al=new CopyOnWriteArrayList<FileNode>();
noStroke();
textFont(font);
textAlign(RIGHT, TOP);
fill(255, 200);
text("Popular Nodes (touches):", width-120, 0);
for (int i = 0; i < nodes.size(); i++) {
FileNode fn = (FileNode) nodes.get(i);
if (fn.qualifies()) {
// Insertion Sort
if (al.size() > 0) {
int j = 0;
for (; j < al.size(); j++) {
if (fn.compareTo(al.get(j)) <= 0) {
continue;
} else {
break;
}
}
al.add(j,fn);
} else {
al.add(fn);
}
}
}
int i = 1;
ListIterator<FileNode> it = al.listIterator();
while (it.hasNext()) {
FileNode n = it.next();
// Limit to the top 10.
if (i <= 10) {
text(n.name + " (" + n.touches + ")", width-100, 10 * i++);
} else if (i > 10) {
break;
}
}
}
/**
* @param name
* @return physics engine instance
*/
@SuppressWarnings("unchecked")
public PhysicsEngine getPhysicsEngine(String name) {
PhysicsEngine pe = null;
try {
Class<PhysicsEngine> c = (Class<PhysicsEngine>)Class.forName(name);
Constructor<PhysicsEngine> peConstructor = c.getConstructor();
pe = peConstructor.newInstance();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return pe;
}
/**
* @return list of people whose life is > 0
*/
public static Iterable<PersonNode> getLivingPeople() {
return filterLiving(people);
}
/**
* @return list of edges whose life is > 0
*/
public static Iterable<Edge> getLivingEdges() {
return filterLiving(edges);
}
/**
* @return list of file nodes whose life is > 0
*/
public static Iterable<FileNode> getLivingNodes() {
return filterLiving(nodes);
}
private static <T extends Drawable> Iterable<T> filterLiving(Iterable<T> iter) {
ArrayList<T> livingThings = new ArrayList<T>();
for (T thing : iter)
if (thing.isAlive())
livingThings.add(thing);
return livingThings;
}
/**
* Take screenshot
*/
public void dumpFrame() {
if (frameCount < this.maxFramesSaved){
final File outputFile = new File(insertFrame(SCREENSHOT_FILE));
final PImage image = get();
outputFile.getParentFile().mkdirs();
backgroundExecutor.execute(new Runnable() {
public void run() {
image.save(outputFile.getAbsolutePath());
}
});
}
}
/**
* Update the particle positions
*/
public void update() {
// Create a new histogram line
ColorBins cb = new ColorBins();
history.add(cb);
nextDate = new Date(prevDate.getTime() + UPDATE_DELTA);
currentEvent = eventsQueue.peek();
while (currentEvent != null && currentEvent.date.before(nextDate)) {
if (finishedLoading){
currentEvent = eventsQueue.poll();
if (currentEvent == null)
return;
}
else {
try {
currentEvent = eventsQueue.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Interrupted while fetching current event from eventsQueue");
e.printStackTrace();
continue;
}
}
FileNode n = findNode(currentEvent.path + currentEvent.filename);
if (n == null) {
n = new FileNode(currentEvent);
nodes.add(n);
} else {
n.freshen();
}
// add to color bin
cb.add(n.nodeHue);
PersonNode p = findPerson(currentEvent.author);
if (p == null) {
p = new PersonNode(currentEvent.author);
people.add(p);
} else {
p.freshen();
}
p.addColor(n.nodeHue);
Edge ped = findEdge(n, p);
if (ped == null) {
ped = new Edge(n, p);
edges.add(ped);
} else
ped.freshen();
/*
* if ( currentEvent.date.equals( prevDate ) ) { Edge e = findEdge( n, prevNode
* ); if ( e == null ) { e = new Edge( n, prevNode ); edges.add( e ); } else {
* e.freshen(); } }
*/
// prevDate = currentEvent.date;
prevNode = n;
if (finishedLoading)
currentEvent = eventsQueue.peek();
else{
while(eventsQueue.isEmpty());
currentEvent = eventsQueue.peek();
}
}
prevDate = nextDate;
// sort colorbins
cb.sort();
// restrict history to drawable area
while (history.size() > 320)
history.remove();
// Do not allow toggle Physics Engine yet.
safeToToggle = false;
// Init frame:
mPhysicsEngine.initializeFrame();
Iterable<Edge> livingEdges = getLivingEdges();
Iterable<FileNode> livingNodes = getLivingNodes();
Iterable<PersonNode> livingPeople = getLivingPeople();
// update velocity
for (Edge edge : livingEdges) {
mPhysicsEngine.onRelaxEdge(edge);
}
// update velocity
for (FileNode node : livingNodes) {
mPhysicsEngine.onRelaxNode(node);
}
// update velocity
for (PersonNode person : livingPeople) {
mPhysicsEngine.onRelaxPerson(person);
}
// update position
for (Edge edge : livingEdges) {
mPhysicsEngine.onUpdateEdge(edge);
}
// update position
for (FileNode node : livingNodes) {
mPhysicsEngine.onUpdateNode(node);
}
// update position
for (PersonNode person : livingPeople) {
mPhysicsEngine.onUpdatePerson(person);
}
// Finalize frame:
mPhysicsEngine.finalizeFrame();
safeToToggle = true;
if (wantToToggle == true) {
switchPhysicsEngine(toggleDirection);
}
}
/**
* Searches the nodes array for a given name
* @param name
* @return FileNode with matching name or null if not found.
*/
public FileNode findNode(String name) {
for (FileNode node : nodes) {
if (node.name.equals(name))
return node;
}
return null;
}
/**
* Searches the nodes array for a given name
* @param n1 From
* @param n2 To
* @return Edge connecting n1 to n2 or null if not found
*/
public Edge findEdge(Node n1, Node n2) {
for (Edge edge : edges) {
if (edge.nodeFrom == n1 && edge.nodeTo == n2)
return edge;
}
return null;
}
/**
* Searches the people array for a given name.
* @param name
* @return PersonNode for given name or null if not found.
*/
public PersonNode findPerson(String name) {
for (PersonNode p : people) {
if (p.name.equals(name))
return p;
}
return null;
}
/**
* Load the standard event-formatted file.
* @param filename
*/
public void loadRepEvents(String filename) {
if (cfg.filename != null) {
String parentPath = new File(cfg.filename).getParentFile().getAbsolutePath();
File fileInConfigDir = new File(parentPath, filename);
if (fileInConfigDir.exists())
filename = fileInConfigDir.getAbsolutePath();
}
final String fullFilename = filename;
Runnable eventLoader = new XMLQueueLoader(fullFilename, eventsQueue, isInputSorted);
if (isInputSorted)
backgroundExecutor.execute(eventLoader);
else
//we have to load all of the data before we can continue if it isn't sorted
eventLoader.run();
}
/*
* Output file events for debugging void printQueue() { while(
* eventsQueue.size() > 0 ) { FileEvent fe = (FileEvent)eventsQueue.poll();
* println( fe.date ); } }
*/
/**
* @note Keystroke callback function
*/
public void keyPressed() {
switch (key) {
case ' ': {
pauseButton();
break;
}
case 'a': {
drawNamesHalos = !drawNamesHalos;
break;
}
case 'b': {
showDebug = !showDebug;
break;
}
case 'd': {
showDate = !showDate;
break;
}
case 'e' : {
showEdges = !showEdges;
break;
}
case 'E' : {
showEngine = !showEngine;
break;
}
case 'f' : {
drawFilesFuzzy = !drawFilesFuzzy;
break;
}
case 'h': {
showHistogram = !showHistogram;
break;
}
case 'j' : {
drawFilesJelly = !drawFilesJelly;
break;
}
case 'l': {
showLegend = !showLegend;
break;
}
case 'p': {
showPopular = !showPopular;
break;
}
case 'q': {
exit();
break;
}
case 's': {
drawNamesSharp = !drawNamesSharp;
break;
}
case 'S': {
drawFilesSharp = !drawFilesSharp;
break;
}
case '-': {
wantToToggle = true;
toggleDirection = false;
break;
}
case '+': {
wantToToggle = true;
toggleDirection = true;
break;
}
case '?': {
showHelp = !showHelp;
break;
}
}
}
/**
* Method to switch between Physics Engines
* @param direction Indicates whether or not to go left or right on the list
*/
public void switchPhysicsEngine(boolean direction) {
if (mPhysicsEngineChoices.size() > 1 && safeToToggle) {
boolean found = false;
for (int i = 0; i < mPhysicsEngineChoices.size() && !found; i++) {
if (mPhysicsEngineChoices.get(i).pe == mPhysicsEngine) {
found = true;
wantToToggle = false;
if (direction == true) {
if ((i+1) < mPhysicsEngineChoices.size()) {
mPhysicsEngine=mPhysicsEngineChoices.get(i+1).pe;
physicsEngineSelection=mPhysicsEngineChoices.get(i+1).name;
} else {
mPhysicsEngine=mPhysicsEngineChoices.get(0).pe;
physicsEngineSelection=mPhysicsEngineChoices.get(0).name;
}
} else {
if ((i-1) >= 0) {
mPhysicsEngine=mPhysicsEngineChoices.get(i-1).pe;
physicsEngineSelection=mPhysicsEngineChoices.get(i-1).name;
} else {
mPhysicsEngine=mPhysicsEngineChoices.get(mPhysicsEngineChoices.size()-1).pe;
physicsEngineSelection=mPhysicsEngineChoices.get(mPhysicsEngineChoices.size()-1).name;
}
}
}
}
}
}
/**
* Toggle pause
*/
public void pauseButton() {
if (looping)
noLoop();
else
loop();
looping = !looping;
}
private class XMLQueueLoader implements Runnable {
private final String fullFilename;
private BlockingQueue<FileEvent> queue;
boolean isXMLSorted;
private XMLQueueLoader(String fullFilename, BlockingQueue<FileEvent> queue, boolean isXMLSorted) {
this.fullFilename = fullFilename;
this.queue = queue;
this.isXMLSorted = isXMLSorted;
}
public void run(){
XMLReader reader = null;
try {
reader = XMLReaderFactory.createXMLReader();
} catch (SAXException e) {
System.out.println("Couldn't find/create an XML SAX Reader");
e.printStackTrace();
System.exit(1);
}
reader.setContentHandler(new DefaultHandler(){
public void startElement(String uri, String localName, String name,
Attributes atts) throws SAXException {
if (name.equals("event")){
String eventFilename = atts.getValue("filename");
String eventDatestr = atts.getValue("date");
long eventDate = Long.parseLong(eventDatestr);
//It's difficult for the user to tell that they're missing events,
//so we should crash in this case
if (isXMLSorted){
if (eventDate < maximumDateSeenSoFar){
System.out.println("Input not sorted, you must set IsInputSorted to false in your config file");
System.exit(1);
}
else
maximumDateSeenSoFar = eventDate;
}
String eventAuthor = atts.getValue("author");
// int eventLinesAdded = atts.getValue( "linesadded" );
// int eventLinesRemoved = atts.getValue( "linesremoved" );
FileEvent evt = new FileEvent(eventDate, eventAuthor, "", eventFilename);
try {
queue.put(evt);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Interrupted while trying to put into eventsQueue");
e.printStackTrace();
System.exit(1);
}
}
}
public void endDocument(){
finishedLoading = true;
}
});
try {
reader.parse(fullFilename);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Error parsing xml:");
e.printStackTrace();
System.exit(1);
}
}
}
class Utils {
Utils () {
}
/**
* Draws a point.
* @param x
* @param y
* @param red
* @param green
* @param blue
*/
public void drawPoint (int x, int y, int red, int green, int blue) {
noStroke();
colorMode(RGB);
stroke(red, green, blue);
point(x, y);
}
/**
* Draws a line.
* @param fromX
* @param fromY
* @param toX
* @param toY
* @param red
* @param green
* @param blue
*/
public void drawLine (int fromX, int fromY, int toX, int toY, int red, int green, int blue) {
noStroke();
colorMode(RGB);
stroke(red, green, blue);
strokeWeight(1.5f);
line(fromX, fromY, toX, toY);
}
}
/**
* Class to associate the Physics Engine name to the
* Physics Engine interface
*/
class peConfig {
protected String name;
protected PhysicsEngine pe;
peConfig(String n, PhysicsEngine p) {
name = n;
pe = p;
}
}
/**
* Describe an event on a file
*/
class FileEvent implements Comparable<Object> {
Date date;
String author;
String filename;
String path;
int linesadded;
int linesremoved;
/**
* short constructor with base data
*/
FileEvent(long datenum, String author, String path, String filename) {
this(datenum, author, path, filename, 0, 0);
}
/**
* constructor with number of modified lines
*/
FileEvent(long datenum, String author, String path, String filename, int linesadded, int linesremoved) {
this.date = new Date(datenum);
this.author = author;
this.path = path;
this.filename = filename;
this.linesadded = linesadded;
this.linesremoved = linesremoved;
}
/**
* Comparing two events by date (Not Used)
* @param o
* @return -1 if <, 0 if =, 1 if >
*/
public int compareTo(Object o) {
return date.compareTo(((FileEvent) o).date);
}
}
/**
* Base class for all drawable objects
*
* Lists and implements features common to all drawable objects
* Edge and Node, FileNode and PersonNode
*/
abstract class Drawable {
public int life;
final public int LIFE_INIT;
final public int LIFE_DECREMENT;
/**
* 1) constructor(s)
*
* Init jobs common to all objects
*/
Drawable(int lifeInit, int lifeDecrement) {
// save config vars
LIFE_INIT = lifeInit;
LIFE_DECREMENT = lifeDecrement;
// init life relative vars
life = LIFE_INIT;
}
/**
* 4) shortening life.
*/
public void decay() {
if (isAlive()) {
life += LIFE_DECREMENT;
if (life < 0) {
life = 0;
}
}
}
/**
* 5) drawing the new state => done in derived class.
*/
public abstract void draw();
/**
* 6) reseting life as if new.
*/
public abstract void freshen();
/**
* @return true if life > 0
*/
public boolean isAlive() {
return life > 0;
}
}
/**
* An Edge link two nodes together : a File to a Person.
*/
class Edge extends Drawable {
protected FileNode nodeFrom;
protected PersonNode nodeTo;
protected float len;
/**
* 1) constructor.
* @param from FileNode
* @param to PersonNode
*/
Edge(FileNode from, PersonNode to) {
super(EDGE_LIFE_INIT, EDGE_LIFE_DECREMENT);
this.nodeFrom = from;
this.nodeTo = to;
this.len = EDGE_LEN; // 25
}
/**
* 5) drawing the new state.
*/
public void draw() {
if (life > 240) {
stroke(255, life);
strokeWeight(0.35f);
line(nodeFrom.mPosition.x, nodeFrom.mPosition.y, nodeTo.mPosition.x, nodeTo.mPosition.y);
}
}
public void freshen() {
life = EDGE_LIFE_INIT;
}
}
/**
* A node is an abstraction for a File or a Person.
*/
public abstract class Node extends Drawable {
protected String name;
protected Vector2f mPosition;
protected Vector2f mSpeed;
protected float maxSpeed = DEFAULT_NODE_SPEED;
/**
* mass of the node
*/
protected float mass;
/**
* 1) constructor.
*/
Node(int lifeInit, int lifeDecrement) {
super(lifeInit, lifeDecrement);
mPosition = new Vector2f();
mSpeed = new Vector2f();
}
}
/**
* A node describing a file, which is repulsed by other files.
*/
class FileNode extends Node implements Comparable<FileNode> {
private int nodeHue;
private int minBold;
protected int touches;
/**
* @return file node as a string
*/
public String toString() {
return "FileNode{" + "name='" + name + '\'' + ", nodeHue=" + nodeHue + ", touches=" + touches + '}';
}
/**
* 1) constructor.
*/
FileNode(FileEvent fe) {
super(FILE_LIFE_INIT, FILE_LIFE_DECREMENT); // 255, -2
name = fe.path + fe.filename;
touches = 1;
life = FILE_LIFE_INIT;
colorMode(RGB);
minBold = (int)(FILE_LIFE_INIT * ((100.0f - HIGHLIGHT_PCT)/100));
nodeHue = colorAssigner.getColor(name);
mass = FILE_MASS;
maxSpeed = DEFAULT_FILE_SPEED;
mPosition.set(mPhysicsEngine.fStartLocation());
mSpeed.set(mPhysicsEngine.fStartVelocity(mass));
}
/**
* 5) drawing the new state.
*/
public void draw() {
if (isAlive()) {
if (drawFilesSharp) {
drawSharp();
}
if (drawFilesFuzzy) {
drawFuzzy();
}
if (drawFilesJelly) {
drawJelly();
}
/** TODO : this would become interesting on some special event, or for special materials
* colorMode( RGB ); fill( 0, life ); textAlign( CENTER, CENTER ); text( name, x, y );
* Example below:
*/
if (showPopular) {
textAlign( CENTER, CENTER );
if (this.qualifies()) {
text(touches, mPosition.x, mPosition.y - (8 + (int)Math.sqrt(touches)));
}
}
}
}
/**
* 6) reseting life as if new.
*/
public void freshen() {
life = FILE_LIFE_INIT;
if (++touches > maxTouches) {
maxTouches = touches;
}
}
public boolean qualifies() {
if (this.touches >= (maxTouches * 0.5f)) {
return true;
}
return false;
}
public int compareTo(FileNode fn) {
int retval = 0;
if (this.touches < fn.touches) {
retval = -1;
} else if (this.touches > fn.touches) {
retval = 1;
}
return retval;
}
public void drawSharp() {
colorMode(RGB);
fill(nodeHue, life);
float w = 3;
if (life >= minBold) {
stroke(255, 128);
w *= 2;
} else {
noStroke();
}
ellipseMode(CENTER);
ellipse(mPosition.x, mPosition.y, w, w);
}
public void drawFuzzy() {
tint(nodeHue, life);
float w = 8 + (sqrt(touches) * 4);
// not used float dubw = w * 2;
float halfw = w / 2;
if (life >= minBold) {
colorMode(HSB);
tint(hue(nodeHue), saturation(nodeHue) - 192, 255, life);
// image( sprite, x - w, y - w, dubw, dubw );
}
// else
image(sprite, mPosition.x - halfw, mPosition.y - halfw, w, w);
}
public void drawJelly() {
noFill();
if (life >= minBold)
stroke(255);
else
stroke(nodeHue, life);
float w = sqrt(touches);
ellipseMode(CENTER);
ellipse(mPosition.x, mPosition.y, w, w);
}
}
/**
* A node describing a person, which is repulsed by other persons.
*/
class PersonNode extends Node {
private int flavor = color(0);
private int colorCount = 1;
private int minBold;
protected int touches;
/**
* 1) constructor.
*/
PersonNode(String n) {
super(PERSON_LIFE_INIT, PERSON_LIFE_DECREMENT); // -1
maxSpeed = DEFAULT_PERSON_SPEED;
name = n;
minBold = (int)(PERSON_LIFE_INIT * (1 - (HIGHLIGHT_PCT)/100));
mass = PERSON_MASS; // bigger mass to person then to node, to stabilize them
touches = 1;
mPosition.set(mPhysicsEngine.pStartLocation());
mSpeed.set(mPhysicsEngine.pStartVelocity(mass));
}
/**
* 5) drawing the new state.
*/
public void draw() {
if (isAlive()) {
textAlign(CENTER, CENTER);
/** TODO: proportional font size, or light intensity,
or some sort of thing to disable the flashing */
if (life >= minBold)
textFont(boldFont);
else
textFont(font);
text(name, mPosition.x, mPosition.y);
}
}
public void freshen () {
life = PERSON_LIFE_INIT;
touches++;
}
public void addColor(int c) {
colorMode(RGB);
flavor = lerpColor(flavor, c, 1.0f / colorCount);
colorCount++;
}
}
/**
* code_swarm Entry point.
* @param args : should be the path to the config file
*/
static public void main(String args[]) {
try {
if (args.length > 0) {
start(new CodeSwarmConfig(args[0]));
} else {
System.err.println("Specify a config file.");
System.exit(2);
}
} catch (IOException e) {
System.err.println("Failed due to exception: " + e.getMessage());
System.exit(2);
}
}
/**
* the alternative entry-point for code_swarm. It gets called from
* {@link MainView} after fetching the repository log.
* @param config the modified config
* (it's InputFile-property has been changed to reflect the
* fetched repository-log)
*/
public static void start(CodeSwarmConfig config){
cfg = config;
PApplet.main(new String[]{"code_swarm"});
}
}
| true | true | public void setup() {
utils = new Utils();
width=cfg.getPositiveIntProperty(CodeSwarmConfig.WIDTH_KEY,640);
height=cfg.getPositiveIntProperty(CodeSwarmConfig.HEIGHT_KEY,480);
if (cfg.getBooleanProperty(CodeSwarmConfig.USE_OPEN_GL, false)) {
size(width, height, OPENGL);
} else {
size(width, height);
}
int maxBackgroundThreads = cfg.getPositiveIntProperty(CodeSwarmConfig.MAX_THREADS_KEY, 8);
backgroundExecutor = new ThreadPoolExecutor(1, maxBackgroundThreads, Long.MAX_VALUE, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(4 * maxBackgroundThreads), new ThreadPoolExecutor.CallerRunsPolicy());
showLegend = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_LEGEND, false);
showHistogram = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_HISTORY, false);
showDate = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DATE, false);
showEdges = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_EDGES, false);
showDebug = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DEBUG, false);
takeSnapshots = cfg.getBooleanProperty(CodeSwarmConfig.TAKE_SNAPSHOTS_KEY,false);
drawNamesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_SHARP, true);
drawNamesHalos = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_HALOS, false);
drawFilesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_SHARP, false);
drawFilesFuzzy = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_FUZZY, true);
drawFilesJelly = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_JELLY, false);
background = cfg.getBackground().getRGB();
// Ensure we have sane values.
EDGE_LIFE_INIT = cfg.getPositiveIntProperty(CodeSwarmConfig.EDGE_LIFE_KEY,255);
FILE_LIFE_INIT = cfg.getPositiveIntProperty(CodeSwarmConfig.FILE_LIFE_KEY,255);
PERSON_LIFE_INIT = cfg.getPositiveIntProperty(CodeSwarmConfig.PERSON_LIFE_KEY,255);
UPDATE_DELTA = cfg.getIntProperty("testsets"/*CodeSwarmConfig.MSEC_PER_FRAME_KEY*/, -1);
/* enforce decrements < 0 */
EDGE_LIFE_DECREMENT = cfg.getNegativeIntProperty(CodeSwarmConfig.EDGE_DECREMENT_KEY,-2);
FILE_LIFE_DECREMENT = cfg.getNegativeIntProperty(CodeSwarmConfig.FILE_DECREMENT_KEY,-2);
PERSON_LIFE_DECREMENT = cfg.getNegativeIntProperty(CodeSwarmConfig.PERSON_DECREMENT_KEY,-1);
DEFAULT_NODE_SPEED = cfg.getFloatProperty(CodeSwarmConfig.NODE_SPEED_KEY, 7.0f);
DEFAULT_FILE_SPEED = cfg.getFloatProperty(CodeSwarmConfig.FILE_SPEED_KEY, DEFAULT_NODE_SPEED);
DEFAULT_PERSON_SPEED = cfg.getFloatProperty(CodeSwarmConfig.PERSON_SPEED_KEY, DEFAULT_NODE_SPEED);
FILE_MASS = cfg.getFloatProperty(CodeSwarmConfig.FILE_MASS_KEY,1.0f);
PERSON_MASS = cfg.getFloatProperty(CodeSwarmConfig.PERSON_MASS_KEY,1.0f);
HIGHLIGHT_PCT = cfg.getIntProperty(CodeSwarmConfig.HIGHLIGHT_PCT_KEY,5);
if (HIGHLIGHT_PCT < 0 || HIGHLIGHT_PCT > 100) {
HIGHLIGHT_PCT = 5;
}
UPDATE_DELTA = cfg.getIntProperty(CodeSwarmConfig.MSEC_PER_FRAME_KEY, -1);
if (UPDATE_DELTA == -1) {
int framesperday = cfg.getIntProperty(CodeSwarmConfig.FRAMES_PER_DAY_KEY, 4);
if (framesperday > 0) {
UPDATE_DELTA = (long) (86400000 / framesperday);
}
}
if (UPDATE_DELTA <= 0) {
// Default to 4 frames per day.
UPDATE_DELTA = 21600000;
}
isInputSorted = cfg.getBooleanProperty(CodeSwarmConfig.IS_INPUT_SORTED_KEY, false);
/**
* This section loads config files and calls the setup method for all physics engines.
*/
physicsEngineConfigDir = cfg.getStringProperty( CodeSwarmConfig.PHYSICS_ENGINE_CONF_DIR, "physics_engine");
File f = new File(physicsEngineConfigDir);
String[] configFiles = null;
if ( f.exists() && f.isDirectory() ) {
configFiles = f.list();
}
for (int i=0; configFiles != null && i<configFiles.length; i++) {
if (configFiles[i].endsWith(".config")) {
String ConfigPath = physicsEngineConfigDir + System.getProperty("file.separator") + configFiles[i];
CodeSwarmConfig physicsConfig = null;
try {
physicsConfig = new CodeSwarmConfig(ConfigPath);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
String ClassName = physicsConfig.getStringProperty("name", "__DEFAULT__");
if ( ! ClassName.equals("__DEFAULT__")) {
PhysicsEngine pe = getPhysicsEngine(ClassName);
pe.setup(physicsConfig);
peConfig pec = new peConfig(ClassName,pe);
mPhysicsEngineChoices.add(pec);
} else {
System.out.println("Skipping config file '" + ConfigPath + "'. Must specify class name via the 'name' parameter.");
System.exit(1);
}
}
}
if (mPhysicsEngineChoices.size() == 0) {
System.out.println("No physics engine config files found in '" + physicsEngineConfigDir + "'.");
System.exit(1);
}
// Physics engine configuration and instantiation
physicsEngineSelection = cfg.getStringProperty( CodeSwarmConfig.PHYSICS_ENGINE_SELECTION, PHYSICS_ENGINE_LEGACY );
for (peConfig p : mPhysicsEngineChoices) {
if (physicsEngineSelection.equals(p.name)) {
mPhysicsEngine = p.pe;
}
}
if (mPhysicsEngine == null) {
System.out.println("No physics engine matches your choice of '" + physicsEngineSelection + "'. Check '" + physicsEngineConfigDir + "' for options.");
System.exit(1);
}
smooth();
frameRate(FRAME_RATE);
// init data structures
nodes = new CopyOnWriteArrayList<FileNode>();
edges = new CopyOnWriteArrayList<Edge>();
people = new CopyOnWriteArrayList<PersonNode>();
history = new LinkedList<ColorBins>();
if (isInputSorted)
//If the input is sorted, we only need to store the next few events
eventsQueue = new ArrayBlockingQueue<FileEvent>(5000);
else
//Otherwise we need to store them all at once in a data structure that will sort them
eventsQueue = new PriorityBlockingQueue<FileEvent>();
// Init color map
initColors();
loadRepEvents(cfg.getStringProperty(CodeSwarmConfig.INPUT_FILE_KEY)); // event formatted (this is the standard)
while(!finishedLoading && eventsQueue.isEmpty());
prevDate = eventsQueue.peek().date;
SCREENSHOT_FILE = cfg.getStringProperty(CodeSwarmConfig.SNAPSHOT_LOCATION_KEY);
EDGE_LEN = cfg.getPositiveIntProperty(CodeSwarmConfig.EDGE_LENGTH_KEY, 25);
maxFramesSaved = (int) Math.pow(10, SCREENSHOT_FILE.replaceAll("[^#]","").length());
// Create fonts
String fontName = cfg.getStringProperty(CodeSwarmConfig.FONT_KEY,"SansSerif");
Integer fontSize = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE, 10);
Integer fontSizeBold = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE_BOLD, 14);
font = createFont(fontName, fontSize);
boldFont = createFont(fontName + ".bold", fontSizeBold);
textFont(font);
String SPRITE_FILE = cfg.getStringProperty(CodeSwarmConfig.SPRITE_FILE_KEY);
// Create the file particle image
sprite = loadImage(SPRITE_FILE);
// Add translucency (using itself in this case)
sprite.mask(sprite);
}
| public void setup() {
utils = new Utils();
width=cfg.getPositiveIntProperty(CodeSwarmConfig.WIDTH_KEY,640);
height=cfg.getPositiveIntProperty(CodeSwarmConfig.HEIGHT_KEY,480);
if (cfg.getBooleanProperty(CodeSwarmConfig.USE_OPEN_GL, false)) {
size(width, height, OPENGL);
} else {
size(width, height);
}
int maxBackgroundThreads = cfg.getPositiveIntProperty(CodeSwarmConfig.MAX_THREADS_KEY, 8);
backgroundExecutor = new ThreadPoolExecutor(1, maxBackgroundThreads, Long.MAX_VALUE, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(4 * maxBackgroundThreads), new ThreadPoolExecutor.CallerRunsPolicy());
showLegend = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_LEGEND, false);
showHistogram = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_HISTORY, false);
showDate = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DATE, false);
showEdges = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_EDGES, false);
showDebug = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DEBUG, false);
takeSnapshots = cfg.getBooleanProperty(CodeSwarmConfig.TAKE_SNAPSHOTS_KEY,false);
drawNamesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_SHARP, true);
drawNamesHalos = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_HALOS, false);
drawFilesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_SHARP, false);
drawFilesFuzzy = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_FUZZY, true);
drawFilesJelly = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_JELLY, false);
background = cfg.getBackground().getRGB();
// Ensure we have sane values.
EDGE_LIFE_INIT = cfg.getPositiveIntProperty(CodeSwarmConfig.EDGE_LIFE_KEY,255);
FILE_LIFE_INIT = cfg.getPositiveIntProperty(CodeSwarmConfig.FILE_LIFE_KEY,255);
PERSON_LIFE_INIT = cfg.getPositiveIntProperty(CodeSwarmConfig.PERSON_LIFE_KEY,255);
UPDATE_DELTA = cfg.getIntProperty("testsets"/*CodeSwarmConfig.MSEC_PER_FRAME_KEY*/, -1);
/* enforce decrements < 0 */
EDGE_LIFE_DECREMENT = cfg.getNegativeIntProperty(CodeSwarmConfig.EDGE_DECREMENT_KEY,-2);
FILE_LIFE_DECREMENT = cfg.getNegativeIntProperty(CodeSwarmConfig.FILE_DECREMENT_KEY,-2);
PERSON_LIFE_DECREMENT = cfg.getNegativeIntProperty(CodeSwarmConfig.PERSON_DECREMENT_KEY,-1);
DEFAULT_NODE_SPEED = cfg.getFloatProperty(CodeSwarmConfig.NODE_SPEED_KEY, 7.0f);
DEFAULT_FILE_SPEED = cfg.getFloatProperty(CodeSwarmConfig.FILE_SPEED_KEY, DEFAULT_NODE_SPEED);
DEFAULT_PERSON_SPEED = cfg.getFloatProperty(CodeSwarmConfig.PERSON_SPEED_KEY, DEFAULT_NODE_SPEED);
FILE_MASS = cfg.getFloatProperty(CodeSwarmConfig.FILE_MASS_KEY,1.0f);
PERSON_MASS = cfg.getFloatProperty(CodeSwarmConfig.PERSON_MASS_KEY,1.0f);
HIGHLIGHT_PCT = cfg.getIntProperty(CodeSwarmConfig.HIGHLIGHT_PCT_KEY,5);
if (HIGHLIGHT_PCT < 0 || HIGHLIGHT_PCT > 100) {
HIGHLIGHT_PCT = 5;
}
UPDATE_DELTA = cfg.getIntProperty(CodeSwarmConfig.MSEC_PER_FRAME_KEY, -1);
if (UPDATE_DELTA == -1) {
int framesperday = cfg.getIntProperty(CodeSwarmConfig.FRAMES_PER_DAY_KEY, 4);
if (framesperday > 0) {
UPDATE_DELTA = (long) (86400000 / framesperday);
}
}
if (UPDATE_DELTA <= 0) {
// Default to 4 frames per day.
UPDATE_DELTA = 21600000;
}
isInputSorted = cfg.getBooleanProperty(CodeSwarmConfig.IS_INPUT_SORTED_KEY, false);
/**
* This section loads config files and calls the setup method for all physics engines.
*/
physicsEngineConfigDir = cfg.getStringProperty( CodeSwarmConfig.PHYSICS_ENGINE_CONF_DIR, "physics_engine");
File f = new File(physicsEngineConfigDir);
String[] configFiles = null;
if ( f.exists() && f.isDirectory() ) {
configFiles = f.list();
}
for (int i=0; configFiles != null && i<configFiles.length; i++) {
if (configFiles[i].endsWith(".config")) {
String ConfigPath = physicsEngineConfigDir + System.getProperty("file.separator") + configFiles[i];
CodeSwarmConfig physicsConfig = null;
try {
physicsConfig = new CodeSwarmConfig(ConfigPath);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
String ClassName = physicsConfig.getStringProperty("name", "__DEFAULT__");
if ( ! ClassName.equals("__DEFAULT__")) {
PhysicsEngine pe = getPhysicsEngine(ClassName);
pe.setup(physicsConfig);
peConfig pec = new peConfig(ClassName,pe);
mPhysicsEngineChoices.add(pec);
} else {
System.out.println("Skipping config file '" + ConfigPath + "'. Must specify class name via the 'name' parameter.");
System.exit(1);
}
}
}
if (mPhysicsEngineChoices.size() == 0) {
System.out.println("No physics engine config files found in '" + physicsEngineConfigDir + "'.");
System.exit(1);
}
// Physics engine configuration and instantiation
physicsEngineSelection = cfg.getStringProperty( CodeSwarmConfig.PHYSICS_ENGINE_SELECTION, PHYSICS_ENGINE_LEGACY );
for (peConfig p : mPhysicsEngineChoices) {
if (physicsEngineSelection.equals(p.name)) {
mPhysicsEngine = p.pe;
}
}
if (mPhysicsEngine == null) {
System.out.println("No physics engine matches your choice of '" + physicsEngineSelection + "'. Check '" + physicsEngineConfigDir + "' for options.");
System.exit(1);
}
smooth();
frameRate(FRAME_RATE);
// init data structures
nodes = new CopyOnWriteArrayList<FileNode>();
edges = new CopyOnWriteArrayList<Edge>();
people = new CopyOnWriteArrayList<PersonNode>();
history = new LinkedList<ColorBins>();
if (isInputSorted)
//If the input is sorted, we only need to store the next few events
eventsQueue = new ArrayBlockingQueue<FileEvent>(5000);
else
//Otherwise we need to store them all at once in a data structure that will sort them
eventsQueue = new PriorityBlockingQueue<FileEvent>();
// Init color map
initColors();
loadRepEvents(cfg.getStringProperty(CodeSwarmConfig.INPUT_FILE_KEY)); // event formatted (this is the standard)
while(!finishedLoading && eventsQueue.isEmpty());
if(eventsQueue.isEmpty()){
System.out.println("No events found in repository xml file.");
System.exit(1);
}
prevDate = eventsQueue.peek().date;
SCREENSHOT_FILE = cfg.getStringProperty(CodeSwarmConfig.SNAPSHOT_LOCATION_KEY);
EDGE_LEN = cfg.getPositiveIntProperty(CodeSwarmConfig.EDGE_LENGTH_KEY, 25);
maxFramesSaved = (int) Math.pow(10, SCREENSHOT_FILE.replaceAll("[^#]","").length());
// Create fonts
String fontName = cfg.getStringProperty(CodeSwarmConfig.FONT_KEY,"SansSerif");
Integer fontSize = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE, 10);
Integer fontSizeBold = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE_BOLD, 14);
font = createFont(fontName, fontSize);
boldFont = createFont(fontName + ".bold", fontSizeBold);
textFont(font);
String SPRITE_FILE = cfg.getStringProperty(CodeSwarmConfig.SPRITE_FILE_KEY);
// Create the file particle image
sprite = loadImage(SPRITE_FILE);
// Add translucency (using itself in this case)
sprite.mask(sprite);
}
|
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Resource.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Resource.java
index b12f64daf..5f7fa3807 100644
--- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Resource.java
+++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Resource.java
@@ -1,1690 +1,1690 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 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
* Dan Rubel <[email protected]> - Implementation of getLocalTimeStamp
* Red Hat Incorporated - get/setResourceAttribute code
*******************************************************************************/
package org.eclipse.core.internal.resources;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import org.eclipse.core.filesystem.*;
import org.eclipse.core.internal.events.LifecycleEvent;
import org.eclipse.core.internal.localstore.FileSystemResourceManager;
import org.eclipse.core.internal.properties.IPropertyManager;
import org.eclipse.core.internal.utils.*;
import org.eclipse.core.internal.watson.*;
import org.eclipse.core.resources.*;
import org.eclipse.core.resources.team.IMoveDeleteHook;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.MultiRule;
import org.eclipse.osgi.util.NLS;
public abstract class Resource extends PlatformObject implements IResource, ICoreConstants, Cloneable, IPathRequestor {
/* package */IPath path;
/* package */Workspace workspace;
protected Resource(IPath path, Workspace workspace) {
this.path = path.removeTrailingSeparator();
this.workspace = workspace;
}
/* (non-Javadoc)
* @see IResource#accept(IResourceProxyVisitor, int)
*/
public void accept(final IResourceProxyVisitor visitor, final int memberFlags) throws CoreException {
// it is invalid to call accept on a phantom when INCLUDE_PHANTOMS is not specified
final boolean includePhantoms = (memberFlags & IContainer.INCLUDE_PHANTOMS) != 0;
checkAccessible(getFlags(getResourceInfo(includePhantoms, false)));
final ResourceProxy proxy = new ResourceProxy();
IElementContentVisitor elementVisitor = new IElementContentVisitor() {
public boolean visitElement(ElementTree tree, IPathRequestor requestor, Object contents) {
ResourceInfo info = (ResourceInfo) contents;
if (!isMember(getFlags(info), memberFlags))
return false;
proxy.requestor = requestor;
proxy.info = info;
try {
return visitor.visit(proxy);
} catch (CoreException e) {
//throw an exception to bail out of the traversal
throw new WrappedRuntimeException(e);
} finally {
proxy.reset();
}
}
};
try {
new ElementTreeIterator(workspace.getElementTree(), getFullPath()).iterate(elementVisitor);
} catch (WrappedRuntimeException e) {
throw (CoreException) e.getTargetException();
} catch (OperationCanceledException e) {
throw e;
} catch (RuntimeException e) {
String msg = Messages.resources_errorVisiting;
IResourceStatus errorStatus = new ResourceStatus(IResourceStatus.INTERNAL_ERROR, getFullPath(), msg, e);
Policy.log(errorStatus);
throw new ResourceException(errorStatus);
} finally {
proxy.requestor = null;
proxy.info = null;
}
}
/* (non-Javadoc)
* @see IResource#accept(IResourceVisitor)
*/
public void accept(IResourceVisitor visitor) throws CoreException {
accept(visitor, IResource.DEPTH_INFINITE, 0);
}
/* (non-Javadoc)
* @see IResource#accept(IResourceVisitor, int, boolean)
*/
public void accept(IResourceVisitor visitor, int depth, boolean includePhantoms) throws CoreException {
accept(visitor, depth, includePhantoms ? IContainer.INCLUDE_PHANTOMS : 0);
}
/* (non-Javadoc)
* @see IResource#accept(IResourceVisitor, int, int)
*/
public void accept(final IResourceVisitor visitor, int depth, int memberFlags) throws CoreException {
//use the fast visitor if visiting to infinite depth
if (depth == IResource.DEPTH_INFINITE) {
accept(new IResourceProxyVisitor() {
public boolean visit(IResourceProxy proxy) throws CoreException {
return visitor.visit(proxy.requestResource());
}
}, memberFlags);
return;
}
// it is invalid to call accept on a phantom when INCLUDE_PHANTOMS is not specified
final boolean includePhantoms = (memberFlags & IContainer.INCLUDE_PHANTOMS) != 0;
ResourceInfo info = getResourceInfo(includePhantoms, false);
int flags = getFlags(info);
checkAccessible(flags);
//check that this resource matches the member flags
if (!isMember(flags, memberFlags))
return;
// visit this resource
if (!visitor.visit(this) || depth == DEPTH_ZERO)
return;
// get the info again because it might have been changed by the visitor
info = getResourceInfo(includePhantoms, false);
if (info == null)
return;
// thread safety: (cache the type to avoid changes -- we might not be inside an operation)
int type = info.getType();
if (type == FILE)
return;
// if we had a gender change we need to fix up the resource before asking for its members
IContainer resource = getType() != type ? (IContainer) workspace.newResource(getFullPath(), type) : (IContainer) this;
IResource[] members = resource.members(memberFlags);
for (int i = 0; i < members.length; i++)
members[i].accept(visitor, DEPTH_ZERO, memberFlags);
}
protected void assertCopyRequirements(IPath destination, int destinationType, int updateFlags) throws CoreException {
IStatus status = checkCopyRequirements(destination, destinationType, updateFlags);
if (!status.isOK()) {
// this assert is ok because the error cases generated by the
// check method above indicate assertion conditions.
Assert.isTrue(false, status.getChildren()[0].getMessage());
}
}
protected void assertLinkRequirements(URI localLocation, int updateFlags) throws CoreException {
boolean allowMissingLocal = (updateFlags & IResource.ALLOW_MISSING_LOCAL) != 0;
if ((updateFlags & IResource.REPLACE) == 0)
checkDoesNotExist(getFlags(getResourceInfo(false, false)), true);
IStatus locationStatus = workspace.validateLinkLocationURI(this, localLocation);
//we only tolerate an undefined path variable in the allow missing local case
final boolean variableUndefined = locationStatus.getCode() == IResourceStatus.VARIABLE_NOT_DEFINED_WARNING;
if (locationStatus.getSeverity() == IStatus.ERROR || (variableUndefined && !allowMissingLocal))
throw new ResourceException(locationStatus);
//check that the parent exists and is open
Container parent = (Container) getParent();
parent.checkAccessible(getFlags(parent.getResourceInfo(false, false)));
//if the variable is undefined we can't do any further checks
if (variableUndefined)
return;
//check if the file exists
URI resolved = workspace.getPathVariableManager().resolveURI(localLocation);
IFileStore store = EFS.getStore(resolved);
IFileInfo fileInfo = store.fetchInfo();
boolean localExists = fileInfo.exists();
if (!allowMissingLocal && !localExists) {
String msg = NLS.bind(Messages.links_localDoesNotExist, store.toString());
throw new ResourceException(IResourceStatus.NOT_FOUND_LOCAL, getFullPath(), msg, null);
}
//resource type and file system type must match
if (localExists && ((getType() == IResource.FOLDER) != fileInfo.isDirectory())) {
String msg = NLS.bind(Messages.links_wrongLocalType, getFullPath());
throw new ResourceException(IResourceStatus.WRONG_TYPE_LOCAL, getFullPath(), msg, null);
}
}
protected void assertMoveRequirements(IPath destination, int destinationType, int updateFlags) throws CoreException {
IStatus status = checkMoveRequirements(destination, destinationType, updateFlags);
if (!status.isOK()) {
// this assert is ok because the error cases generated by the
// check method above indicate assertion conditions.
Assert.isTrue(false, status.getChildren()[0].getMessage());
}
}
public void checkAccessible(int flags) throws CoreException {
checkExists(flags, true);
}
/**
* This method reports errors in two different ways. It can throw a
* CoreException or return a status. CoreExceptions are used according to the
* specification of the copy method. Programming errors, that would usually be
* prevented by using an "Assert" code, are reported as an IStatus. We're doing
* this way because we have two different methods to copy resources:
* IResource#copy and IWorkspace#copy. The first one gets the error and throws
* its message in an AssertionFailureException. The second one just throws a
* CoreException using the status returned by this method.
*
* @see IResource#copy(IPath, int, IProgressMonitor)
*/
public IStatus checkCopyRequirements(IPath destination, int destinationType, int updateFlags) throws CoreException {
String message = Messages.resources_copyNotMet;
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INVALID_VALUE, message, null);
if (destination == null) {
message = Messages.resources_destNotNull;
return new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message);
}
destination = makePathAbsolute(destination);
if (getFullPath().isPrefixOf(destination)) {
message = NLS.bind(Messages.resources_copyDestNotSub, getFullPath());
status.add(new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message));
}
checkValidPath(destination, destinationType, false);
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_INFINITE);
Resource dest = workspace.newResource(destination, destinationType);
dest.checkDoesNotExist();
// ensure we aren't trying to copy a file to a project
if (getType() == IResource.FILE && destinationType == IResource.PROJECT) {
message = Messages.resources_fileToProj;
throw new ResourceException(IResourceStatus.INVALID_VALUE, getFullPath(), message, null);
}
// we can't copy into a closed project
if (destinationType != IResource.PROJECT) {
Project project = (Project) dest.getProject();
info = project.getResourceInfo(false, false);
project.checkAccessible(getFlags(info));
Container parent = (Container) dest.getParent();
if (!parent.equals(project)) {
info = parent.getResourceInfo(false, false);
parent.checkExists(getFlags(info), true);
}
}
if (isUnderLink() || dest.isUnderLink()) {
//make sure location is not null. This can occur with linked resources relative to
//undefined path variables
URI sourceLocation = getLocationURI();
if (sourceLocation == null) {
message = NLS.bind(Messages.localstore_locationUndefined, getFullPath());
throw new ResourceException(IResourceStatus.FAILED_READ_LOCAL, getFullPath(), message, null);
}
URI destLocation = dest.getLocationURI();
if (destLocation == null) {
message = NLS.bind(Messages.localstore_locationUndefined, dest.getFullPath());
throw new ResourceException(IResourceStatus.FAILED_READ_LOCAL, dest.getFullPath(), message, null);
}
//make sure location of source is not a prefix of the location of the destination
//this can occur if the source and/or destination is a linked resource
if (getStore().isParentOf(dest.getStore())) {
message = NLS.bind(Messages.resources_copyDestNotSub, getFullPath());
throw new ResourceException(IResourceStatus.INVALID_VALUE, getFullPath(), message, null);
}
}
return status.isOK() ? Status.OK_STATUS : (IStatus) status;
}
/**
* Checks that this resource does not exist. If the file system is not case
* sensitive, this method also checks for a case variant.
*/
protected void checkDoesNotExist() throws CoreException {
checkDoesNotExist(getFlags(getResourceInfo(false, false)), false);
}
/**
* Checks that this resource does not exist. If the file system is not case
* sensitive, this method also checks for a case variant.
*
* @exception CoreException if this resource exists
*/
public void checkDoesNotExist(int flags, boolean checkType) throws CoreException {
//if this exact resource exists we are done
if (exists(flags, checkType)) {
String message = NLS.bind(Messages.resources_mustNotExist, getFullPath());
throw new ResourceException(checkType ? IResourceStatus.RESOURCE_EXISTS : IResourceStatus.PATH_OCCUPIED, getFullPath(), message, null);
}
if (Workspace.caseSensitive)
return;
//now look for a matching case variant in the tree
IResource variant = findExistingResourceVariant(getFullPath());
if (variant == null)
return;
String msg = NLS.bind(Messages.resources_existsDifferentCase, variant.getFullPath());
throw new ResourceException(IResourceStatus.CASE_VARIANT_EXISTS, variant.getFullPath(), msg, null);
}
/**
* Checks that this resource exists.
* If checkType is true, the type of this resource and the one in the tree must match.
*
* @exception CoreException if this resource does not exist
*/
public void checkExists(int flags, boolean checkType) throws CoreException {
if (!exists(flags, checkType)) {
String message = NLS.bind(Messages.resources_mustExist, getFullPath());
throw new ResourceException(IResourceStatus.RESOURCE_NOT_FOUND, getFullPath(), message, null);
}
}
/**
* Checks that this resource is local to the given depth.
*
* @exception CoreException if this resource is not local
*/
public void checkLocal(int flags, int depth) throws CoreException {
if (!isLocal(flags, depth)) {
String message = NLS.bind(Messages.resources_mustBeLocal, getFullPath());
throw new ResourceException(IResourceStatus.RESOURCE_NOT_LOCAL, getFullPath(), message, null);
}
}
/**
* This method reports errors in two different ways. It can throw a
* CoreException or log a status. CoreExceptions are used according
* to the specification of the move method. Programming errors, that
* would usually be prevented by using an "Assert" code, are reported as
* an IStatus.
* We're doing this way because we have two different methods to move
* resources: IResource#move and IWorkspace#move. The first one gets
* the error and throws its message in an AssertionFailureException. The
* second one just throws a CoreException using the status returned
* by this method.
*
* @see IResource#move(IPath, int, IProgressMonitor)
*/
protected IStatus checkMoveRequirements(IPath destination, int destinationType, int updateFlags) throws CoreException {
String message = Messages.resources_moveNotMet;
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INVALID_VALUE, message, null);
if (destination == null) {
message = Messages.resources_destNotNull;
return new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message);
}
destination = makePathAbsolute(destination);
if (getFullPath().isPrefixOf(destination)) {
message = NLS.bind(Messages.resources_moveDestNotSub, getFullPath());
status.add(new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message));
}
checkValidPath(destination, destinationType, false);
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_INFINITE);
Resource dest = workspace.newResource(destination, destinationType);
// check if we are only changing case
IResource variant = Workspace.caseSensitive ? null : findExistingResourceVariant(destination);
if (variant == null || !this.equals(variant))
dest.checkDoesNotExist();
// ensure we aren't trying to move a file to a project
if (getType() == IResource.FILE && dest.getType() == IResource.PROJECT) {
message = Messages.resources_fileToProj;
throw new ResourceException(new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message));
}
// we can't move into a closed project
if (destinationType != IResource.PROJECT) {
Project project = (Project) dest.getProject();
info = project.getResourceInfo(false, false);
project.checkAccessible(getFlags(info));
Container parent = (Container) dest.getParent();
if (!parent.equals(project)) {
info = parent.getResourceInfo(false, false);
parent.checkExists(getFlags(info), true);
}
}
if (isUnderLink() || dest.isUnderLink()) {
//make sure location is not null. This can occur with linked resources relative to
//undefined path variables
- IPath sourceLocation = getLocation();
+ URI sourceLocation = getLocationURI();
if (sourceLocation == null) {
message = NLS.bind(Messages.localstore_locationUndefined, getFullPath());
throw new ResourceException(IResourceStatus.FAILED_READ_LOCAL, getFullPath(), message, null);
}
- IPath destLocation = dest.getLocation();
+ URI destLocation = dest.getLocationURI();
if (destLocation == null) {
message = NLS.bind(Messages.localstore_locationUndefined, dest.getFullPath());
throw new ResourceException(IResourceStatus.FAILED_READ_LOCAL, dest.getFullPath(), message, null);
}
//make sure location of source is not a prefix of the location of the destination
- //this can occur if the source or destination is a linked resource
- if (sourceLocation.isPrefixOf(destLocation)) {
+ //this can occur if the source and/or destination is a linked resource
+ if (getStore().isParentOf(dest.getStore())) {
message = NLS.bind(Messages.resources_moveDestNotSub, getFullPath());
throw new ResourceException(IResourceStatus.INVALID_VALUE, getFullPath(), message, null);
}
}
return status.isOK() ? Status.OK_STATUS : (IStatus) status;
}
/**
* Checks that the supplied path is valid according to Workspace.validatePath().
*
* @exception CoreException if the path is not valid
*/
public void checkValidPath(IPath toValidate, int type, boolean lastSegmentOnly) throws CoreException {
IStatus result = workspace.locationValidator.validatePath(toValidate, type, lastSegmentOnly);
if (!result.isOK())
throw new ResourceException(result);
}
/* (non-Javadoc)
* @see IResource#clearHistory(IProgressMonitor)
*/
public void clearHistory(IProgressMonitor monitor) {
getLocalManager().getHistoryStore().remove(getFullPath(), monitor);
}
/*
* (non-Javadoc)
* @see ISchedulingRule#contains(ISchedulingRule)
*/
public boolean contains(ISchedulingRule rule) {
if (this == rule)
return true;
//must allow notifications to nest in all resource rules
if (rule.getClass().equals(WorkManager.NotifyRule.class))
return true;
if (rule instanceof MultiRule) {
MultiRule multi = (MultiRule) rule;
ISchedulingRule[] children = multi.getChildren();
for (int i = 0; i < children.length; i++)
if (!contains(children[i]))
return false;
return true;
}
if (!(rule instanceof IResource))
return false;
return path.isPrefixOf(((IResource) rule).getFullPath());
}
public void convertToPhantom() throws CoreException {
ResourceInfo info = getResourceInfo(false, true);
if (info == null || isPhantom(getFlags(info)))
return;
info.clearSessionProperties();
info.set(M_PHANTOM);
getLocalManager().updateLocalSync(info, I_NULL_SYNC_INFO);
info.clearModificationStamp();
// should already be done by the #deleteResource call but left in
// just to be safe and for code clarity.
info.setMarkers(null);
}
/* (non-Javadoc)
* @see IResource#copy(IPath, boolean, IProgressMonitor)
*/
public void copy(IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
copy(destination, updateFlags, monitor);
}
/* (non-Javadoc)
* @see IResource#copy(IPath, int, IProgressMonitor)
*/
public void copy(IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {
try {
monitor = Policy.monitorFor(monitor);
String message = NLS.bind(Messages.resources_copying, getFullPath());
monitor.beginTask(message, Policy.totalWork);
Policy.checkCanceled(monitor);
destination = makePathAbsolute(destination);
checkValidPath(destination, getType(), false);
Resource destResource = workspace.newResource(destination, getType());
final ISchedulingRule rule = workspace.getRuleFactory().copyRule(this, destResource);
try {
workspace.prepareOperation(rule, monitor);
// The following assert method throws CoreExceptions as stated in the IResource.copy API
// and assert for programming errors. See checkCopyRequirements for more information.
assertCopyRequirements(destination, getType(), updateFlags);
workspace.beginOperation(true);
getLocalManager().copy(this, destResource, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork));
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} finally {
workspace.endOperation(rule, true, Policy.subMonitorFor(monitor, Policy.endOpWork));
}
} finally {
monitor.done();
}
}
/* (non-Javadoc)
* @see IResource#copy(IProjectDescription, boolean, IProgressMonitor)
*/
public void copy(IProjectDescription destDesc, boolean force, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
copy(destDesc, updateFlags, monitor);
}
/* (non-Javadoc)
* Used when a folder is to be copied to a project.
* @see IResource#copy(IProjectDescription, int, IProgressMonitor)
*/
public void copy(IProjectDescription destDesc, int updateFlags, IProgressMonitor monitor) throws CoreException {
Assert.isNotNull(destDesc);
monitor = Policy.monitorFor(monitor);
try {
String message = NLS.bind(Messages.resources_copying, getFullPath());
monitor.beginTask(message, Policy.totalWork);
try {
workspace.prepareOperation(workspace.getRoot(), monitor);
// The following assert method throws CoreExceptions as stated in the IResource.copy API
// and assert for programming errors. See checkCopyRequirements for more information.
IPath destPath = new Path(destDesc.getName()).makeAbsolute();
assertCopyRequirements(destPath, getType(), updateFlags);
Project destProject = (Project) workspace.getRoot().getProject(destPath.lastSegment());
workspace.beginOperation(true);
// create and open the new project
destProject.create(destDesc, Policy.subMonitorFor(monitor, Policy.opWork * 5 / 100));
destProject.open(Policy.subMonitorFor(monitor, Policy.opWork * 5 / 100));
// copy the children
// FIXME: fix the progress monitor here...create a sub monitor and do a worked(1) after each child instead
IResource[] children = ((IContainer) this).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS);
for (int i = 0; i < children.length; i++) {
Resource child = (Resource) children[i];
child.copy(destPath.append(child.getName()), updateFlags, Policy.subMonitorFor(monitor, Policy.opWork * 60 / 100 / children.length));
}
// copy over the properties
getPropertyManager().copy(this, destProject, DEPTH_ZERO);
monitor.worked(Policy.opWork * 15 / 100);
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} finally {
workspace.endOperation(workspace.getRoot(), true, Policy.subMonitorFor(monitor, Policy.endOpWork));
}
} finally {
monitor.done();
}
}
/**
* Count the number of resources in the tree from this container to the
* specified depth. Include this resource. Include phantoms if
* the phantom boolean is true.
*/
public int countResources(int depth, boolean phantom) {
return workspace.countResources(path, depth, phantom);
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.IFolder#createLink(IPath, int, IProgressMonitor)
* @see org.eclipse.core.resources.IFile#createLink(IPath, int, IProgressMonitor)
*/
public void createLink(IPath localLocation, int updateFlags, IProgressMonitor monitor) throws CoreException {
Assert.isNotNull(localLocation);
createLink(URIUtil.toURI(localLocation), updateFlags, monitor);
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.IFolder#createLink(URI, int, IProgressMonitor)
* @see org.eclipse.core.resources.IFile#createLink(URI, int, IProgressMonitor)
*/
public void createLink(URI localLocation, int updateFlags, IProgressMonitor monitor) throws CoreException {
Assert.isNotNull(localLocation);
monitor = Policy.monitorFor(monitor);
try {
String message = NLS.bind(Messages.links_creating, getFullPath());
monitor.beginTask(message, Policy.totalWork);
Policy.checkCanceled(monitor);
checkValidPath(path, FOLDER, true);
final ISchedulingRule rule = workspace.getRuleFactory().createRule(this);
try {
workspace.prepareOperation(rule, monitor);
assertLinkRequirements(localLocation, updateFlags);
workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_LINK_CREATE, this));
workspace.beginOperation(true);
//replace existing resource, if applicable
if ((updateFlags & REPLACE) != 0) {
IResource existing = workspace.getRoot().findMember(getFullPath());
if (existing != null)
workspace.deleteResource(existing);
}
ResourceInfo info = workspace.createResource(this, false);
info.set(M_LINK);
localLocation = FileUtil.canonicalURI(localLocation);
getLocalManager().link(this, localLocation);
monitor.worked(Policy.opWork * 5 / 100);
//save the location in the project description
Project project = (Project) getProject();
project.internalGetDescription().setLinkLocation(getProjectRelativePath(), new LinkDescription(this, localLocation));
project.writeDescription(IResource.NONE);
monitor.worked(Policy.opWork * 5 / 100);
//refresh to discover any new resources below this linked location
if (getType() != IResource.FILE)
refreshLocal(DEPTH_INFINITE, Policy.subMonitorFor(monitor, Policy.opWork * 90 / 100));
else
monitor.worked(Policy.opWork * 90 / 100);
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} finally {
workspace.endOperation(rule, true, Policy.subMonitorFor(monitor, Policy.endOpWork));
}
} finally {
monitor.done();
}
}
/* (non-Javadoc)
* @see IResource#createMarker(String)
*/
public IMarker createMarker(String type) throws CoreException {
Assert.isNotNull(type);
final ISchedulingRule rule = workspace.getRuleFactory().markerRule(this);
try {
workspace.prepareOperation(rule, null);
checkAccessible(getFlags(getResourceInfo(false, false)));
workspace.beginOperation(true);
MarkerInfo info = new MarkerInfo();
info.setType(type);
info.setCreationTime(System.currentTimeMillis());
workspace.getMarkerManager().add(this, info);
return new Marker(this, info.getId());
} finally {
workspace.endOperation(rule, false, null);
}
}
public IResourceProxy createProxy() {
ResourceProxy result = new ResourceProxy();
result.info = getResourceInfo(false, false);
result.requestor = this;
result.resource = this;
return result;
}
/* (non-Javadoc)
* @see IProject#delete(boolean, boolean, IProgressMonitor)
* @see IWorkspaceRoot#delete(boolean, boolean, IProgressMonitor)
* N.B. This is not an IResource method!
*/
public void delete(boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
updateFlags |= keepHistory ? IResource.KEEP_HISTORY : IResource.NONE;
delete(updateFlags, monitor);
}
/* (non-Javadoc)
* @see IResource#delete(boolean, IProgressMonitor)
*/
public void delete(boolean force, IProgressMonitor monitor) throws CoreException {
delete(force ? IResource.FORCE : IResource.NONE, monitor);
}
/* (non-Javadoc)
* @see IResource#delete(int, IProgressMonitor)
*/
public void delete(int updateFlags, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
String message = NLS.bind(Messages.resources_deleting, getFullPath());
monitor.beginTask("", Policy.totalWork * 1000); //$NON-NLS-1$
monitor.subTask(message);
final ISchedulingRule rule = workspace.getRuleFactory().deleteRule(this);
try {
workspace.prepareOperation(rule, monitor);
// if there is no resource then there is nothing to delete so just return
if (!exists())
return;
workspace.beginOperation(true);
final IFileStore originalStore = getStore();
boolean wasLinked = isLinked();
message = Messages.resources_deleteProblem;
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_DELETE_LOCAL, message, null);
WorkManager workManager = workspace.getWorkManager();
ResourceTree tree = new ResourceTree(workspace.getFileSystemManager(), workManager.getLock(), status, updateFlags);
int depth = 0;
try {
depth = workManager.beginUnprotected();
unprotectedDelete(tree, updateFlags, monitor);
} finally {
workManager.endUnprotected(depth);
}
if (getType() == ROOT) {
// need to clear out the root info
workspace.getMarkerManager().removeMarkers(this, IResource.DEPTH_ZERO);
getPropertyManager().deleteProperties(this, IResource.DEPTH_ZERO);
getResourceInfo(false, false).clearSessionProperties();
}
// Invalidate the tree for further use by clients.
tree.makeInvalid();
if (!tree.getStatus().isOK())
throw new ResourceException(tree.getStatus());
//update any aliases of this resource
//note that deletion of a linked resource cannot affect other resources
if (!wasLinked)
workspace.getAliasManager().updateAliases(this, originalStore, IResource.DEPTH_INFINITE, monitor);
//make sure the rule factory is cleared on project deletion
if (getType() == PROJECT)
((Rules) workspace.getRuleFactory()).setRuleFactory((IProject) this, null);
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} finally {
workspace.endOperation(rule, true, Policy.subMonitorFor(monitor, Policy.endOpWork * 1000));
}
} finally {
monitor.done();
}
}
/* (non-Javadoc)
* @see IResource#deleteMarkers(String, boolean, int)
*/
public void deleteMarkers(String type, boolean includeSubtypes, int depth) throws CoreException {
final ISchedulingRule rule = workspace.getRuleFactory().markerRule(this);
try {
workspace.prepareOperation(rule, null);
ResourceInfo info = getResourceInfo(false, false);
checkAccessible(getFlags(info));
workspace.beginOperation(true);
workspace.getMarkerManager().removeMarkers(this, type, includeSubtypes, depth);
} finally {
workspace.endOperation(rule, false, null);
}
}
/**
* This method should be called to delete a resource from the tree because it will also
* delete its properties and markers. If a status object is provided, minor exceptions are
* added, otherwise they are thrown. If major exceptions occur, they are always thrown.
*/
public void deleteResource(boolean convertToPhantom, MultiStatus status) throws CoreException {
// remove markers on this resource and its descendents
if (exists())
getMarkerManager().removeMarkers(this, IResource.DEPTH_INFINITE);
// if this is a linked resource, remove the entry from the project description
final boolean wasLinked = isLinked();
//pre-delete notification to internal infrastructure
if (wasLinked)
workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_LINK_DELETE, this));
// check if we deleted a preferences file
ProjectPreferences.deleted(this);
/* if we are synchronizing, do not delete the resource. Convert it
into a phantom. Actual deletion will happen when we refresh or push. */
if (convertToPhantom && getType() != PROJECT && synchronizing(getResourceInfo(true, false)))
convertToPhantom();
else
workspace.deleteResource(this);
//update project description for linked resource
if (wasLinked) {
Project project = (Project) getProject();
ProjectDescription description = project.internalGetDescription();
description.setLinkLocation(getProjectRelativePath(), null);
project.internalSetDescription(description, true);
project.writeDescription(IResource.FORCE);
}
// Delete properties after the resource is deleted from the tree. See bug 84584.
CoreException err = null;
try {
getPropertyManager().deleteResource(this);
} catch (CoreException e) {
if (status != null)
status.add(e.getStatus());
else
err = e;
}
if (err != null)
throw err;
}
/* (non-Javadoc)
* @see IResource#equals(Object)
*/
public boolean equals(Object target) {
if (this == target)
return true;
if (!(target instanceof Resource))
return false;
Resource resource = (Resource) target;
return getType() == resource.getType() && path.equals(resource.path) && workspace.equals(resource.workspace);
}
/* (non-Javadoc)
* @see IResource#exists()
*/
public boolean exists() {
ResourceInfo info = getResourceInfo(false, false);
return exists(getFlags(info), true);
}
public boolean exists(int flags, boolean checkType) {
return flags != NULL_FLAG && !(checkType && ResourceInfo.getType(flags) != getType());
}
/**
* Helper method for case insensitive file systems. Returns
* an existing resource whose path differs only in case from
* the given path, or null if no such resource exists.
*/
public IResource findExistingResourceVariant(IPath target) {
if (!workspace.tree.includesIgnoreCase(target))
return null;
//ignore phantoms
ResourceInfo info = (ResourceInfo) workspace.tree.getElementDataIgnoreCase(target);
if (info != null && info.isSet(M_PHANTOM))
return null;
//resort to slow lookup to find exact case variant
IPath result = Path.ROOT;
int segmentCount = target.segmentCount();
for (int i = 0; i < segmentCount; i++) {
String[] childNames = workspace.tree.getNamesOfChildren(result);
String name = findVariant(target.segment(i), childNames);
if (name == null)
return null;
result = result.append(name);
}
return workspace.getRoot().findMember(result);
}
/* (non-Javadoc)
* @see IResource#findMarker(long)
*/
public IMarker findMarker(long id) {
return workspace.getMarkerManager().findMarker(this, id);
}
/* (non-Javadoc)
* @see IResource#findMarkers(String, boolean, int)
*/
public IMarker[] findMarkers(String type, boolean includeSubtypes, int depth) throws CoreException {
ResourceInfo info = getResourceInfo(false, false);
checkAccessible(getFlags(info));
// It might happen that from this point the resource is not accessible anymore.
// But markers have the #exists method that callers can use to check if it is
// still valid.
return workspace.getMarkerManager().findMarkers(this, type, includeSubtypes, depth);
}
/**
* Searches for a variant of the given target in the list,
* that differs only in case. Returns the variant from
* the list if one is found, otherwise returns null.
*/
private String findVariant(String target, String[] list) {
for (int i = 0; i < list.length; i++) {
if (target.equalsIgnoreCase(list[i]))
return list[i];
}
return null;
}
protected void fixupAfterMoveSource() throws CoreException {
ResourceInfo info = getResourceInfo(true, true);
//if a linked resource is moved, we need to remove the location info from the .project
if (isLinked()) {
Project project = (Project) getProject();
project.internalGetDescription().setLinkLocation(getProjectRelativePath(), null);
project.writeDescription(IResource.NONE);
}
// check if we deleted a preferences file
ProjectPreferences.deleted(this);
if (!synchronizing(info)) {
workspace.deleteResource(this);
return;
}
info.clearSessionProperties();
info.clear(M_LOCAL_EXISTS);
info.setLocalSyncInfo(I_NULL_SYNC_INFO);
info.set(M_PHANTOM);
info.clearModificationStamp();
info.setMarkers(null);
}
/* (non-Javadoc)
* @see IResource#getFileExtension()
*/
public String getFileExtension() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1)
return null;
if (index == (name.length() - 1))
return ""; //$NON-NLS-1$
return name.substring(index + 1);
}
public int getFlags(ResourceInfo info) {
return (info == null) ? NULL_FLAG : info.getFlags();
}
/* (non-Javadoc)
* @see IResource#getFullPath()
*/
public IPath getFullPath() {
return path;
}
public FileSystemResourceManager getLocalManager() {
return workspace.getFileSystemManager();
}
/* (non-Javadoc)
* @see IResource#getLocalTimeStamp()
*/
public long getLocalTimeStamp() {
ResourceInfo info = getResourceInfo(false, false);
return info == null ? IResource.NULL_STAMP : info.getLocalSyncInfo();
}
/* (non-Javadoc)
* @see IResource#getLocation()
*/
public IPath getLocation() {
IProject project = getProject();
if (project != null && !project.exists())
return null;
return getLocalManager().locationFor(this);
}
/* (non-Javadoc)
* @see IResource#getLocation()
*/
public URI getLocationURI() {
IProject project = getProject();
if (project != null && !project.exists())
return null;
return getLocalManager().locationURIFor(this);
}
/* (non-Javadoc)
* @see IResource#getMarker(long)
*/
public IMarker getMarker(long id) {
return new Marker(this, id);
}
protected MarkerManager getMarkerManager() {
return workspace.getMarkerManager();
}
/* (non-Javadoc)
* @see IResource#getModificationStamp()
*/
public long getModificationStamp() {
ResourceInfo info = getResourceInfo(false, false);
return info == null ? IResource.NULL_STAMP : info.getModificationStamp();
}
/* (non-Javadoc)
* @see IResource#getName()
*/
public String getName() {
return path.lastSegment();
}
/* (non-Javadoc)
* @see IResource#getParent()
*/
public IContainer getParent() {
int segments = path.segmentCount();
//zero and one segments handled by subclasses
Assert.isLegal(segments > 1, path.toString());
if (segments == 2)
return workspace.getRoot().getProject(path.segment(0));
return (IFolder) workspace.newResource(path.removeLastSegments(1), IResource.FOLDER);
}
/* (non-Javadoc)
* @see IResource#getPersistentProperty(QualifiedName)
*/
public String getPersistentProperty(QualifiedName key) throws CoreException {
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_ZERO);
return getPropertyManager().getProperty(this, key);
}
/* (non-Javadoc)
* @see IResource#getProject()
*/
public IProject getProject() {
return workspace.getRoot().getProject(path.segment(0));
}
/* (non-Javadoc)
* @see IResource#getProjectRelativePath()
*/
public IPath getProjectRelativePath() {
return getFullPath().removeFirstSegments(ICoreConstants.PROJECT_SEGMENT_LENGTH);
}
public IPropertyManager getPropertyManager() {
return workspace.getPropertyManager();
}
/* (non-Javadoc)
* @see IResource#getRawLocation()
*/
public IPath getRawLocation() {
if (isLinked())
return FileUtil.toPath(((Project) getProject()).internalGetDescription().getLinkLocationURI(getProjectRelativePath()));
return getLocation();
}
/* (non-Javadoc)
* @see IResource#getRawLocation()
*/
public URI getRawLocationURI() {
if (isLinked())
return ((Project) getProject()).internalGetDescription().getLinkLocationURI(getProjectRelativePath());
return getLocationURI();
}
/* (non-Javadoc)
* @see IResource#getResourceAttributes()
*/
public ResourceAttributes getResourceAttributes() {
if (!isAccessible())
return null;
return getLocalManager().attributes(this);
}
/**
* Returns the resource info. Returns null if the resource doesn't exist.
* If the phantom flag is true, phantom resources are considered.
* If the mutable flag is true, a mutable info is returned.
*/
public ResourceInfo getResourceInfo(boolean phantom, boolean mutable) {
return workspace.getResourceInfo(getFullPath(), phantom, mutable);
}
/* (non-Javadoc)
* @see IResource#getSessionProperty(QualifiedName)
*/
public Object getSessionProperty(QualifiedName key) throws CoreException {
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_ZERO);
return info.getSessionProperty(key);
}
public IFileStore getStore() {
return getLocalManager().getStore(this);
}
/* (non-Javadoc)
* @see IResource#getType()
*/
public abstract int getType();
public String getTypeString() {
switch (getType()) {
case FILE :
return "L"; //$NON-NLS-1$
case FOLDER :
return "F"; //$NON-NLS-1$
case PROJECT :
return "P"; //$NON-NLS-1$
case ROOT :
return "R"; //$NON-NLS-1$
}
return ""; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see IResource#getWorkspace()
*/
public IWorkspace getWorkspace() {
return workspace;
}
public int hashCode() {
// the container may be null if the identified resource
// does not exist so don't bother with it in the hash
return getFullPath().hashCode();
}
/**
* Sets the M_LOCAL_EXISTS flag. Is internal so we don't have
* to begin an operation.
*/
protected void internalSetLocal(boolean flag, int depth) throws CoreException {
ResourceInfo info = getResourceInfo(true, true);
//only make the change if it's not already in desired state
if (info.isSet(M_LOCAL_EXISTS) != flag) {
if (flag && !isPhantom(getFlags(info))) {
info.set(M_LOCAL_EXISTS);
workspace.updateModificationStamp(info);
} else {
info.clear(M_LOCAL_EXISTS);
info.clearModificationStamp();
}
}
if (getType() == IResource.FILE || depth == IResource.DEPTH_ZERO)
return;
if (depth == IResource.DEPTH_ONE)
depth = IResource.DEPTH_ZERO;
IResource[] children = ((IContainer) this).members();
for (int i = 0; i < children.length; i++)
((Resource) children[i]).internalSetLocal(flag, depth);
}
/* (non-Javadoc)
* @see IResource#isAccessible()
*/
public boolean isAccessible() {
return exists();
}
/* (non-Javadoc)
* @see ISchedulingRule#isConflicting(ISchedulingRule)
*/
public boolean isConflicting(ISchedulingRule rule) {
//must not schedule at same time as notification
if (rule.getClass().equals(WorkManager.NotifyRule.class))
return true;
if (!(rule instanceof IResource))
return false;
IPath otherPath = ((IResource) rule).getFullPath();
return path.isPrefixOf(otherPath) || otherPath.isPrefixOf(path);
}
/* (non-Javadoc)
* @see IResource#isDerived()
*/
public boolean isDerived() {
ResourceInfo info = getResourceInfo(false, false);
return isDerived(getFlags(info));
}
/**
* Returns whether the derived flag is set in the given resource info flags.
*
* @param flags resource info flags (bitwise or of M_* constants)
* @return <code>true</code> if the derived flag is set, and <code>false</code>
* if the derived flag is not set or if the flags are <code>NULL_FLAG</code>
*/
public boolean isDerived(int flags) {
return flags != NULL_FLAG && ResourceInfo.isSet(flags, ICoreConstants.M_DERIVED);
}
/* (non-Javadoc)
* @see IResource#isLinked()
*/
public boolean isLinked() {
return isLinked(NONE);
}
/* (non-Javadoc)
* @see IResource#isLinked()
*/
public boolean isLinked(int options) {
if ((options & CHECK_ANCESTORS) != 0) {
IProject project = getProject();
if (project == null)
return false;
ProjectDescription desc = ((Project) project).internalGetDescription();
if (desc == null)
return false;
HashMap links = desc.getLinks();
if (links == null)
return false;
IPath myPath = getProjectRelativePath();
for (Iterator it = links.values().iterator(); it.hasNext();) {
if (((LinkDescription) it.next()).getProjectRelativePath().isPrefixOf(myPath))
return true;
}
return false;
}
//the no ancestor checking case
ResourceInfo info = getResourceInfo(false, false);
return info != null && info.isSet(M_LINK);
}
/**
* @see IResource#isLocal(int)
* @deprecated
*/
public boolean isLocal(int depth) {
ResourceInfo info = getResourceInfo(false, false);
return isLocal(getFlags(info), depth);
}
/**
* Note the depth parameter is intentionally ignored because
* this method is over-ridden by Container.isLocal().
* @deprecated
*/
public boolean isLocal(int flags, int depth) {
return flags != NULL_FLAG && ResourceInfo.isSet(flags, M_LOCAL_EXISTS);
}
/**
* Returns whether a resource should be included in a traversal
* based on the provided member flags.
*
* @param flags The resource info flags
* @param memberFlags The member flag mask
* @return Whether the resource is included
*/
protected boolean isMember(int flags, int memberFlags) {
int excludeMask = 0;
if ((memberFlags & IContainer.INCLUDE_PHANTOMS) == 0)
excludeMask |= M_PHANTOM;
if ((memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) == 0)
excludeMask |= M_TEAM_PRIVATE_MEMBER;
if ((memberFlags & IContainer.EXCLUDE_DERIVED) != 0)
excludeMask |= M_DERIVED;
//the resource is a matching member if it matches none of the exclude flags
return flags != NULL_FLAG && (flags & excludeMask) == 0;
}
/* (non-Javadoc)
* @see IResource#isPhantom()
*/
public boolean isPhantom() {
ResourceInfo info = getResourceInfo(true, false);
return isPhantom(getFlags(info));
}
public boolean isPhantom(int flags) {
return flags != NULL_FLAG && ResourceInfo.isSet(flags, M_PHANTOM);
}
/** (non-Javadoc)
* @see IResource#isReadOnly()
* @deprecated
*/
public boolean isReadOnly() {
final ResourceAttributes attributes = getResourceAttributes();
return attributes == null ? false : attributes.isReadOnly();
}
/* (non-Javadoc)
* @see IResource#isSynchronized(int)
*/
public boolean isSynchronized(int depth) {
return getLocalManager().isSynchronized(this, depth);
}
/* (non-Javadoc)
* @see IResource#isTeamPrivateMember()
*/
public boolean isTeamPrivateMember() {
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
return flags != NULL_FLAG && ResourceInfo.isSet(flags, ICoreConstants.M_TEAM_PRIVATE_MEMBER);
}
/**
* Returns true if this resource is a linked resource, or a child of a linked
* resource, and false otherwise.
*/
public boolean isUnderLink() {
int depth = path.segmentCount();
if (depth < 2)
return false;
if (depth == 2)
return isLinked();
//check if parent at depth two is a link
IPath linkParent = path.removeLastSegments(depth - 2);
return workspace.getResourceInfo(linkParent, false, false).isSet(ICoreConstants.M_LINK);
}
protected IPath makePathAbsolute(IPath target) {
if (target.isAbsolute())
return target;
return getParent().getFullPath().append(target);
}
/* (non-Javadoc)
* @see IFile#move(IPath, boolean, boolean, IProgressMonitor)
* @see IFolder#move(IPath, boolean, boolean, IProgressMonitor)
*/
public void move(IPath destination, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
updateFlags |= keepHistory ? IResource.KEEP_HISTORY : IResource.NONE;
move(destination, updateFlags, monitor);
}
/* (non-Javadoc)
* @see IResource#move(IPath, boolean, IProgressMonitor)
*/
public void move(IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {
move(destination, force ? IResource.FORCE : IResource.NONE, monitor);
}
/* (non-Javadoc)
* @see IResource#move(IPath, int, IProgressMonitor)
*/
public void move(IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
String message = NLS.bind(Messages.resources_moving, getFullPath());
monitor.beginTask(message, Policy.totalWork);
Policy.checkCanceled(monitor);
destination = makePathAbsolute(destination);
checkValidPath(destination, getType(), false);
Resource destResource = workspace.newResource(destination, getType());
final ISchedulingRule rule = workspace.getRuleFactory().moveRule(this, destResource);
try {
workspace.prepareOperation(rule, monitor);
// The following assert method throws CoreExceptions as stated in the IResource.move API
// and assert for programming errors. See checkMoveRequirements for more information.
assertMoveRequirements(destination, getType(), updateFlags);
workspace.beginOperation(true);
IFileStore originalStore = getStore();
message = Messages.resources_moveProblem;
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, null);
WorkManager workManager = workspace.getWorkManager();
ResourceTree tree = new ResourceTree(workspace.getFileSystemManager(), workManager.getLock(), status, updateFlags);
boolean success = false;
int depth = 0;
try {
depth = workManager.beginUnprotected();
success = unprotectedMove(tree, destResource, updateFlags, monitor);
} finally {
workManager.endUnprotected(depth);
}
// Invalidate the tree for further use by clients.
tree.makeInvalid();
//update any aliases of this resource and the destination
if (success) {
workspace.getAliasManager().updateAliases(this, originalStore, IResource.DEPTH_INFINITE, monitor);
workspace.getAliasManager().updateAliases(destResource, destResource.getStore(), IResource.DEPTH_INFINITE, monitor);
}
if (!tree.getStatus().isOK())
throw new ResourceException(tree.getStatus());
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} finally {
workspace.endOperation(rule, true, Policy.subMonitorFor(monitor, Policy.endOpWork));
}
} finally {
monitor.done();
}
}
/* (non-Javadoc)
* @see IResource#move(IProjectDescription, boolean, IProgressMonitor)
*/
public void move(IProjectDescription description, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {
int updateFlags = force ? IResource.FORCE : IResource.NONE;
updateFlags |= keepHistory ? IResource.KEEP_HISTORY : IResource.NONE;
move(description, updateFlags, monitor);
}
/* (non-Javadoc)
* @see IResource#move(IPath, int, IProgressMonitor)
*/
public void move(IProjectDescription description, int updateFlags, IProgressMonitor monitor) throws CoreException {
Assert.isNotNull(description);
if (getType() != IResource.PROJECT) {
String message = NLS.bind(Messages.resources_moveNotProject, getFullPath(), description.getName());
throw new ResourceException(IResourceStatus.INVALID_VALUE, getFullPath(), message, null);
}
((Project) this).move(description, updateFlags, monitor);
}
/* (non-Javadoc)
* @see IResource#refreshLocal(int, IProgressMonitor)
*/
public void refreshLocal(int depth, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
boolean isRoot = getType() == ROOT;
String message = isRoot ? Messages.resources_refreshingRoot : NLS.bind(Messages.resources_refreshing, getFullPath());
monitor.beginTask("", Policy.totalWork); //$NON-NLS-1$
monitor.subTask(message);
boolean build = false;
final ISchedulingRule rule = workspace.getRuleFactory().refreshRule(this);
try {
workspace.prepareOperation(rule, monitor);
if (!isRoot && !getProject().isAccessible())
return;
workspace.beginOperation(true);
build = getLocalManager().refresh(this, depth, true, Policy.subMonitorFor(monitor, Policy.opWork));
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} catch (Error e) {
//support to track down Bug 95089
Policy.log(e);
throw e;
} catch (RuntimeException e) {
//support to track down Bug 95089
Policy.log(e);
throw e;
} finally {
workspace.endOperation(rule, build, Policy.subMonitorFor(monitor, Policy.endOpWork));
}
} finally {
monitor.done();
}
}
/* (non-Javadoc)
* Method declared on {@link IPathRequestor}.
*/
public String requestName() {
return getName();
}
/* (non-Javadoc)
* Method declared on {@link IPathRequestor}.
*/
public IPath requestPath() {
return getFullPath();
}
/* (non-Javadoc)
* @see IResource#revertModificationStamp
*/
public void revertModificationStamp(long value) throws CoreException {
if (value < 0)
throw new IllegalArgumentException("Illegal value: " + value); //$NON-NLS-1$
// fetch the info but don't bother making it mutable even though we are going
// to modify it. It really doesn't matter as the change we are doing does not show up in deltas.
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_ZERO);
info.setModificationStamp(value);
}
/* (non-Javadoc)
* @see IResource#setDerived(boolean)
*/
public void setDerived(boolean isDerived) throws CoreException {
// fetch the info but don't bother making it mutable even though we are going
// to modify it. We don't know whether or not the tree is open and it really doesn't
// matter as the change we are doing does not show up in deltas.
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
// ignore attempts to set derived flag on anything except files and folders
if (info.getType() == FILE || info.getType() == FOLDER) {
if (isDerived) {
info.set(ICoreConstants.M_DERIVED);
} else {
info.clear(ICoreConstants.M_DERIVED);
}
}
}
/**
* @see IResource#setLocal(boolean, int, IProgressMonitor)
* @deprecated
*/
public void setLocal(boolean flag, int depth, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
String message = Messages.resources_setLocal;
monitor.beginTask(message, Policy.totalWork);
try {
workspace.prepareOperation(null, monitor);
workspace.beginOperation(true);
internalSetLocal(flag, depth);
monitor.worked(Policy.opWork);
} finally {
workspace.endOperation(null, true, Policy.subMonitorFor(monitor, Policy.endOpWork));
}
} finally {
monitor.done();
}
}
/* (non-Javadoc)
* @see IResource#setLocalTimeStamp(long)
*/
public long setLocalTimeStamp(long value) throws CoreException {
if (value < 0)
throw new IllegalArgumentException("Illegal value: " + value); //$NON-NLS-1$
// fetch the info but don't bother making it mutable even though we are going
// to modify it. It really doesn't matter as the change we are doing does not show up in deltas.
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_ZERO);
return getLocalManager().setLocalTimeStamp(this, info, value);
}
/* (non-Javadoc)
* @see IResource#setPersistentProperty(QualifiedName, String)
*/
public void setPersistentProperty(QualifiedName key, String value) throws CoreException {
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_ZERO);
getPropertyManager().setProperty(this, key, value);
}
/** (non-Javadoc)
* @see IResource#setReadOnly(boolean)
* @deprecated
*/
public void setReadOnly(boolean readonly) {
ResourceAttributes attributes = new ResourceAttributes();
attributes.setReadOnly(readonly);
try {
setResourceAttributes(attributes);
} catch (CoreException e) {
//failure is not an option
}
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.IResource#setResourceAttributes(org.eclipse.core.resources.IResourceAttributes)
*/
public void setResourceAttributes(ResourceAttributes attributes) throws CoreException {
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_ZERO);
getLocalManager().setResourceAttributes(this, attributes);
}
/* (non-Javadoc)
* @see IResource#setSessionProperty(QualifiedName, Object)
*/
public void setSessionProperty(QualifiedName key, Object value) throws CoreException {
// fetch the info but don't bother making it mutable even though we are going
// to modify it. We don't know whether or not the tree is open and it really doesn't
// matter as the change we are doing does not show up in deltas.
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_ZERO);
info.setSessionProperty(key, value);
}
/* (non-Javadoc)
* @see IResource#setTeamPrivateMember(boolean)
*/
public void setTeamPrivateMember(boolean isTeamPrivate) throws CoreException {
// fetch the info but don't bother making it mutable even though we are going
// to modify it. We don't know whether or not the tree is open and it really doesn't
// matter as the change we are doing does not show up in deltas.
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
// ignore attempts to set team private member flag on anything except files and folders
if (info.getType() == FILE || info.getType() == FOLDER) {
if (isTeamPrivate) {
info.set(ICoreConstants.M_TEAM_PRIVATE_MEMBER);
} else {
info.clear(ICoreConstants.M_TEAM_PRIVATE_MEMBER);
}
}
}
/**
* Returns true if this resource has the potential to be
* (or have been) synchronized.
*/
public boolean synchronizing(ResourceInfo info) {
return info != null && info.getSyncInfo(false) != null;
}
/* (non-Javadoc)
* @see Object#toString()
*/
public String toString() {
return getTypeString() + getFullPath().toString();
}
/* (non-Javadoc)
* @see IResource#touch(IProgressMonitor)
*/
public void touch(IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
String message = NLS.bind(Messages.resources_touch, getFullPath());
monitor.beginTask(message, Policy.totalWork);
final ISchedulingRule rule = workspace.getRuleFactory().modifyRule(this);
try {
workspace.prepareOperation(rule, monitor);
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_ZERO);
workspace.beginOperation(true);
// fake a change by incrementing the content ID
info = getResourceInfo(false, true);
info.incrementContentId();
// forget content-related caching flags
info.clear(M_CONTENT_CACHE);
workspace.updateModificationStamp(info);
monitor.worked(Policy.opWork);
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} finally {
workspace.endOperation(rule, true, Policy.subMonitorFor(monitor, Policy.endOpWork));
}
} finally {
monitor.done();
}
}
/**
* Calls the move/delete hook to perform the deletion. Since this method calls
* client code, it is run "unprotected", so the workspace lock is not held.
*/
private void unprotectedDelete(ResourceTree tree, int updateFlags, IProgressMonitor monitor) throws CoreException {
IMoveDeleteHook hook = workspace.getMoveDeleteHook();
switch (getType()) {
case IResource.FILE :
if (!hook.deleteFile(tree, (IFile) this, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork * 1000 / 2)))
tree.standardDeleteFile((IFile) this, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork * 1000));
break;
case IResource.FOLDER :
if (!hook.deleteFolder(tree, (IFolder) this, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork * 1000 / 2)))
tree.standardDeleteFolder((IFolder) this, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork * 1000));
break;
case IResource.PROJECT :
workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_DELETE, this));
if (!hook.deleteProject(tree, (IProject) this, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork * 1000 / 2)))
tree.standardDeleteProject((IProject) this, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork * 1000));
break;
case IResource.ROOT :
IProject[] projects = ((IWorkspaceRoot) this).getProjects();
for (int i = 0; i < projects.length; i++) {
workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_DELETE, projects[i]));
if (!hook.deleteProject(tree, projects[i], updateFlags, Policy.subMonitorFor(monitor, Policy.opWork * 1000 / projects.length / 2)))
tree.standardDeleteProject(projects[i], updateFlags, Policy.subMonitorFor(monitor, Policy.opWork * 1000 / projects.length));
}
}
}
/**
* Calls the move/delete hook to perform the move. Since this method calls
* client code, it is run "unprotected", so the workspace lock is not held.
* Returns true if resources were actually moved, and false otherwise.
*/
private boolean unprotectedMove(ResourceTree tree, final IResource destination, int updateFlags, IProgressMonitor monitor) throws CoreException, ResourceException {
IMoveDeleteHook hook = workspace.getMoveDeleteHook();
switch (getType()) {
case IResource.FILE :
if (isLinked())
workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_LINK_MOVE, this, destination, updateFlags));
if (!hook.moveFile(tree, (IFile) this, (IFile) destination, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork / 2)))
tree.standardMoveFile((IFile) this, (IFile) destination, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork));
break;
case IResource.FOLDER :
if (isLinked())
workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_LINK_MOVE, this, destination, updateFlags));
if (!hook.moveFolder(tree, (IFolder) this, (IFolder) destination, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork / 2)))
tree.standardMoveFolder((IFolder) this, (IFolder) destination, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork));
break;
case IResource.PROJECT :
IProject project = (IProject) this;
// if there is no change in name, there is nothing to do so return.
if (getName().equals(destination.getName()))
return false;
//we are deleting the source project so notify.
workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_MOVE, this, destination, updateFlags));
IProjectDescription description = project.getDescription();
description.setName(destination.getName());
if (!hook.moveProject(tree, project, description, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork / 2)))
tree.standardMoveProject(project, description, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork));
break;
case IResource.ROOT :
String msg = Messages.resources_moveRoot;
throw new ResourceException(new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), msg));
}
return true;
}
}
| false | true | protected IStatus checkMoveRequirements(IPath destination, int destinationType, int updateFlags) throws CoreException {
String message = Messages.resources_moveNotMet;
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INVALID_VALUE, message, null);
if (destination == null) {
message = Messages.resources_destNotNull;
return new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message);
}
destination = makePathAbsolute(destination);
if (getFullPath().isPrefixOf(destination)) {
message = NLS.bind(Messages.resources_moveDestNotSub, getFullPath());
status.add(new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message));
}
checkValidPath(destination, destinationType, false);
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_INFINITE);
Resource dest = workspace.newResource(destination, destinationType);
// check if we are only changing case
IResource variant = Workspace.caseSensitive ? null : findExistingResourceVariant(destination);
if (variant == null || !this.equals(variant))
dest.checkDoesNotExist();
// ensure we aren't trying to move a file to a project
if (getType() == IResource.FILE && dest.getType() == IResource.PROJECT) {
message = Messages.resources_fileToProj;
throw new ResourceException(new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message));
}
// we can't move into a closed project
if (destinationType != IResource.PROJECT) {
Project project = (Project) dest.getProject();
info = project.getResourceInfo(false, false);
project.checkAccessible(getFlags(info));
Container parent = (Container) dest.getParent();
if (!parent.equals(project)) {
info = parent.getResourceInfo(false, false);
parent.checkExists(getFlags(info), true);
}
}
if (isUnderLink() || dest.isUnderLink()) {
//make sure location is not null. This can occur with linked resources relative to
//undefined path variables
IPath sourceLocation = getLocation();
if (sourceLocation == null) {
message = NLS.bind(Messages.localstore_locationUndefined, getFullPath());
throw new ResourceException(IResourceStatus.FAILED_READ_LOCAL, getFullPath(), message, null);
}
IPath destLocation = dest.getLocation();
if (destLocation == null) {
message = NLS.bind(Messages.localstore_locationUndefined, dest.getFullPath());
throw new ResourceException(IResourceStatus.FAILED_READ_LOCAL, dest.getFullPath(), message, null);
}
//make sure location of source is not a prefix of the location of the destination
//this can occur if the source or destination is a linked resource
if (sourceLocation.isPrefixOf(destLocation)) {
message = NLS.bind(Messages.resources_moveDestNotSub, getFullPath());
throw new ResourceException(IResourceStatus.INVALID_VALUE, getFullPath(), message, null);
}
}
return status.isOK() ? Status.OK_STATUS : (IStatus) status;
}
| protected IStatus checkMoveRequirements(IPath destination, int destinationType, int updateFlags) throws CoreException {
String message = Messages.resources_moveNotMet;
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INVALID_VALUE, message, null);
if (destination == null) {
message = Messages.resources_destNotNull;
return new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message);
}
destination = makePathAbsolute(destination);
if (getFullPath().isPrefixOf(destination)) {
message = NLS.bind(Messages.resources_moveDestNotSub, getFullPath());
status.add(new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message));
}
checkValidPath(destination, destinationType, false);
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkAccessible(flags);
checkLocal(flags, DEPTH_INFINITE);
Resource dest = workspace.newResource(destination, destinationType);
// check if we are only changing case
IResource variant = Workspace.caseSensitive ? null : findExistingResourceVariant(destination);
if (variant == null || !this.equals(variant))
dest.checkDoesNotExist();
// ensure we aren't trying to move a file to a project
if (getType() == IResource.FILE && dest.getType() == IResource.PROJECT) {
message = Messages.resources_fileToProj;
throw new ResourceException(new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), message));
}
// we can't move into a closed project
if (destinationType != IResource.PROJECT) {
Project project = (Project) dest.getProject();
info = project.getResourceInfo(false, false);
project.checkAccessible(getFlags(info));
Container parent = (Container) dest.getParent();
if (!parent.equals(project)) {
info = parent.getResourceInfo(false, false);
parent.checkExists(getFlags(info), true);
}
}
if (isUnderLink() || dest.isUnderLink()) {
//make sure location is not null. This can occur with linked resources relative to
//undefined path variables
URI sourceLocation = getLocationURI();
if (sourceLocation == null) {
message = NLS.bind(Messages.localstore_locationUndefined, getFullPath());
throw new ResourceException(IResourceStatus.FAILED_READ_LOCAL, getFullPath(), message, null);
}
URI destLocation = dest.getLocationURI();
if (destLocation == null) {
message = NLS.bind(Messages.localstore_locationUndefined, dest.getFullPath());
throw new ResourceException(IResourceStatus.FAILED_READ_LOCAL, dest.getFullPath(), message, null);
}
//make sure location of source is not a prefix of the location of the destination
//this can occur if the source and/or destination is a linked resource
if (getStore().isParentOf(dest.getStore())) {
message = NLS.bind(Messages.resources_moveDestNotSub, getFullPath());
throw new ResourceException(IResourceStatus.INVALID_VALUE, getFullPath(), message, null);
}
}
return status.isOK() ? Status.OK_STATUS : (IStatus) status;
}
|
diff --git a/jnlp-agent/src/main/java/hudson/jnlp/Engine.java b/jnlp-agent/src/main/java/hudson/jnlp/Engine.java
index 7f8a355d6..2f8d7ded3 100644
--- a/jnlp-agent/src/main/java/hudson/jnlp/Engine.java
+++ b/jnlp-agent/src/main/java/hudson/jnlp/Engine.java
@@ -1,80 +1,78 @@
package hudson.jnlp;
import hudson.remoting.Channel;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Kohsuke Kawaguchi
*/
public class Engine extends Thread {
private final ExecutorService executor = Executors.newCachedThreadPool();
private Listener listener;
private final String host;
private final String hudsonUrl;
private final String secretKey;
private final String slaveName;
public Engine(Listener listener, String host, String hudsonUrl, String secretKey, String slaveName) {
this.listener = listener;
this.host = host;
this.hudsonUrl = hudsonUrl;
this.secretKey = secretKey;
this.slaveName = slaveName;
}
public void run() {
try {
while(true) {
listener.status("Locating Server");
// find out the TCP port
HttpURLConnection con = (HttpURLConnection)new URL(hudsonUrl).openConnection();
con.connect();
String port = con.getHeaderField("X-Hudson-JNLP-Port");
if(con.getResponseCode()!=200
|| port ==null) {
listener.error(new Exception(hudsonUrl+" is not Hudson: "+con.getResponseMessage()));
return;
}
listener.status("Connecting");
Socket s = new Socket(host, Integer.parseInt(port));
listener.status("Handshaking");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(secretKey);
dos.writeUTF(slaveName);
Channel channel = new Channel("channel", executor, s.getInputStream(), s.getOutputStream());
listener.status("Connected");
channel.join();
listener.status("Terminated");
// try to connect back to the server every 10 secs.
while(true) {
Thread.sleep(1000*10);
try {
con = (HttpURLConnection)new URL(hudsonUrl).openConnection();
con.connect();
if(con.getResponseCode()!=200)
continue;
} catch (IOException e) {
continue;
}
break;
}
}
- } catch (IOException e) {
- listener.error(e);
- } catch (InterruptedException e) {
+ } catch (Throwable e) {
listener.error(e);
}
}
}
| true | true | public void run() {
try {
while(true) {
listener.status("Locating Server");
// find out the TCP port
HttpURLConnection con = (HttpURLConnection)new URL(hudsonUrl).openConnection();
con.connect();
String port = con.getHeaderField("X-Hudson-JNLP-Port");
if(con.getResponseCode()!=200
|| port ==null) {
listener.error(new Exception(hudsonUrl+" is not Hudson: "+con.getResponseMessage()));
return;
}
listener.status("Connecting");
Socket s = new Socket(host, Integer.parseInt(port));
listener.status("Handshaking");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(secretKey);
dos.writeUTF(slaveName);
Channel channel = new Channel("channel", executor, s.getInputStream(), s.getOutputStream());
listener.status("Connected");
channel.join();
listener.status("Terminated");
// try to connect back to the server every 10 secs.
while(true) {
Thread.sleep(1000*10);
try {
con = (HttpURLConnection)new URL(hudsonUrl).openConnection();
con.connect();
if(con.getResponseCode()!=200)
continue;
} catch (IOException e) {
continue;
}
break;
}
}
} catch (IOException e) {
listener.error(e);
} catch (InterruptedException e) {
listener.error(e);
}
}
| public void run() {
try {
while(true) {
listener.status("Locating Server");
// find out the TCP port
HttpURLConnection con = (HttpURLConnection)new URL(hudsonUrl).openConnection();
con.connect();
String port = con.getHeaderField("X-Hudson-JNLP-Port");
if(con.getResponseCode()!=200
|| port ==null) {
listener.error(new Exception(hudsonUrl+" is not Hudson: "+con.getResponseMessage()));
return;
}
listener.status("Connecting");
Socket s = new Socket(host, Integer.parseInt(port));
listener.status("Handshaking");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(secretKey);
dos.writeUTF(slaveName);
Channel channel = new Channel("channel", executor, s.getInputStream(), s.getOutputStream());
listener.status("Connected");
channel.join();
listener.status("Terminated");
// try to connect back to the server every 10 secs.
while(true) {
Thread.sleep(1000*10);
try {
con = (HttpURLConnection)new URL(hudsonUrl).openConnection();
con.connect();
if(con.getResponseCode()!=200)
continue;
} catch (IOException e) {
continue;
}
break;
}
}
} catch (Throwable e) {
listener.error(e);
}
}
|
diff --git a/src/test/java/au/net/netstorm/boost/retire/reflect/DefaultAssertTestChecker.java b/src/test/java/au/net/netstorm/boost/retire/reflect/DefaultAssertTestChecker.java
index c43f28707..fc55e71a1 100644
--- a/src/test/java/au/net/netstorm/boost/retire/reflect/DefaultAssertTestChecker.java
+++ b/src/test/java/au/net/netstorm/boost/retire/reflect/DefaultAssertTestChecker.java
@@ -1,60 +1,60 @@
package au.net.netstorm.boost.retire.reflect;
import junit.framework.Assert;
public final class DefaultAssertTestChecker implements AssertTestChecker {
// SUGGEST Refactor duplication, if possible.
public void checkEquals(Object[] o1, Object[] o2) {
basicCheck(o1, o2);
for (int i = 0; i < o2.length; i++) Assert.assertEquals("" + i, o1[i], o2[i]);
}
public void checkBagEquals(Object[] o1, Object[] o2) {
basicCheck(o1, o2);
boolean[] used = usedFlags(o1);
- for (int i = 0; i < o1.length; i++) {
- Object ref = o1[i];
- if (!find(used, o2, ref)) Assert.fail("Not in bag " + ref);
+ for (int i = 0; i < o2.length; i++) {
+ Object ref = o2[i];
+ if (!find(used, o1, ref)) Assert.fail("Not in bag " + ref);
}
}
public void checkEquals(byte[] value1, byte[] value2) {
Assert.assertNotNull(value1);
Assert.assertNotNull(value2);
Assert.assertEquals(value1.length, value2.length);
for (int i = 0; i < value2.length; i++) Assert.assertEquals("" + i, value1[i], value2[i]);
}
public void checkEquals(int[] value1, int[] value2) {
Assert.assertEquals(value1.length, value2.length);
for (int i = 0; i < value1.length; i++) Assert.assertEquals(value1[i], value2[i]);
}
public void checkNotEquals(byte[] value1, byte[] value2) {
if (value1.length != value2.length) return;
for (int i = 0; i < value1.length; i++)
if (value1[i] != value2[i]) return;
Assert.fail();
}
private boolean find(boolean[] used, Object[] array, Object toFind) {
for (int i = 0; i < array.length; i++) {
if (used[i]) continue;
if (toFind.equals(array[i])) return true;
}
return false;
}
private boolean[] usedFlags(Object[] o1) {
boolean[] used = new boolean[o1.length];
for (int i = 0; i < used.length; i++) used[i] = false;
return used;
}
private void basicCheck(Object[] o1, Object[] o2) {
Assert.assertNotNull(o1);
Assert.assertNotNull(o2);
Assert.assertEquals("Array lengths do not match.", o1.length, o2.length);
}
}
| true | true | public void checkBagEquals(Object[] o1, Object[] o2) {
basicCheck(o1, o2);
boolean[] used = usedFlags(o1);
for (int i = 0; i < o1.length; i++) {
Object ref = o1[i];
if (!find(used, o2, ref)) Assert.fail("Not in bag " + ref);
}
}
| public void checkBagEquals(Object[] o1, Object[] o2) {
basicCheck(o1, o2);
boolean[] used = usedFlags(o1);
for (int i = 0; i < o2.length; i++) {
Object ref = o2[i];
if (!find(used, o1, ref)) Assert.fail("Not in bag " + ref);
}
}
|
diff --git a/src/main/java/com/drtshock/willie/command/utility/AuthorCommandHandler.java b/src/main/java/com/drtshock/willie/command/utility/AuthorCommandHandler.java
index 1ea733c..5b48414 100644
--- a/src/main/java/com/drtshock/willie/command/utility/AuthorCommandHandler.java
+++ b/src/main/java/com/drtshock/willie/command/utility/AuthorCommandHandler.java
@@ -1,188 +1,187 @@
package com.drtshock.willie.command.utility;
import com.drtshock.willie.Willie;
import com.drtshock.willie.command.CommandHandler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.pircbotx.Channel;
import org.pircbotx.Colors;
import org.pircbotx.User;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
public class AuthorCommandHandler implements CommandHandler {
private static final Logger LOG = Logger.getLogger(AuthorCommandHandler.class.getName());
private SimpleDateFormat dateFormat;
public AuthorCommandHandler() {
this.dateFormat = new SimpleDateFormat("EEEE dd MMMM YYYY");
}
@Override
public void handle(Willie bot, Channel channel, User sender, String[] args) throws Exception {
LOG.info("Started to handle !author command from " + sender.getNick() + "...");
if (args.length != 1 && args.length != 2) {
nope(channel);
return;
}
try {
int amount = 5;
if (args.length == 2) {
try {
amount = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
nope(channel);
return;
}
if (amount == 0) {
nope(channel);
return;
}
}
LOG.info("Selected amount: " + amount);
SortedSet<Plugin> plugins = new TreeSet<>();
boolean hasNextPage;
Document document;
String devBukkitLink = "http://dev.bukkit.org/";
String profilePageLink = devBukkitLink + "profiles/" + args[0];
String nextPageLink = profilePageLink + "/bukkit-plugins/";
do {
// Get the page
LOG.info("Getting page \"" + nextPageLink + "\"...");
document = getPage(nextPageLink);
// Check if we will have to look at another page
Elements pages = document.getElementsByClass("listing-pagination-pages").get(0).children();
if (pages.size() > 1) {
Element lastLink = pages.get(pages.size() - 1).child(0);
if (lastLink.ownText().trim().startsWith("Next")) {
hasNextPage = true;
nextPageLink = devBukkitLink + lastLink.attr("href");
} else {
hasNextPage = false;
nextPageLink = null;
}
} else {
hasNextPage = false;
nextPageLink = null;
}
// List stuff on this page
Plugin plugin;
String date;
Elements pluginsTd = document.getElementsByClass("col-project");
for (Element e : pluginsTd) {
if ("td".equalsIgnoreCase(e.tagName())) {
plugin = new Plugin();
plugin.name = e.getElementsByTag("h2").get(0).getElementsByTag("a").get(0).ownText().trim();
- date = e.nextElementSibling().attr("data-epoch");
+ date = e.nextElementSibling().child(0).attr("data-epoch");
try {
plugin.lastUpdate = Long.parseLong(date);
} catch (NumberFormatException ex) {
channel.sendMessage(Colors.RED + "An error occured: Cannot parse \"" + date + "\" as a long.");
- LOG.info(e.nextElementSibling().html());
return;
}
LOG.info("Adding plugin " + plugin.name);
plugins.add(plugin);
}
}
} while (hasNextPage);
String name = document.getElementsByTag("h1").get(1).ownText().trim();
String nbPlugins = document.getElementsByClass("listing-pagination-pages-total").get(0).ownText().trim();
Iterator<Plugin> it = plugins.iterator();
channel.sendMessage(name + " (" + profilePageLink + ")");
channel.sendMessage("Plugins: " + nbPlugins);
if (plugins.isEmpty()) {
channel.sendMessage(Colors.RED + "Unknown user or user without plugins");
} else if (amount == 1) {
Plugin plugin = it.next();
channel.sendMessage("Last updated plugin: " + plugin.name + " (" + formatDate(plugin.lastUpdate) + ")");
} else {
channel.sendMessage(amount + " last updated plugins:");
int i = 0;
while (it.hasNext() && i < amount) {
Plugin plugin = it.next();
channel.sendMessage("- " + plugin.name + " (" + formatDate(plugin.lastUpdate) + ")");
i++;
}
}
LOG.info("Command execution successful!");
} catch (FileNotFoundException | MalformedURLException e) {
channel.sendMessage(Colors.RED + "Unable to find that user!");
} catch (IOException e) {
channel.sendMessage(Colors.RED + "Failed: " + e.getMessage());
throw e;
}
}
private final class Plugin implements Comparable<Plugin> {
public String name;
public long lastUpdate;
@Override
public int compareTo(Plugin o) {
return -Long.compare(lastUpdate, o.lastUpdate);
}
}
private Document getPage(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setUseCaches(false);
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = input.readLine()) != null) {
buffer.append(line);
buffer.append('\n');
}
String page = buffer.toString();
input.close();
return Jsoup.parse(page);
}
private void nope(Channel channel) {
channel.sendMessage(Colors.RED + "Look up an author with !author <name> [amount]");
}
private String formatDate(long date) {
return this.dateFormat.format(new Date(date * 1000));
}
}
| false | true | public void handle(Willie bot, Channel channel, User sender, String[] args) throws Exception {
LOG.info("Started to handle !author command from " + sender.getNick() + "...");
if (args.length != 1 && args.length != 2) {
nope(channel);
return;
}
try {
int amount = 5;
if (args.length == 2) {
try {
amount = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
nope(channel);
return;
}
if (amount == 0) {
nope(channel);
return;
}
}
LOG.info("Selected amount: " + amount);
SortedSet<Plugin> plugins = new TreeSet<>();
boolean hasNextPage;
Document document;
String devBukkitLink = "http://dev.bukkit.org/";
String profilePageLink = devBukkitLink + "profiles/" + args[0];
String nextPageLink = profilePageLink + "/bukkit-plugins/";
do {
// Get the page
LOG.info("Getting page \"" + nextPageLink + "\"...");
document = getPage(nextPageLink);
// Check if we will have to look at another page
Elements pages = document.getElementsByClass("listing-pagination-pages").get(0).children();
if (pages.size() > 1) {
Element lastLink = pages.get(pages.size() - 1).child(0);
if (lastLink.ownText().trim().startsWith("Next")) {
hasNextPage = true;
nextPageLink = devBukkitLink + lastLink.attr("href");
} else {
hasNextPage = false;
nextPageLink = null;
}
} else {
hasNextPage = false;
nextPageLink = null;
}
// List stuff on this page
Plugin plugin;
String date;
Elements pluginsTd = document.getElementsByClass("col-project");
for (Element e : pluginsTd) {
if ("td".equalsIgnoreCase(e.tagName())) {
plugin = new Plugin();
plugin.name = e.getElementsByTag("h2").get(0).getElementsByTag("a").get(0).ownText().trim();
date = e.nextElementSibling().attr("data-epoch");
try {
plugin.lastUpdate = Long.parseLong(date);
} catch (NumberFormatException ex) {
channel.sendMessage(Colors.RED + "An error occured: Cannot parse \"" + date + "\" as a long.");
LOG.info(e.nextElementSibling().html());
return;
}
LOG.info("Adding plugin " + plugin.name);
plugins.add(plugin);
}
}
} while (hasNextPage);
String name = document.getElementsByTag("h1").get(1).ownText().trim();
String nbPlugins = document.getElementsByClass("listing-pagination-pages-total").get(0).ownText().trim();
Iterator<Plugin> it = plugins.iterator();
channel.sendMessage(name + " (" + profilePageLink + ")");
channel.sendMessage("Plugins: " + nbPlugins);
if (plugins.isEmpty()) {
channel.sendMessage(Colors.RED + "Unknown user or user without plugins");
} else if (amount == 1) {
Plugin plugin = it.next();
channel.sendMessage("Last updated plugin: " + plugin.name + " (" + formatDate(plugin.lastUpdate) + ")");
} else {
channel.sendMessage(amount + " last updated plugins:");
int i = 0;
while (it.hasNext() && i < amount) {
Plugin plugin = it.next();
channel.sendMessage("- " + plugin.name + " (" + formatDate(plugin.lastUpdate) + ")");
i++;
}
}
LOG.info("Command execution successful!");
} catch (FileNotFoundException | MalformedURLException e) {
channel.sendMessage(Colors.RED + "Unable to find that user!");
} catch (IOException e) {
channel.sendMessage(Colors.RED + "Failed: " + e.getMessage());
throw e;
}
}
| public void handle(Willie bot, Channel channel, User sender, String[] args) throws Exception {
LOG.info("Started to handle !author command from " + sender.getNick() + "...");
if (args.length != 1 && args.length != 2) {
nope(channel);
return;
}
try {
int amount = 5;
if (args.length == 2) {
try {
amount = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
nope(channel);
return;
}
if (amount == 0) {
nope(channel);
return;
}
}
LOG.info("Selected amount: " + amount);
SortedSet<Plugin> plugins = new TreeSet<>();
boolean hasNextPage;
Document document;
String devBukkitLink = "http://dev.bukkit.org/";
String profilePageLink = devBukkitLink + "profiles/" + args[0];
String nextPageLink = profilePageLink + "/bukkit-plugins/";
do {
// Get the page
LOG.info("Getting page \"" + nextPageLink + "\"...");
document = getPage(nextPageLink);
// Check if we will have to look at another page
Elements pages = document.getElementsByClass("listing-pagination-pages").get(0).children();
if (pages.size() > 1) {
Element lastLink = pages.get(pages.size() - 1).child(0);
if (lastLink.ownText().trim().startsWith("Next")) {
hasNextPage = true;
nextPageLink = devBukkitLink + lastLink.attr("href");
} else {
hasNextPage = false;
nextPageLink = null;
}
} else {
hasNextPage = false;
nextPageLink = null;
}
// List stuff on this page
Plugin plugin;
String date;
Elements pluginsTd = document.getElementsByClass("col-project");
for (Element e : pluginsTd) {
if ("td".equalsIgnoreCase(e.tagName())) {
plugin = new Plugin();
plugin.name = e.getElementsByTag("h2").get(0).getElementsByTag("a").get(0).ownText().trim();
date = e.nextElementSibling().child(0).attr("data-epoch");
try {
plugin.lastUpdate = Long.parseLong(date);
} catch (NumberFormatException ex) {
channel.sendMessage(Colors.RED + "An error occured: Cannot parse \"" + date + "\" as a long.");
return;
}
LOG.info("Adding plugin " + plugin.name);
plugins.add(plugin);
}
}
} while (hasNextPage);
String name = document.getElementsByTag("h1").get(1).ownText().trim();
String nbPlugins = document.getElementsByClass("listing-pagination-pages-total").get(0).ownText().trim();
Iterator<Plugin> it = plugins.iterator();
channel.sendMessage(name + " (" + profilePageLink + ")");
channel.sendMessage("Plugins: " + nbPlugins);
if (plugins.isEmpty()) {
channel.sendMessage(Colors.RED + "Unknown user or user without plugins");
} else if (amount == 1) {
Plugin plugin = it.next();
channel.sendMessage("Last updated plugin: " + plugin.name + " (" + formatDate(plugin.lastUpdate) + ")");
} else {
channel.sendMessage(amount + " last updated plugins:");
int i = 0;
while (it.hasNext() && i < amount) {
Plugin plugin = it.next();
channel.sendMessage("- " + plugin.name + " (" + formatDate(plugin.lastUpdate) + ")");
i++;
}
}
LOG.info("Command execution successful!");
} catch (FileNotFoundException | MalformedURLException e) {
channel.sendMessage(Colors.RED + "Unable to find that user!");
} catch (IOException e) {
channel.sendMessage(Colors.RED + "Failed: " + e.getMessage());
throw e;
}
}
|
diff --git a/apps/xgap/plugins/qtlfinder2/QtlFinder2.java b/apps/xgap/plugins/qtlfinder2/QtlFinder2.java
index 6a8f7a8b0..8e37d2159 100644
--- a/apps/xgap/plugins/qtlfinder2/QtlFinder2.java
+++ b/apps/xgap/plugins/qtlfinder2/QtlFinder2.java
@@ -1,577 +1,577 @@
/* Date: February 2, 2010
* Template: PluginScreenJavaTemplateGen.java.ftl
* generator: org.molgenis.generators.ui.PluginScreenJavaTemplateGen 3.3.2-testing
*
* THIS FILE IS A TEMPLATE. PLEASE EDIT :-)
*/
package plugins.qtlfinder2;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import matrix.DataMatrixInstance;
import matrix.general.DataMatrixHandler;
import org.molgenis.data.Data;
import org.molgenis.framework.db.Database;
import org.molgenis.framework.db.DatabaseException;
import org.molgenis.framework.db.Query;
import org.molgenis.framework.db.QueryRule;
import org.molgenis.framework.db.QueryRule.Operator;
import org.molgenis.framework.ui.PluginModel;
import org.molgenis.framework.ui.ScreenController;
import org.molgenis.framework.ui.ScreenMessage;
import org.molgenis.model.elements.Field;
import org.molgenis.pheno.ObservableFeature;
import org.molgenis.pheno.ObservationElement;
import org.molgenis.pheno.ObservationTarget;
import org.molgenis.util.Entity;
import org.molgenis.util.Tuple;
import org.molgenis.xgap.Locus;
import org.molgenis.xgap.Marker;
import org.molgenis.xgap.Probe;
import plugins.qtlfinder.QTLInfo;
import plugins.qtlfinder.QTLMultiPlotResult;
import plugins.reportbuilder.Report;
import plugins.reportbuilder.ReportBuilder;
import plugins.reportbuilder.Statistics;
import plugins.rplot.MakeRPlot;
import app.JDBCMetaDatabase;
public class QtlFinder2 extends PluginModel<Entity>
{
private static final long serialVersionUID = 1L;
private QtlFinderModel2 model = new QtlFinderModel2();
static String __ALL__DATATYPES__SEARCH__KEY = "__ALL__DATATYPES__SEARCH__KEY";
private int plotWidth = 1024;
private int plotHeight = 768;
public QtlFinderModel2 getMyModel()
{
return model;
}
public QtlFinder2(String name, ScreenController<?> parent)
{
super(name, parent);
}
@Override
public String getViewName()
{
return "QtlFinder2";
}
@Override
public String getViewTemplate()
{
return "plugins/qtlfinder2/QtlFinder2.ftl";
}
public void handleRequest(Database db, Tuple request)
{
if (request.getString("__action") != null)
{
String action = request.getString("__action");
try
{
String query = request.getString("query");
this.model.setQuery(query);
String dataType = request.getString("dataTypeSelect");
this.model.setSelectedAnnotationTypeAndNr(dataType);
if (action.equals("shop"))
{
String shopMeName = request.getString("__shopMeName");
int shopMeId = request.getInt("__shopMeId");
//Entity e = db.findById(ObservationElement.class, shopMeId); cannot use this: problem with lists and java generics when load()
List<? extends Entity> input = db.find(ObservationElement.class, new QueryRule(ObservationElement.NAME, Operator.EQUALS, shopMeName));
input = db.load((Class)ObservationElement.class, input);
this.model.getShoppingCart().put(shopMeName, input.get(0));
}
if (action.equals("unshop"))
{
String shopMeName = request.getString("__shopMeName");
this.model.getShoppingCart().remove((shopMeName));
}
if(action.equals("shopAll"))
{
this.model.getShoppingCart().putAll(this.model.getHits());
}
if(action.equals("plotShoppingCart"))
{
QTLMultiPlotResult res = multiplot(new ArrayList<Entity>(this.model.getShoppingCart().values()), db);
this.model.setReport(null);
this.model.setMultiplot(res);
}
if(action.equals("emptyShoppingCart"))
{
this.model.setShoppingCart(null);
}
if(action.startsWith("__entity__report__for__"))
{
System.out.println("action.startsWith(\"__entity__report__for__\")");
String name = action.substring("__entity__report__for__".length());
QueryRule nameQuery = new QueryRule(ObservationElement.NAME, Operator.EQUALS, name);
//we expect 1 hit exactly: ObservationElement names are unique, and since they have already been found, it should exist (unless deleted in the meantime..)
ObservationElement o = db.find(ObservationElement.class, nameQuery).get(0);
String entityClassString = o.get(Field.TYPE_FIELD).toString();
Class<? extends Entity> entityClass = db.getClassForName(entityClassString);
//now get the properly typed result entity
List<? extends Entity> typedResults = db.find(entityClass, nameQuery);
Report report = ReportBuilder.makeReport(typedResults.get(0), db);
this.model.setReport(report);
List<QTLInfo> qtls = PlotHelper.createQTLReportFor(typedResults.get(0), plotWidth, plotHeight, db);
this.model.setQtls(qtls);
}
if (action.equals("search"))
{
this.model.setShortenedQuery(null);
this.model.setMultiplot(null);
this.model.setReport(null);
this.model.setQtls(null);
if(query == null)
{
throw new Exception("Please enter a search term");
}
if(query.length() > 25)
{
throw new Exception("Queries longer than 25 characters are not allowed");
}
if(query.length() < 2)
{
throw new Exception("Queries shorter than 2 characters are not allowed");
}
Class<? extends Entity> entityClass;
if(dataType.equals(__ALL__DATATYPES__SEARCH__KEY))
{
entityClass = db.getClassForName("ObservationElement"); // more broad than "ObservableFeature", but OK
}
else
{
entityClass = db.getClassForName(dataType);
}
Map<String, Entity> hits = query(entityClass, db, query, 100);
System.out.println("initial number of hits: " + hits.size());
hits = genesToProbes(db, 100, hits);
System.out.println("after converting genes to probes, number of hits: " + hits.size());
this.model.setHits(hits);
}
}
catch (Exception e)
{
e.printStackTrace();
this.setMessages(new ScreenMessage(e.getMessage() != null ? e.getMessage() : "null", false));
}
}
}
private Map<String, Entity> genesToProbes(Database db, int limit, Map<String, Entity> hits) throws DatabaseException{
Map<String, Entity> result = new HashMap<String, Entity>();
int nrOfResults = 0;
outer:
for(String name : hits.keySet())
{
Entity e = hits.get(name);
//System.out.println("looking at " + e.get(Field.TYPE_FIELD).toString() + " " + e.get(ObservationElement.NAME).toString());
if(e.get(Field.TYPE_FIELD).equals("Gene"))
{
QueryRule r = new QueryRule(Probe.REPORTSFOR_NAME, Operator.EQUALS, name);
QueryRule o = new QueryRule(Operator.OR);
QueryRule s = new QueryRule(Probe.SYMBOL, Operator.EQUALS, name);
List<Probe> probes = db.find(Probe.class, r, o, s);
//System.out.println("RESULT WITH JUST REPORTSFOR: " +db.find(Probe.class, r).size());
//System.out.println("RESULT WITH JUST SYMBOL: " +db.find(Probe.class, s).size());
for(Probe p : probes)
{
result.put(p.getName(), p);
//System.out.println("GENE2PROBE SEARCH HIT: " +p.getName());
nrOfResults++;
if(nrOfResults == limit)
{
//System.out.println("breaking genesToProbes on adding probes");
break outer;
}
}
}
else
{
result.put(e.get(ObservationElement.NAME).toString(), e);
//System.out.println("GENE2PROBE ADDING ALSO: " +e.get(ObservationElement.NAME).toString());
nrOfResults++;
if(nrOfResults == limit)
{
//System.out.println("breaking genesToProbes on other entities");
break outer;
}
}
}
return result;
}
private Map<String, Entity> query(Class entityClass, Database db, String query, int limit) throws DatabaseException
{
List<? extends Entity> result = db.search(entityClass, query);
result = db.load(entityClass, result);
if(result.size() == 0)
{
boolean noResults = true;
String shortenedQuery = query;
while(noResults && shortenedQuery.length() > 0)
{
result = db.search(entityClass, shortenedQuery);
result = db.load(entityClass, result);
if(result.size() > 0)
{
noResults = false;
this.model.setShortenedQuery(shortenedQuery);
}
shortenedQuery = shortenedQuery.substring(0, shortenedQuery.length()-1);
}
if(noResults)
{
throw new DatabaseException("No results found");
}
}
int nrOfResults = 0;
Map<String, Entity> hits = new HashMap<String, Entity>();
for(Entity e : result)
{
hits.put(e.get(ObservationElement.NAME).toString(), e);
//System.out.println("REGULAR SEARCH HIT: " + e.get(ObservationElement.NAME));
nrOfResults++;
if(nrOfResults == limit)
{
break;
}
}
return hits;
}
private QTLMultiPlotResult multiplot(List<Entity> entities, Database db) throws Exception
{
HashMap<String,Entity> matches = new HashMap<String,Entity>();
HashMap<String, Entity> datasets = new HashMap<String,Entity>();
int totalAmountOfElementsInPlot = 0;
int overallIndex = 1;
List<Data> allData = db.find(Data.class);
DataMatrixHandler dmh = new DataMatrixHandler(db);
//writer for data table
File tmpData = new File(System.getProperty("java.io.tmpdir") + File.separator + "rplot_data_table_" + System.nanoTime() + ".txt");
File cytoscapeNetwork = new File(System.getProperty("java.io.tmpdir") + File.separator + "cyto_qtl_network_" + System.nanoTime() + ".txt");
File cytoscapeNodes = new File(System.getProperty("java.io.tmpdir") + File.separator + "cyto_node_attr_" + System.nanoTime() + ".txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(tmpData));
BufferedWriter bw_network = new BufferedWriter(new FileWriter(cytoscapeNetwork));
BufferedWriter bw_nodes = new BufferedWriter(new FileWriter(cytoscapeNodes));
List<String> nodesInFile = new ArrayList<String>();
for(Data d : allData)
{
if(PlotHelper.isEffectSizeData(db, d))
{
continue;
}
//if something fails with this matrix, don't break the loop
//e.g. backend file is missing
try{
//loop over Text data (can't be QTL)
if(d.getValueType().equals("Text")){
continue;
}
//check if one of the matrix dimensions if of type 'Marker'
//TODO: limited, could also be SNP or another potential subclass
if((d.getTargetType().equals("Marker") || d.getFeatureType().equals("Marker")))
{
//create instance and get name of the row/col we want
DataMatrixInstance instance = dmh.createInstance(d, db);
List<String> rowNames = instance.getRowNames();
List<String> colNames = instance.getColNames();
//get the markers
List<Marker> markers = db.find(Marker.class, new QueryRule(Marker.NAME, Operator.IN, d.getFeatureType().equals("Marker") ? colNames : rowNames));
HashMap<String,Marker> nameToMarker = new HashMap<String,Marker>();
for(Marker m : markers)
{
nameToMarker.put(m.getName(), m);
}
//for each entity, see if the types match to the matrix
for(Entity e : entities)
{
//skip markers, we are interested in traits here
if(e.get(Field.TYPE_FIELD).equals("Marker")){
continue;
}
//matrix may not have the trait type on rows AND columns (this is correlation data or so)
if(d.getTargetType().equals(e.get(Field.TYPE_FIELD)) && d.getFeatureType().equals(e.get(Field.TYPE_FIELD)))
{
continue;
}
//one of the matrix dimensions must match the type of the trait
if(d.getTargetType().equals(e.get(Field.TYPE_FIELD)) || d.getFeatureType().equals(e.get(Field.TYPE_FIELD)))
{
//if so, use this entity to 'query' the matrix and store the values
String name = e.get(ObservableFeature.NAME).toString();
//find out if the name is in the row or col names
int rowIndex = rowNames.indexOf(name);
int colIndex = colNames.indexOf(name);
List<String> markerNames = null;
Double[] Dvalues = null;
//if its in row, do row stuff
if(rowIndex != -1)
{
markerNames = colNames;
Dvalues = Statistics.getAsDoubles(instance.getRow(rowIndex));
}
//if its in col, and not in row, do col stuff
else if(rowIndex == -1 && colIndex != -1)
{
markerNames = rowNames;
Dvalues = Statistics.getAsDoubles(instance.getCol(colIndex));
}
else
{
//this trait is not in the matrix.. skip
continue;
}
//add entity and dataset to matches
matches.put(name, e);
datasets.put(d.getName(), d);
totalAmountOfElementsInPlot++;
//get the basepair position of the trait and chromosome name, if possible
long locus;
String traitChrName;
if(e instanceof Locus)
{
locus = ((Locus)e).getBpStart();
traitChrName = ((Locus)e).getChromosome_Name();
}
else
{
locus = -10000000;
traitChrName = "-";
}
//rewrite name to include label
- name = e.get(ObservableFeature.NAME).toString() + (e.get(ObservableFeature.LABEL) != null ? " / " + e.get(ObservableFeature.LABEL).toString() : "");
+ name = e.get(ObservableFeature.NAME).toString() + (e.get(ObservableFeature.LABEL) != null ? "/" + e.get(ObservableFeature.LABEL).toString() : "");
//iterate over the markers and write out input files for R / CytoScape
for(int markerIndex = 0; markerIndex < markerNames.size(); markerIndex++)
{
if(nameToMarker.containsKey(markerNames.get(markerIndex)))
{
String chrId = nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Id() != null ? nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Id().toString() : "-";
// index, marker, chrId, markerLoc, trait, traitLoc, LODscore, dataId
bw.write(overallIndex + " \"" + markerNames.get(markerIndex) + "\" " + chrId + " " + nameToMarker.get(markerNames.get(markerIndex)).getBpStart() + " \"" + name + "\" " + locus + " " + Dvalues[markerIndex] + " " + d.getId());
bw.newLine();
if(Dvalues[markerIndex].doubleValue() > 3.5)
{
// trait, "QTL", marker, LODscore
bw_network.write(name + "\t" + "QTL" + "\t" + markerNames.get(markerIndex) + "\t" + Dvalues[markerIndex]);
bw_network.newLine();
String marker_chrName = nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Name() != null ? nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Name() : "-";
if(!nodesInFile.contains(name))
{
// trait, traitChr, traitLocus, dataName
bw_nodes.write(name + "\t" + "trait" + "\t" + traitChrName + "\t" + locus + "\t" + d.getName());
bw_nodes.newLine();
nodesInFile.add(name);
}
if(!nodesInFile.contains(markerNames.get(markerIndex)))
{
// marker, markerChr, markerLocus, dataName
bw_nodes.write(markerNames.get(markerIndex) + "\t" + "marker" + "\t" + marker_chrName + "\t" + nameToMarker.get(markerNames.get(markerIndex)).getBpStart() + "\t" + d.getName());
bw_nodes.newLine();
nodesInFile.add(markerNames.get(markerIndex));
}
}
overallIndex++;
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
//too bad, data matrix failed
}
}
bw.close();
bw_network.close();
bw_nodes.close();
int height = 200 + (totalAmountOfElementsInPlot * 20);
File plot = MakeRPlot.qtlMultiPlot(tmpData, plotWidth, height, this.model.getQuery());
File cisTransplot = MakeRPlot.qtlCisTransPlot(tmpData, plotWidth, plotHeight, this.model.getQuery());
QTLMultiPlotResult result = new QTLMultiPlotResult();
result.setSrcData(tmpData.getName());
result.setCytoNetwork(cytoscapeNetwork.getName());
result.setCytoNodes(cytoscapeNodes.getName());
result.setPlot(plot.getName());
result.setCisTransPlot(cisTransplot.getName());
result.setMatches(matches);
result.setDatasets(datasets);
return result;
}
@Override
public void reload(Database db)
{
try
{
if(model.getShoppingCart() == null)
{
Map<String, Entity> shoppingCart = new HashMap<String, Entity>();
this.model.setShoppingCart(shoppingCart);
}
if (model.getAnnotationTypeAndNr() == null)
{
int totalAmount = 0;
JDBCMetaDatabase metadb = new JDBCMetaDatabase();
Map<String, Integer> annotationTypeAndNr = new HashMap<String, Integer>();
Vector<org.molgenis.model.elements.Entity> entityList = metadb.getEntities();
// iterate over all entity types
for (org.molgenis.model.elements.Entity entityType : entityList)
{
// get the ancestors for one such entity
for (org.molgenis.model.elements.Entity e : entityType.getAllAncestors())
{
// if one of the ancestors is ObservationElement..
if (e.getName().equals(ObservationElement.class.getSimpleName()))
{
Class<? extends Entity> entityClass = db.getClassForName(entityType.getName());
// and the class is not ObservableFeature or
// ObservationTarget..
if (!entityClass.getSimpleName().equals(ObservableFeature.class.getSimpleName())
&& !entityClass.getSimpleName().equals(ObservationTarget.class.getSimpleName()))
{
// count the number of entities in the database
int count = db.count(entityClass);
if (count > 0)
{
annotationTypeAndNr.put(entityType.getName(), count);
totalAmount += count;
}
}
break;
}
}
}
annotationTypeAndNr.put(__ALL__DATATYPES__SEARCH__KEY, totalAmount);
model.setAnnotationTypeAndNr(annotationTypeAndNr);
}
}
catch (Exception e)
{
e.printStackTrace();
this.setMessages(new ScreenMessage(e.getMessage() != null ? e.getMessage() : "null", false));
}
}
@Override
public String getCustomHtmlHeaders()
{
return "<link rel=\"stylesheet\" style=\"text/css\" href=\"clusterdemo/qtlfinder.css\">" + "\n" +
"<script type=\"text/javascript\" src=\"etc/js/clear-default-text.js\"></script>" ;
}
}
| true | true | private QTLMultiPlotResult multiplot(List<Entity> entities, Database db) throws Exception
{
HashMap<String,Entity> matches = new HashMap<String,Entity>();
HashMap<String, Entity> datasets = new HashMap<String,Entity>();
int totalAmountOfElementsInPlot = 0;
int overallIndex = 1;
List<Data> allData = db.find(Data.class);
DataMatrixHandler dmh = new DataMatrixHandler(db);
//writer for data table
File tmpData = new File(System.getProperty("java.io.tmpdir") + File.separator + "rplot_data_table_" + System.nanoTime() + ".txt");
File cytoscapeNetwork = new File(System.getProperty("java.io.tmpdir") + File.separator + "cyto_qtl_network_" + System.nanoTime() + ".txt");
File cytoscapeNodes = new File(System.getProperty("java.io.tmpdir") + File.separator + "cyto_node_attr_" + System.nanoTime() + ".txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(tmpData));
BufferedWriter bw_network = new BufferedWriter(new FileWriter(cytoscapeNetwork));
BufferedWriter bw_nodes = new BufferedWriter(new FileWriter(cytoscapeNodes));
List<String> nodesInFile = new ArrayList<String>();
for(Data d : allData)
{
if(PlotHelper.isEffectSizeData(db, d))
{
continue;
}
//if something fails with this matrix, don't break the loop
//e.g. backend file is missing
try{
//loop over Text data (can't be QTL)
if(d.getValueType().equals("Text")){
continue;
}
//check if one of the matrix dimensions if of type 'Marker'
//TODO: limited, could also be SNP or another potential subclass
if((d.getTargetType().equals("Marker") || d.getFeatureType().equals("Marker")))
{
//create instance and get name of the row/col we want
DataMatrixInstance instance = dmh.createInstance(d, db);
List<String> rowNames = instance.getRowNames();
List<String> colNames = instance.getColNames();
//get the markers
List<Marker> markers = db.find(Marker.class, new QueryRule(Marker.NAME, Operator.IN, d.getFeatureType().equals("Marker") ? colNames : rowNames));
HashMap<String,Marker> nameToMarker = new HashMap<String,Marker>();
for(Marker m : markers)
{
nameToMarker.put(m.getName(), m);
}
//for each entity, see if the types match to the matrix
for(Entity e : entities)
{
//skip markers, we are interested in traits here
if(e.get(Field.TYPE_FIELD).equals("Marker")){
continue;
}
//matrix may not have the trait type on rows AND columns (this is correlation data or so)
if(d.getTargetType().equals(e.get(Field.TYPE_FIELD)) && d.getFeatureType().equals(e.get(Field.TYPE_FIELD)))
{
continue;
}
//one of the matrix dimensions must match the type of the trait
if(d.getTargetType().equals(e.get(Field.TYPE_FIELD)) || d.getFeatureType().equals(e.get(Field.TYPE_FIELD)))
{
//if so, use this entity to 'query' the matrix and store the values
String name = e.get(ObservableFeature.NAME).toString();
//find out if the name is in the row or col names
int rowIndex = rowNames.indexOf(name);
int colIndex = colNames.indexOf(name);
List<String> markerNames = null;
Double[] Dvalues = null;
//if its in row, do row stuff
if(rowIndex != -1)
{
markerNames = colNames;
Dvalues = Statistics.getAsDoubles(instance.getRow(rowIndex));
}
//if its in col, and not in row, do col stuff
else if(rowIndex == -1 && colIndex != -1)
{
markerNames = rowNames;
Dvalues = Statistics.getAsDoubles(instance.getCol(colIndex));
}
else
{
//this trait is not in the matrix.. skip
continue;
}
//add entity and dataset to matches
matches.put(name, e);
datasets.put(d.getName(), d);
totalAmountOfElementsInPlot++;
//get the basepair position of the trait and chromosome name, if possible
long locus;
String traitChrName;
if(e instanceof Locus)
{
locus = ((Locus)e).getBpStart();
traitChrName = ((Locus)e).getChromosome_Name();
}
else
{
locus = -10000000;
traitChrName = "-";
}
//rewrite name to include label
name = e.get(ObservableFeature.NAME).toString() + (e.get(ObservableFeature.LABEL) != null ? " / " + e.get(ObservableFeature.LABEL).toString() : "");
//iterate over the markers and write out input files for R / CytoScape
for(int markerIndex = 0; markerIndex < markerNames.size(); markerIndex++)
{
if(nameToMarker.containsKey(markerNames.get(markerIndex)))
{
String chrId = nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Id() != null ? nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Id().toString() : "-";
// index, marker, chrId, markerLoc, trait, traitLoc, LODscore, dataId
bw.write(overallIndex + " \"" + markerNames.get(markerIndex) + "\" " + chrId + " " + nameToMarker.get(markerNames.get(markerIndex)).getBpStart() + " \"" + name + "\" " + locus + " " + Dvalues[markerIndex] + " " + d.getId());
bw.newLine();
if(Dvalues[markerIndex].doubleValue() > 3.5)
{
// trait, "QTL", marker, LODscore
bw_network.write(name + "\t" + "QTL" + "\t" + markerNames.get(markerIndex) + "\t" + Dvalues[markerIndex]);
bw_network.newLine();
String marker_chrName = nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Name() != null ? nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Name() : "-";
if(!nodesInFile.contains(name))
{
// trait, traitChr, traitLocus, dataName
bw_nodes.write(name + "\t" + "trait" + "\t" + traitChrName + "\t" + locus + "\t" + d.getName());
bw_nodes.newLine();
nodesInFile.add(name);
}
if(!nodesInFile.contains(markerNames.get(markerIndex)))
{
// marker, markerChr, markerLocus, dataName
bw_nodes.write(markerNames.get(markerIndex) + "\t" + "marker" + "\t" + marker_chrName + "\t" + nameToMarker.get(markerNames.get(markerIndex)).getBpStart() + "\t" + d.getName());
bw_nodes.newLine();
nodesInFile.add(markerNames.get(markerIndex));
}
}
overallIndex++;
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
//too bad, data matrix failed
}
}
bw.close();
bw_network.close();
bw_nodes.close();
int height = 200 + (totalAmountOfElementsInPlot * 20);
File plot = MakeRPlot.qtlMultiPlot(tmpData, plotWidth, height, this.model.getQuery());
File cisTransplot = MakeRPlot.qtlCisTransPlot(tmpData, plotWidth, plotHeight, this.model.getQuery());
QTLMultiPlotResult result = new QTLMultiPlotResult();
result.setSrcData(tmpData.getName());
result.setCytoNetwork(cytoscapeNetwork.getName());
result.setCytoNodes(cytoscapeNodes.getName());
result.setPlot(plot.getName());
result.setCisTransPlot(cisTransplot.getName());
result.setMatches(matches);
result.setDatasets(datasets);
return result;
}
| private QTLMultiPlotResult multiplot(List<Entity> entities, Database db) throws Exception
{
HashMap<String,Entity> matches = new HashMap<String,Entity>();
HashMap<String, Entity> datasets = new HashMap<String,Entity>();
int totalAmountOfElementsInPlot = 0;
int overallIndex = 1;
List<Data> allData = db.find(Data.class);
DataMatrixHandler dmh = new DataMatrixHandler(db);
//writer for data table
File tmpData = new File(System.getProperty("java.io.tmpdir") + File.separator + "rplot_data_table_" + System.nanoTime() + ".txt");
File cytoscapeNetwork = new File(System.getProperty("java.io.tmpdir") + File.separator + "cyto_qtl_network_" + System.nanoTime() + ".txt");
File cytoscapeNodes = new File(System.getProperty("java.io.tmpdir") + File.separator + "cyto_node_attr_" + System.nanoTime() + ".txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(tmpData));
BufferedWriter bw_network = new BufferedWriter(new FileWriter(cytoscapeNetwork));
BufferedWriter bw_nodes = new BufferedWriter(new FileWriter(cytoscapeNodes));
List<String> nodesInFile = new ArrayList<String>();
for(Data d : allData)
{
if(PlotHelper.isEffectSizeData(db, d))
{
continue;
}
//if something fails with this matrix, don't break the loop
//e.g. backend file is missing
try{
//loop over Text data (can't be QTL)
if(d.getValueType().equals("Text")){
continue;
}
//check if one of the matrix dimensions if of type 'Marker'
//TODO: limited, could also be SNP or another potential subclass
if((d.getTargetType().equals("Marker") || d.getFeatureType().equals("Marker")))
{
//create instance and get name of the row/col we want
DataMatrixInstance instance = dmh.createInstance(d, db);
List<String> rowNames = instance.getRowNames();
List<String> colNames = instance.getColNames();
//get the markers
List<Marker> markers = db.find(Marker.class, new QueryRule(Marker.NAME, Operator.IN, d.getFeatureType().equals("Marker") ? colNames : rowNames));
HashMap<String,Marker> nameToMarker = new HashMap<String,Marker>();
for(Marker m : markers)
{
nameToMarker.put(m.getName(), m);
}
//for each entity, see if the types match to the matrix
for(Entity e : entities)
{
//skip markers, we are interested in traits here
if(e.get(Field.TYPE_FIELD).equals("Marker")){
continue;
}
//matrix may not have the trait type on rows AND columns (this is correlation data or so)
if(d.getTargetType().equals(e.get(Field.TYPE_FIELD)) && d.getFeatureType().equals(e.get(Field.TYPE_FIELD)))
{
continue;
}
//one of the matrix dimensions must match the type of the trait
if(d.getTargetType().equals(e.get(Field.TYPE_FIELD)) || d.getFeatureType().equals(e.get(Field.TYPE_FIELD)))
{
//if so, use this entity to 'query' the matrix and store the values
String name = e.get(ObservableFeature.NAME).toString();
//find out if the name is in the row or col names
int rowIndex = rowNames.indexOf(name);
int colIndex = colNames.indexOf(name);
List<String> markerNames = null;
Double[] Dvalues = null;
//if its in row, do row stuff
if(rowIndex != -1)
{
markerNames = colNames;
Dvalues = Statistics.getAsDoubles(instance.getRow(rowIndex));
}
//if its in col, and not in row, do col stuff
else if(rowIndex == -1 && colIndex != -1)
{
markerNames = rowNames;
Dvalues = Statistics.getAsDoubles(instance.getCol(colIndex));
}
else
{
//this trait is not in the matrix.. skip
continue;
}
//add entity and dataset to matches
matches.put(name, e);
datasets.put(d.getName(), d);
totalAmountOfElementsInPlot++;
//get the basepair position of the trait and chromosome name, if possible
long locus;
String traitChrName;
if(e instanceof Locus)
{
locus = ((Locus)e).getBpStart();
traitChrName = ((Locus)e).getChromosome_Name();
}
else
{
locus = -10000000;
traitChrName = "-";
}
//rewrite name to include label
name = e.get(ObservableFeature.NAME).toString() + (e.get(ObservableFeature.LABEL) != null ? "/" + e.get(ObservableFeature.LABEL).toString() : "");
//iterate over the markers and write out input files for R / CytoScape
for(int markerIndex = 0; markerIndex < markerNames.size(); markerIndex++)
{
if(nameToMarker.containsKey(markerNames.get(markerIndex)))
{
String chrId = nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Id() != null ? nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Id().toString() : "-";
// index, marker, chrId, markerLoc, trait, traitLoc, LODscore, dataId
bw.write(overallIndex + " \"" + markerNames.get(markerIndex) + "\" " + chrId + " " + nameToMarker.get(markerNames.get(markerIndex)).getBpStart() + " \"" + name + "\" " + locus + " " + Dvalues[markerIndex] + " " + d.getId());
bw.newLine();
if(Dvalues[markerIndex].doubleValue() > 3.5)
{
// trait, "QTL", marker, LODscore
bw_network.write(name + "\t" + "QTL" + "\t" + markerNames.get(markerIndex) + "\t" + Dvalues[markerIndex]);
bw_network.newLine();
String marker_chrName = nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Name() != null ? nameToMarker.get(markerNames.get(markerIndex)).getChromosome_Name() : "-";
if(!nodesInFile.contains(name))
{
// trait, traitChr, traitLocus, dataName
bw_nodes.write(name + "\t" + "trait" + "\t" + traitChrName + "\t" + locus + "\t" + d.getName());
bw_nodes.newLine();
nodesInFile.add(name);
}
if(!nodesInFile.contains(markerNames.get(markerIndex)))
{
// marker, markerChr, markerLocus, dataName
bw_nodes.write(markerNames.get(markerIndex) + "\t" + "marker" + "\t" + marker_chrName + "\t" + nameToMarker.get(markerNames.get(markerIndex)).getBpStart() + "\t" + d.getName());
bw_nodes.newLine();
nodesInFile.add(markerNames.get(markerIndex));
}
}
overallIndex++;
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
//too bad, data matrix failed
}
}
bw.close();
bw_network.close();
bw_nodes.close();
int height = 200 + (totalAmountOfElementsInPlot * 20);
File plot = MakeRPlot.qtlMultiPlot(tmpData, plotWidth, height, this.model.getQuery());
File cisTransplot = MakeRPlot.qtlCisTransPlot(tmpData, plotWidth, plotHeight, this.model.getQuery());
QTLMultiPlotResult result = new QTLMultiPlotResult();
result.setSrcData(tmpData.getName());
result.setCytoNetwork(cytoscapeNetwork.getName());
result.setCytoNodes(cytoscapeNodes.getName());
result.setPlot(plot.getName());
result.setCisTransPlot(cisTransplot.getName());
result.setMatches(matches);
result.setDatasets(datasets);
return result;
}
|
diff --git a/OsmAnd/src/net/osmand/plus/routing/RouteAnimation.java b/OsmAnd/src/net/osmand/plus/routing/RouteAnimation.java
index 23a90fd6..4d47f5ea 100644
--- a/OsmAnd/src/net/osmand/plus/routing/RouteAnimation.java
+++ b/OsmAnd/src/net/osmand/plus/routing/RouteAnimation.java
@@ -1,67 +1,78 @@
package net.osmand.plus.routing;
import java.util.ArrayList;
import java.util.List;
import net.osmand.LatLonUtils;
import net.osmand.plus.activities.MapActivity;
import android.location.Location;
public class RouteAnimation {
private Thread routeAnimation;
public boolean isRouteAnimating() {
return routeAnimation != null;
}
public void startStopRouteAnimation(final RoutingHelper routingHelper,
final MapActivity ma) {
if (!isRouteAnimating()) {
routeAnimation = new Thread() {
@Override
public void run() {
final List<Location> directions = new ArrayList<Location>(
routingHelper.getCurrentRoute());
Location current = null;
+ Location prev = null;
float meters = 20.0f;
while (!directions.isEmpty() && routeAnimation != null) {
if (current == null) {
current = new Location(directions.remove(0));
} else {
if (current.distanceTo(directions.get(0)) > meters) {
current = LatLonUtils.middleLocation(current,
directions.get(0), meters);
} else {
current = new Location(directions.remove(0));
}
}
current.setSpeed(meters);
current.setTime(System.currentTimeMillis());
- ma.setLocation(current);
+ if (prev != null) {
+ current.setBearing(prev.bearingTo(current));
+ }
+ final Location toset = current;
+ ma.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ ma.setLocation(toset);
+ }
+ });
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
+ prev = current;
}
RouteAnimation.this.stop();
};
};
routeAnimation.start();
} else {
// stop the animation
stop();
}
}
private void stop() {
routeAnimation = null;
}
public void close() {
if (isRouteAnimating()) {
stop();
}
}
}
| false | true | public void startStopRouteAnimation(final RoutingHelper routingHelper,
final MapActivity ma) {
if (!isRouteAnimating()) {
routeAnimation = new Thread() {
@Override
public void run() {
final List<Location> directions = new ArrayList<Location>(
routingHelper.getCurrentRoute());
Location current = null;
float meters = 20.0f;
while (!directions.isEmpty() && routeAnimation != null) {
if (current == null) {
current = new Location(directions.remove(0));
} else {
if (current.distanceTo(directions.get(0)) > meters) {
current = LatLonUtils.middleLocation(current,
directions.get(0), meters);
} else {
current = new Location(directions.remove(0));
}
}
current.setSpeed(meters);
current.setTime(System.currentTimeMillis());
ma.setLocation(current);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
}
RouteAnimation.this.stop();
};
};
routeAnimation.start();
} else {
// stop the animation
stop();
}
}
| public void startStopRouteAnimation(final RoutingHelper routingHelper,
final MapActivity ma) {
if (!isRouteAnimating()) {
routeAnimation = new Thread() {
@Override
public void run() {
final List<Location> directions = new ArrayList<Location>(
routingHelper.getCurrentRoute());
Location current = null;
Location prev = null;
float meters = 20.0f;
while (!directions.isEmpty() && routeAnimation != null) {
if (current == null) {
current = new Location(directions.remove(0));
} else {
if (current.distanceTo(directions.get(0)) > meters) {
current = LatLonUtils.middleLocation(current,
directions.get(0), meters);
} else {
current = new Location(directions.remove(0));
}
}
current.setSpeed(meters);
current.setTime(System.currentTimeMillis());
if (prev != null) {
current.setBearing(prev.bearingTo(current));
}
final Location toset = current;
ma.runOnUiThread(new Runnable() {
@Override
public void run() {
ma.setLocation(toset);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
prev = current;
}
RouteAnimation.this.stop();
};
};
routeAnimation.start();
} else {
// stop the animation
stop();
}
}
|
diff --git a/features/edb/service-engine/src/main/java/org/openengsb/edb/jbi/endpoints/commands/EDBCommit.java b/features/edb/service-engine/src/main/java/org/openengsb/edb/jbi/endpoints/commands/EDBCommit.java
index d7d091bb5..6e9cb25b8 100644
--- a/features/edb/service-engine/src/main/java/org/openengsb/edb/jbi/endpoints/commands/EDBCommit.java
+++ b/features/edb/service-engine/src/main/java/org/openengsb/edb/jbi/endpoints/commands/EDBCommit.java
@@ -1,102 +1,102 @@
/**
Copyright 2010 OpenEngSB Division, Vienna University of Technology
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openengsb.edb.jbi.endpoints.commands;
import java.util.ArrayList;
import java.util.List;
import javax.jbi.messaging.NormalizedMessage;
import org.apache.commons.logging.Log;
import org.openengsb.edb.core.api.EDBException;
import org.openengsb.edb.core.api.EDBHandler;
import org.openengsb.edb.core.entities.GenericContent;
import org.openengsb.edb.core.entities.OperationType;
import org.openengsb.edb.jbi.endpoints.EdbEndpoint;
import org.openengsb.edb.jbi.endpoints.XmlParserFunctions;
import org.openengsb.edb.jbi.endpoints.XmlParserFunctions.ContentWrapper;
public class EDBCommit implements EDBEndpointCommand {
private final EDBHandler handler;
private final Log log;
public EDBCommit(EDBHandler handler, Log log) {
this.handler = handler;
this.log = log;
}
public CommandResult execute(NormalizedMessage in) throws Exception {
String body = null;
String userName = "author";
try {
List<ContentWrapper> contentWrappers = XmlParserFunctions.parseCommitMessage(in, handler
.getRepositoryBase().toString());
if (contentWrappers.size() < 1) {
throw new EDBException("Message did not contain files to commit");
}
final List<GenericContent> listAdd = new ArrayList<GenericContent>();
final List<GenericContent> listRemove = new ArrayList<GenericContent>();
userName = extractUserInfo(contentWrappers);
for (final ContentWrapper content : contentWrappers) {
// update search index
if (content.getOperation() == OperationType.UPDATE) {
listAdd.add(content.getContent());
} else if (content.getOperation() == OperationType.DELETE) {
listRemove.add(content.getContent());
}
}
handler.add(listAdd);
handler.remove(listRemove);
String commitId = handler.commit(userName, EdbEndpoint.DEFAULT_EMAIL);
body = XmlParserFunctions.buildCommitResponseBody(contentWrappers, commitId);
} catch (EDBException e) {
body = XmlParserFunctions.buildCommitErrorResponseBody(e.getMessage(), makeStackTraceString(e));
this.log.info(body);
}
CommandResult result = new CommandResult();
result.responseString = body;
- result.eventAttributes.put("author", "[email protected]");
+ result.eventAttributes.put("author", userName);
return result;
}
private static String extractUserInfo(List<ContentWrapper> contentWrappers) {
String result = EdbEndpoint.DEFAULT_USER;
ContentWrapper content = contentWrappers.get(0);
if (!(content.getUser() == null)) {
if (!content.getUser().equals("")) {
result = content.getUser();
contentWrappers.remove(0);
}
}
return result;
}
private String makeStackTraceString(Exception e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement ste : e.getStackTrace()) {
sb.append(ste.toString());
sb.append("\n");
}
return sb.toString();
}
}
| true | true | public CommandResult execute(NormalizedMessage in) throws Exception {
String body = null;
String userName = "author";
try {
List<ContentWrapper> contentWrappers = XmlParserFunctions.parseCommitMessage(in, handler
.getRepositoryBase().toString());
if (contentWrappers.size() < 1) {
throw new EDBException("Message did not contain files to commit");
}
final List<GenericContent> listAdd = new ArrayList<GenericContent>();
final List<GenericContent> listRemove = new ArrayList<GenericContent>();
userName = extractUserInfo(contentWrappers);
for (final ContentWrapper content : contentWrappers) {
// update search index
if (content.getOperation() == OperationType.UPDATE) {
listAdd.add(content.getContent());
} else if (content.getOperation() == OperationType.DELETE) {
listRemove.add(content.getContent());
}
}
handler.add(listAdd);
handler.remove(listRemove);
String commitId = handler.commit(userName, EdbEndpoint.DEFAULT_EMAIL);
body = XmlParserFunctions.buildCommitResponseBody(contentWrappers, commitId);
} catch (EDBException e) {
body = XmlParserFunctions.buildCommitErrorResponseBody(e.getMessage(), makeStackTraceString(e));
this.log.info(body);
}
CommandResult result = new CommandResult();
result.responseString = body;
result.eventAttributes.put("author", "[email protected]");
return result;
}
| public CommandResult execute(NormalizedMessage in) throws Exception {
String body = null;
String userName = "author";
try {
List<ContentWrapper> contentWrappers = XmlParserFunctions.parseCommitMessage(in, handler
.getRepositoryBase().toString());
if (contentWrappers.size() < 1) {
throw new EDBException("Message did not contain files to commit");
}
final List<GenericContent> listAdd = new ArrayList<GenericContent>();
final List<GenericContent> listRemove = new ArrayList<GenericContent>();
userName = extractUserInfo(contentWrappers);
for (final ContentWrapper content : contentWrappers) {
// update search index
if (content.getOperation() == OperationType.UPDATE) {
listAdd.add(content.getContent());
} else if (content.getOperation() == OperationType.DELETE) {
listRemove.add(content.getContent());
}
}
handler.add(listAdd);
handler.remove(listRemove);
String commitId = handler.commit(userName, EdbEndpoint.DEFAULT_EMAIL);
body = XmlParserFunctions.buildCommitResponseBody(contentWrappers, commitId);
} catch (EDBException e) {
body = XmlParserFunctions.buildCommitErrorResponseBody(e.getMessage(), makeStackTraceString(e));
this.log.info(body);
}
CommandResult result = new CommandResult();
result.responseString = body;
result.eventAttributes.put("author", userName);
return result;
}
|
diff --git a/src/com/dmdirc/addons/ui_swing/components/statusbar/StatusbarPopupWindow.java b/src/com/dmdirc/addons/ui_swing/components/statusbar/StatusbarPopupWindow.java
index 29aa502e0..155b3d101 100644
--- a/src/com/dmdirc/addons/ui_swing/components/statusbar/StatusbarPopupWindow.java
+++ b/src/com/dmdirc/addons/ui_swing/components/statusbar/StatusbarPopupWindow.java
@@ -1,158 +1,155 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.ui_swing.components.statusbar;
import com.dmdirc.addons.ui_swing.dialogs.StandardDialog;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Window;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import net.miginfocom.swing.MigLayout;
/**
* A popup window which is shown above a status bar component to provide more
* detailed information.
*
* @since 0.6.3m1
* @author chris
*/
public abstract class StatusbarPopupWindow extends StandardDialog {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** The parent JPanel. */
private final JPanel parent;
/** Parent window. */
private Window parentWindow;
/**
* Creates a new status bar popup window.
*
* @param parent The {@link JPanel} to use for positioning
* @param parentWindow Parent window
*/
public StatusbarPopupWindow(final JPanel parent, final Window parentWindow) {
super(parentWindow, ModalityType.MODELESS);
this.parent = parent;
this.parentWindow = parentWindow;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
/** {@inheritDoc} */
@Override
public void setVisible(boolean b) {
- if (!parent.isVisible()) {
- return;
- }
- if (b) {
+ if (b && parent.isVisible()) {
final JPanel panel = new JPanel();
panel.setLayout(new MigLayout("ins 3 5 6 10, gap 10 5"));
panel.setBackground(UIManager.getColor("ToolTip.background"));
panel.setForeground(UIManager.getColor("ToolTip.foreground"));
initContent(panel);
add(panel);
setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);
setResizable(false);
pack();
final Point point = parent.getLocationOnScreen();
point.translate(parent.getWidth() / 2 - this.getWidth() / 2, - this.getHeight());
final int maxX = Math.max(parentWindow.getLocationOnScreen().x
+ parentWindow.getWidth() - 10 - getWidth(),
parent.getLocationOnScreen().x + parent.getWidth() - 1 - getWidth());
point.x = Math.min(maxX, point.x);
setLocation(point);
panel.setBorder(new GappedEtchedBorder());
}
super.setVisible(b);
}
/**
* Initialises the content of the popup window.
*
* @param panel The {@link JPanel} to which content should be added
*/
protected abstract void initContent(final JPanel panel);
/**
* An {@link EtchedBorder} that leaves a gap in the bottom where the
* lag display panel is.
*/
private class GappedEtchedBorder extends EtchedBorder {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** {@inheritDoc} */
@Override
public void paintBorder(final Component c, final Graphics g,
final int x, final int y, final int width, final int height) {
int w = width;
int h = height;
g.translate(x, y);
g.setColor(etchType == LOWERED? getShadowColor(c) : getHighlightColor(c));
g.drawLine(0, 0, w-1, 0);
g.drawLine(0, h-1, parent.getLocationOnScreen().x
- getLocationOnScreen().x, h-1);
g.drawLine(parent.getWidth() + parent.getLocationOnScreen().x
- getLocationOnScreen().x - 2, h-1, w-1, h-1);
g.drawLine(0, 0, 0, h-1);
g.drawLine(w-1, 0, w-1, h-1);
g.translate(-x, -y);
}
}
}
| true | true | public void setVisible(boolean b) {
if (!parent.isVisible()) {
return;
}
if (b) {
final JPanel panel = new JPanel();
panel.setLayout(new MigLayout("ins 3 5 6 10, gap 10 5"));
panel.setBackground(UIManager.getColor("ToolTip.background"));
panel.setForeground(UIManager.getColor("ToolTip.foreground"));
initContent(panel);
add(panel);
setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);
setResizable(false);
pack();
final Point point = parent.getLocationOnScreen();
point.translate(parent.getWidth() / 2 - this.getWidth() / 2, - this.getHeight());
final int maxX = Math.max(parentWindow.getLocationOnScreen().x
+ parentWindow.getWidth() - 10 - getWidth(),
parent.getLocationOnScreen().x + parent.getWidth() - 1 - getWidth());
point.x = Math.min(maxX, point.x);
setLocation(point);
panel.setBorder(new GappedEtchedBorder());
}
super.setVisible(b);
}
| public void setVisible(boolean b) {
if (b && parent.isVisible()) {
final JPanel panel = new JPanel();
panel.setLayout(new MigLayout("ins 3 5 6 10, gap 10 5"));
panel.setBackground(UIManager.getColor("ToolTip.background"));
panel.setForeground(UIManager.getColor("ToolTip.foreground"));
initContent(panel);
add(panel);
setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);
setResizable(false);
pack();
final Point point = parent.getLocationOnScreen();
point.translate(parent.getWidth() / 2 - this.getWidth() / 2, - this.getHeight());
final int maxX = Math.max(parentWindow.getLocationOnScreen().x
+ parentWindow.getWidth() - 10 - getWidth(),
parent.getLocationOnScreen().x + parent.getWidth() - 1 - getWidth());
point.x = Math.min(maxX, point.x);
setLocation(point);
panel.setBorder(new GappedEtchedBorder());
}
super.setVisible(b);
}
|
diff --git a/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java b/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java
index ad5e5c167..e26f1dee5 100644
--- a/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java
+++ b/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java
@@ -1,124 +1,124 @@
/*******************************************************************************
* Copyright (c) 2006-2009
* Software Technology Group, Dresden University of Technology
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version. This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU Lesser General Public License for more details. You should have
* received a copy of the GNU Lesser General Public License along with this
* program; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.finders;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.emftext.runtime.EMFTextRuntimePlugin;
import org.emftext.runtime.resource.ITextResource;
import org.emftext.sdk.concretesyntax.GenPackageDependentElement;
/**
* A finder that looks up generator packages in the EMF package
* registry. This implementation queries the registry once at its first usage
* and loads and caches all valid generator packages.
*/
public class GenPackageInRegistryFinder implements IGenPackageFinder {
private static final Map<String, GenPackageInRegistryFinderResult> cache = new HashMap<String, GenPackageInRegistryFinderResult>();
static { init(); }
private static void init() {
//search all registered generator models
final Map<String, URI> packageNsURIToGenModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
for (String nextNS : packageNsURIToGenModelLocationMap.keySet()) {
URI genModelURI = packageNsURIToGenModelLocationMap.get(nextNS);
try {
final ResourceSet rs = new ResourceSetImpl();
Resource genModelResource = rs.getResource(genModelURI, true);
if (genModelResource == null) {
continue;
}
final EList<EObject> contents = genModelResource.getContents();
if (contents == null || contents.size() == 0) {
continue;
}
GenModel genModel = (GenModel) contents.get(0);
for (GenPackage genPackage : genModel.getGenPackages()) {
if (genPackage != null && !genPackage.eIsProxy()) {
String nsURI = genPackage.getNSURI();
final GenPackageInRegistryFinderResult result = new GenPackageInRegistryFinderResult(genPackage);
cache.put(nsURI, result);
registerSubGenPackages(genPackage);
}
}
} catch (Exception e ) {
- EMFTextRuntimePlugin.logError("Exception while looking up concrete syntaxes in the registry.", e);
+ EMFTextRuntimePlugin.logError("Exception while looking up generator model (" + nextNS + ") in the registry.", e);
}
}
}
private static void registerSubGenPackages(GenPackage parentPackage) {
for(GenPackage genPackage : parentPackage.getSubGenPackages()) {
if (genPackage != null && !genPackage.eIsProxy()) {
String nsURI = genPackage.getNSURI();
final GenPackageInRegistryFinderResult result = new GenPackageInRegistryFinderResult(genPackage);
cache.put(nsURI, result);
registerSubGenPackages(genPackage);
}
}
}
/**
* An implementation of the IGenPackageFinderResult that is used to
* return generator package found in the EMF registry.
*/
private static class GenPackageInRegistryFinderResult implements IGenPackageFinderResult {
private GenPackage genPackage;
public GenPackageInRegistryFinderResult(GenPackage genPackage) {
Assert.isNotNull(genPackage);
this.genPackage = genPackage;
}
public boolean hasChanged() {
return false;
}
public GenPackage getResult() {
return genPackage;
}
}
public IGenPackageFinderResult findGenPackage(String nsURI, String locationHint, GenPackageDependentElement container, ITextResource resource) {
if (cache.containsKey(nsURI)) {
return cache.get(nsURI);
}
return null;
}
}
| true | true | private static void init() {
//search all registered generator models
final Map<String, URI> packageNsURIToGenModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
for (String nextNS : packageNsURIToGenModelLocationMap.keySet()) {
URI genModelURI = packageNsURIToGenModelLocationMap.get(nextNS);
try {
final ResourceSet rs = new ResourceSetImpl();
Resource genModelResource = rs.getResource(genModelURI, true);
if (genModelResource == null) {
continue;
}
final EList<EObject> contents = genModelResource.getContents();
if (contents == null || contents.size() == 0) {
continue;
}
GenModel genModel = (GenModel) contents.get(0);
for (GenPackage genPackage : genModel.getGenPackages()) {
if (genPackage != null && !genPackage.eIsProxy()) {
String nsURI = genPackage.getNSURI();
final GenPackageInRegistryFinderResult result = new GenPackageInRegistryFinderResult(genPackage);
cache.put(nsURI, result);
registerSubGenPackages(genPackage);
}
}
} catch (Exception e ) {
EMFTextRuntimePlugin.logError("Exception while looking up concrete syntaxes in the registry.", e);
}
}
}
| private static void init() {
//search all registered generator models
final Map<String, URI> packageNsURIToGenModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
for (String nextNS : packageNsURIToGenModelLocationMap.keySet()) {
URI genModelURI = packageNsURIToGenModelLocationMap.get(nextNS);
try {
final ResourceSet rs = new ResourceSetImpl();
Resource genModelResource = rs.getResource(genModelURI, true);
if (genModelResource == null) {
continue;
}
final EList<EObject> contents = genModelResource.getContents();
if (contents == null || contents.size() == 0) {
continue;
}
GenModel genModel = (GenModel) contents.get(0);
for (GenPackage genPackage : genModel.getGenPackages()) {
if (genPackage != null && !genPackage.eIsProxy()) {
String nsURI = genPackage.getNSURI();
final GenPackageInRegistryFinderResult result = new GenPackageInRegistryFinderResult(genPackage);
cache.put(nsURI, result);
registerSubGenPackages(genPackage);
}
}
} catch (Exception e ) {
EMFTextRuntimePlugin.logError("Exception while looking up generator model (" + nextNS + ") in the registry.", e);
}
}
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/factory/GTFSPatternHopFactory.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/factory/GTFSPatternHopFactory.java
index 3ddada515..68be83f9a 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/factory/GTFSPatternHopFactory.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/factory/GTFSPatternHopFactory.java
@@ -1,1288 +1,1285 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.edgetype.factory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.onebusaway.gtfs.model.Agency;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Frequency;
import org.onebusaway.gtfs.model.Pathway;
import org.onebusaway.gtfs.model.ShapePoint;
import org.onebusaway.gtfs.model.Stop;
import org.onebusaway.gtfs.model.StopTime;
import org.onebusaway.gtfs.model.Transfer;
import org.onebusaway.gtfs.model.Trip;
import org.onebusaway.gtfs.services.GtfsRelationalDao;
import org.opentripplanner.common.geometry.DistanceLibrary;
import org.opentripplanner.common.geometry.PackedCoordinateSequence;
import org.opentripplanner.common.model.T2;
import org.opentripplanner.gtfs.GtfsContext;
import org.opentripplanner.gtfs.GtfsLibrary;
import org.opentripplanner.routing.core.GraphBuilderAnnotation;
import org.opentripplanner.routing.core.TransferTable;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.GraphBuilderAnnotation.Variety;
import org.opentripplanner.routing.edgetype.Alight;
import org.opentripplanner.routing.edgetype.BasicTripPattern;
import org.opentripplanner.routing.edgetype.Board;
import org.opentripplanner.routing.edgetype.Dwell;
import org.opentripplanner.routing.edgetype.FreeEdge;
import org.opentripplanner.routing.edgetype.FrequencyAlight;
import org.opentripplanner.routing.edgetype.FrequencyBasedTripPattern;
import org.opentripplanner.routing.edgetype.FrequencyBoard;
import org.opentripplanner.routing.edgetype.FrequencyDwell;
import org.opentripplanner.routing.edgetype.FrequencyHop;
import org.opentripplanner.routing.edgetype.Hop;
import org.opentripplanner.routing.edgetype.PathwayEdge;
import org.opentripplanner.routing.edgetype.PatternAlight;
import org.opentripplanner.routing.edgetype.PatternBoard;
import org.opentripplanner.routing.edgetype.PatternDwell;
import org.opentripplanner.routing.edgetype.PatternHop;
import org.opentripplanner.routing.edgetype.PatternInterlineDwell;
import org.opentripplanner.routing.edgetype.PreAlightEdge;
import org.opentripplanner.routing.edgetype.PreBoardEdge;
import org.opentripplanner.routing.edgetype.TimedTransferEdge;
import org.opentripplanner.routing.edgetype.TransferEdge;
import org.opentripplanner.routing.edgetype.TripPattern;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.impl.DefaultFareServiceFactory;
import org.opentripplanner.routing.services.FareService;
import org.opentripplanner.routing.services.FareServiceFactory;
import org.opentripplanner.routing.vertextype.PatternArriveVertex;
import org.opentripplanner.routing.vertextype.PatternDepartVertex;
import org.opentripplanner.routing.vertextype.PatternStopVertex;
import org.opentripplanner.routing.vertextype.TransitStop;
import org.opentripplanner.routing.vertextype.TransitStopArrive;
import org.opentripplanner.routing.vertextype.TransitStopDepart;
import org.opentripplanner.routing.vertextype.TransitVertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.linearref.LinearLocation;
import com.vividsolutions.jts.linearref.LocationIndexedLine;
/**
*
* A ScheduledStopPattern is an intermediate object used when processing GTFS files. It represents an ordered
* list of stops and a service ID. Any two trips with the same stops in the same order, and that
* operate on the same days, can be combined using a TripPattern to save memory.
*/
class ScheduledStopPattern {
ArrayList<Stop> stops;
ArrayList<Integer> pickups;
ArrayList<Integer> dropoffs;
AgencyAndId calendarId;
public ScheduledStopPattern(ArrayList<Stop> stops, ArrayList<Integer> pickups, ArrayList<Integer> dropoffs, AgencyAndId calendarId) {
this.stops = stops;
this.pickups = pickups;
this.dropoffs = dropoffs;
this.calendarId = calendarId;
}
public boolean equals(Object other) {
if (other instanceof ScheduledStopPattern) {
ScheduledStopPattern pattern = (ScheduledStopPattern) other;
return pattern.stops.equals(stops) && pattern.calendarId.equals(calendarId) && pattern.pickups.equals(pickups) && pattern.dropoffs.equals(dropoffs);
} else {
return false;
}
}
public int hashCode() {
return this.stops.hashCode() ^ this.calendarId.hashCode() + this.pickups.hashCode() + this.dropoffs.hashCode();
}
public String toString() {
return "StopPattern(" + stops + ", " + calendarId + ")";
}
}
class InterliningTrip implements Comparable<InterliningTrip> {
public Trip trip;
public StopTime firstStopTime;
public StopTime lastStopTime;
BasicTripPattern tripPattern;
InterliningTrip(Trip trip, List<StopTime> stopTimes, BasicTripPattern tripPattern) {
this.trip = trip;
this.firstStopTime = stopTimes.get(0);
this.lastStopTime = stopTimes.get(stopTimes.size() - 1);
this.tripPattern = tripPattern;
}
public int getPatternIndex() {
return tripPattern.getPatternIndex(trip);
}
@Override
public int compareTo(InterliningTrip o) {
return firstStopTime.getArrivalTime() - o.firstStopTime.getArrivalTime();
}
@Override
public boolean equals(Object o) {
if (o instanceof InterliningTrip) {
return compareTo((InterliningTrip) o) == 0;
}
return false;
}
}
class BlockIdAndServiceId {
public String blockId;
public AgencyAndId serviceId;
BlockIdAndServiceId(String blockId, AgencyAndId serviceId) {
this.blockId = blockId;
this.serviceId = serviceId;
}
public boolean equals(Object o) {
if (o instanceof BlockIdAndServiceId) {
BlockIdAndServiceId other = ((BlockIdAndServiceId) o);
return other.blockId.equals(blockId) && other.serviceId.equals(serviceId);
}
return false;
}
@Override
public int hashCode() {
return blockId.hashCode() * 31 + serviceId.hashCode();
}
}
class InterlineSwitchoverKey {
public Stop s0, s1;
public BasicTripPattern pattern1, pattern2;
public InterlineSwitchoverKey(Stop s0, Stop s1, BasicTripPattern pattern1,
BasicTripPattern pattern2) {
this.s0 = s0;
this.s1 = s1;
this.pattern1 = pattern1;
this.pattern2 = pattern2;
}
public boolean equals(Object o) {
if (o instanceof InterlineSwitchoverKey) {
InterlineSwitchoverKey other = (InterlineSwitchoverKey) o;
return other.s0.equals(s0) &&
other.s1.equals(s1) &&
other.pattern1 == pattern1 &&
other.pattern2 == pattern2;
}
return false;
}
public int hashCode() {
return (((s0.hashCode() * 31) + s1.hashCode()) * 31 + pattern1.hashCode()) * 31 + pattern2.hashCode();
}
}
/**
* Generates a set of edges from GTFS.
*/
public class GTFSPatternHopFactory {
private static final Logger _log = LoggerFactory.getLogger(GTFSPatternHopFactory.class);
private static GeometryFactory _factory = new GeometryFactory();
private GtfsRelationalDao _dao;
private Map<ShapeSegmentKey, LineString> _geometriesByShapeSegmentKey = new HashMap<ShapeSegmentKey, LineString>();
private Map<AgencyAndId, LineString> _geometriesByShapeId = new HashMap<AgencyAndId, LineString>();
private Map<AgencyAndId, double[]> _distancesByShapeId = new HashMap<AgencyAndId, double[]>();
private ArrayList<PatternDwell> potentiallyUselessDwells = new ArrayList<PatternDwell> ();
private FareServiceFactory fareServiceFactory;
private HashMap<BlockIdAndServiceId, List<InterliningTrip>> tripsForBlock = new HashMap<BlockIdAndServiceId, List<InterliningTrip>>();
private Map<InterlineSwitchoverKey, PatternInterlineDwell> interlineDwells = new HashMap<InterlineSwitchoverKey, PatternInterlineDwell>();
HashMap<ScheduledStopPattern, BasicTripPattern> patterns = new HashMap<ScheduledStopPattern, BasicTripPattern>();
/* maps replacing label lookup */
private Map<Stop, Vertex> stopNodes = new HashMap<Stop, Vertex>();
Map<Stop, TransitStopArrive> stopArriveNodes = new HashMap<Stop, TransitStopArrive>();
Map<Stop, TransitStopDepart> stopDepartNodes = new HashMap<Stop, TransitStopDepart>();
Map<T2<Stop, Trip>, Vertex> patternArriveNodes = new HashMap<T2<Stop, Trip>, Vertex>();
Map<T2<Stop, Trip>, Vertex> patternDepartNodes = new HashMap<T2<Stop, Trip>, Vertex>(); // exemplar trip
private HashSet<Stop> stops = new HashSet<Stop>();
private int defaultStreetToStopTime;
public GTFSPatternHopFactory(GtfsContext context) {
_dao = context.getDao();
}
public static ScheduledStopPattern stopPatternfromTrip(Trip trip, GtfsRelationalDao dao) {
ArrayList<Stop> stops = new ArrayList<Stop>();
ArrayList<Integer> pickups = new ArrayList<Integer>();
ArrayList<Integer> dropoffs = new ArrayList<Integer>();
for (StopTime stoptime : dao.getStopTimesForTrip(trip)) {
stops.add(stoptime.getStop());
pickups.add(stoptime.getPickupType());
dropoffs.add(stoptime.getDropOffType());
}
ScheduledStopPattern pattern = new ScheduledStopPattern(stops, pickups, dropoffs, trip.getServiceId());
return pattern;
}
/**
* Generate the edges. Assumes that there are already vertices in the graph for the stops.
*/
public void run(Graph graph) {
if (fareServiceFactory == null) {
fareServiceFactory = new DefaultFareServiceFactory();
}
fareServiceFactory.setDao(_dao);
// Load stops
loadStops(graph);
loadPathways(graph);
loadAgencies(graph);
// Load hops
_log.debug("Loading hops");
clearCachedData();
/*
* For each trip, create either pattern edges, the entries in a trip pattern's list of
* departures, or simple hops
*/
// Load hops
Collection<Trip> trips = _dao.getAllTrips();
int index = 0;
HashMap<Trip, List<Frequency>> tripFrequencies = new HashMap<Trip, List<Frequency>>();
for(Frequency freq : _dao.getAllFrequencies()) {
List<Frequency> freqs = tripFrequencies.get(freq.getTrip());
if(freqs == null) {
freqs = new ArrayList<Frequency>();
tripFrequencies.put(freq.getTrip(), freqs);
}
freqs.add(freq);
}
for (Trip trip : trips) {
+ index++;
if (index % 100000 == 0)
_log.debug("trips=" + index + "/" + trips.size());
- index++;
List<StopTime> stopTimes = getNonduplicateStopTimesForTrip(trip);
filterStopTimes(stopTimes, graph);
interpolateStopTimes(stopTimes);
if (stopTimes.size() < 2) {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.TRIP_DEGENERATE, trip));
continue;
}
List<Frequency> frequencies = tripFrequencies.get(trip);
ScheduledStopPattern stopPattern = stopPatternfromTrip(trip, _dao);
BasicTripPattern tripPattern = patterns.get(stopPattern);
String blockId = trip.getBlockId();
if(frequencies != null) {
//before creating frequency-based trips, check for
//single-instance frequencies.
Frequency frequency = frequencies.get(0);
if (frequencies.size() > 1 || frequency.getStartTime() != stopTimes.get(0).getDepartureTime() ||
frequency.getEndTime() - frequency.getStartTime() > frequency.getHeadwaySecs()) {
FrequencyBasedTripPattern frequencyPattern = makeFrequencyPattern(graph, trip,
stopTimes);
if (frequencyPattern == null) {
continue;
}
frequencyPattern.createRanges(frequencies);
continue;
}
}
boolean simple = false;
if (tripPattern == null) {
tripPattern = makeTripPattern(graph, trip, stopTimes);
if (tripPattern == null) {
continue;
}
patterns.put(stopPattern, tripPattern);
if (blockId != null && !blockId.equals("")) {
addTripToInterliningMap(trip, stopTimes, tripPattern);
}
} else {
int insertionPoint = tripPattern.getDepartureTimeInsertionPoint(stopTimes.get(0)
.getDepartureTime());
if (insertionPoint < 0) {
insertionPoint = -(insertionPoint + 1);
// There's already a departure at this time on this trip pattern. This means
// that either (a) this will have all the same stop times as that one, and thus
// will be a duplicate of it, or (b) it will have different stops, and thus
// break the assumption that trips are non-overlapping.
if (!tripPattern.stopTimesIdentical(stopTimes, insertionPoint)) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.TRIP_DUPLICATE_DEPARTURE, trip.getId(),
tripPattern.getTrip(insertionPoint)));
simple = true;
createSimpleHops(graph, trip, stopTimes);
- // break;//?
} else {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.TRIP_DUPLICATE,
trip.getId(), tripPattern.getTrip(insertionPoint)));
- break; // not continue - for frequency case
+ simple = true;
}
} else {
// try to insert this trip at this location
StopTime st1 = null;
int i;
for (i = 0; i < stopTimes.size() - 1; i++) {
StopTime st0 = stopTimes.get(i);
st1 = stopTimes.get(i + 1);
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
if (runningTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.NEGATIVE_HOP_TIME, st0, st1));
// back out hops and give up
for (i = i - 1; i >= 0; --i) {
tripPattern.removeHop(i, insertionPoint);
}
simple = true;
break;
}
if (dwellTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.NEGATIVE_DWELL_TIME, st0));
dwellTime = 0;
}
try {
tripPattern.addHop(i, insertionPoint, st0.getDepartureTime(),
runningTime, st1.getArrivalTime(), dwellTime,
st0.getStopHeadsign(), trip);
} catch (TripOvertakingException e) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.TRIP_OVERTAKING, e.overtaker, e.overtaken, e.stopIndex));
// back out trips and revert to the simple method
for (i = i - 1; i >= 0; --i) {
tripPattern.removeHop(i, insertionPoint);
}
createSimpleHops(graph, trip, stopTimes);
simple = true;
break;
}
}
}
if (!simple) {
if (blockId != null && !blockId.equals("")) {
addTripToInterliningMap(trip, stopTimes, tripPattern);
}
- tripPattern
- .setTripFlags(
- insertionPoint,
- ((trip.getWheelchairAccessible() == 1) ? TripPattern.FLAG_WHEELCHAIR_ACCESSIBLE
- : 0)
- | (((trip.getRoute().getBikesAllowed() == 2 && trip
- .getTripBikesAllowed() != 1) || trip
- .getTripBikesAllowed() == 2) ? TripPattern.FLAG_BIKES_ALLOWED
- : 0));
+ tripPattern.setTripFlags(insertionPoint,
+ ((trip.getWheelchairAccessible() == 1) ? TripPattern.FLAG_WHEELCHAIR_ACCESSIBLE
+ : 0)
+ | (((trip.getRoute().getBikesAllowed() == 2 && trip
+ .getTripBikesAllowed() != 1) || trip
+ .getTripBikesAllowed() == 2) ? TripPattern.FLAG_BIKES_ALLOWED
+ : 0));
}
}
}
for (List<InterliningTrip> blockTrips : tripsForBlock.values()) {
if (blockTrips.size() == 1) {
//blocks of only a single trip do not need processing
continue;
}
Collections.sort(blockTrips);
/* this is all the trips for this block/schedule */
for (int i = 0; i < blockTrips.size() - 1; ++i) {
InterliningTrip fromInterlineTrip = blockTrips.get(i);
InterliningTrip toInterlineTrip = blockTrips.get(i + 1);
Trip fromTrip = fromInterlineTrip.trip;
Trip toTrip = toInterlineTrip.trip;
StopTime st0 = fromInterlineTrip.lastStopTime;
StopTime st1 = toInterlineTrip.firstStopTime;
Stop s0 = st0.getStop();
Stop s1 = st1.getStop();
if (st0.getPickupType() == 1) {
// do not create an interline dwell when
// the last stop on the arriving trip does not
// allow pickups, since this probably means
// that, while two trips share a block,
// riders cannot stay on the vehicle during the
// deadhead
continue;
}
Trip fromExemplar = fromInterlineTrip.tripPattern.exemplar;
Trip toExemplar = toInterlineTrip.tripPattern.exemplar;
PatternInterlineDwell dwell;
// do we already have a PID for this dwell?
InterlineSwitchoverKey dwellKey = new InterlineSwitchoverKey(s0, s1, fromInterlineTrip.tripPattern, toInterlineTrip.tripPattern);
dwell = getInterlineDwell(dwellKey);
if (dwell == null) {
// create the dwell
Vertex startJourney = patternArriveNodes.get(new T2<Stop, Trip>(s0,fromExemplar));
Vertex endJourney = patternDepartNodes.get(new T2<Stop, Trip>(s1,toExemplar));
dwell = new PatternInterlineDwell(startJourney, endJourney, toTrip);
putInterlineDwell(dwellKey, dwell);
}
int dwellTime = st1.getDepartureTime() - st0.getArrivalTime();
dwell.addTrip(fromTrip.getId(), toTrip.getId(), dwellTime,
fromInterlineTrip.getPatternIndex(), toInterlineTrip.getPatternIndex());
}
}
loadTransfers(graph);
deleteUselessDwells(graph);
clearCachedData();
graph.putService(FareService.class, fareServiceFactory.makeFareService());
}
private FrequencyBasedTripPattern makeFrequencyPattern(Graph graph, Trip trip,
List<StopTime> stopTimes) {
FrequencyBasedTripPattern pattern = new FrequencyBasedTripPattern(trip, stopTimes.size());
TraverseMode mode = GtfsLibrary.getTraverseMode(trip.getRoute());
int lastStop = stopTimes.size() - 1;
int i;
StopTime st1 = null;
TransitVertex psv0arrive, psv1arrive = null;
TransitVertex psv0depart;
ArrayList<Edge> createdEdges = new ArrayList<Edge>();
ArrayList<Vertex> createdVertices = new ArrayList<Vertex>();
int offset = stopTimes.get(0).getDepartureTime();
for (i = 0; i < lastStop; i++) {
StopTime st0 = stopTimes.get(i);
Stop s0 = st0.getStop();
st1 = stopTimes.get(i + 1);
Stop s1 = st1.getStop();
int arrivalTime = st1.getArrivalTime() - offset;
int departureTime = st0.getDepartureTime() - offset;
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = arrivalTime - departureTime;
if (runningTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.NEGATIVE_HOP_TIME, st0, st1));
//back out hops and give up
for (Edge e: createdEdges) {
e.getFromVertex().removeOutgoing(e);
e.getToVertex().removeIncoming(e);
}
for (Vertex v : createdVertices) {
graph.removeVertexAndEdges(v);
}
return null;
}
// create journey vertices
if (i != 0) {
//dwells are possible on stops after the first
psv0arrive = psv1arrive;
if (dwellTime == 0) {
//if dwell time is zero, we would like to not create psv0depart
//use psv0arrive instead
psv0depart = psv0arrive;
} else {
psv0depart = new PatternDepartVertex(graph, trip, st0);
createdVertices.add(psv0depart);
FrequencyDwell dwell = new FrequencyDwell(psv0arrive, psv0depart, i, pattern);
createdEdges.add(dwell);
}
} else {
psv0depart = new PatternDepartVertex(graph, trip, st0);
createdVertices.add(psv0depart);
}
psv1arrive = new PatternArriveVertex(graph, trip, st1);
createdVertices.add(psv1arrive);
FrequencyHop hop = new FrequencyHop(psv0depart, psv1arrive, s0, s1, i,
pattern);
createdEdges.add(hop);
hop.setGeometry(getHopGeometry(graph, trip.getShapeId(), st0, st1, psv0depart,
psv1arrive));
pattern.addHop(i, departureTime, runningTime, arrivalTime, dwellTime,
st0.getStopHeadsign());
TransitStopDepart stopDepart = stopDepartNodes.get(s0);
TransitStopArrive stopArrive = stopArriveNodes.get(s1);
Edge board = new FrequencyBoard(stopDepart, psv0depart, pattern, i, mode);
Edge alight = new FrequencyAlight(psv1arrive, stopArrive, pattern, i, mode);
createdEdges.add(board);
createdEdges.add(alight);
}
pattern.setTripFlags(((trip.getWheelchairAccessible() == 1) ? TripPattern.FLAG_WHEELCHAIR_ACCESSIBLE : 0)
| (((trip.getRoute().getBikesAllowed() == 2 && trip.getTripBikesAllowed() != 1)
|| trip.getTripBikesAllowed() == 2) ? TripPattern.FLAG_BIKES_ALLOWED : 0));
return pattern;
}
/**
* scan through the given list, looking for clearly incorrect series of stoptimes
* and unsetting / annotating them. unsetting the arrival/departure time of clearly incorrect
* stoptimes will cause them to be interpolated in the next step.
*
* @param stopTimes the stoptimes to be filtered (from a single trip)
* @param graph the graph where annotations will be registered
*/
private void filterStopTimes(List<StopTime> stopTimes, Graph graph) {
if (stopTimes.size() < 2)
return;
StopTime st0 = stopTimes.get(0);
if (!st0.isDepartureTimeSet() && st0.isArrivalTimeSet()) {
/* set depature time if it is missing */
st0.setDepartureTime(st0.getArrivalTime());
}
for (int i = 1; i < stopTimes.size(); i++) {
boolean st1bogus = false;
StopTime st1 = stopTimes.get(i);
if (!st1.isDepartureTimeSet() && st1.isArrivalTimeSet()) {
/* set depature time if it is missing */
st1.setDepartureTime(st1.getArrivalTime());
}
/* do not process non-timepoint stoptimes,
* which are of course identical to other adjacent non-timepoint stoptimes */
if ( ! (st1.isArrivalTimeSet() && st1.isDepartureTimeSet())) {
continue;
}
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
double hopDistance = DistanceLibrary.fastDistance(
st0.getStop().getLon(), st0.getStop().getLat(),
st1.getStop().getLon(), st1.getStop().getLat());
double hopSpeed = hopDistance/runningTime;
/* zero-distance hops are probably not harmful, though they could be better represented as dwell times
if (hopDistance == 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.HOP_ZERO_DISTANCE, runningTime,
st1.getTrip().getId(),
st1.getStopSequence()));
}
*/
// sanity-check the hop
if (st0.getArrivalTime() == st1.getArrivalTime() ||
st0.getDepartureTime() == st1.getDepartureTime()) {
_log.trace("{} {}", st0, st1);
// series of identical stop times at different stops
_log.trace(GraphBuilderAnnotation.register(graph,
Variety.HOP_ZERO_TIME, hopDistance,
st1.getTrip().getRoute(),
st1.getTrip().getId(), st1.getStopSequence()));
// clear stoptimes that are obviously wrong, causing them to later be interpolated
/* FIXME (lines commented out because they break routability in multi-feed NYC for some reason -AMB) */
// st1.clearArrivalTime();
// st1.clearDepartureTime();
st1bogus = true;
} else if (hopSpeed > 45) {
// 45 m/sec ~= 100 miles/hr
// elapsed time of 0 will give speed of +inf
_log.trace(GraphBuilderAnnotation.register(graph,
Variety.HOP_SPEED, hopSpeed, hopDistance,
st0.getTrip().getRoute(),
st0.getTrip().getId(), st0.getStopSequence()));
}
// st0 should reflect the last stoptime that was not clearly incorrect
if ( ! st1bogus)
st0 = st1;
} // END for loop over stop times
}
private void loadAgencies(Graph graph) {
for (Agency agency : _dao.getAllAgencies()) {
graph.addAgencyId(agency.getId());
}
}
private void putInterlineDwell(InterlineSwitchoverKey key, PatternInterlineDwell dwell) {
interlineDwells.put(key, dwell);
}
private PatternInterlineDwell getInterlineDwell(InterlineSwitchoverKey key) {
return interlineDwells.get(key);
}
private void loadPathways(Graph graph) {
for (Pathway pathway : _dao.getAllPathways()) {
Vertex fromVertex = stopNodes.get(pathway.getFromStop());
Vertex toVertex = stopNodes.get(pathway.getToStop());
if (pathway.isWheelchairTraversalTimeSet()) {
new PathwayEdge(fromVertex, toVertex, pathway.getTraversalTime());
} else {
new PathwayEdge(fromVertex, toVertex, pathway.getTraversalTime(), pathway.getWheelchairTraversalTime());
}
}
}
private void loadStops(Graph graph) {
for (Stop stop : _dao.getAllStops()) {
if (stops.contains(stop)) {
continue;
}
stops.add(stop);
//add a vertex representing the stop
TransitStop stopVertex = new TransitStop(graph, stop);
stopVertex.setStreetToStopTime(defaultStreetToStopTime);
stopNodes.put(stop, stopVertex);
if (stop.getLocationType() != 2) {
//add a vertex representing arriving at the stop
TransitStopArrive arrive = new TransitStopArrive(graph, stop);
stopArriveNodes.put(stop, arrive);
//add a vertex representing departing from the stop
TransitStopDepart depart = new TransitStopDepart(graph, stop);
stopDepartNodes.put(stop, depart);
//add edges from arrive to stop and stop to depart
new PreAlightEdge(arrive, stopVertex);
new PreBoardEdge(stopVertex, depart);
}
}
}
/**
* Delete dwell edges that take no time, and merge their start and end vertices.
* For trip patterns that have no trips with dwells, remove the dwell data, and merge the arrival
* and departure times.
*/
private void deleteUselessDwells(Graph graph) {
HashSet<BasicTripPattern> possiblySimplePatterns = new HashSet<BasicTripPattern>();
HashSet<BasicTripPattern> notSimplePatterns = new HashSet<BasicTripPattern>();
for (PatternDwell dwell : potentiallyUselessDwells) {
BasicTripPattern pattern = (BasicTripPattern) dwell.getPattern();
boolean useless = true;
for (int i = 0; i < pattern.getNumDwells(); ++i) {
if (pattern.getDwellTime(dwell.getStopIndex(), i) != 0) {
useless = false;
break;
}
}
if (!useless) {
possiblySimplePatterns.remove(pattern);
notSimplePatterns.add(pattern);
continue;
}
Vertex v = dwell.getFromVertex();
v.mergeFrom(graph, dwell.getToVertex());
if (!notSimplePatterns.contains(pattern)) {
possiblySimplePatterns.add(pattern);
}
}
for (BasicTripPattern pattern: possiblySimplePatterns) {
pattern.simplify();
}
}
private void addTripToInterliningMap(Trip trip, List<StopTime> stopTimes, BasicTripPattern tripPattern) {
String blockId = trip.getBlockId();
BlockIdAndServiceId key = new BlockIdAndServiceId(blockId, trip.getServiceId());
List<InterliningTrip> trips = tripsForBlock.get(key);
if (trips == null) {
trips = new ArrayList<InterliningTrip>();
tripsForBlock.put(key, trips);
}
trips.add(new InterliningTrip(trip, stopTimes, tripPattern));
}
/**
* scan through the given list of stoptimes, interpolating the missing ones.
* this is currently done by assuming equidistant stops and constant speed.
* while we may not be able to improve the constant speed assumption,
* TODO: use route matching (or shape distance etc.) to improve inter-stop distances
*
* @param stopTimes the stoptimes to be filtered (from a single trip)
*/
private void interpolateStopTimes(List<StopTime> stopTimes) {
int lastStop = stopTimes.size() - 1;
int numInterpStops = -1;
int departureTime = -1, prevDepartureTime = -1;
int interpStep = 0;
int i;
for (i = 0; i < lastStop; i++) {
StopTime st0 = stopTimes.get(i);
prevDepartureTime = departureTime;
departureTime = st0.getDepartureTime();
/* Interpolate, if necessary, the times of non-timepoint stops */
/* genuine interpolation needed */
if (!(st0.isDepartureTimeSet() && st0.isArrivalTimeSet())) {
// figure out how many such stops there are in a row.
int j;
StopTime st = null;
for (j = i + 1; j < lastStop + 1; ++j) {
st = stopTimes.get(j);
if ((st.isDepartureTimeSet() && st.getDepartureTime() != departureTime)
|| (st.isArrivalTimeSet() && st.getArrivalTime() != departureTime)) {
break;
}
}
if (j == lastStop + 1) {
throw new RuntimeException(
"Could not interpolate arrival/departure time on stop " + i
+ " (missing final stop time) on trip " + st0.getTrip());
}
numInterpStops = j - i;
int arrivalTime;
if (st.isArrivalTimeSet()) {
arrivalTime = st.getArrivalTime();
} else {
arrivalTime = st.getDepartureTime();
}
interpStep = (arrivalTime - prevDepartureTime) / (numInterpStops + 1);
if (interpStep < 0) {
throw new RuntimeException(
"trip goes backwards for some reason");
}
for (j = i; j < i + numInterpStops; ++j) {
//System.out.println("interpolating " + j + " between " + prevDepartureTime + " and " + arrivalTime);
departureTime = prevDepartureTime + interpStep * (j - i + 1);
st = stopTimes.get(j);
if (st.isArrivalTimeSet()) {
departureTime = st.getArrivalTime();
} else {
st.setArrivalTime(departureTime);
}
if (!st.isDepartureTimeSet()) {
st.setDepartureTime(departureTime);
}
}
i = j - 1;
}
}
}
private BasicTripPattern makeTripPattern(Graph graph, Trip trip, List<StopTime> stopTimes) {
BasicTripPattern tripPattern = new BasicTripPattern(trip, stopTimes);
TraverseMode mode = GtfsLibrary.getTraverseMode(trip.getRoute());
int lastStop = stopTimes.size() - 1;
int i;
StopTime st1 = null;
PatternArriveVertex psv0arrive, psv1arrive = null;
PatternDepartVertex psv0depart;
ArrayList<Edge> createdEdges = new ArrayList<Edge>();
ArrayList<Vertex> createdVertices = new ArrayList<Vertex>();
for (i = 0; i < lastStop; i++) {
StopTime st0 = stopTimes.get(i);
Stop s0 = st0.getStop();
st1 = stopTimes.get(i + 1);
Stop s1 = st1.getStop();
int arrivalTime = st1.getArrivalTime();
int departureTime = st0.getDepartureTime();
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = arrivalTime - departureTime ;
if (runningTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.NEGATIVE_HOP_TIME, st0, st1));
//back out hops and give up
for (Edge e: createdEdges) {
e.getFromVertex().removeOutgoing(e);
e.getToVertex().removeIncoming(e);
}
for (Vertex v : createdVertices) {
graph.removeVertexAndEdges(v);
}
return null;
}
// create journey vertices
psv0depart = new PatternDepartVertex(graph, tripPattern, st0);
createdVertices.add(psv0depart);
patternDepartNodes.put(new T2<Stop, Trip>(s0, trip), psv0depart);
if (i != 0) {
psv0arrive = psv1arrive;
PatternDwell dwell = new PatternDwell(psv0arrive, psv0depart, i, tripPattern);
createdEdges.add(dwell);
if (dwellTime == 0) {
potentiallyUselessDwells.add(dwell);
}
}
psv1arrive = new PatternArriveVertex(graph, tripPattern, st1);
createdVertices.add(psv1arrive);
patternArriveNodes.put(new T2<Stop, Trip>(s1, trip), psv1arrive);
PatternHop hop = new PatternHop(psv0depart, psv1arrive, s0, s1, i,
tripPattern);
createdEdges.add(hop);
hop.setGeometry(getHopGeometry(graph, trip.getShapeId(), st0, st1, psv0depart,
psv1arrive));
tripPattern.addHop(i, 0, departureTime, runningTime, arrivalTime, dwellTime,
st0.getStopHeadsign(), trip);
TransitStopDepart stopDepart = stopDepartNodes.get(s0);
TransitStopArrive stopArrive = stopArriveNodes.get(s1);
Edge board = new PatternBoard(stopDepart, psv0depart, tripPattern, i, mode);
Edge alight = new PatternAlight(psv1arrive, stopArrive, tripPattern, i, mode);
createdEdges.add(board);
createdEdges.add(alight);
}
tripPattern.setTripFlags(0,
((trip.getWheelchairAccessible() == 1) ? TripPattern.FLAG_WHEELCHAIR_ACCESSIBLE : 0)
| (((trip.getRoute().getBikesAllowed() == 2 && trip.getTripBikesAllowed() != 1)
|| trip.getTripBikesAllowed() == 2) ? TripPattern.FLAG_BIKES_ALLOWED : 0));
return tripPattern;
}
private void clearCachedData() {
_log.debug("shapes=" + _geometriesByShapeId.size());
_log.debug("segments=" + _geometriesByShapeSegmentKey.size());
_geometriesByShapeId.clear();
_distancesByShapeId.clear();
_geometriesByShapeSegmentKey.clear();
potentiallyUselessDwells.clear();
}
private void loadTransfers(Graph graph) {
Collection<Transfer> transfers = _dao.getAllTransfers();
TransferTable transferTable = graph.getTransferTable();
for (Transfer t : transfers) {
Stop fromStop = t.getFromStop();
Stop toStop = t.getToStop();
Vertex fromVertex = stopArriveNodes.get(fromStop);
Vertex toVertex = stopDepartNodes.get(toStop);
switch (t.getTransferType()) {
case 1:
// timed (synchronized) transfer
// Handle with edges that bypass the street network.
// from and to vertex here are stop_arrive and stop_depart vertices
new TimedTransferEdge(fromVertex, toVertex);
break;
case 2:
// min transfer time
transferTable.setTransferTime(fromVertex, toVertex, t.getMinTransferTime());
break;
case 3:
// forbidden transfer
transferTable.setTransferTime(fromVertex, toVertex, TransferTable.FORBIDDEN_TRANSFER);
break;
case 0:
default:
// preferred transfer
transferTable.setTransferTime(fromVertex, toVertex, TransferTable.PREFERRED_TRANSFER);
break;
}
}
}
private void createSimpleHops(Graph graph, Trip trip, List<StopTime> stopTimes) {
ArrayList<Hop> hops = new ArrayList<Hop>();
boolean tripWheelchairAccessible = trip.getWheelchairAccessible() == 1;
PatternStopVertex psv0arrive, psv0depart, psv1arrive = null;
ArrayList<Edge> created = new ArrayList<Edge>();
for (int i = 0; i < stopTimes.size() - 1; i++) {
StopTime st0 = stopTimes.get(i);
Stop s0 = st0.getStop();
StopTime st1 = stopTimes.get(i + 1);
Stop s1 = st1.getStop();
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
if (runningTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.NEGATIVE_HOP_TIME, st0, st1));
//back out trip and give up
for (Edge e: created) {
e.getFromVertex().removeOutgoing(e);
e.getToVertex().removeIncoming(e);
}
return;
}
if (dwellTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.NEGATIVE_DWELL_TIME, st0));
dwellTime = 0;
}
Vertex startStation = stopDepartNodes.get(s0);
Vertex endStation = stopArriveNodes.get(s1);
// create and connect journey vertices
if (psv1arrive == null) {
// first iteration
psv0arrive = new PatternArriveVertex(graph, trip, st0);
} else {
// subsequent iterations
psv0arrive = psv1arrive;
}
psv0depart = new PatternDepartVertex(graph, trip, st0);
psv1arrive = new PatternArriveVertex(graph, trip, st1);
new Dwell(psv0arrive, psv0depart, st0);
Hop hop = new Hop(psv0depart, psv1arrive, st0, st1, trip);
created.add(hop);
hop.setGeometry(getHopGeometry(graph, trip.getShapeId(), st0, st1, psv0depart,
psv1arrive));
hops.add(hop);
if (st0.getPickupType() != 1) {
Edge board = new Board(startStation, psv0depart, hop,
tripWheelchairAccessible && s0.getWheelchairBoarding() == 1,
st0.getStop().getZoneId(), trip, st0.getPickupType());
created.add(board);
}
if (st0.getDropOffType() != 1) {
Edge alight = new Alight(psv1arrive, endStation, hop,
tripWheelchairAccessible && s1.getWheelchairBoarding() == 1,
st0.getStop().getZoneId(), trip, st0.getDropOffType());
created.add(alight);
}
}
}
private Geometry getHopGeometry(Graph graph, AgencyAndId shapeId, StopTime st0, StopTime st1,
Vertex startJourney, Vertex endJourney) {
if (shapeId == null || shapeId.getId() == null || shapeId.getId().equals(""))
return null;
double startDistance = st0.getShapeDistTraveled();
double endDistance = st1.getShapeDistTraveled();
boolean hasShapeDist = st0.isShapeDistTraveledSet() && st1.isShapeDistTraveledSet();
if (hasShapeDist) {
ShapeSegmentKey key = new ShapeSegmentKey(shapeId, startDistance, endDistance);
LineString geometry = _geometriesByShapeSegmentKey.get(key);
if (geometry != null)
return geometry;
double[] distances = getDistanceForShapeId(shapeId);
if (distances == null) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.BOGUS_SHAPE_GEOMETRY, shapeId));
return null;
} else {
LinearLocation startIndex = getSegmentFraction(distances, startDistance);
LinearLocation endIndex = getSegmentFraction(distances, endDistance);
LineString line = getLineStringForShapeId(shapeId);
LocationIndexedLine lol = new LocationIndexedLine(line);
return getSegmentGeometry(shapeId, lol, startIndex, endIndex, startDistance,
endDistance);
}
}
LineString line = getLineStringForShapeId(shapeId);
if (line == null) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.BOGUS_SHAPE_GEOMETRY, shapeId));
return null;
}
LocationIndexedLine lol = new LocationIndexedLine(line);
LinearLocation startCoord = lol.indexOf(startJourney.getCoordinate());
LinearLocation endCoord = lol.indexOf(endJourney.getCoordinate());
double distanceFrom = startCoord.getSegmentLength(line);
double distanceTo = endCoord.getSegmentLength(line);
return getSegmentGeometry(shapeId, lol, startCoord, endCoord, distanceFrom, distanceTo);
}
private Geometry getSegmentGeometry(AgencyAndId shapeId,
LocationIndexedLine locationIndexedLine, LinearLocation startIndex,
LinearLocation endIndex, double startDistance, double endDistance) {
ShapeSegmentKey key = new ShapeSegmentKey(shapeId, startDistance, endDistance);
Geometry geometry = _geometriesByShapeSegmentKey.get(key);
if (geometry == null) {
geometry = locationIndexedLine.extractLine(startIndex, endIndex);
// Pack the resulting line string
CoordinateSequence sequence = new PackedCoordinateSequence.Float(geometry
.getCoordinates(), 2);
geometry = _factory.createLineString(sequence);
_geometriesByShapeSegmentKey.put(key, (LineString) geometry);
}
return geometry;
}
/*
* If a shape appears in more than one feed, the shape points will be loaded several
* times, and there will be duplicates in the DAO. Filter out duplicates and repeated
* coordinates because 1) they are unnecessary, and 2) they define 0-length line segments
* which cause JTS location indexed line to return a segment location of NaN,
* which we do not want.
*/
private List<ShapePoint> getUniqueShapePointsForShapeId(AgencyAndId shapeId) {
List<ShapePoint> points = _dao.getShapePointsForShapeId(shapeId);
ArrayList<ShapePoint> filtered = new ArrayList<ShapePoint>(points.size());
ShapePoint last = null;
for (ShapePoint sp : points) {
if (last == null || last.getSequence() != sp.getSequence()) {
if (last != null &&
last.getLat() == sp.getLat() &&
last.getLon() == sp.getLon()) {
_log.trace("pair of identical shape points (skipping): {} {}", last, sp);
} else {
filtered.add(sp);
}
}
last = sp;
}
if (filtered.size() != points.size()) {
filtered.trimToSize();
return filtered;
} else {
return points;
}
}
private LineString getLineStringForShapeId(AgencyAndId shapeId) {
LineString geometry = _geometriesByShapeId.get(shapeId);
if (geometry != null)
return geometry;
List<ShapePoint> points = getUniqueShapePointsForShapeId(shapeId);
if (points.size() < 2) {
return null;
}
Coordinate[] coordinates = new Coordinate[points.size()];
double[] distances = new double[points.size()];
boolean hasAllDistances = true;
int i = 0;
for (ShapePoint point : points) {
coordinates[i] = new Coordinate(point.getLon(), point.getLat());
distances[i] = point.getDistTraveled();
if (!point.isDistTraveledSet())
hasAllDistances = false;
i++;
}
/**
* If we don't have distances here, we can't calculate them ourselves because we can't
* assume the units will match
*/
if (!hasAllDistances) {
distances = null;
}
CoordinateSequence sequence = new PackedCoordinateSequence.Float(coordinates, 2);
geometry = _factory.createLineString(sequence);
_geometriesByShapeId.put(shapeId, geometry);
_distancesByShapeId.put(shapeId, distances);
return geometry;
}
private double[] getDistanceForShapeId(AgencyAndId shapeId) {
getLineStringForShapeId(shapeId);
return _distancesByShapeId.get(shapeId);
}
private LinearLocation getSegmentFraction(double[] distances, double distance) {
int index = Arrays.binarySearch(distances, distance);
if (index < 0)
index = -(index + 1);
if (index == 0)
return new LinearLocation(0, 0.0);
if (index == distances.length)
return new LinearLocation(distances.length, 0.0);
double prevDistance = distances[index - 1];
if (prevDistance == distances[index]) {
return new LinearLocation(index - 1, 1.0);
}
double indexPart = (distance - distances[index - 1])
/ (distances[index] - prevDistance);
return new LinearLocation(index - 1, indexPart);
}
private List<StopTime> getNonduplicateStopTimesForTrip(Trip trip) {
List<StopTime> unfiltered = _dao.getStopTimesForTrip(trip);
ArrayList<StopTime> filtered = new ArrayList<StopTime>(unfiltered.size());
for (StopTime st : unfiltered) {
if (filtered.size() > 0) {
StopTime lastStopTime = filtered.get(filtered.size() - 1);
if (lastStopTime.getStop().equals(st.getStop())) {
lastStopTime.setDepartureTime(st.getDepartureTime());
} else {
filtered.add(st);
}
} else {
filtered.add(st);
}
}
if (filtered.size() == unfiltered.size()) {
return unfiltered;
}
return filtered;
}
public void setFareServiceFactory(FareServiceFactory fareServiceFactory) {
this.fareServiceFactory = fareServiceFactory;
}
/**
* Create transfer edges between stops which are listed in transfers.txt.
* This is not usually useful, but it's nice for the NYC subway system, where
* it's important to provide in-station transfers for fare computation.
*/
public void createStationTransfers(Graph graph) {
/* connect stops to their parent stations
* TODO: provide a cost for these edges when stations and
* stops have different locations
*/
for (Stop stop : _dao.getAllStops()) {
String parentStation = stop.getParentStation();
if (parentStation != null) {
Vertex stopVertex = stopNodes.get(stop);
String agencyId = stop.getId().getAgencyId();
AgencyAndId parentStationId = new AgencyAndId(agencyId, parentStation);
Stop parentStop = _dao.getStopForId(parentStationId);
Vertex parentStopVertex = stopNodes.get(parentStop);
new FreeEdge(parentStopVertex, stopVertex);
new FreeEdge(stopVertex, parentStopVertex);
Vertex stopArriveVertex = stopArriveNodes.get(stop);
Vertex parentStopArriveVertex = stopArriveNodes.get(parentStop);
new FreeEdge(parentStopArriveVertex, stopArriveVertex);
new FreeEdge(stopArriveVertex, parentStopArriveVertex);
Vertex stopDepartVertex = stopDepartNodes.get(stop);
Vertex parentStopDepartVertex = stopDepartNodes.get(parentStop);
new FreeEdge(parentStopDepartVertex, stopDepartVertex);
new FreeEdge(stopDepartVertex, parentStopDepartVertex);
}
}
for (Transfer transfer : _dao.getAllTransfers()) {
int type = transfer.getTransferType();
if (type == 3)
continue;
Vertex fromv = stopArriveNodes.get(transfer.getFromStop());
Vertex tov = stopDepartNodes.get(transfer.getToStop());
if (fromv.equals(tov))
continue;
double distance = DistanceLibrary.distance(fromv.getCoordinate(), tov.getCoordinate());
int time;
if (transfer.getTransferType() == 2) {
time = transfer.getMinTransferTime();
} else {
time = (int) distance; // fixme: handle timed transfers
}
TransferEdge transferEdge = new TransferEdge(fromv, tov, distance, time);
CoordinateSequence sequence = new PackedCoordinateSequence.Float(new Coordinate[] {
fromv.getCoordinate(), tov.getCoordinate() }, 2);
Geometry geometry = _factory.createLineString(sequence);
transferEdge.setGeometry(geometry);
}
}
public int getDefaultStreetToStopTime() {
return defaultStreetToStopTime;
}
public void setDefaultStreetToStopTime(int defaultStreetToStopTime) {
this.defaultStreetToStopTime = defaultStreetToStopTime;
}
}
| false | true | public void run(Graph graph) {
if (fareServiceFactory == null) {
fareServiceFactory = new DefaultFareServiceFactory();
}
fareServiceFactory.setDao(_dao);
// Load stops
loadStops(graph);
loadPathways(graph);
loadAgencies(graph);
// Load hops
_log.debug("Loading hops");
clearCachedData();
/*
* For each trip, create either pattern edges, the entries in a trip pattern's list of
* departures, or simple hops
*/
// Load hops
Collection<Trip> trips = _dao.getAllTrips();
int index = 0;
HashMap<Trip, List<Frequency>> tripFrequencies = new HashMap<Trip, List<Frequency>>();
for(Frequency freq : _dao.getAllFrequencies()) {
List<Frequency> freqs = tripFrequencies.get(freq.getTrip());
if(freqs == null) {
freqs = new ArrayList<Frequency>();
tripFrequencies.put(freq.getTrip(), freqs);
}
freqs.add(freq);
}
for (Trip trip : trips) {
if (index % 100000 == 0)
_log.debug("trips=" + index + "/" + trips.size());
index++;
List<StopTime> stopTimes = getNonduplicateStopTimesForTrip(trip);
filterStopTimes(stopTimes, graph);
interpolateStopTimes(stopTimes);
if (stopTimes.size() < 2) {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.TRIP_DEGENERATE, trip));
continue;
}
List<Frequency> frequencies = tripFrequencies.get(trip);
ScheduledStopPattern stopPattern = stopPatternfromTrip(trip, _dao);
BasicTripPattern tripPattern = patterns.get(stopPattern);
String blockId = trip.getBlockId();
if(frequencies != null) {
//before creating frequency-based trips, check for
//single-instance frequencies.
Frequency frequency = frequencies.get(0);
if (frequencies.size() > 1 || frequency.getStartTime() != stopTimes.get(0).getDepartureTime() ||
frequency.getEndTime() - frequency.getStartTime() > frequency.getHeadwaySecs()) {
FrequencyBasedTripPattern frequencyPattern = makeFrequencyPattern(graph, trip,
stopTimes);
if (frequencyPattern == null) {
continue;
}
frequencyPattern.createRanges(frequencies);
continue;
}
}
boolean simple = false;
if (tripPattern == null) {
tripPattern = makeTripPattern(graph, trip, stopTimes);
if (tripPattern == null) {
continue;
}
patterns.put(stopPattern, tripPattern);
if (blockId != null && !blockId.equals("")) {
addTripToInterliningMap(trip, stopTimes, tripPattern);
}
} else {
int insertionPoint = tripPattern.getDepartureTimeInsertionPoint(stopTimes.get(0)
.getDepartureTime());
if (insertionPoint < 0) {
insertionPoint = -(insertionPoint + 1);
// There's already a departure at this time on this trip pattern. This means
// that either (a) this will have all the same stop times as that one, and thus
// will be a duplicate of it, or (b) it will have different stops, and thus
// break the assumption that trips are non-overlapping.
if (!tripPattern.stopTimesIdentical(stopTimes, insertionPoint)) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.TRIP_DUPLICATE_DEPARTURE, trip.getId(),
tripPattern.getTrip(insertionPoint)));
simple = true;
createSimpleHops(graph, trip, stopTimes);
// break;//?
} else {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.TRIP_DUPLICATE,
trip.getId(), tripPattern.getTrip(insertionPoint)));
break; // not continue - for frequency case
}
} else {
// try to insert this trip at this location
StopTime st1 = null;
int i;
for (i = 0; i < stopTimes.size() - 1; i++) {
StopTime st0 = stopTimes.get(i);
st1 = stopTimes.get(i + 1);
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
if (runningTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.NEGATIVE_HOP_TIME, st0, st1));
// back out hops and give up
for (i = i - 1; i >= 0; --i) {
tripPattern.removeHop(i, insertionPoint);
}
simple = true;
break;
}
if (dwellTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.NEGATIVE_DWELL_TIME, st0));
dwellTime = 0;
}
try {
tripPattern.addHop(i, insertionPoint, st0.getDepartureTime(),
runningTime, st1.getArrivalTime(), dwellTime,
st0.getStopHeadsign(), trip);
} catch (TripOvertakingException e) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.TRIP_OVERTAKING, e.overtaker, e.overtaken, e.stopIndex));
// back out trips and revert to the simple method
for (i = i - 1; i >= 0; --i) {
tripPattern.removeHop(i, insertionPoint);
}
createSimpleHops(graph, trip, stopTimes);
simple = true;
break;
}
}
}
if (!simple) {
if (blockId != null && !blockId.equals("")) {
addTripToInterliningMap(trip, stopTimes, tripPattern);
}
tripPattern
.setTripFlags(
insertionPoint,
((trip.getWheelchairAccessible() == 1) ? TripPattern.FLAG_WHEELCHAIR_ACCESSIBLE
: 0)
| (((trip.getRoute().getBikesAllowed() == 2 && trip
.getTripBikesAllowed() != 1) || trip
.getTripBikesAllowed() == 2) ? TripPattern.FLAG_BIKES_ALLOWED
: 0));
}
}
}
for (List<InterliningTrip> blockTrips : tripsForBlock.values()) {
if (blockTrips.size() == 1) {
//blocks of only a single trip do not need processing
continue;
}
Collections.sort(blockTrips);
/* this is all the trips for this block/schedule */
for (int i = 0; i < blockTrips.size() - 1; ++i) {
InterliningTrip fromInterlineTrip = blockTrips.get(i);
InterliningTrip toInterlineTrip = blockTrips.get(i + 1);
Trip fromTrip = fromInterlineTrip.trip;
Trip toTrip = toInterlineTrip.trip;
StopTime st0 = fromInterlineTrip.lastStopTime;
StopTime st1 = toInterlineTrip.firstStopTime;
Stop s0 = st0.getStop();
Stop s1 = st1.getStop();
if (st0.getPickupType() == 1) {
// do not create an interline dwell when
// the last stop on the arriving trip does not
// allow pickups, since this probably means
// that, while two trips share a block,
// riders cannot stay on the vehicle during the
// deadhead
continue;
}
Trip fromExemplar = fromInterlineTrip.tripPattern.exemplar;
Trip toExemplar = toInterlineTrip.tripPattern.exemplar;
PatternInterlineDwell dwell;
// do we already have a PID for this dwell?
InterlineSwitchoverKey dwellKey = new InterlineSwitchoverKey(s0, s1, fromInterlineTrip.tripPattern, toInterlineTrip.tripPattern);
dwell = getInterlineDwell(dwellKey);
if (dwell == null) {
// create the dwell
Vertex startJourney = patternArriveNodes.get(new T2<Stop, Trip>(s0,fromExemplar));
Vertex endJourney = patternDepartNodes.get(new T2<Stop, Trip>(s1,toExemplar));
dwell = new PatternInterlineDwell(startJourney, endJourney, toTrip);
putInterlineDwell(dwellKey, dwell);
}
int dwellTime = st1.getDepartureTime() - st0.getArrivalTime();
dwell.addTrip(fromTrip.getId(), toTrip.getId(), dwellTime,
fromInterlineTrip.getPatternIndex(), toInterlineTrip.getPatternIndex());
}
}
loadTransfers(graph);
deleteUselessDwells(graph);
clearCachedData();
graph.putService(FareService.class, fareServiceFactory.makeFareService());
}
| public void run(Graph graph) {
if (fareServiceFactory == null) {
fareServiceFactory = new DefaultFareServiceFactory();
}
fareServiceFactory.setDao(_dao);
// Load stops
loadStops(graph);
loadPathways(graph);
loadAgencies(graph);
// Load hops
_log.debug("Loading hops");
clearCachedData();
/*
* For each trip, create either pattern edges, the entries in a trip pattern's list of
* departures, or simple hops
*/
// Load hops
Collection<Trip> trips = _dao.getAllTrips();
int index = 0;
HashMap<Trip, List<Frequency>> tripFrequencies = new HashMap<Trip, List<Frequency>>();
for(Frequency freq : _dao.getAllFrequencies()) {
List<Frequency> freqs = tripFrequencies.get(freq.getTrip());
if(freqs == null) {
freqs = new ArrayList<Frequency>();
tripFrequencies.put(freq.getTrip(), freqs);
}
freqs.add(freq);
}
for (Trip trip : trips) {
index++;
if (index % 100000 == 0)
_log.debug("trips=" + index + "/" + trips.size());
List<StopTime> stopTimes = getNonduplicateStopTimesForTrip(trip);
filterStopTimes(stopTimes, graph);
interpolateStopTimes(stopTimes);
if (stopTimes.size() < 2) {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.TRIP_DEGENERATE, trip));
continue;
}
List<Frequency> frequencies = tripFrequencies.get(trip);
ScheduledStopPattern stopPattern = stopPatternfromTrip(trip, _dao);
BasicTripPattern tripPattern = patterns.get(stopPattern);
String blockId = trip.getBlockId();
if(frequencies != null) {
//before creating frequency-based trips, check for
//single-instance frequencies.
Frequency frequency = frequencies.get(0);
if (frequencies.size() > 1 || frequency.getStartTime() != stopTimes.get(0).getDepartureTime() ||
frequency.getEndTime() - frequency.getStartTime() > frequency.getHeadwaySecs()) {
FrequencyBasedTripPattern frequencyPattern = makeFrequencyPattern(graph, trip,
stopTimes);
if (frequencyPattern == null) {
continue;
}
frequencyPattern.createRanges(frequencies);
continue;
}
}
boolean simple = false;
if (tripPattern == null) {
tripPattern = makeTripPattern(graph, trip, stopTimes);
if (tripPattern == null) {
continue;
}
patterns.put(stopPattern, tripPattern);
if (blockId != null && !blockId.equals("")) {
addTripToInterliningMap(trip, stopTimes, tripPattern);
}
} else {
int insertionPoint = tripPattern.getDepartureTimeInsertionPoint(stopTimes.get(0)
.getDepartureTime());
if (insertionPoint < 0) {
insertionPoint = -(insertionPoint + 1);
// There's already a departure at this time on this trip pattern. This means
// that either (a) this will have all the same stop times as that one, and thus
// will be a duplicate of it, or (b) it will have different stops, and thus
// break the assumption that trips are non-overlapping.
if (!tripPattern.stopTimesIdentical(stopTimes, insertionPoint)) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.TRIP_DUPLICATE_DEPARTURE, trip.getId(),
tripPattern.getTrip(insertionPoint)));
simple = true;
createSimpleHops(graph, trip, stopTimes);
} else {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.TRIP_DUPLICATE,
trip.getId(), tripPattern.getTrip(insertionPoint)));
simple = true;
}
} else {
// try to insert this trip at this location
StopTime st1 = null;
int i;
for (i = 0; i < stopTimes.size() - 1; i++) {
StopTime st0 = stopTimes.get(i);
st1 = stopTimes.get(i + 1);
int dwellTime = st0.getDepartureTime() - st0.getArrivalTime();
int runningTime = st1.getArrivalTime() - st0.getDepartureTime();
if (runningTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.NEGATIVE_HOP_TIME, st0, st1));
// back out hops and give up
for (i = i - 1; i >= 0; --i) {
tripPattern.removeHop(i, insertionPoint);
}
simple = true;
break;
}
if (dwellTime < 0) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.NEGATIVE_DWELL_TIME, st0));
dwellTime = 0;
}
try {
tripPattern.addHop(i, insertionPoint, st0.getDepartureTime(),
runningTime, st1.getArrivalTime(), dwellTime,
st0.getStopHeadsign(), trip);
} catch (TripOvertakingException e) {
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.TRIP_OVERTAKING, e.overtaker, e.overtaken, e.stopIndex));
// back out trips and revert to the simple method
for (i = i - 1; i >= 0; --i) {
tripPattern.removeHop(i, insertionPoint);
}
createSimpleHops(graph, trip, stopTimes);
simple = true;
break;
}
}
}
if (!simple) {
if (blockId != null && !blockId.equals("")) {
addTripToInterliningMap(trip, stopTimes, tripPattern);
}
tripPattern.setTripFlags(insertionPoint,
((trip.getWheelchairAccessible() == 1) ? TripPattern.FLAG_WHEELCHAIR_ACCESSIBLE
: 0)
| (((trip.getRoute().getBikesAllowed() == 2 && trip
.getTripBikesAllowed() != 1) || trip
.getTripBikesAllowed() == 2) ? TripPattern.FLAG_BIKES_ALLOWED
: 0));
}
}
}
for (List<InterliningTrip> blockTrips : tripsForBlock.values()) {
if (blockTrips.size() == 1) {
//blocks of only a single trip do not need processing
continue;
}
Collections.sort(blockTrips);
/* this is all the trips for this block/schedule */
for (int i = 0; i < blockTrips.size() - 1; ++i) {
InterliningTrip fromInterlineTrip = blockTrips.get(i);
InterliningTrip toInterlineTrip = blockTrips.get(i + 1);
Trip fromTrip = fromInterlineTrip.trip;
Trip toTrip = toInterlineTrip.trip;
StopTime st0 = fromInterlineTrip.lastStopTime;
StopTime st1 = toInterlineTrip.firstStopTime;
Stop s0 = st0.getStop();
Stop s1 = st1.getStop();
if (st0.getPickupType() == 1) {
// do not create an interline dwell when
// the last stop on the arriving trip does not
// allow pickups, since this probably means
// that, while two trips share a block,
// riders cannot stay on the vehicle during the
// deadhead
continue;
}
Trip fromExemplar = fromInterlineTrip.tripPattern.exemplar;
Trip toExemplar = toInterlineTrip.tripPattern.exemplar;
PatternInterlineDwell dwell;
// do we already have a PID for this dwell?
InterlineSwitchoverKey dwellKey = new InterlineSwitchoverKey(s0, s1, fromInterlineTrip.tripPattern, toInterlineTrip.tripPattern);
dwell = getInterlineDwell(dwellKey);
if (dwell == null) {
// create the dwell
Vertex startJourney = patternArriveNodes.get(new T2<Stop, Trip>(s0,fromExemplar));
Vertex endJourney = patternDepartNodes.get(new T2<Stop, Trip>(s1,toExemplar));
dwell = new PatternInterlineDwell(startJourney, endJourney, toTrip);
putInterlineDwell(dwellKey, dwell);
}
int dwellTime = st1.getDepartureTime() - st0.getArrivalTime();
dwell.addTrip(fromTrip.getId(), toTrip.getId(), dwellTime,
fromInterlineTrip.getPatternIndex(), toInterlineTrip.getPatternIndex());
}
}
loadTransfers(graph);
deleteUselessDwells(graph);
clearCachedData();
graph.putService(FareService.class, fareServiceFactory.makeFareService());
}
|
diff --git a/plugins/org.eclipse.emf.mwe2.language/src-gen/org/eclipse/emf/mwe2/language/parser/antlr/Mwe2Parser.java b/plugins/org.eclipse.emf.mwe2.language/src-gen/org/eclipse/emf/mwe2/language/parser/antlr/Mwe2Parser.java
index 45f0c976..ee384a72 100644
--- a/plugins/org.eclipse.emf.mwe2.language/src-gen/org/eclipse/emf/mwe2/language/parser/antlr/Mwe2Parser.java
+++ b/plugins/org.eclipse.emf.mwe2.language/src-gen/org/eclipse/emf/mwe2/language/parser/antlr/Mwe2Parser.java
@@ -1,55 +1,56 @@
/*
* generated by Xtext
*/
package org.eclipse.emf.mwe2.language.parser.antlr;
import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.TokenSource;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.parser.ParseException;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import com.google.inject.Inject;
import org.eclipse.emf.mwe2.language.services.Mwe2GrammarAccess;
public class Mwe2Parser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser {
@Inject
private Mwe2GrammarAccess grammarAccess;
@Override
protected IParseResult parse(String ruleName, ANTLRInputStream in) {
TokenSource tokenSource = createLexer(in);
XtextTokenStream tokenStream = createTokenStream(tokenSource);
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
org.eclipse.emf.mwe2.language.parser.antlr.internal.InternalMwe2Parser parser = createParser(tokenStream);
parser.setTokenTypeMap(getTokenDefProvider().getTokenDefMap());
parser.setSyntaxErrorProvider(getSyntaxErrorProvider());
+ parser.setUnorderedGroupHelper(getUnorderedGroupHelper().get());
try {
if(ruleName != null)
return parser.parse(ruleName);
return parser.parse();
} catch (Exception re) {
throw new ParseException(re.getMessage(),re);
}
}
protected org.eclipse.emf.mwe2.language.parser.antlr.internal.InternalMwe2Parser createParser(XtextTokenStream stream) {
return new org.eclipse.emf.mwe2.language.parser.antlr.internal.InternalMwe2Parser(stream, getElementFactory(), getGrammarAccess());
}
@Override
protected String getDefaultRuleName() {
return "Module";
}
public Mwe2GrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(Mwe2GrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}
| true | true | protected IParseResult parse(String ruleName, ANTLRInputStream in) {
TokenSource tokenSource = createLexer(in);
XtextTokenStream tokenStream = createTokenStream(tokenSource);
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
org.eclipse.emf.mwe2.language.parser.antlr.internal.InternalMwe2Parser parser = createParser(tokenStream);
parser.setTokenTypeMap(getTokenDefProvider().getTokenDefMap());
parser.setSyntaxErrorProvider(getSyntaxErrorProvider());
try {
if(ruleName != null)
return parser.parse(ruleName);
return parser.parse();
} catch (Exception re) {
throw new ParseException(re.getMessage(),re);
}
}
| protected IParseResult parse(String ruleName, ANTLRInputStream in) {
TokenSource tokenSource = createLexer(in);
XtextTokenStream tokenStream = createTokenStream(tokenSource);
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
org.eclipse.emf.mwe2.language.parser.antlr.internal.InternalMwe2Parser parser = createParser(tokenStream);
parser.setTokenTypeMap(getTokenDefProvider().getTokenDefMap());
parser.setSyntaxErrorProvider(getSyntaxErrorProvider());
parser.setUnorderedGroupHelper(getUnorderedGroupHelper().get());
try {
if(ruleName != null)
return parser.parse(ruleName);
return parser.parse();
} catch (Exception re) {
throw new ParseException(re.getMessage(),re);
}
}
|
diff --git a/src/risk/view/client/AttackPanel.java b/src/risk/view/client/AttackPanel.java
index 06900f0..457506c 100644
--- a/src/risk/view/client/AttackPanel.java
+++ b/src/risk/view/client/AttackPanel.java
@@ -1,387 +1,386 @@
package risk.view.client;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.SwingConstants;
import java.awt.GridLayout;
import javax.swing.JButton;
import risk.game.Attack;
import risk.game.Controller;
import risk.game.CountryPair;
import java.awt.FlowLayout;
import java.awt.Component;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Font;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.Action;
public class AttackPanel extends JPanel {
private int fromCurrentArmies, toCurrentArmies;
private AttackDialog parent;
private JLabel thrownAttacker, thrownDefender, lblFromAfterArmies, lblToAfterArmies;
private JButton aThreeDice, aTwoDice, aOneDice, btnCancelAttack, dTwoDice, dOneDice;
private Controller controller;
private int viewerType;
private CountryPair cp;
private final Action a3 = new SwingAction();
private final Action a2 = new SwingAction_1();
private final Action a1 = new SwingAction_2();
private final Action aCancel = new SwingAction_3();
private final Action d2 = new SwingAction_4();
private final Action d1 = new SwingAction_5();
/**
* Create the panel.
* viewerType==0: all buttons disabled
* viewerType==1: defender buttons disabled (attacker mode)
* viewerType==2: attacker buttons disabled (defender mode)
*/
public AttackPanel(AttackDialog ad, Attack a, int viewerType, Controller controller) {
this.controller=controller;
this.viewerType=viewerType;
cp=a.getCountryPair();
parent=ad;
setLayout(new BorderLayout(0, 0));
JLabel lblAttack = new JLabel("Attack");
lblAttack.setFont(new Font("Tahoma", Font.BOLD, 12));
lblAttack.setHorizontalAlignment(SwingConstants.CENTER);
add(lblAttack, BorderLayout.NORTH);
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
JPanel panel_1 = new JPanel();
panel.add(panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{102, 0};
gbl_panel_1.rowHeights = new int[]{0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel_1.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
JLabel lblAttacker = new JLabel(cp.From.getOwner().getName());
lblAttacker.setForeground(cp.From.getOwner().getColor());
GridBagConstraints gbc_lblAttacker = new GridBagConstraints();
gbc_lblAttacker.insets = new Insets(0, 0, 5, 0);
gbc_lblAttacker.gridx = 0;
gbc_lblAttacker.gridy = 0;
panel_1.add(lblAttacker, gbc_lblAttacker);
JLabel lblFrom = new JLabel(cp.From.getName());
GridBagConstraints gbc_lblFrom = new GridBagConstraints();
gbc_lblFrom.insets = new Insets(0, 0, 5, 0);
gbc_lblFrom.gridx = 0;
gbc_lblFrom.gridy = 1;
panel_1.add(lblFrom, gbc_lblFrom);
JPanel panel_2 = new JPanel();
GridBagConstraints gbc_panel_2 = new GridBagConstraints();
gbc_panel_2.insets = new Insets(0, 0, 5, 0);
gbc_panel_2.gridx = 0;
gbc_panel_2.gridy = 2;
panel_1.add(panel_2, gbc_panel_2);
panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_2 = new JLabel("Current armies:");
panel_2.add(label_2);
JLabel lblFromCurrentArmies = new JLabel(cp.From.getTroops()+"");
panel_2.add(lblFromCurrentArmies);
JButton aThreeDice = new JButton("Attack with 3 dice");
aThreeDice.setAction(a3);
GridBagConstraints gbc_AThreeDice = new GridBagConstraints();
gbc_AThreeDice.insets = new Insets(0, 0, 5, 0);
gbc_AThreeDice.gridx = 0;
gbc_AThreeDice.gridy = 3;
panel_1.add(aThreeDice, gbc_AThreeDice);
aTwoDice = new JButton("Attack with 2 dice");
aTwoDice.setAction(a2);
GridBagConstraints gbc_ATwoDice = new GridBagConstraints();
gbc_ATwoDice.insets = new Insets(0, 0, 5, 0);
gbc_ATwoDice.gridx = 0;
gbc_ATwoDice.gridy = 4;
panel_1.add(aTwoDice, gbc_ATwoDice);
aOneDice = new JButton("Attack with 1 dice");
aOneDice.setAction(a1);
GridBagConstraints gbc_AOneDice = new GridBagConstraints();
gbc_AOneDice.insets = new Insets(0, 0, 5, 0);
gbc_AOneDice.gridx = 0;
gbc_AOneDice.gridy = 5;
panel_1.add(aOneDice, gbc_AOneDice);
btnCancelAttack = new JButton("Cancel attack");
btnCancelAttack.setAction(aCancel);
GridBagConstraints gbc_btnCancelAttack = new GridBagConstraints();
gbc_btnCancelAttack.insets = new Insets(0, 0, 5, 0);
gbc_btnCancelAttack.gridx = 0;
gbc_btnCancelAttack.gridy = 6;
panel_1.add(btnCancelAttack, gbc_btnCancelAttack);
JPanel panel_6 = new JPanel();
GridBagConstraints gbc_panel_6 = new GridBagConstraints();
gbc_panel_6.insets = new Insets(0, 0, 5, 0);
gbc_panel_6.fill = GridBagConstraints.BOTH;
gbc_panel_6.gridx = 0;
gbc_panel_6.gridy = 7;
panel_1.add(panel_6, gbc_panel_6);
JPanel panel_7 = new JPanel();
GridBagConstraints gbc_panel_7 = new GridBagConstraints();
gbc_panel_7.insets = new Insets(2, 0, 5, 0);
gbc_panel_7.fill = GridBagConstraints.BOTH;
gbc_panel_7.gridx = 0;
gbc_panel_7.gridy = 8;
panel_1.add(panel_7, gbc_panel_7);
panel_7.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_4 = new JLabel("Thrown:");
panel_7.add(label_4);
thrownAttacker = new JLabel("");
panel_7.add(thrownAttacker);
JPanel panel_8 = new JPanel();
GridBagConstraints gbc_panel_8 = new GridBagConstraints();
gbc_panel_8.insets = new Insets(0, 0, 5, 0);
gbc_panel_8.fill = GridBagConstraints.BOTH;
gbc_panel_8.gridx = 0;
gbc_panel_8.gridy = 9;
panel_1.add(panel_8, gbc_panel_8);
panel_8.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_6 = new JLabel("Armies after throwing:");
panel_8.add(label_6);
lblFromAfterArmies = new JLabel("?");
panel_8.add(lblFromAfterArmies);
JPanel panel_3 = new JPanel();
panel.add(panel_3);
GridBagLayout gbl_panel_3 = new GridBagLayout();
gbl_panel_3.columnWidths = new int[]{102, 0};
gbl_panel_3.rowHeights = new int[]{0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel_3.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_3.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, Double.MIN_VALUE};
panel_3.setLayout(gbl_panel_3);
JLabel lblDefender = new JLabel(cp.To.getOwner().getName());
lblDefender.setForeground(cp.To.getOwner().getColor());
GridBagConstraints gbc_lblDefender = new GridBagConstraints();
gbc_lblDefender.insets = new Insets(0, 0, 5, 0);
gbc_lblDefender.gridx = 0;
gbc_lblDefender.gridy = 0;
panel_3.add(lblDefender, gbc_lblDefender);
JLabel lblTo = new JLabel(cp.To.getName());
GridBagConstraints gbc_lblTo = new GridBagConstraints();
gbc_lblTo.insets = new Insets(0, 0, 5, 0);
gbc_lblTo.gridx = 0;
gbc_lblTo.gridy = 1;
panel_3.add(lblTo, gbc_lblTo);
JPanel panel_5 = new JPanel();
GridBagConstraints gbc_panel_5 = new GridBagConstraints();
gbc_panel_5.insets = new Insets(0, 0, 5, 0);
gbc_panel_5.gridx = 0;
gbc_panel_5.gridy = 2;
panel_3.add(panel_5, gbc_panel_5);
panel_5.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
JLabel label = new JLabel("Current armies:");
panel_5.add(label);
JLabel lblToCurrentArmies = new JLabel(cp.To.getTroops()+"");
panel_5.add(lblToCurrentArmies);
dTwoDice = new JButton("Defend with 2 dice");
dTwoDice.setAction(d2);
GridBagConstraints gbc_DTwoDice = new GridBagConstraints();
gbc_DTwoDice.insets = new Insets(0, 0, 5, 0);
gbc_DTwoDice.gridx = 0;
gbc_DTwoDice.gridy = 3;
panel_3.add(dTwoDice, gbc_DTwoDice);
dOneDice = new JButton("Defend with 1 dice");
dOneDice.setAction(d1);
GridBagConstraints gbc_DOneDice = new GridBagConstraints();
gbc_DOneDice.insets = new Insets(0, 0, 5, 0);
gbc_DOneDice.gridx = 0;
gbc_DOneDice.gridy = 4;
panel_3.add(dOneDice, gbc_DOneDice);
JPanel panel_4 = new JPanel();
GridBagConstraints gbc_panel_4 = new GridBagConstraints();
gbc_panel_4.insets = new Insets(0, 0, 5, 0);
gbc_panel_4.fill = GridBagConstraints.BOTH;
gbc_panel_4.gridx = 0;
gbc_panel_4.gridy = 5;
panel_3.add(panel_4, gbc_panel_4);
JPanel panel_9 = new JPanel();
GridBagConstraints gbc_panel_9 = new GridBagConstraints();
gbc_panel_9.anchor = GridBagConstraints.SOUTH;
gbc_panel_9.insets = new Insets(33, 0, 5, 0);
gbc_panel_9.gridx = 0;
gbc_panel_9.gridy = 7;
panel_3.add(panel_9, gbc_panel_9);
panel_9.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_8 = new JLabel("Thrown:");
panel_9.add(label_8);
thrownDefender = new JLabel("");
panel_9.add(thrownDefender);
JPanel panel_10 = new JPanel();
GridBagConstraints gbc_panel_10 = new GridBagConstraints();
gbc_panel_10.anchor = GridBagConstraints.SOUTH;
gbc_panel_10.insets = new Insets(0, 0, 5, 0);
gbc_panel_10.fill = GridBagConstraints.HORIZONTAL;
gbc_panel_10.gridx = 0;
gbc_panel_10.gridy = 8;
panel_3.add(panel_10, gbc_panel_10);
panel_10.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_10 = new JLabel("Armies after throwing:");
panel_10.add(label_10);
lblToAfterArmies = new JLabel("?");
panel_10.add(lblToAfterArmies);
- setButtonsStatus();
setButtonsStatus();
}
public void refresh(Attack attack){
setButtonsStatus();
Collection<Integer> temp=attack.getaDiceResults();
String tempS="";
for(Integer i: temp){
tempS+=i+";";
}
if(tempS.endsWith(";")) tempS.substring(0, tempS.length()-1);
thrownAttacker.setText(tempS);
temp=attack.getdDiceResults();
for(Integer i: temp){
tempS+=i+";";
}
if(tempS.endsWith(";")) tempS.substring(0, tempS.length()-1);
thrownDefender.setText(tempS);
int deltaA=0, deltaD=0;
attack.calcLosses(deltaA, deltaD);
//lblToAfterArmies=
}
private void disableAllButtons(){
dOneDice.setEnabled(false);
dTwoDice.setEnabled(false);
aOneDice.setEnabled(false);
aTwoDice.setEnabled(false);
aThreeDice.setEnabled(false);
btnCancelAttack.setEnabled(false);
}
private void setButtonsStatus(){
if(viewerType==0){
dOneDice.setEnabled(false);
dTwoDice.setEnabled(false);
aOneDice.setEnabled(false);
aTwoDice.setEnabled(false);
aThreeDice.setEnabled(false);
btnCancelAttack.setEnabled(false);
}
if (viewerType==1){
if(cp.From.getTroops()<4) aThreeDice.setEnabled(false);
if(cp.From.getTroops()<3) aTwoDice.setEnabled(false);
if(cp.From.getTroops()<2) aOneDice.setEnabled(false);
dOneDice.setEnabled(false);
dTwoDice.setEnabled(false);
}
if(viewerType==2){
if(cp.From.getTroops()<2) dTwoDice.setEnabled(false);
if(cp.From.getTroops()<1) dOneDice.setEnabled(false);
aOneDice.setEnabled(false);
aTwoDice.setEnabled(false);
aThreeDice.setEnabled(false);
btnCancelAttack.setEnabled(false);
}
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Attack with 3 dice");
putValue(SHORT_DESCRIPTION, "Attack with 3 dice");
}
public void actionPerformed(ActionEvent e) {
disableAllButtons();
controller.onAttack_AttackerChose(3);
}
}
private class SwingAction_1 extends AbstractAction {
public SwingAction_1() {
putValue(NAME, "Attack with 2 dice");
putValue(SHORT_DESCRIPTION, "Attack with 2 dice");
}
public void actionPerformed(ActionEvent e) {
disableAllButtons();
controller.onAttack_AttackerChose(2);
}
}
private class SwingAction_2 extends AbstractAction {
public SwingAction_2() {
putValue(NAME, "Attack with 1 dice");
putValue(SHORT_DESCRIPTION, "Attack with 1 dice");
}
public void actionPerformed(ActionEvent e) {
disableAllButtons();
controller.onAttack_AttackerChose(1);
}
}
private class SwingAction_3 extends AbstractAction {
public SwingAction_3() {
putValue(NAME, "Cancel attack");
putValue(SHORT_DESCRIPTION, "Cancel attack");
}
public void actionPerformed(ActionEvent e) {
disableAllButtons();
controller.onAttackRetreat();
}
}
private class SwingAction_4 extends AbstractAction {
public SwingAction_4() {
putValue(NAME, "Defend with 2 dice");
putValue(SHORT_DESCRIPTION, "Defend with 1 dice");
}
public void actionPerformed(ActionEvent e) {
disableAllButtons();
controller.onAttack_DefenderChose(2);
}
}
private class SwingAction_5 extends AbstractAction {
public SwingAction_5() {
putValue(NAME, "Defend with 1 dice");
putValue(SHORT_DESCRIPTION, "Defend with 1 dice");
}
public void actionPerformed(ActionEvent e) {
disableAllButtons();
controller.onAttack_DefenderChose(1);
}
}
}
| true | true | public AttackPanel(AttackDialog ad, Attack a, int viewerType, Controller controller) {
this.controller=controller;
this.viewerType=viewerType;
cp=a.getCountryPair();
parent=ad;
setLayout(new BorderLayout(0, 0));
JLabel lblAttack = new JLabel("Attack");
lblAttack.setFont(new Font("Tahoma", Font.BOLD, 12));
lblAttack.setHorizontalAlignment(SwingConstants.CENTER);
add(lblAttack, BorderLayout.NORTH);
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
JPanel panel_1 = new JPanel();
panel.add(panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{102, 0};
gbl_panel_1.rowHeights = new int[]{0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel_1.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
JLabel lblAttacker = new JLabel(cp.From.getOwner().getName());
lblAttacker.setForeground(cp.From.getOwner().getColor());
GridBagConstraints gbc_lblAttacker = new GridBagConstraints();
gbc_lblAttacker.insets = new Insets(0, 0, 5, 0);
gbc_lblAttacker.gridx = 0;
gbc_lblAttacker.gridy = 0;
panel_1.add(lblAttacker, gbc_lblAttacker);
JLabel lblFrom = new JLabel(cp.From.getName());
GridBagConstraints gbc_lblFrom = new GridBagConstraints();
gbc_lblFrom.insets = new Insets(0, 0, 5, 0);
gbc_lblFrom.gridx = 0;
gbc_lblFrom.gridy = 1;
panel_1.add(lblFrom, gbc_lblFrom);
JPanel panel_2 = new JPanel();
GridBagConstraints gbc_panel_2 = new GridBagConstraints();
gbc_panel_2.insets = new Insets(0, 0, 5, 0);
gbc_panel_2.gridx = 0;
gbc_panel_2.gridy = 2;
panel_1.add(panel_2, gbc_panel_2);
panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_2 = new JLabel("Current armies:");
panel_2.add(label_2);
JLabel lblFromCurrentArmies = new JLabel(cp.From.getTroops()+"");
panel_2.add(lblFromCurrentArmies);
JButton aThreeDice = new JButton("Attack with 3 dice");
aThreeDice.setAction(a3);
GridBagConstraints gbc_AThreeDice = new GridBagConstraints();
gbc_AThreeDice.insets = new Insets(0, 0, 5, 0);
gbc_AThreeDice.gridx = 0;
gbc_AThreeDice.gridy = 3;
panel_1.add(aThreeDice, gbc_AThreeDice);
aTwoDice = new JButton("Attack with 2 dice");
aTwoDice.setAction(a2);
GridBagConstraints gbc_ATwoDice = new GridBagConstraints();
gbc_ATwoDice.insets = new Insets(0, 0, 5, 0);
gbc_ATwoDice.gridx = 0;
gbc_ATwoDice.gridy = 4;
panel_1.add(aTwoDice, gbc_ATwoDice);
aOneDice = new JButton("Attack with 1 dice");
aOneDice.setAction(a1);
GridBagConstraints gbc_AOneDice = new GridBagConstraints();
gbc_AOneDice.insets = new Insets(0, 0, 5, 0);
gbc_AOneDice.gridx = 0;
gbc_AOneDice.gridy = 5;
panel_1.add(aOneDice, gbc_AOneDice);
btnCancelAttack = new JButton("Cancel attack");
btnCancelAttack.setAction(aCancel);
GridBagConstraints gbc_btnCancelAttack = new GridBagConstraints();
gbc_btnCancelAttack.insets = new Insets(0, 0, 5, 0);
gbc_btnCancelAttack.gridx = 0;
gbc_btnCancelAttack.gridy = 6;
panel_1.add(btnCancelAttack, gbc_btnCancelAttack);
JPanel panel_6 = new JPanel();
GridBagConstraints gbc_panel_6 = new GridBagConstraints();
gbc_panel_6.insets = new Insets(0, 0, 5, 0);
gbc_panel_6.fill = GridBagConstraints.BOTH;
gbc_panel_6.gridx = 0;
gbc_panel_6.gridy = 7;
panel_1.add(panel_6, gbc_panel_6);
JPanel panel_7 = new JPanel();
GridBagConstraints gbc_panel_7 = new GridBagConstraints();
gbc_panel_7.insets = new Insets(2, 0, 5, 0);
gbc_panel_7.fill = GridBagConstraints.BOTH;
gbc_panel_7.gridx = 0;
gbc_panel_7.gridy = 8;
panel_1.add(panel_7, gbc_panel_7);
panel_7.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_4 = new JLabel("Thrown:");
panel_7.add(label_4);
thrownAttacker = new JLabel("");
panel_7.add(thrownAttacker);
JPanel panel_8 = new JPanel();
GridBagConstraints gbc_panel_8 = new GridBagConstraints();
gbc_panel_8.insets = new Insets(0, 0, 5, 0);
gbc_panel_8.fill = GridBagConstraints.BOTH;
gbc_panel_8.gridx = 0;
gbc_panel_8.gridy = 9;
panel_1.add(panel_8, gbc_panel_8);
panel_8.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_6 = new JLabel("Armies after throwing:");
panel_8.add(label_6);
lblFromAfterArmies = new JLabel("?");
panel_8.add(lblFromAfterArmies);
JPanel panel_3 = new JPanel();
panel.add(panel_3);
GridBagLayout gbl_panel_3 = new GridBagLayout();
gbl_panel_3.columnWidths = new int[]{102, 0};
gbl_panel_3.rowHeights = new int[]{0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel_3.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_3.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, Double.MIN_VALUE};
panel_3.setLayout(gbl_panel_3);
JLabel lblDefender = new JLabel(cp.To.getOwner().getName());
lblDefender.setForeground(cp.To.getOwner().getColor());
GridBagConstraints gbc_lblDefender = new GridBagConstraints();
gbc_lblDefender.insets = new Insets(0, 0, 5, 0);
gbc_lblDefender.gridx = 0;
gbc_lblDefender.gridy = 0;
panel_3.add(lblDefender, gbc_lblDefender);
JLabel lblTo = new JLabel(cp.To.getName());
GridBagConstraints gbc_lblTo = new GridBagConstraints();
gbc_lblTo.insets = new Insets(0, 0, 5, 0);
gbc_lblTo.gridx = 0;
gbc_lblTo.gridy = 1;
panel_3.add(lblTo, gbc_lblTo);
JPanel panel_5 = new JPanel();
GridBagConstraints gbc_panel_5 = new GridBagConstraints();
gbc_panel_5.insets = new Insets(0, 0, 5, 0);
gbc_panel_5.gridx = 0;
gbc_panel_5.gridy = 2;
panel_3.add(panel_5, gbc_panel_5);
panel_5.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
JLabel label = new JLabel("Current armies:");
panel_5.add(label);
JLabel lblToCurrentArmies = new JLabel(cp.To.getTroops()+"");
panel_5.add(lblToCurrentArmies);
dTwoDice = new JButton("Defend with 2 dice");
dTwoDice.setAction(d2);
GridBagConstraints gbc_DTwoDice = new GridBagConstraints();
gbc_DTwoDice.insets = new Insets(0, 0, 5, 0);
gbc_DTwoDice.gridx = 0;
gbc_DTwoDice.gridy = 3;
panel_3.add(dTwoDice, gbc_DTwoDice);
dOneDice = new JButton("Defend with 1 dice");
dOneDice.setAction(d1);
GridBagConstraints gbc_DOneDice = new GridBagConstraints();
gbc_DOneDice.insets = new Insets(0, 0, 5, 0);
gbc_DOneDice.gridx = 0;
gbc_DOneDice.gridy = 4;
panel_3.add(dOneDice, gbc_DOneDice);
JPanel panel_4 = new JPanel();
GridBagConstraints gbc_panel_4 = new GridBagConstraints();
gbc_panel_4.insets = new Insets(0, 0, 5, 0);
gbc_panel_4.fill = GridBagConstraints.BOTH;
gbc_panel_4.gridx = 0;
gbc_panel_4.gridy = 5;
panel_3.add(panel_4, gbc_panel_4);
JPanel panel_9 = new JPanel();
GridBagConstraints gbc_panel_9 = new GridBagConstraints();
gbc_panel_9.anchor = GridBagConstraints.SOUTH;
gbc_panel_9.insets = new Insets(33, 0, 5, 0);
gbc_panel_9.gridx = 0;
gbc_panel_9.gridy = 7;
panel_3.add(panel_9, gbc_panel_9);
panel_9.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_8 = new JLabel("Thrown:");
panel_9.add(label_8);
thrownDefender = new JLabel("");
panel_9.add(thrownDefender);
JPanel panel_10 = new JPanel();
GridBagConstraints gbc_panel_10 = new GridBagConstraints();
gbc_panel_10.anchor = GridBagConstraints.SOUTH;
gbc_panel_10.insets = new Insets(0, 0, 5, 0);
gbc_panel_10.fill = GridBagConstraints.HORIZONTAL;
gbc_panel_10.gridx = 0;
gbc_panel_10.gridy = 8;
panel_3.add(panel_10, gbc_panel_10);
panel_10.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_10 = new JLabel("Armies after throwing:");
panel_10.add(label_10);
lblToAfterArmies = new JLabel("?");
panel_10.add(lblToAfterArmies);
setButtonsStatus();
setButtonsStatus();
}
| public AttackPanel(AttackDialog ad, Attack a, int viewerType, Controller controller) {
this.controller=controller;
this.viewerType=viewerType;
cp=a.getCountryPair();
parent=ad;
setLayout(new BorderLayout(0, 0));
JLabel lblAttack = new JLabel("Attack");
lblAttack.setFont(new Font("Tahoma", Font.BOLD, 12));
lblAttack.setHorizontalAlignment(SwingConstants.CENTER);
add(lblAttack, BorderLayout.NORTH);
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
JPanel panel_1 = new JPanel();
panel.add(panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{102, 0};
gbl_panel_1.rowHeights = new int[]{0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel_1.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
JLabel lblAttacker = new JLabel(cp.From.getOwner().getName());
lblAttacker.setForeground(cp.From.getOwner().getColor());
GridBagConstraints gbc_lblAttacker = new GridBagConstraints();
gbc_lblAttacker.insets = new Insets(0, 0, 5, 0);
gbc_lblAttacker.gridx = 0;
gbc_lblAttacker.gridy = 0;
panel_1.add(lblAttacker, gbc_lblAttacker);
JLabel lblFrom = new JLabel(cp.From.getName());
GridBagConstraints gbc_lblFrom = new GridBagConstraints();
gbc_lblFrom.insets = new Insets(0, 0, 5, 0);
gbc_lblFrom.gridx = 0;
gbc_lblFrom.gridy = 1;
panel_1.add(lblFrom, gbc_lblFrom);
JPanel panel_2 = new JPanel();
GridBagConstraints gbc_panel_2 = new GridBagConstraints();
gbc_panel_2.insets = new Insets(0, 0, 5, 0);
gbc_panel_2.gridx = 0;
gbc_panel_2.gridy = 2;
panel_1.add(panel_2, gbc_panel_2);
panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_2 = new JLabel("Current armies:");
panel_2.add(label_2);
JLabel lblFromCurrentArmies = new JLabel(cp.From.getTroops()+"");
panel_2.add(lblFromCurrentArmies);
JButton aThreeDice = new JButton("Attack with 3 dice");
aThreeDice.setAction(a3);
GridBagConstraints gbc_AThreeDice = new GridBagConstraints();
gbc_AThreeDice.insets = new Insets(0, 0, 5, 0);
gbc_AThreeDice.gridx = 0;
gbc_AThreeDice.gridy = 3;
panel_1.add(aThreeDice, gbc_AThreeDice);
aTwoDice = new JButton("Attack with 2 dice");
aTwoDice.setAction(a2);
GridBagConstraints gbc_ATwoDice = new GridBagConstraints();
gbc_ATwoDice.insets = new Insets(0, 0, 5, 0);
gbc_ATwoDice.gridx = 0;
gbc_ATwoDice.gridy = 4;
panel_1.add(aTwoDice, gbc_ATwoDice);
aOneDice = new JButton("Attack with 1 dice");
aOneDice.setAction(a1);
GridBagConstraints gbc_AOneDice = new GridBagConstraints();
gbc_AOneDice.insets = new Insets(0, 0, 5, 0);
gbc_AOneDice.gridx = 0;
gbc_AOneDice.gridy = 5;
panel_1.add(aOneDice, gbc_AOneDice);
btnCancelAttack = new JButton("Cancel attack");
btnCancelAttack.setAction(aCancel);
GridBagConstraints gbc_btnCancelAttack = new GridBagConstraints();
gbc_btnCancelAttack.insets = new Insets(0, 0, 5, 0);
gbc_btnCancelAttack.gridx = 0;
gbc_btnCancelAttack.gridy = 6;
panel_1.add(btnCancelAttack, gbc_btnCancelAttack);
JPanel panel_6 = new JPanel();
GridBagConstraints gbc_panel_6 = new GridBagConstraints();
gbc_panel_6.insets = new Insets(0, 0, 5, 0);
gbc_panel_6.fill = GridBagConstraints.BOTH;
gbc_panel_6.gridx = 0;
gbc_panel_6.gridy = 7;
panel_1.add(panel_6, gbc_panel_6);
JPanel panel_7 = new JPanel();
GridBagConstraints gbc_panel_7 = new GridBagConstraints();
gbc_panel_7.insets = new Insets(2, 0, 5, 0);
gbc_panel_7.fill = GridBagConstraints.BOTH;
gbc_panel_7.gridx = 0;
gbc_panel_7.gridy = 8;
panel_1.add(panel_7, gbc_panel_7);
panel_7.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_4 = new JLabel("Thrown:");
panel_7.add(label_4);
thrownAttacker = new JLabel("");
panel_7.add(thrownAttacker);
JPanel panel_8 = new JPanel();
GridBagConstraints gbc_panel_8 = new GridBagConstraints();
gbc_panel_8.insets = new Insets(0, 0, 5, 0);
gbc_panel_8.fill = GridBagConstraints.BOTH;
gbc_panel_8.gridx = 0;
gbc_panel_8.gridy = 9;
panel_1.add(panel_8, gbc_panel_8);
panel_8.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_6 = new JLabel("Armies after throwing:");
panel_8.add(label_6);
lblFromAfterArmies = new JLabel("?");
panel_8.add(lblFromAfterArmies);
JPanel panel_3 = new JPanel();
panel.add(panel_3);
GridBagLayout gbl_panel_3 = new GridBagLayout();
gbl_panel_3.columnWidths = new int[]{102, 0};
gbl_panel_3.rowHeights = new int[]{0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel_3.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_3.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, Double.MIN_VALUE};
panel_3.setLayout(gbl_panel_3);
JLabel lblDefender = new JLabel(cp.To.getOwner().getName());
lblDefender.setForeground(cp.To.getOwner().getColor());
GridBagConstraints gbc_lblDefender = new GridBagConstraints();
gbc_lblDefender.insets = new Insets(0, 0, 5, 0);
gbc_lblDefender.gridx = 0;
gbc_lblDefender.gridy = 0;
panel_3.add(lblDefender, gbc_lblDefender);
JLabel lblTo = new JLabel(cp.To.getName());
GridBagConstraints gbc_lblTo = new GridBagConstraints();
gbc_lblTo.insets = new Insets(0, 0, 5, 0);
gbc_lblTo.gridx = 0;
gbc_lblTo.gridy = 1;
panel_3.add(lblTo, gbc_lblTo);
JPanel panel_5 = new JPanel();
GridBagConstraints gbc_panel_5 = new GridBagConstraints();
gbc_panel_5.insets = new Insets(0, 0, 5, 0);
gbc_panel_5.gridx = 0;
gbc_panel_5.gridy = 2;
panel_3.add(panel_5, gbc_panel_5);
panel_5.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
JLabel label = new JLabel("Current armies:");
panel_5.add(label);
JLabel lblToCurrentArmies = new JLabel(cp.To.getTroops()+"");
panel_5.add(lblToCurrentArmies);
dTwoDice = new JButton("Defend with 2 dice");
dTwoDice.setAction(d2);
GridBagConstraints gbc_DTwoDice = new GridBagConstraints();
gbc_DTwoDice.insets = new Insets(0, 0, 5, 0);
gbc_DTwoDice.gridx = 0;
gbc_DTwoDice.gridy = 3;
panel_3.add(dTwoDice, gbc_DTwoDice);
dOneDice = new JButton("Defend with 1 dice");
dOneDice.setAction(d1);
GridBagConstraints gbc_DOneDice = new GridBagConstraints();
gbc_DOneDice.insets = new Insets(0, 0, 5, 0);
gbc_DOneDice.gridx = 0;
gbc_DOneDice.gridy = 4;
panel_3.add(dOneDice, gbc_DOneDice);
JPanel panel_4 = new JPanel();
GridBagConstraints gbc_panel_4 = new GridBagConstraints();
gbc_panel_4.insets = new Insets(0, 0, 5, 0);
gbc_panel_4.fill = GridBagConstraints.BOTH;
gbc_panel_4.gridx = 0;
gbc_panel_4.gridy = 5;
panel_3.add(panel_4, gbc_panel_4);
JPanel panel_9 = new JPanel();
GridBagConstraints gbc_panel_9 = new GridBagConstraints();
gbc_panel_9.anchor = GridBagConstraints.SOUTH;
gbc_panel_9.insets = new Insets(33, 0, 5, 0);
gbc_panel_9.gridx = 0;
gbc_panel_9.gridy = 7;
panel_3.add(panel_9, gbc_panel_9);
panel_9.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_8 = new JLabel("Thrown:");
panel_9.add(label_8);
thrownDefender = new JLabel("");
panel_9.add(thrownDefender);
JPanel panel_10 = new JPanel();
GridBagConstraints gbc_panel_10 = new GridBagConstraints();
gbc_panel_10.anchor = GridBagConstraints.SOUTH;
gbc_panel_10.insets = new Insets(0, 0, 5, 0);
gbc_panel_10.fill = GridBagConstraints.HORIZONTAL;
gbc_panel_10.gridx = 0;
gbc_panel_10.gridy = 8;
panel_3.add(panel_10, gbc_panel_10);
panel_10.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel label_10 = new JLabel("Armies after throwing:");
panel_10.add(label_10);
lblToAfterArmies = new JLabel("?");
panel_10.add(lblToAfterArmies);
setButtonsStatus();
}
|
diff --git a/src/main/java/uk/co/oliwali/HawkEye/SearchParser.java b/src/main/java/uk/co/oliwali/HawkEye/SearchParser.java
index 30c8bf8..ec2def6 100644
--- a/src/main/java/uk/co/oliwali/HawkEye/SearchParser.java
+++ b/src/main/java/uk/co/oliwali/HawkEye/SearchParser.java
@@ -1,194 +1,196 @@
package uk.co.oliwali.HawkEye;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import uk.co.oliwali.HawkEye.util.Permission;
import uk.co.oliwali.HawkEye.util.Util;
/**
* Class for parsing HawkEye arguments ready to be used by an instance of {@SearchQuery}
* @author oliverw92
*/
public class SearchParser {
public Player player = null;
public String[] players = null;
public Vector loc = null;
public Vector minLoc = null;
public Vector maxLoc = null;
public Integer radius = null;
public List<DataType> actions = new ArrayList<DataType>();
public String[] worlds = null;
public String dateFrom = null;
public String dateTo = null;
public String[] filters = null;
public SearchParser() { }
public SearchParser(Player player) {
this.player = player;
}
public SearchParser(Player player, int radius) {
this.player = player;
this.radius = radius;
parseLocations();
}
public SearchParser(Player player, List<String> args) throws IllegalArgumentException {
this.player = player;
for (String arg : args) {
//Check if argument has a valid prefix
if (arg.equalsIgnoreCase("")) continue;
String param = arg.substring(0,1).toLowerCase();
+ if (!arg.contains(":"))
+ throw new IllegalArgumentException("Invalid argument format: &7" + arg);
if (!arg.substring(1,2).equals(":"))
throw new IllegalArgumentException("Invalid argument format: &7" + arg);
String[] values = arg.substring(2).split(",");
//Players
if (param.equals("p")) players = values;
//Worlds
else if (param.equals("w")) worlds = values;
//Filters
else if (param.equals("f")) {
if (filters != null) filters = Util.concat(filters, values);
else filters = values;
}
//Blocks
else if (param.equals("b")) {
for (int i = 1; i < values.length; i++) {
if (Material.getMaterial(values[i]) != null)
values[i] = Integer.toString(Material.getMaterial(values[i]).getId());
}
if (filters != null) filters = Util.concat(filters, values);
else filters = values;
}
//Actions
else if (param.equals("a")) {
for (String value : values) {
DataType type = DataType.fromName(value);
if (type == null) throw new IllegalArgumentException("Invalid action supplied: &7" + value);
if (!Permission.searchType(player, type.getConfigName())) throw new IllegalArgumentException("You do not have permission to search for: &7" + type.getConfigName());
actions.add(type);
}
}
//Location
else if (param.equals("l")) {
if (values[0].equalsIgnoreCase("here"))
loc = player.getLocation().toVector();
else {
loc = new Vector();
loc.setX(Integer.parseInt(values[0]));
loc.setY(Integer.parseInt(values[1]));
loc.setZ(Integer.parseInt(values[2]));
}
}
//Radius
else if (param.equals("r")) {
if (!Util.isInteger(values[0])) throw new IllegalArgumentException("Invalid radius supplied: &7" + values[0]);
radius = Integer.parseInt(values[0]);
}
//Time
else if (param.equals("t")) {
int type = 2;
for (int i = 0; i < arg.length(); i++) {
String c = arg.substring(i, i+1);
if (!Util.isInteger(c)) {
if (c.equals("m") || c .equals("s") || c.equals("h") || c.equals("d") || c.equals("w"))
type = 0;
if (c.equals("-") || c.equals(":"))
type = 1;
}
}
//If the time is in the format '0w0d0h0m0s'
if (type == 0) {
int weeks = 0;
int days = 0;
int hours = 0;
int mins = 0;
int secs = 0;
String nums = "";
for (int i = 0; i < values[0].length(); i++) {
String c = values[0].substring(i, i+1);
if (Util.isInteger(c)) {
nums += c;
continue;
}
int num = Integer.parseInt(nums);
if (c.equals("w")) weeks = num;
else if (c.equals("d")) days = num;
else if (c.equals("h")) hours = num;
else if (c.equals("m")) mins = num;
else if (c.equals("s")) secs = num;
else throw new IllegalArgumentException("Invalid time measurement: &7" + c);
nums = "";
}
Calendar cal = Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks);
cal.add(Calendar.DAY_OF_MONTH, -1 * days);
cal.add(Calendar.HOUR, -1 * hours);
cal.add(Calendar.MINUTE, -1 * mins);
cal.add(Calendar.SECOND, -1 * secs);
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFrom = form.format(cal.getTime());
}
//If the time is in the format 'yyyy-MM-dd HH:mm:ss'
else if (type == 1) {
if (values.length == 1) {
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd");
dateFrom = form.format(Calendar.getInstance().getTime()) + " " + values[0];
}
if (values.length >= 2)
dateFrom = values[0] + " " + values[1];
if (values.length == 4)
dateTo = values[2] + " " + values[3];
}
//Invalid time format
else if (type == 2)
throw new IllegalArgumentException("Invalid time format!");
}
else throw new IllegalArgumentException("Invalid parameter supplied: &7" + param);
}
//Sort out locations
parseLocations();
}
/**
* Formats min and max locations if the radius is set
*/
public void parseLocations() {
//If the radius is set we need to format the min and max locations
if (radius != null) {
//Check if location and world are supplied
if (loc == null) loc = player.getLocation().toVector();
if (worlds == null) worlds = new String[]{ player.getWorld().getName() };
//Format min and max
minLoc = new Vector(loc.getX() - radius, loc.getY() - radius, loc.getZ() - radius);
maxLoc = new Vector(loc.getX() + radius, loc.getY() + radius, loc.getZ() + radius);
}
}
}
| true | true | public SearchParser(Player player, List<String> args) throws IllegalArgumentException {
this.player = player;
for (String arg : args) {
//Check if argument has a valid prefix
if (arg.equalsIgnoreCase("")) continue;
String param = arg.substring(0,1).toLowerCase();
if (!arg.substring(1,2).equals(":"))
throw new IllegalArgumentException("Invalid argument format: &7" + arg);
String[] values = arg.substring(2).split(",");
//Players
if (param.equals("p")) players = values;
//Worlds
else if (param.equals("w")) worlds = values;
//Filters
else if (param.equals("f")) {
if (filters != null) filters = Util.concat(filters, values);
else filters = values;
}
//Blocks
else if (param.equals("b")) {
for (int i = 1; i < values.length; i++) {
if (Material.getMaterial(values[i]) != null)
values[i] = Integer.toString(Material.getMaterial(values[i]).getId());
}
if (filters != null) filters = Util.concat(filters, values);
else filters = values;
}
//Actions
else if (param.equals("a")) {
for (String value : values) {
DataType type = DataType.fromName(value);
if (type == null) throw new IllegalArgumentException("Invalid action supplied: &7" + value);
if (!Permission.searchType(player, type.getConfigName())) throw new IllegalArgumentException("You do not have permission to search for: &7" + type.getConfigName());
actions.add(type);
}
}
//Location
else if (param.equals("l")) {
if (values[0].equalsIgnoreCase("here"))
loc = player.getLocation().toVector();
else {
loc = new Vector();
loc.setX(Integer.parseInt(values[0]));
loc.setY(Integer.parseInt(values[1]));
loc.setZ(Integer.parseInt(values[2]));
}
}
//Radius
else if (param.equals("r")) {
if (!Util.isInteger(values[0])) throw new IllegalArgumentException("Invalid radius supplied: &7" + values[0]);
radius = Integer.parseInt(values[0]);
}
//Time
else if (param.equals("t")) {
int type = 2;
for (int i = 0; i < arg.length(); i++) {
String c = arg.substring(i, i+1);
if (!Util.isInteger(c)) {
if (c.equals("m") || c .equals("s") || c.equals("h") || c.equals("d") || c.equals("w"))
type = 0;
if (c.equals("-") || c.equals(":"))
type = 1;
}
}
//If the time is in the format '0w0d0h0m0s'
if (type == 0) {
int weeks = 0;
int days = 0;
int hours = 0;
int mins = 0;
int secs = 0;
String nums = "";
for (int i = 0; i < values[0].length(); i++) {
String c = values[0].substring(i, i+1);
if (Util.isInteger(c)) {
nums += c;
continue;
}
int num = Integer.parseInt(nums);
if (c.equals("w")) weeks = num;
else if (c.equals("d")) days = num;
else if (c.equals("h")) hours = num;
else if (c.equals("m")) mins = num;
else if (c.equals("s")) secs = num;
else throw new IllegalArgumentException("Invalid time measurement: &7" + c);
nums = "";
}
Calendar cal = Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks);
cal.add(Calendar.DAY_OF_MONTH, -1 * days);
cal.add(Calendar.HOUR, -1 * hours);
cal.add(Calendar.MINUTE, -1 * mins);
cal.add(Calendar.SECOND, -1 * secs);
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFrom = form.format(cal.getTime());
}
//If the time is in the format 'yyyy-MM-dd HH:mm:ss'
else if (type == 1) {
if (values.length == 1) {
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd");
dateFrom = form.format(Calendar.getInstance().getTime()) + " " + values[0];
}
if (values.length >= 2)
dateFrom = values[0] + " " + values[1];
if (values.length == 4)
dateTo = values[2] + " " + values[3];
}
//Invalid time format
else if (type == 2)
throw new IllegalArgumentException("Invalid time format!");
}
else throw new IllegalArgumentException("Invalid parameter supplied: &7" + param);
}
//Sort out locations
parseLocations();
}
| public SearchParser(Player player, List<String> args) throws IllegalArgumentException {
this.player = player;
for (String arg : args) {
//Check if argument has a valid prefix
if (arg.equalsIgnoreCase("")) continue;
String param = arg.substring(0,1).toLowerCase();
if (!arg.contains(":"))
throw new IllegalArgumentException("Invalid argument format: &7" + arg);
if (!arg.substring(1,2).equals(":"))
throw new IllegalArgumentException("Invalid argument format: &7" + arg);
String[] values = arg.substring(2).split(",");
//Players
if (param.equals("p")) players = values;
//Worlds
else if (param.equals("w")) worlds = values;
//Filters
else if (param.equals("f")) {
if (filters != null) filters = Util.concat(filters, values);
else filters = values;
}
//Blocks
else if (param.equals("b")) {
for (int i = 1; i < values.length; i++) {
if (Material.getMaterial(values[i]) != null)
values[i] = Integer.toString(Material.getMaterial(values[i]).getId());
}
if (filters != null) filters = Util.concat(filters, values);
else filters = values;
}
//Actions
else if (param.equals("a")) {
for (String value : values) {
DataType type = DataType.fromName(value);
if (type == null) throw new IllegalArgumentException("Invalid action supplied: &7" + value);
if (!Permission.searchType(player, type.getConfigName())) throw new IllegalArgumentException("You do not have permission to search for: &7" + type.getConfigName());
actions.add(type);
}
}
//Location
else if (param.equals("l")) {
if (values[0].equalsIgnoreCase("here"))
loc = player.getLocation().toVector();
else {
loc = new Vector();
loc.setX(Integer.parseInt(values[0]));
loc.setY(Integer.parseInt(values[1]));
loc.setZ(Integer.parseInt(values[2]));
}
}
//Radius
else if (param.equals("r")) {
if (!Util.isInteger(values[0])) throw new IllegalArgumentException("Invalid radius supplied: &7" + values[0]);
radius = Integer.parseInt(values[0]);
}
//Time
else if (param.equals("t")) {
int type = 2;
for (int i = 0; i < arg.length(); i++) {
String c = arg.substring(i, i+1);
if (!Util.isInteger(c)) {
if (c.equals("m") || c .equals("s") || c.equals("h") || c.equals("d") || c.equals("w"))
type = 0;
if (c.equals("-") || c.equals(":"))
type = 1;
}
}
//If the time is in the format '0w0d0h0m0s'
if (type == 0) {
int weeks = 0;
int days = 0;
int hours = 0;
int mins = 0;
int secs = 0;
String nums = "";
for (int i = 0; i < values[0].length(); i++) {
String c = values[0].substring(i, i+1);
if (Util.isInteger(c)) {
nums += c;
continue;
}
int num = Integer.parseInt(nums);
if (c.equals("w")) weeks = num;
else if (c.equals("d")) days = num;
else if (c.equals("h")) hours = num;
else if (c.equals("m")) mins = num;
else if (c.equals("s")) secs = num;
else throw new IllegalArgumentException("Invalid time measurement: &7" + c);
nums = "";
}
Calendar cal = Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks);
cal.add(Calendar.DAY_OF_MONTH, -1 * days);
cal.add(Calendar.HOUR, -1 * hours);
cal.add(Calendar.MINUTE, -1 * mins);
cal.add(Calendar.SECOND, -1 * secs);
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFrom = form.format(cal.getTime());
}
//If the time is in the format 'yyyy-MM-dd HH:mm:ss'
else if (type == 1) {
if (values.length == 1) {
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd");
dateFrom = form.format(Calendar.getInstance().getTime()) + " " + values[0];
}
if (values.length >= 2)
dateFrom = values[0] + " " + values[1];
if (values.length == 4)
dateTo = values[2] + " " + values[3];
}
//Invalid time format
else if (type == 2)
throw new IllegalArgumentException("Invalid time format!");
}
else throw new IllegalArgumentException("Invalid parameter supplied: &7" + param);
}
//Sort out locations
parseLocations();
}
|
diff --git a/java/target/src/common/com/jopdesign/sys/GC.java b/java/target/src/common/com/jopdesign/sys/GC.java
index cfb79bef..05b83042 100644
--- a/java/target/src/common/com/jopdesign/sys/GC.java
+++ b/java/target/src/common/com/jopdesign/sys/GC.java
@@ -1,865 +1,865 @@
/*
This file is part of JOP, the Java Optimized Processor
see <http://www.jopdesign.com/>
Copyright (C) 2005-2008, Martin Schoeberl ([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 com.jopdesign.sys;
/**
* Real-time garbage collection for JOP
*
* @author Martin Schoeberl ([email protected])
*
*/
public class GC {
/**
* Use either scoped memories or a GC.
* Combining scopes and the GC needs some extra work.
*/
final static boolean USE_SCOPES = false;
static int mem_start; // read from memory
// get a effective heap size with fixed handle count
// for our RT-GC tests
static int full_heap_size;
/**
* Fields in the handle structure.
*
* WARNING: Don't change the size as long
* as we do conservative stack scanning.
*/
static final int HANDLE_SIZE = 8;
/**
* The handle contains following data:
* 0 pointer to the object in the heap or 0 when the handle is free
* 1 pointer to the method table or length of an array
* 2 size - could be in class info
* 3 type info: object, primitve array or ref array
* 4 pointer to next handle of same type (used or free)
* 5 gray list
* 6 space marker - either toSpace or fromSpace
*
* !!! be carefule when changing the handle structure, it's
* used in System.arraycopy() and probably in jvm.asm!!!
*/
public static final int OFF_PTR = 0;
public static final int OFF_MTAB_ALEN = 1;
public static final int OFF_SIZE = 2;
public static final int OFF_TYPE = 3;
// size != array length (think about long/double)
// use array types 4..11 are standard boolean to long
// our addition:
// 1 reference
// 0 a plain object
public static final int IS_OBJ = 0;
public static final int IS_REFARR = 1;
/**
* Free and Use list.
*/
static final int OFF_NEXT = 4;
/**
* Threading the gray list. End of list is 'special' value -1.
* 0 means not in list.
*/
static final int OFF_GREY = 5;
/**
* Special end of list marker -1
*/
static final int GREY_END = -1;
/**
* Denote in which space the object is
*/
static final int OFF_SPACE = 6;
static final int TYPICAL_OBJ_SIZE = 5;
static int handle_cnt;
/**
* Size of one semi-space, complete heap is two times
* the semi_size
*/
static int semi_size;
static int heapStartA, heapStartB;
static boolean useA;
static int fromSpace;
static int toSpace;
/**
* Points to the start of the to-space after
* a flip. Objects are copied to copyPtr and
* copyPtr is incremented.
*/
static int copyPtr;
/**
* Points to the end of the to-space after
* a flip. Objects are allocated from the end
* and allocPtr gets decremented.
*/
static int allocPtr;
static int freeList;
// TODO: useList is only used for a faster handle sweep
// do we need it?
static int useList;
static int greyList;
static int addrStaticRefs;
static Object mutex;
static boolean concurrentGc;
static int roots[];
static void init(int mem_size, int addr) {
addrStaticRefs = addr;
mem_start = Native.rdMem(0);
// align mem_start to 8 word boundary for the
// conservative handle check
//mem_start = 261300;
mem_start = (mem_start+7)&0xfffffff8;
//mem_size = mem_start + 2000;
full_heap_size = mem_size-mem_start;
handle_cnt = full_heap_size/2/(TYPICAL_OBJ_SIZE+HANDLE_SIZE);
semi_size = (full_heap_size-handle_cnt*HANDLE_SIZE)/2;
heapStartA = mem_start+handle_cnt*HANDLE_SIZE;
heapStartB = heapStartA+semi_size;
// log("");
// log("memory size", mem_size);
// log("handle start ", mem_start);
// log("heap start (toSpace)", heapStartA);
// log("fromSpace", heapStartB);
// log("heap size (bytes)", semi_size*4*2);
useA = true;
copyPtr = heapStartA;
allocPtr = copyPtr+semi_size;
toSpace = heapStartA;
fromSpace = heapStartB;
freeList = 0;
useList = 0;
greyList = GREY_END;
for (int i=0; i<handle_cnt; ++i) {
int ref = mem_start+i*HANDLE_SIZE;
// pointer to former freelist head
Native.wrMem(freeList, ref+OFF_NEXT);
// mark handle as free
Native.wrMem(0, ref+OFF_PTR);
freeList = ref;
Native.wrMem(0, ref+OFF_GREY);
Native.wrMem(0, ref+OFF_SPACE);
}
// clean the heap
int end = heapStartA+2*semi_size;
for (int i=heapStartA; i<end; ++i) {
Native.wrMem(0, i);
}
concurrentGc = false;
// allocate the monitor
mutex = new Object();
}
public static Object getMutex() {
return mutex;
}
/**
* Add object to the gray list/stack
* @param ref
*/
static void push(int ref) {
// null pointer check is in the following handle check
// Only objects that are referenced by a handle in the
// handle area are considered for GC.
// Null pointer and references to static strings are not
// investigated.
if (ref<mem_start || ref>=mem_start+handle_cnt*HANDLE_SIZE) {
return;
}
// does the reference point to a handle start?
// TODO: happens in concurrent
if ((ref&0x7)!=0) {
// log("a not aligned handle");
return;
}
synchronized (mutex) {
// Is this handle on the free list?
// Is possible when using conservative stack scanning
if (Native.rdMem(ref+OFF_PTR)==0) {
// TODO: that happens in concurrent!
// log("push of a handle with 0 at OFF_PRT!", ref);
return;
}
// Is it black?
// Can happen from a left over from the last GC cycle, can it?
// -- it's checked in the write barrier
// -- but not in mark....
if (Native.rdMem(ref+OFF_SPACE)==toSpace) {
// log("push: allready in toSpace");
return;
}
// only objects not allready in the grey list
// are added
if (Native.rdMem(ref+OFF_GREY)==0) {
// pointer to former gray list head
Native.wrMem(greyList, ref+OFF_GREY);
greyList = ref;
}
}
}
/**
* switch from-space and to-space
*/
static void flip() {
synchronized (mutex) {
if (greyList!=GREY_END) log("GC: grey list not empty");
useA = !useA;
if (useA) {
copyPtr = heapStartA;
fromSpace = heapStartB;
toSpace = heapStartA;
} else {
copyPtr = heapStartB;
fromSpace = heapStartA;
toSpace = heapStartB;
}
allocPtr = copyPtr+semi_size;
}
}
/**
* Scan all thread stacks atomic.
*
*/
static void getStackRoots() {
int i, j, cnt;
// only pushing stack roots need to be atomic
synchronized (mutex) {
// add complete stack of the current thread to the root list
// roots = GCStkWalk.swk(RtThreadImpl.getActive(),true,false);
i = Native.getSP();
for (j = Const.STACK_OFF; j <= i; ++j) {
// disable the if when not using gc stack info
// if (roots[j - Const.STACK_OFF] == 1) {
push(Native.rdIntMem(j));
// }
}
// Stacks from the other threads
cnt = RtThreadImpl.getCnt();
for (i = 0; i < cnt; ++i) {
if (i != RtThreadImpl.getActive()) {
int[] mem = RtThreadImpl.getStack(i);
// sp starts at Const.STACK_OFF
int sp = RtThreadImpl.getSP(i) - Const.STACK_OFF;
// roots = GCStkWalk.swk(i, false, false);
for (j = 0; j <= sp; ++j) {
// disable the if when not using gc stack info
// if (roots[j] == 1) {
push(mem[j]);
// }
}
}
}
}
}
/**
* Scan all static fields
*
*/
private static void getStaticRoots() {
int i;
// add static refs to root list
int addr = Native.rdMem(addrStaticRefs);
int cnt = Native.rdMem(addrStaticRefs+1);
for (i=0; i<cnt; ++i) {
push(Native.rdMem(addr+i));
}
}
static void markAndCopy() {
int i, ref;
- getStaticRoots();
if (!concurrentGc) {
getStackRoots();
}
+ getStaticRoots();
for (;;) {
// pop one object from the gray list
synchronized (mutex) {
ref = greyList;
if (ref==GREY_END) {
break;
}
greyList = Native.rdMem(ref+OFF_GREY);
Native.wrMem(0, ref+OFF_GREY); // mark as not in list
}
// allready moved
// can this happen? - yes, as we do not check it in mark
// TODO: no, it's checked in push()
// What happens when the actuall scanning object is
// again pushed on the grey stack by the mutator?
if (Native.rdMem(ref+OFF_SPACE)==toSpace) {
// it happens
// log("mark/copy allready in toSpace");
continue;
}
// there should be no null pointers on the mark stack
// if (Native.rdMem(ref+OFF_PTR)==0) {
// log("mark/copy OFF_PTR=0!!!");
// continue;
// }
// push all childs
// get pointer to object
int addr = Native.rdMem(ref);
int flags = Native.rdMem(ref+OFF_TYPE);
if (flags==IS_REFARR) {
// is an array of references
int size = Native.rdMem(ref+OFF_MTAB_ALEN);
for (i=0; i<size; ++i) {
push(Native.rdMem(addr+i));
}
// However, multianewarray does probably NOT work
} else if (flags==IS_OBJ){
// it's a plain object
// get pointer to method table
flags = Native.rdMem(ref+OFF_MTAB_ALEN);
// get real flags
flags = Native.rdMem(flags+Const.MTAB2GC_INFO);
for (i=0; flags!=0; ++i) {
if ((flags&1)!=0) {
push(Native.rdMem(addr+i));
}
flags >>>= 1;
}
}
// now copy it - color it BLACK
int size;
int dest;
synchronized(mutex) {
size = Native.rdMem(ref+OFF_SIZE);
dest = copyPtr;
copyPtr += size;
// set it BLACK
Native.wrMem(toSpace, ref+OFF_SPACE);
}
if (size>0) {
// copy it
for (i=0; i<size; i++) {
// Native.wrMem(Native.rdMem(addr+i), dest+i);
Native.memCopy(dest, addr, i);
}
}
// update object pointer to the new location
Native.wrMem(dest, ref+OFF_PTR);
// wait until everybody uses the new location
for (i = 0; i < 10; i++);
// turn off address translation
Native.memCopy(dest, dest, -1);
}
}
/**
* Sweep through the 'old' use list and move garbage to free list.
*/
static void sweepHandles() {
int ref;
synchronized (mutex) {
ref = useList; // get start of the list
useList = 0; // new uselist starts empty
}
while (ref!=0) {
// read next element, as it is destroyed
// by addTo*List()
int next = Native.rdMem(ref+OFF_NEXT);
synchronized (mutex) {
// a BLACK one
if (Native.rdMem(ref+OFF_SPACE)==toSpace) {
// add to used list
Native.wrMem(useList, ref+OFF_NEXT);
useList = ref;
// a WHITE one
} else {
// pointer to former freelist head
Native.wrMem(freeList, ref+OFF_NEXT);
freeList = ref;
// mark handle as free
Native.wrMem(0, ref+OFF_PTR);
}
}
ref = next;
}
}
/**
* Clean the from-space
*/
static void zapSemi() {
// clean the from-space to prepare for the next
// flip
int end = fromSpace+semi_size;
for (int i=fromSpace; i<end; ++i) {
Native.wrMem(0, i);
}
// for tests clean also the remainig memory in the to-space
// synchronized (mutex) {
// for (int i=copyPtr; i<allocPtr; ++i) {
// Native.wrMem(0, i);
// }
// }
}
public static void setConcurrent() {
concurrentGc = true;
}
static void gc_alloc() {
log("");
log("GC allocation triggered");
if (USE_SCOPES) {
log("No GC when scopes are used");
System.exit(1);
}
if (concurrentGc) {
log("meaning out of memory for RT-GC");
System.exit(1);
} else {
gc();
}
}
public static void gc() {
// log("GC called - free memory:", freeMemory());
flip();
markAndCopy();
sweepHandles();
zapSemi();
// log("GC end - free memory:",freeMemory());
}
static int free() {
return allocPtr-copyPtr;
}
// TODO this has to be exchanged on a thread switch
// TODO add the javax.realtime classes to the CVS
static Scope currentArea;
public static Scope getCurrentArea() {
return currentArea;
}
public static void setCurrentArea(Scope sc) {
currentArea = sc;
}
/**
* Size of scratchpad memory in 32-bit words
* @return
*/
public static int getScratchpadSize() {
return Startup.spm_size;
}
/**
* Allocate a new Object. Invoked from JVM.f_new(cons);
* @param cons pointer to class struct
* @return address of the handle
*/
static int newObject(int cons) {
int size = Native.rdMem(cons); // instance size
if (USE_SCOPES) {
// allocate in scope
Scope sc = currentArea;
if (sc!=null) {
int rem = sc.backingStore.length - sc.allocPtr;
if (size+2 > rem) {
log("Out of memory in scoped memory");
System.exit(1);
}
int ref = sc.allocPtr;
sc.allocPtr += size+2;
int ptr = Native.toInt(sc.backingStore);
ptr = Native.rdMem(ptr);
ptr += ref;
sc.backingStore[ref] = ptr+2;
sc.backingStore[ref+1] = cons+Const.CLASS_HEADR;
return ptr;
}
}
// that's the stop-the-world GC
synchronized (mutex) {
if (copyPtr+size >= allocPtr) {
gc_alloc();
if (copyPtr+size >= allocPtr) {
// still not enough memory
log("Out of memory error!");
System.exit(1);
}
}
}
synchronized (mutex) {
if (freeList==0) {
log("Run out of handles in new Object!");
// is this a good place to call gc????
// better check available handles on newObject
gc_alloc();
if (freeList==0) {
log("Still out of handles!");
System.exit(1);
}
}
}
int ref;
synchronized (mutex) {
// we allocate from the upper part
allocPtr -= size;
// get one from free list
ref = freeList;
// if ((ref&0x07)!=0) {
// log("getHandle problem");
// }
// if (Native.rdMem(ref+OFF_PTR)!=0) {
// log("getHandle not free");
// }
freeList = Native.rdMem(ref+OFF_NEXT);
// and add it to use list
Native.wrMem(useList, ref+OFF_NEXT);
useList = ref;
// pointer to real object, also marks it as non free
Native.wrMem(allocPtr, ref); // +OFF_PTR
// should be from the class info
Native.wrMem(size, ref+OFF_SIZE);
// mark it as BLACK - means it will be in toSpace
Native.wrMem(toSpace, ref+OFF_SPACE);
// TODO: should not be necessary - now just for sure
Native.wrMem(0, ref+OFF_GREY);
// BTW: when we create mutex we synchronize on the not yet
// created Object!
// ref. flags used for array marker
Native.wrMem(IS_OBJ, ref+OFF_TYPE);
// pointer to method table in the handle
Native.wrMem(cons+Const.CLASS_HEADR, ref+OFF_MTAB_ALEN);
}
return ref;
}
static int newArray(int size, int type) {
int arrayLength = size;
// long or double array
if((type==11)||(type==7)) size <<= 1;
// reference array type is 1 (our convention)
if (USE_SCOPES) {
// allocate in scope
Scope sc = currentArea;
if (sc!=null) {
int rem = sc.backingStore.length - sc.allocPtr;
if (size+2 > rem) {
log("Out of memory in scoped memory");
System.exit(1);
}
int ref = sc.allocPtr;
sc.allocPtr += size+2;
int ptr = Native.toInt(sc.backingStore);
ptr = Native.rdMem(ptr);
ptr += ref;
sc.backingStore[ref] = ptr+2;
sc.backingStore[ref+1] = arrayLength;
return ptr;
}
}
synchronized (mutex) {
if (copyPtr+size >= allocPtr) {
gc_alloc();
if (copyPtr+size >= allocPtr) {
// still not enough memory
log("Out of memory error!");
System.exit(1);
}
}
}
synchronized (mutex) {
if (freeList==0) {
log("Run out of handles in new array!");
// is this a good place to call gc????
// better check available handles on newObject
gc_alloc();
if (freeList==0) {
log("Still out of handles!");
System.exit(1);
}
}
}
int ref;
synchronized (mutex) {
// we allocate from the upper part
allocPtr -= size;
// get one from free list
ref = freeList;
// if ((ref&0x07)!=0) {
// log("getHandle problem");
// }
// if (Native.rdMem(ref+OFF_PTR)!=0) {
// log("getHandle not free");
// }
freeList = Native.rdMem(ref+OFF_NEXT);
// and add it to use list
Native.wrMem(useList, ref+OFF_NEXT);
useList = ref;
// pointer to real object, also marks it as non free
Native.wrMem(allocPtr, ref); // +OFF_PTR
// should be from the class info
Native.wrMem(size, ref+OFF_SIZE);
// mark it as BLACK - means it will be in toSpace
Native.wrMem(toSpace, ref+OFF_SPACE);
// TODO: should not be necessary - now just for sure
Native.wrMem(0, ref+OFF_GREY);
// ref. flags used for array marker
Native.wrMem(type, ref+OFF_TYPE);
// array length in the handle
Native.wrMem(arrayLength, ref+OFF_MTAB_ALEN);
}
return ref;
}
/**
* @return
*/
public static int freeMemory() {
return free()*4;
}
/**
* @return
*/
public static int totalMemory() {
return semi_size*4;
}
/**
* Check if a given value is a valid handle.
*
* This method traverse the list of handles (in use) to check
* if the handle provided belong to the list.
*
* It does *not* check the free handle list.
*
* One detail: the result may state that a handle to a
* (still unknown garbage) object is valid, in case
* the object is not reachable but still present
* on the use list.
* This happens in case the object becomes unreachable
* during execution, but GC has not reclaimed it yet.
* Anyway, it's still a valid object handle.
*
* @param handle the value to be checked.
* @return
*/
public static final boolean isValidObjectHandle(int handle)
{
boolean isValid;
int handlePointer;
// assume it's not valid and try to show otherwise
isValid = false;
// synchronize on the GC lock
synchronized (mutex) {
// start on the first element of the list
handlePointer = useList;
// traverse the list until the element is found or the list is over
while(handlePointer != 0)
{
if(handle == handlePointer)
{
// found it! hence, it's a valid handle. Stop the search.
isValid = true;
break;
}
// not found yet. Let's go to the next element and try again.
handlePointer = Native.rdMem(handlePointer+OFF_NEXT);
}
}
return isValid;
}
/**
* Write barrier for an object field. May be used with regular objects
* and reference arrays.
*
* @param handle the object handle
* @param index the field index
*/
public static final void writeBarrier(int handle, int index)
{
boolean shouldExecuteBarrier = false;
int gcInfo;
// log("WriteBarrier: snapshot-at-beginning.");
if (handle == 0)
{
throw new NullPointerException();
}
synchronized (GC.mutex)
{
// ignore objects with size zero (is this correct?)
if(Native.rdMem(handle) == 0)
{
// log("ignore objects with size zero");
return;
}
// get information on the object type.
int type = Native.rdMem(handle + GC.OFF_TYPE);
// if it's an object or reference array, execute the barrier
if(type == GC.IS_REFARR)
{
// log("Reference array.");
shouldExecuteBarrier = true;
}
if(type == GC.IS_OBJ)
{
// log("Regular object.");
// get the object GC info from the class structure.
gcInfo = Native.rdMem(handle + GC.OFF_MTAB_ALEN) + Const.MTAB2GC_INFO;
gcInfo = Native.rdMem(gcInfo);
// log("GCInfo field: ", gcInfo);
// if the correct bit is set for the field, it may hold a reference.
// then, execute the write barrier.
if((gcInfo & (0x01 << index)) != 0)
{
// log("Field can hold a reference. Execute barrier!");
shouldExecuteBarrier = true;
}
}
// execute the write barrier, if necessary.
if(shouldExecuteBarrier)
{
// handle indirection
handle = Native.rdMem(handle);
// snapshot-at-beginning barrier
int oldVal = Native.rdMem(handle+index);
// log("Old val: ", oldVal);
// if(oldVal != 0)
// {
// log("Current space: ", Native.rdMem(oldVal+GC.OFF_SPACE));
// }
// else
// {
// log("Current space: NULL object.");
// }
// log("toSpace: ", GC.toSpace);
if (oldVal!=0 && Native.rdMem(oldVal+GC.OFF_SPACE)!=GC.toSpace) {
// log("Executing write barrier for old handle: ", handle);
GC.push(oldVal);
}
}
// else
// {
// log("Should not execute the barrier.");
// }
}
}
/************************************************************************************************/
static void log(String s, int i) {
JVMHelp.wr(s);
JVMHelp.wr(" ");
JVMHelp.wrSmall(i);
JVMHelp.wr("\n");
}
static void log(String s) {
JVMHelp.wr(s);
JVMHelp.wr("\n");
}
}
| false | true | static void markAndCopy() {
int i, ref;
getStaticRoots();
if (!concurrentGc) {
getStackRoots();
}
for (;;) {
// pop one object from the gray list
synchronized (mutex) {
ref = greyList;
if (ref==GREY_END) {
break;
}
greyList = Native.rdMem(ref+OFF_GREY);
Native.wrMem(0, ref+OFF_GREY); // mark as not in list
}
// allready moved
// can this happen? - yes, as we do not check it in mark
// TODO: no, it's checked in push()
// What happens when the actuall scanning object is
// again pushed on the grey stack by the mutator?
if (Native.rdMem(ref+OFF_SPACE)==toSpace) {
// it happens
// log("mark/copy allready in toSpace");
continue;
}
// there should be no null pointers on the mark stack
// if (Native.rdMem(ref+OFF_PTR)==0) {
// log("mark/copy OFF_PTR=0!!!");
// continue;
// }
// push all childs
// get pointer to object
int addr = Native.rdMem(ref);
int flags = Native.rdMem(ref+OFF_TYPE);
if (flags==IS_REFARR) {
// is an array of references
int size = Native.rdMem(ref+OFF_MTAB_ALEN);
for (i=0; i<size; ++i) {
push(Native.rdMem(addr+i));
}
// However, multianewarray does probably NOT work
} else if (flags==IS_OBJ){
// it's a plain object
// get pointer to method table
flags = Native.rdMem(ref+OFF_MTAB_ALEN);
// get real flags
flags = Native.rdMem(flags+Const.MTAB2GC_INFO);
for (i=0; flags!=0; ++i) {
if ((flags&1)!=0) {
push(Native.rdMem(addr+i));
}
flags >>>= 1;
}
}
// now copy it - color it BLACK
int size;
int dest;
synchronized(mutex) {
size = Native.rdMem(ref+OFF_SIZE);
dest = copyPtr;
copyPtr += size;
// set it BLACK
Native.wrMem(toSpace, ref+OFF_SPACE);
}
if (size>0) {
// copy it
for (i=0; i<size; i++) {
// Native.wrMem(Native.rdMem(addr+i), dest+i);
Native.memCopy(dest, addr, i);
}
}
// update object pointer to the new location
Native.wrMem(dest, ref+OFF_PTR);
// wait until everybody uses the new location
for (i = 0; i < 10; i++);
// turn off address translation
Native.memCopy(dest, dest, -1);
}
}
| static void markAndCopy() {
int i, ref;
if (!concurrentGc) {
getStackRoots();
}
getStaticRoots();
for (;;) {
// pop one object from the gray list
synchronized (mutex) {
ref = greyList;
if (ref==GREY_END) {
break;
}
greyList = Native.rdMem(ref+OFF_GREY);
Native.wrMem(0, ref+OFF_GREY); // mark as not in list
}
// allready moved
// can this happen? - yes, as we do not check it in mark
// TODO: no, it's checked in push()
// What happens when the actuall scanning object is
// again pushed on the grey stack by the mutator?
if (Native.rdMem(ref+OFF_SPACE)==toSpace) {
// it happens
// log("mark/copy allready in toSpace");
continue;
}
// there should be no null pointers on the mark stack
// if (Native.rdMem(ref+OFF_PTR)==0) {
// log("mark/copy OFF_PTR=0!!!");
// continue;
// }
// push all childs
// get pointer to object
int addr = Native.rdMem(ref);
int flags = Native.rdMem(ref+OFF_TYPE);
if (flags==IS_REFARR) {
// is an array of references
int size = Native.rdMem(ref+OFF_MTAB_ALEN);
for (i=0; i<size; ++i) {
push(Native.rdMem(addr+i));
}
// However, multianewarray does probably NOT work
} else if (flags==IS_OBJ){
// it's a plain object
// get pointer to method table
flags = Native.rdMem(ref+OFF_MTAB_ALEN);
// get real flags
flags = Native.rdMem(flags+Const.MTAB2GC_INFO);
for (i=0; flags!=0; ++i) {
if ((flags&1)!=0) {
push(Native.rdMem(addr+i));
}
flags >>>= 1;
}
}
// now copy it - color it BLACK
int size;
int dest;
synchronized(mutex) {
size = Native.rdMem(ref+OFF_SIZE);
dest = copyPtr;
copyPtr += size;
// set it BLACK
Native.wrMem(toSpace, ref+OFF_SPACE);
}
if (size>0) {
// copy it
for (i=0; i<size; i++) {
// Native.wrMem(Native.rdMem(addr+i), dest+i);
Native.memCopy(dest, addr, i);
}
}
// update object pointer to the new location
Native.wrMem(dest, ref+OFF_PTR);
// wait until everybody uses the new location
for (i = 0; i < 10; i++);
// turn off address translation
Native.memCopy(dest, dest, -1);
}
}
|
diff --git a/api/src/com/todoroo/astrid/data/TaskApiDao.java b/api/src/com/todoroo/astrid/data/TaskApiDao.java
index a279d2878..2ad16339e 100644
--- a/api/src/com/todoroo/astrid/data/TaskApiDao.java
+++ b/api/src/com/todoroo/astrid/data/TaskApiDao.java
@@ -1,197 +1,197 @@
package com.todoroo.astrid.data;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import com.todoroo.andlib.data.ContentResolverDao;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.Functions;
import com.todoroo.andlib.sql.Query;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.api.PermaSql;
/**
* Data access object for accessing Astrid's {@link Task} table. If you
* are looking to store extended information about a Task, you probably
* want to use the {@link MetadataApiDao} object.
*
* @author Tim Su <[email protected]>
*
*/
public class TaskApiDao extends ContentResolverDao<Task> {
public TaskApiDao(Context context) {
super(Task.class, context, Task.CONTENT_URI);
}
/**
* Generates SQL clauses
*/
public static class TaskCriteria {
/** @return tasks by id */
public static Criterion byId(long id) {
return Task.ID.eq(id);
}
/** @return tasks that were deleted */
public static Criterion isDeleted() {
return Task.DELETION_DATE.neq(0);
}
/** @return tasks that were not deleted */
public static Criterion notDeleted() {
return Task.DELETION_DATE.eq(0);
}
/** @return tasks that have not yet been completed or deleted */
public static Criterion activeAndVisible() {
return Criterion.and(Task.COMPLETION_DATE.eq(0),
Task.DELETION_DATE.eq(0),
Task.HIDE_UNTIL.lt(Functions.now()));
}
/** @return tasks that have not yet been completed or deleted */
public static Criterion isActive() {
return Criterion.and(Task.COMPLETION_DATE.eq(0),
Task.DELETION_DATE.eq(0));
}
/** @return tasks that are not hidden at current time */
public static Criterion isVisible() {
return Task.HIDE_UNTIL.lt(Functions.now());
}
/** @return tasks that have a due date */
public static Criterion hasDeadlines() {
return Task.DUE_DATE.neq(0);
}
/** @return tasks that are due before a certain unixtime */
public static Criterion dueBeforeNow() {
return Criterion.and(Task.DUE_DATE.gt(0), Task.DUE_DATE.lt(Functions.now()));
}
/** @return tasks that are due after a certain unixtime */
public static Criterion dueAfterNow() {
return Task.DUE_DATE.gt(Functions.now());
}
/** @return tasks completed before a given unixtime */
public static Criterion completed() {
return Criterion.and(Task.COMPLETION_DATE.gt(0), Task.COMPLETION_DATE.lt(Functions.now()));
}
/** @return tasks that have a blank or null title */
@SuppressWarnings("nls")
public static Criterion hasNoTitle() {
return Criterion.or(Task.TITLE.isNull(), Task.TITLE.eq(""));
}
}
/**
* Count tasks matching criterion
* @param criterion
* @return # of tasks matching
*/
public int countTasks(Criterion criterion) {
TodorooCursor<Task> cursor = query(Query.select(Task.ID).where(criterion));
try {
return cursor.getCount();
} finally {
cursor.close();
}
}
/**
* Count tasks matching query tepmlate
* @param queryTemplate
* @return # of tasks matching
*/
public int countTasks(String queryTemplate) {
queryTemplate = PermaSql.replacePlaceholders(queryTemplate);
TodorooCursor<Task> cursor = query(Query.select(Task.ID).withQueryTemplate(queryTemplate));
try {
return cursor.getCount();
} finally {
cursor.close();
}
}
@Override
public boolean save(Task model) {
ContentValues setValues = model.getSetValues();
if(super.save(model)) {
afterSave(model, setValues);
return true;
}
return false;
}
/** @return true if task change shouldn't be broadcast */
public static boolean insignificantChange(ContentValues values) {
if(values == null || values.size() == 0)
return true;
if(values.containsKey(Task.DETAILS_DATE.name) &&
values.containsKey(Task.DETAILS.name) &&
- values.size() == 2)
+ values.size() <= 3)
return true;
if(values.containsKey(Task.REMINDER_LAST.name) &&
values.size() <= 2)
return true;
if(values.containsKey(Task.REMINDER_SNOOZE.name) &&
values.size() <= 2)
return true;
if(values.containsKey(Task.TIMER_START.name) &&
values.size() <= 2)
return true;
if(values.containsKey(Task.ELAPSED_SECONDS.name) &&
values.size() <= 2)
return true;
return false;
}
/**
* Send broadcasts on task change (triggers things like task repeats)
* @param task task that was saved
* @param values values that were updated
*/
public static void afterSave(Task task, ContentValues values) {
if(insignificantChange(values))
return;
if(values.containsKey(Task.COMPLETION_DATE.name) && task.isCompleted()) {
Context context = ContextManager.getContext();
if(context != null) {
Intent broadcastIntent;
broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_TASK_COMPLETED);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_TASK_ID, task.getId());
context.sendOrderedBroadcast(broadcastIntent, null);
}
}
afterTaskListChanged();
}
/**
* Send broadcast when task list changes. Widgets should update.
*/
public static void afterTaskListChanged() {
Context context = ContextManager.getContext();
if(context != null) {
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_TASK_LIST_UPDATED);
context.sendOrderedBroadcast(broadcastIntent, null);
}
}
}
| true | true | public static boolean insignificantChange(ContentValues values) {
if(values == null || values.size() == 0)
return true;
if(values.containsKey(Task.DETAILS_DATE.name) &&
values.containsKey(Task.DETAILS.name) &&
values.size() == 2)
return true;
if(values.containsKey(Task.REMINDER_LAST.name) &&
values.size() <= 2)
return true;
if(values.containsKey(Task.REMINDER_SNOOZE.name) &&
values.size() <= 2)
return true;
if(values.containsKey(Task.TIMER_START.name) &&
values.size() <= 2)
return true;
if(values.containsKey(Task.ELAPSED_SECONDS.name) &&
values.size() <= 2)
return true;
return false;
}
| public static boolean insignificantChange(ContentValues values) {
if(values == null || values.size() == 0)
return true;
if(values.containsKey(Task.DETAILS_DATE.name) &&
values.containsKey(Task.DETAILS.name) &&
values.size() <= 3)
return true;
if(values.containsKey(Task.REMINDER_LAST.name) &&
values.size() <= 2)
return true;
if(values.containsKey(Task.REMINDER_SNOOZE.name) &&
values.size() <= 2)
return true;
if(values.containsKey(Task.TIMER_START.name) &&
values.size() <= 2)
return true;
if(values.containsKey(Task.ELAPSED_SECONDS.name) &&
values.size() <= 2)
return true;
return false;
}
|
diff --git a/src/net/sf/freecol/common/model/SimpleCombatModel.java b/src/net/sf/freecol/common/model/SimpleCombatModel.java
index 2848e2eda..9c8136e9c 100644
--- a/src/net/sf/freecol/common/model/SimpleCombatModel.java
+++ b/src/net/sf/freecol/common/model/SimpleCombatModel.java
@@ -1,1122 +1,1124 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.PseudoRandom;
import net.sf.freecol.common.model.CombatModel.CombatResult;
import net.sf.freecol.common.model.Player.Stance;
import net.sf.freecol.common.model.Settlement.SettlementType;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.common.model.UnitType.DowngradeType;
/**
* This class implements the original Colonization combat model.
*/
public class SimpleCombatModel implements CombatModel {
private static final Logger logger = Logger.getLogger(SimpleCombatModel.class.getName());
private static PseudoRandom random;
public static final Modifier SMALL_MOVEMENT_PENALTY =
new Modifier("model.modifier.offence", "modifiers.movementPenalty",
-33, Modifier.Type.PERCENTAGE);
public static final Modifier BIG_MOVEMENT_PENALTY =
new Modifier("model.modifier.offence", "modifiers.movementPenalty",
-66, Modifier.Type.PERCENTAGE);
public static final Modifier ARTILLERY_PENALTY =
new Modifier("model.modifier.offence", "modifiers.artilleryPenalty",
-75, Modifier.Type.PERCENTAGE);
public static final Modifier ATTACK_BONUS =
new Modifier("model.modifier.offence", "modifiers.attackBonus",
50, Modifier.Type.PERCENTAGE);
public static final Modifier FORTIFICATION_BONUS =
new Modifier("model.modifier.defence", "modifiers.fortified",
50, Modifier.Type.PERCENTAGE);
public static final Modifier INDIAN_RAID_BONUS =
new Modifier("model.modifier.defence", "modifiers.artilleryAgainstRaid",
100, Modifier.Type.PERCENTAGE);
public SimpleCombatModel(PseudoRandom pseudoRandom) {
this.random = pseudoRandom;
}
/**
* Generates a result of an attack.
*
* @param attacker The <code>Unit</code> attacking.
* @param defender The defending unit.
* @return a <code>CombatResult</code> value
*/
public CombatResult generateAttackResult(Unit attacker, Unit defender) {
float attackPower = getOffencePower(attacker, defender);
float defencePower = getDefencePower(attacker, defender);
float victory = attackPower / (attackPower + defencePower);
int r = random.nextInt(100);
CombatResultType result = CombatResultType.EVADES;
if (r <= victory * 20) {
// 10% of the times winning:
result = CombatResultType.GREAT_WIN;
} else if (r <= 100 * victory) {
// 90% of the times winning:
result = CombatResultType.WIN;
} else if (defender.isNaval()
&& r <= (80 * victory) + 20) {
// 20% of the times loosing:
result = CombatResultType.EVADES;
} else if (r <= (10 * victory) + 90) {
// 70% of the times loosing:
result = CombatResultType.LOSS;
} else {
// 10% of the times loosing:
result = CombatResultType.GREAT_LOSS;
}
if (result.compareTo(CombatResultType.WIN) >= 0 &&
defender.getTile().getSettlement() != null) {
final boolean lastDefender;
if (defender.getTile().getSettlement() instanceof Colony) {
lastDefender = !defender.isDefensiveUnit();
} else if (defender.getTile().getSettlement() instanceof IndianSettlement) {
final int defenders = defender.getTile().getUnitCount()
+ defender.getTile().getSettlement().getUnitCount();
lastDefender = (defenders <= 1);
} else {
throw new IllegalStateException("Unknown Settlement.");
}
if (lastDefender) {
result = CombatResultType.DONE_SETTLEMENT;
}
}
return new CombatResult(result, 0);
}
/**
* Generates the result of a colony bombarding a Unit.
*
* @param colony the bombarding <code>Colony</code>
* @param defender the defending <code>Unit</code>
* @return a <code>CombatResult</code> value
*/
public CombatResult generateAttackResult(Colony colony, Unit defender) {
float attackPower = getOffencePower(colony, defender);
float defencePower = getDefencePower(colony, defender);
float totalProbability = attackPower + defencePower;
CombatResultType result = CombatResultType.EVADES;
int r = random.nextInt(Math.round(totalProbability) + 1);
if (r < attackPower) {
int diff = Math.round(defencePower * 2 - attackPower);
int r2 = random.nextInt((diff < 3) ? 3 : diff);
if (r2 == 0) {
result = CombatResultType.GREAT_WIN;
} else {
result = CombatResultType.WIN;
}
}
return new CombatResult(result, 0);
}
/**
* Returns the power for bombarding
*
* @param colony a <code>Colony</code> value
* @param defender an <code>Unit</code> value
* @return the power for bombarding
*/
public float getOffencePower(Colony colony, Unit defender) {
float attackPower = 0;
if (defender.isNaval() &&
colony.hasAbility("model.ability.bombardShips")) {
for (Unit unit : colony.getTile().getUnitList()) {
if (unit.hasAbility("model.ability.bombard")) {
attackPower += unit.getType().getOffence();
}
}
if (attackPower > 48) {
attackPower = 48;
}
}
return attackPower;
}
/**
* Return the offensive power of the attacker versus the defender.
*
* @param attacker an <code>Unit</code> value
* @param defender an <code>Unit</code> value
* @return a <code>float</code> value
*/
public float getOffencePower(Unit attacker, Unit defender) {
return FeatureContainer.applyModifierSet(0, attacker.getGame().getTurn(),
getOffensiveModifiers(attacker, defender));
}
/**
* Return a list of all offensive modifiers that apply to the attacker
* versus the defender.
*
* @param colony an <code>Colony</code> value
* @param defender an <code>Unit</code> value
* @return a <code>List</code> of Modifiers
*/
public Set<Modifier> getOffensiveModifiers(Colony colony, Unit defender) {
Set<Modifier> result = new HashSet<Modifier>();
result.add(new Modifier("model.modifier.bombardModifier",
getOffencePower(colony, defender),
Modifier.Type.ADDITIVE));
return result;
}
/**
* Return a list of all offensive modifiers that apply to the attacker
* versus the defender.
*
* @param attacker an <code>Unit</code> value
* @param defender an <code>Unit</code> value
* @return a <code>List</code> of Modifiers
*/
public Set<Modifier> getOffensiveModifiers(Unit attacker, Unit defender) {
Set<Modifier> result = new LinkedHashSet<Modifier>();
result.add(new Modifier("model.modifier.offence",
"modifiers.baseOffence",
attacker.getType().getOffence(),
Modifier.Type.ADDITIVE));
result.addAll(attacker.getType().getFeatureContainer()
.getModifierSet("model.modifier.offence"));
result.addAll(attacker.getOwner().getFeatureContainer()
.getModifierSet("model.modifier.offence", attacker.getType()));
if (attacker.isNaval()) {
int goodsCount = attacker.getGoodsCount();
if (goodsCount > 0) {
// -12.5% penalty for every unit of cargo.
// TODO: shouldn't this be -cargo/capacity?
result.add(new Modifier("model.modifier.offence",
"modifiers.cargoPenalty",
-12.5f * goodsCount,
Modifier.Type.PERCENTAGE));
}
/* this should no longer be necessary, as Drake adds an
* offence bonus directly
if (attacker.hasAbility("model.ability.piracy")) {
result.addAll(attacker.getModifierSet("model.modifier.piracyBonus"));
}
*/
} else {
for (EquipmentType equipment : attacker.getEquipment()) {
result.addAll(equipment.getFeatureContainer().getModifierSet("model.modifier.offence"));
}
// 50% attack bonus
result.add(ATTACK_BONUS);
// movement penalty
int movesLeft = attacker.getMovesLeft();
if (movesLeft == 1) {
result.add(BIG_MOVEMENT_PENALTY);
} else if (movesLeft == 2) {
result.add(SMALL_MOVEMENT_PENALTY);
}
// In the open
if (defender != null && defender.getTile() != null && defender.getTile().getSettlement() == null) {
/**
* Ambush bonus in the open = defender's defence bonus, if
* defender is REF, or attacker is indian.
*/
if (attacker.hasAbility("model.ability.ambushBonus") ||
defender.hasAbility("model.ability.ambushPenalty")) {
result.add(new Modifier("model.modifier.offence",
"modifiers.ambushBonus",
defender.getTile().defenceBonus(),
Modifier.Type.PERCENTAGE));
}
// 75% Artillery in the open penalty
// TODO: is it right? or should it be another ability?
if (attacker.hasAbility("model.ability.bombard")) {
result.add(ARTILLERY_PENALTY);
}
}
// Attacking a settlement
if (defender != null && defender.getTile() != null && defender.getTile().getSettlement() != null) {
// REF bombardment bonus
result.addAll(attacker.getModifierSet("model.modifier.bombardBonus"));
}
}
return result;
}
/**
* Return the defensive power of the defender versus the
* bombarding colony.
*
* @param colony a <code>Colony</code> value
* @param defender a <code>Unit</code> value
* @return an <code>float</code> value
*/
public float getDefencePower(Colony colony, Unit defender) {
return defender.getType().getDefence();
}
/**
* Return the defensive power of the defender versus the attacker.
*
* @param attacker an <code>Unit</code> value
* @param defender an <code>Unit</code> value
* @return an <code>float</code> value
*/
public float getDefencePower(Unit attacker, Unit defender) {
return FeatureContainer.applyModifierSet(0, attacker.getGame().getTurn(),
getDefensiveModifiers(attacker, defender));
}
/**
* Return a list of all defensive modifiers that apply to the defender
* versus the bombarding colony.
*
* @param colony a <code>Colony</code> value
* @param defender an <code>Unit</code> value
* @return a <code>List</code> of Modifiers
*/
public Set<Modifier> getDefensiveModifiers(Colony colony, Unit defender) {
Set<Modifier> result = new LinkedHashSet<Modifier>();
result.add(new Modifier("model.modifier.defenceBonus",
defender.getType().getDefence(),
Modifier.Type.ADDITIVE));
return result;
}
/**
* Return a list of all defensive modifiers that apply to the defender
* versus the attacker.
*
* @param attacker an <code>Unit</code> value
* @param defender an <code>Unit</code> value
* @return a <code>List</code> of Modifiers
*/
public Set<Modifier> getDefensiveModifiers(Unit attacker, Unit defender) {
Set<Modifier> result = new LinkedHashSet<Modifier>();
if (defender == null) {
return result;
}
result.add(new Modifier("model.modifier.defence",
"modifiers.baseDefence",
defender.getType().getDefence(),
Modifier.Type.ADDITIVE));
result.addAll(defender.getType().getFeatureContainer()
.getModifierSet("model.modifier.defence"));
if (defender.isNaval()) {
int goodsCount = defender.getVisibleGoodsCount();
if (goodsCount > 0) {
// -12.5% penalty for every unit of cargo.
// TODO: shouldn't this be -cargo/capacity?
result.add(new Modifier("model.modifier.defence",
"modifiers.cargoPenalty",
-12.5f * goodsCount,
Modifier.Type.PERCENTAGE));
}
/* this should no longer be necessary, as Drake adds an
* defence bonus directly
if (defender.hasAbility("model.ability.piracy")) {
result.addAll(defender.getModifierSet("model.modifier.piracyBonus"));
}
*/
} else {
// Paul Revere makes an unarmed colonist in a settlement pick up
// a stock-piled musket if attacked, so the bonus should be applied
// for unarmed colonists inside colonies where there are muskets
// available.
if (!defender.isArmed() &&
defender.isColonist() &&
defender.getLocation() instanceof WorkLocation &&
defender.getOwner().hasAbility("model.ability.automaticDefence") &&
defender.getColony().getGoodsCount(Goods.MUSKETS) >= 50) {
Set<Ability> autoDefence = defender.getOwner().getFeatureContainer()
.getAbilitySet("model.ability.automaticDefence");
result.add(new Modifier("model.modifier.defence",
autoDefence.iterator().next().getSource(),
1, Modifier.Type.ADDITIVE));
}
for (EquipmentType equipment : defender.getEquipment()) {
result.addAll(equipment.getFeatureContainer().getModifierSet("model.modifier.defence"));
}
// 50% fortify bonus
if (defender.getState() == UnitState.FORTIFIED) {
result.add(FORTIFICATION_BONUS);
}
if (defender.getTile() != null) {
Tile tile = defender.getTile();
if (tile.getSettlement() != null) {
result.addAll(tile.getSettlement().getFeatureContainer()
.getModifierSet("model.modifier.defence"));
// TODO: is it right? or should it be another ability?
if (defender.hasAbility("model.ability.bombard") &&
attacker.getOwner().isIndian()) {
// 100% defence bonus against an Indian raid
result.add(INDIAN_RAID_BONUS);
}
} else {
// In the open
if (!(attacker.hasAbility("model.ability.ambushBonus") ||
defender.hasAbility("model.ability.ambushPenalty"))) {
// Terrain defensive bonus.
result.addAll(tile.getType().getDefenceBonus());
}
// TODO: is it right? or should it be another ability?
if (defender.hasAbility("model.ability.bombard") &&
defender.getState() != UnitState.FORTIFIED) {
// -75% Artillery in the Open penalty
result.add(ARTILLERY_PENALTY);
}
}
}
}
return result;
}
/**
* Attack a unit with the given outcome. This method ignores the damage parameter.
*
* @param attacker an <code>Unit</code> value
* @param defender The <code>Unit</code> defending against attack.
* @param result The result of the attack.
* @param plunderGold an <code>int</code> value
*/
public void attack(Unit attacker, Unit defender, CombatResult result, int plunderGold) {
Player attackingPlayer = attacker.getOwner();
Player defendingPlayer = defender.getOwner();
if (attackingPlayer.getStance(defendingPlayer) == Stance.ALLIANCE) {
throw new IllegalStateException("Cannot attack allied players.");
}
// make sure we are at war, unless one of both units is a privateer
//getOwner().isEuropean() && defendingPlayer.isEuropean() &&
if (attacker.hasAbility("model.ability.piracy")) {
defendingPlayer.setAttackedByPrivateers();
} else if (!defender.hasAbility("model.ability.piracy")) {
attackingPlayer.setStance(defendingPlayer, Stance.WAR);
defendingPlayer.setStance(attackingPlayer, Stance.WAR);
}
// Wake up if you're attacking something.
// Before, a unit could stay fortified during execution of an
// attack. - sjm
attacker.setState(UnitState.ACTIVE);
// The Revenger unit can attack multiple times
// Other units can only attack once
if (!attacker.hasAbility("model.ability.multipleAttacks")) {
attacker.setMovesLeft(0);
}
Tile newTile = defender.getTile();
//attacker.adjustTension(defender);
Settlement settlement = newTile.getSettlement();
switch (result.type) {
case EVADES:
if (attacker.isNaval()) {
// send message to both parties
attacker.addModelMessage(attacker, "model.unit.enemyShipEvaded",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT, attacker);
defender.addModelMessage(defender, "model.unit.shipEvaded",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT, defender);
} else {
logger.warning("Non-naval unit evades!");
}
break;
case LOSS:
if (attacker.isNaval()) {
Location repairLocation = attackingPlayer.getRepairLocation(attacker);
damageShip(attacker, null, attacker);
attacker.addModelMessage(attacker, "model.unit.shipDamaged",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%repairLocation%", repairLocation.getLocationName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.UNIT_DEMOTED);
defender.addModelMessage(defender, "model.unit.enemyShipDamaged",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() },
}, ModelMessage.COMBAT_RESULT);
} else {
demote(attacker, defender);
if (defendingPlayer.hasAbility("model.ability.automaticPromotion")) {
promote(defender);
}
}
break;
case GREAT_LOSS:
if (attacker.isNaval()) {
sinkShip(attacker, null, attacker);
attacker.addModelMessage(attacker, "model.unit.shipSunk",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.UNIT_LOST);
defender.addModelMessage(defender, "model.unit.enemyShipSunk",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT);
} else {
demote(attacker, defender);
promote(defender);
}
break;
case DONE_SETTLEMENT:
if (settlement instanceof IndianSettlement) {
defender.dispose();
destroySettlement(attacker, (IndianSettlement) settlement);
} else if (settlement instanceof Colony) {
captureColony(attacker, (Colony) settlement, plunderGold);
} else {
throw new IllegalStateException("Unknown type of settlement.");
}
break;
case WIN:
if (attacker.isNaval()) {
Location repairLocation = defendingPlayer.getRepairLocation(defender);
attacker.captureGoods(defender);
damageShip(defender, null, attacker);
attacker.addModelMessage(attacker, "model.unit.enemyShipDamaged",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT);
- defender.addModelMessage(defender, "model.unit.shipDamaged",
+ if (repairLocation != null ) {
+ defender.addModelMessage(defender, "model.unit.shipDamaged",
new String[][] {
{ "%unit%", defender.getName() },
{ "%repairLocation%", repairLocation.getLocationName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() },
}, ModelMessage.UNIT_DEMOTED);
+ }
} else if (attacker.hasAbility("model.ability.pillageUnprotectedColony") &&
!defender.isDefensiveUnit() &&
defender.getColony() != null &&
!defender.getColony().hasStockade()) {
pillageColony(attacker, defender.getColony());
} else {
if (attacker.hasAbility("model.ability.automaticPromotion")) {
promote(attacker);
}
if (!defender.isNaval()) {
demote(defender, attacker);
if (settlement instanceof IndianSettlement) {
getConvert(attacker, (IndianSettlement) settlement);
}
}
}
break;
case GREAT_WIN:
if (attacker.isNaval()) {
attacker.captureGoods(defender);
sinkShip(defender, null, attacker);
attacker.addModelMessage(attacker, "model.unit.enemyShipSunk",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT);
defender.addModelMessage(defender, "model.unit.shipSunk",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() }
}, ModelMessage.UNIT_LOST);
} else {
promote(attacker);
if (!defender.isNaval()) {
demote(defender, attacker);
if (settlement instanceof IndianSettlement) {
getConvert(attacker, (IndianSettlement) settlement);
}
}
}
break;
default:
logger.warning("Illegal result of attack!");
throw new IllegalArgumentException("Illegal result of attack!");
}
}
/**
* Bombard a unit with the given outcome.
*
* @param colony a <code>Colony</code> value
* @param defender The <code>Unit</code> defending against bombardment.
* @param result The result of the bombardment.
*/
public void bombard(Colony colony, Unit defender, CombatResult result) {
Player attackingPlayer = colony.getOwner();
Player defendingPlayer = defender.getOwner();
switch (result.type) {
case EVADES:
// send message to both parties
attackingPlayer.addModelMessage(colony, "model.unit.shipEvadedBombardment",
new String[][] {
{ "%colony%", colony.getName() },
{ "%unit%", defender.getName() },
{ "%nation%", defender.getOwner().getNationAsString() } },
ModelMessage.DEFAULT, colony);
defendingPlayer.addModelMessage(defender, "model.unit.shipEvadedBombardment",
new String[][] { { "%colony%", colony.getName() },
{ "%unit%", defender.getName() },
{ "%nation%", defender.getOwner().getNationAsString() } },
ModelMessage.DEFAULT, colony);
break;
case WIN:
damageShip(defender, colony, null);
attackingPlayer.addModelMessage(colony, "model.unit.enemyShipDamagedByBombardment",
new String[][] {
{ "%colony%", colony.getName() },
{ "%unit%", defender.getName() },
{ "%nation%", defender.getOwner().getNationAsString() }
}, ModelMessage.UNIT_DEMOTED);
break;
case GREAT_WIN:
sinkShip(defender, colony, null);
defendingPlayer.addModelMessage(colony, "model.unit.shipSunkByBombardment",
new String[][] {
{ "%colony%", colony.getName() },
{ "%unit%", defender.getName() },
{ "%nation%", defender.getOwner().getNationAsString() } },
ModelMessage.UNIT_DEMOTED);
break;
}
}
/**
* Captures an enemy colony and plunders gold.
*
* @param attacker an <code>Unit</code> value
* @param colony a <code>Colony</code> value
* @param plunderGold The amount of gold to plunder.
*/
public void captureColony(Unit attacker, Colony colony, int plunderGold) {
Player enemy = colony.getOwner();
Player myPlayer = attacker.getOwner();
enemy.modifyTension(attacker.getOwner(), Tension.TENSION_ADD_MAJOR);
if (myPlayer.isEuropean()) {
enemy.addModelMessage(enemy, "model.unit.colonyCapturedBy",
new String[][] {
{ "%colony%", colony.getName() },
{ "%amount%", Integer.toString(plunderGold) },
{ "%player%", myPlayer.getNationAsString() }
}, ModelMessage.DEFAULT);
damageAllShips(colony, attacker);
myPlayer.modifyGold(plunderGold);
enemy.modifyGold(-plunderGold);
colony.setOwner(myPlayer); // This also changes over all of the
// units...
myPlayer.addModelMessage(colony, "model.unit.colonyCaptured",
new String[][] {
{ "%colony%", colony.getName() },
{ "%amount%", Integer.toString(plunderGold) }
}, ModelMessage.DEFAULT);
// Demote all soldiers and clear all orders:
for (Unit capturedUnit : colony.getTile().getUnitList()) {
if (attacker.isUndead()) {
capturedUnit.setType(attacker.getType());
} else {
UnitType downgrade = capturedUnit.getType().getDowngrade(DowngradeType.CAPTURE);
if (downgrade != null) {
capturedUnit.setType(downgrade);
}
}
capturedUnit.setState(UnitState.ACTIVE);
}
if (attacker.isUndead()) {
for (Unit capturedUnit : colony.getUnitList()) {
capturedUnit.setType(attacker.getType());
}
attacker.setLocation(colony.getTile());
} else { // Indian:
if (colony.getUnitCount() <= 1) {
myPlayer.modifyGold(plunderGold);
enemy.modifyGold(-plunderGold);
myPlayer.addModelMessage(enemy, "model.unit.colonyBurning",
new String[][] { { "%colony%", colony.getName() },
{ "%amount%", Integer.toString(plunderGold) },
{ "%nation%", myPlayer.getNationAsString() },
{ "%unit%", attacker.getName() }
}, ModelMessage.DEFAULT);
damageAllShips(colony, attacker);
colony.dispose();
} else {
Unit victim = colony.getRandomUnit();
if (victim == null) {
return;
}
myPlayer.addModelMessage(colony, "model.unit.colonistSlaughtered",
new String[][] {
{ "%colony%", colony.getName() },
{ "%unit%", victim.getName() },
{ "%nation%", myPlayer.getNationAsString() },
{ "%enemyUnit%", attacker.getName() }
}, ModelMessage.UNIT_LOST);
victim.dispose();
}
}
}
}
/**
* Damages all ship located on this <code>Colony</code>'s
* <code>Tile</code>. That is: they are sent to the closest location for
* repair.
*
* @see #damageShip
*/
private void damageAllShips(Colony colony, Unit attacker) {
for (Unit unit : colony.getTile().getUnitList()) {
if (unit.isNaval()) {
damageShip(unit, null, attacker);
}
}
}
/**
* Damage a building or a ship or steal some goods or gold. It's called
* from attack when an indian attacks a colony and lose the combat with
* LOSS as result
*
* @param colony The attacked colony
*/
private void pillageColony(Unit attacker, Colony colony) {
ArrayList<Building> buildingList = new ArrayList<Building>();
ArrayList<Unit> shipList = new ArrayList<Unit>();
List<Goods> goodsList = colony.getGoodsContainer().getCompactGoods();
for (Building building : colony.getBuildings()) {
if (building.canBeDamaged()) {
buildingList.add(building);
}
}
List<Unit> unitList = colony.getTile().getUnitList();
for (Unit unit : unitList) {
if (unit.isNaval()) {
shipList.add(unit);
}
}
String nation = attacker.getOwner().getNationAsString();
String unitName = attacker.getName();
String colonyName = colony.getName();
int limit = buildingList.size() + goodsList.size() + shipList.size() + 1;
int random = attacker.getGame().getModelController().getRandom(attacker.getId() + "pillageColony", limit);
if (random < buildingList.size()) {
Building building = buildingList.get(random);
colony.addModelMessage(colony, "model.unit.buildingDamaged",
new String[][] {
{"%building%", building.getName()}, {"%colony%", colonyName},
{"%enemyNation%", nation}, {"%enemyUnit%", unitName}},
ModelMessage.DEFAULT, colony);
building.damage();
} else if (random < buildingList.size() + goodsList.size()) {
Goods goods = goodsList.get(random - buildingList.size());
goods.setAmount(Math.min(goods.getAmount() / 2, 50));
colony.removeGoods(goods);
if (attacker.getSpaceLeft() > 0) {
attacker.add(goods);
}
colony.addModelMessage(colony, "model.unit.goodsStolen",
new String[][] {
{"%amount%", String.valueOf(goods.getAmount())},
{"%goods%", goods.getName()}, {"%colony%", colonyName},
{"%enemyNation%", nation}, {"%enemyUnit%", unitName}},
ModelMessage.DEFAULT, goods);
} else if (random < buildingList.size() + goodsList.size() + shipList.size()) {
Unit ship = shipList.get(random - buildingList.size() - goodsList.size());
damageShip(ship, null, attacker);
} else { // steal gold
int gold = colony.getOwner().getGold() / 10;
colony.getOwner().modifyGold(-gold);
attacker.getOwner().modifyGold(gold);
colony.addModelMessage(colony, "model.unit.indianPlunder",
new String[][] {
{"%amount%", String.valueOf(gold)}, {"%colony%", colonyName},
{"%enemyNation%", nation}, {"%enemyUnit%", unitName}},
ModelMessage.DEFAULT, colony);
}
}
/**
* Destroys an Indian settlement.
*
* @param attacker an <code>Unit</code> value
* @param settlement an <code>IndianSettlement</code> value
*/
private void destroySettlement(Unit attacker, IndianSettlement settlement) {
Player enemy = settlement.getOwner();
boolean wasCapital = settlement.isCapital();
Tile newTile = settlement.getTile();
ModelController modelController = attacker.getGame().getModelController();
settlement.dispose();
enemy.modifyTension(attacker.getOwner(), Tension.TENSION_ADD_MAJOR);
List<UnitType> treasureUnitTypes = FreeCol.getSpecification()
.getUnitTypesWithAbility("model.ability.carryTreasure");
if (treasureUnitTypes.size() > 0) {
int randomTreasure = modelController.getRandom(attacker.getId() + "indianTreasureRandom" +
attacker.getId(), 11);
int random = modelController.getRandom(attacker.getId() + "newUnitForTreasure" +
attacker.getId(), treasureUnitTypes.size());
Unit tTrain = modelController.createUnit(attacker.getId() + "indianTreasure" +
attacker.getId(), newTile, attacker.getOwner(),
treasureUnitTypes.get(random));
// Larger treasure if Hernan Cortes is present in the congress:
Set<Modifier> modifierSet = attacker.getModifierSet("model.modifier.nativeTreasureModifier");
randomTreasure = (int) FeatureContainer.applyModifierSet(randomTreasure, attacker.getGame().getTurn(),
modifierSet);
SettlementType settlementType = ((IndianNationType) enemy.getNationType()).getTypeOfSettlement();
if (settlementType == SettlementType.INCA_CITY ||
settlementType == SettlementType.AZTEC_CITY) {
tTrain.setTreasureAmount(randomTreasure * 500 + 10000);
} else {
tTrain.setTreasureAmount(randomTreasure * 50 + 300);
}
// capitals give more gold
if (wasCapital) {
tTrain.setTreasureAmount((tTrain.getTreasureAmount() * 3) / 2);
}
attacker.addModelMessage(attacker, "model.unit.indianTreasure", new String[][] {
{ "%indian%", enemy.getNationAsString() },
{ "%amount%", Integer.toString(tTrain.getTreasureAmount()) }
}, ModelMessage.DEFAULT);
}
attacker.setLocation(newTile);
}
/**
* Check whether some indian converts due to the attack or they burn all missions
*
* @param indianSettlement The attacked indian settlement
*/
private void getConvert(Unit attacker, IndianSettlement indianSettlement) {
ModelController modelController = attacker.getGame().getModelController();
int random = modelController.getRandom(attacker.getId() + "getConvert", 100);
int convertProbability = (int) FeatureContainer
.applyModifierSet(attacker.getOwner().getDifficulty().getNativeConvertProbability(),
attacker.getGame().getTurn(),
attacker.getModifierSet("model.ability.nativeConvertBonus"));
// TODO: it should be bigger when tension is high
int burnProbability = attacker.getOwner().getDifficulty().getBurnProbability();
if (random < convertProbability) {
Unit missionary = indianSettlement.getMissionary();
if (missionary != null && missionary.getOwner() == attacker.getOwner() &&
attacker.getGame().getViewOwner() == null && indianSettlement.getUnitCount() > 1) {
List<UnitType> converts = FreeCol.getSpecification().getUnitTypesWithAbility("model.ability.convert");
if (converts.size() > 0) {
indianSettlement.getFirstUnit().dispose();
random = modelController.getRandom(attacker.getId() + "getConvertType", converts.size());
modelController.createUnit(attacker.getId() + "indianConvert", attacker.getLocation(),
attacker.getOwner(), converts.get(random));
}
}
} else if (random >= 100 - burnProbability) {
boolean burn = false;
List<Settlement> settlements = indianSettlement.getOwner().getSettlements();
for (Settlement settlement : settlements) {
IndianSettlement indian = (IndianSettlement) settlement;
Unit missionary = indian.getMissionary();
if (missionary != null && missionary.getOwner() == attacker.getOwner()) {
burn = true;
indian.setMissionary(null);
}
}
if (burn) {
attacker.addModelMessage(attacker, "model.unit.burnMissions", new String[][] {
{"%nation%", attacker.getOwner().getNationAsString()},
{"%enemyNation%", indianSettlement.getOwner().getNationAsString()}},
ModelMessage.DEFAULT, indianSettlement);
}
}
}
/**
* Sets the damage to this ship and sends it to its repair location.
*
* @param damagedShip A ship that is loosing a battle and getting damaged
* @param attackerColony The colony that may have opened fire on this unit (using fort coastal defenses)
* @param attackerUnit A unit which may have damaged the ship (when capturing the colony the ship was docked at)
*/
private void damageShip(Unit damagedShip, Colony attackerColony, Unit attackerUnit) {
String nation = damagedShip.getOwner().getNationAsString();
Location repairLocation = damagedShip.getOwner().getRepairLocation(damagedShip);
if (repairLocation == null) {
// This fixes a problem with enemy ships without a known repair
// location.
damagedShip.dispose();
return;
}
String repairLocationName = repairLocation.getLocationName();
if (attackerColony != null) {
damagedShip.addModelMessage(damagedShip, "model.unit.damageShipByBombardment",
new String[][] {
{ "%colony%", attackerColony.getName() },
{ "%unit%", damagedShip.getName() },
{ "%repairLocation%", repairLocationName },
{ "%nation%", nation } },
ModelMessage.UNIT_DEMOTED);
} else if (attackerUnit != null) {
damagedShip.addModelMessage(damagedShip, "model.unit.shipDamaged",
new String[][] {
{ "%unit%", damagedShip.getName() },
{ "%repairLocation%", repairLocationName },
{ "%enemyUnit%", attackerUnit.getName() },
{ "%enemyNation%", attackerUnit.getOwner().getNationAsString() } },
ModelMessage.UNIT_DEMOTED);
}
damagedShip.setHitpoints(1);
damagedShip.getUnitContainer().disposeAllUnits();
damagedShip.getGoodsContainer().removeAll();
damagedShip.sendToRepairLocation();
}
/**
* Sinks this ship.
*
* @param sinkingShip the Unit that is going to sink
* @param attackerColony The colony that may have opened fire on this unit (coastal defense bombardment)
* @param attackerUnit The unit which may have fought a battle against the ship
*/
private void sinkShip(Unit sinkingShip, Colony attackerColony, Unit attackerUnit) {
String nation = sinkingShip.getOwner().getNationAsString();
if (attackerColony != null) {
sinkingShip.addModelMessage(sinkingShip, "model.unit.sinkShipByBombardment",
new String[][] {
{ "%colony%", attackerColony.getName() },
{ "%unit%", sinkingShip.getName() },
{ "%nation%", nation }
}, ModelMessage.UNIT_LOST);
} else if (attackerUnit != null) {
sinkingShip.addModelMessage(sinkingShip, "model.unit.shipSunk",
new String[][] {
{ "%unit%", sinkingShip.getName() },
{ "%enemyUnit%", attackerUnit.getName() },
{ "%enemyNation%", attackerUnit.getOwner().getNationAsString() }
}, ModelMessage.UNIT_LOST);
}
sinkingShip.dispose();
}
/**
* Demotes a unit. A unit that can not be further demoted is
* captured or destroyed. The enemy may plunder equipment.
*
* @param unit a <code>Unit</code> value
* @param enemyUnit a <code>Unit</code> value
*/
private void demote(Unit unit, Unit enemyUnit) {
UnitType oldType = unit.getType();
String messageID = "model.unit.unitDemoted";
String nation = unit.getOwner().getNationAsString();
int messageType = ModelMessage.UNIT_LOST;
if (unit.hasAbility("model.ability.canBeCaptured")) {
if (enemyUnit.hasAbility("model.ability.captureUnits")) {
unit.setLocation(enemyUnit.getTile());
unit.setOwner(enemyUnit.getOwner());
if (enemyUnit.isUndead()) {
unit.setType(enemyUnit.getType());
} else {
UnitType downgrade = unit.getType().getDowngrade(DowngradeType.CAPTURE);
if (downgrade != null) {
unit.setType(downgrade);
}
}
String tempID = oldType.getId() + ".captured";
if (Messages.containsKey(tempID)) {
messageID = tempID;
} else {
messageID = "model.unit.unitCaptured";
}
} else {
String tempID = oldType.getId() + ".destroyed";
if (Messages.containsKey(tempID)) {
messageID = tempID;
} else {
messageID = "model.unit.unitSlaughtered";
}
unit.dispose();
}
} else {
// unit has equipment that protects from capture, or will
// be downgraded
EquipmentType typeToLose = null;
int combatLossPriority = 0;
for (EquipmentType equipmentType : unit.getEquipment()) {
if (equipmentType.getCombatLossPriority() > combatLossPriority) {
typeToLose = equipmentType;
combatLossPriority = equipmentType.getCombatLossPriority();
}
}
if (typeToLose != null) {
// lose equipment as a result of combat
unit.removeEquipment(typeToLose, true);
if (unit.getEquipment().isEmpty()) {
messageID = "model.unit.unitDemotedToUnarmed";
}
if (enemyUnit.hasAbility("model.ability.captureEquipment") &&
enemyUnit.canBeEquippedWith(typeToLose)) {
enemyUnit.equipWith(typeToLose, true);
unit.addModelMessage(unit, "model.unit.equipmentCaptured",
new String[][] {
{"%nation%", enemyUnit.getOwner().getNationAsString()},
{"%equipment%", typeToLose.getName()}},
ModelMessage.FOREIGN_DIPLOMACY);
}
} else {
// be downgraded as a result of combat
UnitType downgrade = unit.getType().getDowngrade(DowngradeType.DEMOTION);
if (downgrade != null) {
unit.setType(downgrade);
messageType = ModelMessage.UNIT_DEMOTED;
String tempID = oldType.getId() + ".demoted";
if (Messages.containsKey(tempID)) {
messageID = tempID;
} else {
messageID = "model.unit.unitDemoted";
}
} else {
String tempID = oldType.getId() + ".destroyed";
if (Messages.containsKey(tempID)) {
messageID = tempID;
} else {
messageID = "model.unit.unitSlaughtered";
}
unit.dispose();
}
}
}
String newName = unit.getName();
FreeColGameObject source = unit;
if (unit.getColony() != null) {
source = unit.getColony();
}
// TODO: this still doesn't work as intended
unit.addModelMessage(source, messageID, new String[][] {
{ "%oldName%", oldType.getName() },
{ "%unit%", newName },
{ "%nation%", nation },
{ "%enemyUnit%", enemyUnit.getName() },
{ "%enemyNation%", enemyUnit.getOwner().getNationAsString() }
}, messageType, unit);
if (unit.getOwner() != enemyUnit.getOwner()) {
// unit unit hasn't been captured by enemyUnit, show message to
// enemyUnit's owner
source = enemyUnit;
if (enemyUnit.getColony() != null) {
source = enemyUnit.getColony();
}
unit.addModelMessage(source, messageID, new String[][] {
{ "%oldName%", oldType.getName() },
{ "%unit%", newName },
{ "%enemyUnit%", enemyUnit.getName() },
{ "%nation%", nation },
{ "%enemyNation%", enemyUnit.getOwner().getNationAsString() }
}, messageType, unit);
}
}
/**
* Promotes this unit.
*
* @param unit an <code>Unit</code> value
*/
private void promote(Unit unit) {
String oldName = unit.getName();
String nation = unit.getOwner().getNationAsString();
UnitType newType = unit.getType().getPromotion();
if (newType != null) {
unit.setType(newType);
if (unit.getType().equals(newType)) {
// the new unit type was successfully applied
unit.addModelMessage(unit, "model.unit.unitPromoted",
new String[][] {
{ "%oldName%", oldName },
{ "%unit%", unit.getName() },
{ "%nation%", nation }
}, ModelMessage.UNIT_IMPROVED);
}
}
}
}
| false | true | public void attack(Unit attacker, Unit defender, CombatResult result, int plunderGold) {
Player attackingPlayer = attacker.getOwner();
Player defendingPlayer = defender.getOwner();
if (attackingPlayer.getStance(defendingPlayer) == Stance.ALLIANCE) {
throw new IllegalStateException("Cannot attack allied players.");
}
// make sure we are at war, unless one of both units is a privateer
//getOwner().isEuropean() && defendingPlayer.isEuropean() &&
if (attacker.hasAbility("model.ability.piracy")) {
defendingPlayer.setAttackedByPrivateers();
} else if (!defender.hasAbility("model.ability.piracy")) {
attackingPlayer.setStance(defendingPlayer, Stance.WAR);
defendingPlayer.setStance(attackingPlayer, Stance.WAR);
}
// Wake up if you're attacking something.
// Before, a unit could stay fortified during execution of an
// attack. - sjm
attacker.setState(UnitState.ACTIVE);
// The Revenger unit can attack multiple times
// Other units can only attack once
if (!attacker.hasAbility("model.ability.multipleAttacks")) {
attacker.setMovesLeft(0);
}
Tile newTile = defender.getTile();
//attacker.adjustTension(defender);
Settlement settlement = newTile.getSettlement();
switch (result.type) {
case EVADES:
if (attacker.isNaval()) {
// send message to both parties
attacker.addModelMessage(attacker, "model.unit.enemyShipEvaded",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT, attacker);
defender.addModelMessage(defender, "model.unit.shipEvaded",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT, defender);
} else {
logger.warning("Non-naval unit evades!");
}
break;
case LOSS:
if (attacker.isNaval()) {
Location repairLocation = attackingPlayer.getRepairLocation(attacker);
damageShip(attacker, null, attacker);
attacker.addModelMessage(attacker, "model.unit.shipDamaged",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%repairLocation%", repairLocation.getLocationName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.UNIT_DEMOTED);
defender.addModelMessage(defender, "model.unit.enemyShipDamaged",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() },
}, ModelMessage.COMBAT_RESULT);
} else {
demote(attacker, defender);
if (defendingPlayer.hasAbility("model.ability.automaticPromotion")) {
promote(defender);
}
}
break;
case GREAT_LOSS:
if (attacker.isNaval()) {
sinkShip(attacker, null, attacker);
attacker.addModelMessage(attacker, "model.unit.shipSunk",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.UNIT_LOST);
defender.addModelMessage(defender, "model.unit.enemyShipSunk",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT);
} else {
demote(attacker, defender);
promote(defender);
}
break;
case DONE_SETTLEMENT:
if (settlement instanceof IndianSettlement) {
defender.dispose();
destroySettlement(attacker, (IndianSettlement) settlement);
} else if (settlement instanceof Colony) {
captureColony(attacker, (Colony) settlement, plunderGold);
} else {
throw new IllegalStateException("Unknown type of settlement.");
}
break;
case WIN:
if (attacker.isNaval()) {
Location repairLocation = defendingPlayer.getRepairLocation(defender);
attacker.captureGoods(defender);
damageShip(defender, null, attacker);
attacker.addModelMessage(attacker, "model.unit.enemyShipDamaged",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT);
defender.addModelMessage(defender, "model.unit.shipDamaged",
new String[][] {
{ "%unit%", defender.getName() },
{ "%repairLocation%", repairLocation.getLocationName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() },
}, ModelMessage.UNIT_DEMOTED);
} else if (attacker.hasAbility("model.ability.pillageUnprotectedColony") &&
!defender.isDefensiveUnit() &&
defender.getColony() != null &&
!defender.getColony().hasStockade()) {
pillageColony(attacker, defender.getColony());
} else {
if (attacker.hasAbility("model.ability.automaticPromotion")) {
promote(attacker);
}
if (!defender.isNaval()) {
demote(defender, attacker);
if (settlement instanceof IndianSettlement) {
getConvert(attacker, (IndianSettlement) settlement);
}
}
}
break;
case GREAT_WIN:
if (attacker.isNaval()) {
attacker.captureGoods(defender);
sinkShip(defender, null, attacker);
attacker.addModelMessage(attacker, "model.unit.enemyShipSunk",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT);
defender.addModelMessage(defender, "model.unit.shipSunk",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() }
}, ModelMessage.UNIT_LOST);
} else {
promote(attacker);
if (!defender.isNaval()) {
demote(defender, attacker);
if (settlement instanceof IndianSettlement) {
getConvert(attacker, (IndianSettlement) settlement);
}
}
}
break;
default:
logger.warning("Illegal result of attack!");
throw new IllegalArgumentException("Illegal result of attack!");
}
}
| public void attack(Unit attacker, Unit defender, CombatResult result, int plunderGold) {
Player attackingPlayer = attacker.getOwner();
Player defendingPlayer = defender.getOwner();
if (attackingPlayer.getStance(defendingPlayer) == Stance.ALLIANCE) {
throw new IllegalStateException("Cannot attack allied players.");
}
// make sure we are at war, unless one of both units is a privateer
//getOwner().isEuropean() && defendingPlayer.isEuropean() &&
if (attacker.hasAbility("model.ability.piracy")) {
defendingPlayer.setAttackedByPrivateers();
} else if (!defender.hasAbility("model.ability.piracy")) {
attackingPlayer.setStance(defendingPlayer, Stance.WAR);
defendingPlayer.setStance(attackingPlayer, Stance.WAR);
}
// Wake up if you're attacking something.
// Before, a unit could stay fortified during execution of an
// attack. - sjm
attacker.setState(UnitState.ACTIVE);
// The Revenger unit can attack multiple times
// Other units can only attack once
if (!attacker.hasAbility("model.ability.multipleAttacks")) {
attacker.setMovesLeft(0);
}
Tile newTile = defender.getTile();
//attacker.adjustTension(defender);
Settlement settlement = newTile.getSettlement();
switch (result.type) {
case EVADES:
if (attacker.isNaval()) {
// send message to both parties
attacker.addModelMessage(attacker, "model.unit.enemyShipEvaded",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT, attacker);
defender.addModelMessage(defender, "model.unit.shipEvaded",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT, defender);
} else {
logger.warning("Non-naval unit evades!");
}
break;
case LOSS:
if (attacker.isNaval()) {
Location repairLocation = attackingPlayer.getRepairLocation(attacker);
damageShip(attacker, null, attacker);
attacker.addModelMessage(attacker, "model.unit.shipDamaged",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%repairLocation%", repairLocation.getLocationName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.UNIT_DEMOTED);
defender.addModelMessage(defender, "model.unit.enemyShipDamaged",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() },
}, ModelMessage.COMBAT_RESULT);
} else {
demote(attacker, defender);
if (defendingPlayer.hasAbility("model.ability.automaticPromotion")) {
promote(defender);
}
}
break;
case GREAT_LOSS:
if (attacker.isNaval()) {
sinkShip(attacker, null, attacker);
attacker.addModelMessage(attacker, "model.unit.shipSunk",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.UNIT_LOST);
defender.addModelMessage(defender, "model.unit.enemyShipSunk",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT);
} else {
demote(attacker, defender);
promote(defender);
}
break;
case DONE_SETTLEMENT:
if (settlement instanceof IndianSettlement) {
defender.dispose();
destroySettlement(attacker, (IndianSettlement) settlement);
} else if (settlement instanceof Colony) {
captureColony(attacker, (Colony) settlement, plunderGold);
} else {
throw new IllegalStateException("Unknown type of settlement.");
}
break;
case WIN:
if (attacker.isNaval()) {
Location repairLocation = defendingPlayer.getRepairLocation(defender);
attacker.captureGoods(defender);
damageShip(defender, null, attacker);
attacker.addModelMessage(attacker, "model.unit.enemyShipDamaged",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT);
if (repairLocation != null ) {
defender.addModelMessage(defender, "model.unit.shipDamaged",
new String[][] {
{ "%unit%", defender.getName() },
{ "%repairLocation%", repairLocation.getLocationName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() },
}, ModelMessage.UNIT_DEMOTED);
}
} else if (attacker.hasAbility("model.ability.pillageUnprotectedColony") &&
!defender.isDefensiveUnit() &&
defender.getColony() != null &&
!defender.getColony().hasStockade()) {
pillageColony(attacker, defender.getColony());
} else {
if (attacker.hasAbility("model.ability.automaticPromotion")) {
promote(attacker);
}
if (!defender.isNaval()) {
demote(defender, attacker);
if (settlement instanceof IndianSettlement) {
getConvert(attacker, (IndianSettlement) settlement);
}
}
}
break;
case GREAT_WIN:
if (attacker.isNaval()) {
attacker.captureGoods(defender);
sinkShip(defender, null, attacker);
attacker.addModelMessage(attacker, "model.unit.enemyShipSunk",
new String[][] {
{ "%unit%", attacker.getName() },
{ "%enemyUnit%", defender.getName() },
{ "%enemyNation%", defendingPlayer.getNationAsString() }
}, ModelMessage.COMBAT_RESULT);
defender.addModelMessage(defender, "model.unit.shipSunk",
new String[][] {
{ "%unit%", defender.getName() },
{ "%enemyUnit%", attacker.getName() },
{ "%enemyNation%", attackingPlayer.getNationAsString() }
}, ModelMessage.UNIT_LOST);
} else {
promote(attacker);
if (!defender.isNaval()) {
demote(defender, attacker);
if (settlement instanceof IndianSettlement) {
getConvert(attacker, (IndianSettlement) settlement);
}
}
}
break;
default:
logger.warning("Illegal result of attack!");
throw new IllegalArgumentException("Illegal result of attack!");
}
}
|
diff --git a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPQualifiedNameConverter.java b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPQualifiedNameConverter.java
index 72fbd43b..de04c9f1 100644
--- a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPQualifiedNameConverter.java
+++ b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPQualifiedNameConverter.java
@@ -1,45 +1,47 @@
/**
* Copyright (c) 2011 Cloudsmith Inc. and other contributors, as listed below.
* 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:
* Cloudsmith
*
*/
package org.cloudsmith.geppetto.pp.dsl.linking;
import org.eclipse.xtext.naming.IQualifiedNameConverter;
import org.eclipse.xtext.naming.QualifiedName;
/**
* Puppet Qualified Name Converter defines the separator '::'
*
*/
public class PPQualifiedNameConverter extends IQualifiedNameConverter.DefaultImpl {
private static final String separator = "::";
/*
* (non-Javadoc)
*
* @see org.eclipse.xtext.naming.IQualifiedNameConverter.DefaultImpl#getDelimiter()
*/
@Override
public String getDelimiter() {
return separator;
}
/**
* Removes leading '$' before converting to qualified name.
*
* @see org.eclipse.xtext.naming.IQualifiedNameConverter.DefaultImpl#toQualifiedName(java.lang.String)
*/
@Override
public QualifiedName toQualifiedName(String qualifiedNameAsString) {
+ if(qualifiedNameAsString == null || qualifiedNameAsString.length() < 1)
+ return QualifiedName.EMPTY;
return super.toQualifiedName(qualifiedNameAsString.startsWith("$")
? qualifiedNameAsString.substring(1)
: qualifiedNameAsString);
}
}
| true | true | public QualifiedName toQualifiedName(String qualifiedNameAsString) {
return super.toQualifiedName(qualifiedNameAsString.startsWith("$")
? qualifiedNameAsString.substring(1)
: qualifiedNameAsString);
}
| public QualifiedName toQualifiedName(String qualifiedNameAsString) {
if(qualifiedNameAsString == null || qualifiedNameAsString.length() < 1)
return QualifiedName.EMPTY;
return super.toQualifiedName(qualifiedNameAsString.startsWith("$")
? qualifiedNameAsString.substring(1)
: qualifiedNameAsString);
}
|
diff --git a/de.blizzy.backup/src/de/blizzy/backup/Updater.java b/de.blizzy.backup/src/de/blizzy/backup/Updater.java
index a2c1168..9c6795f 100644
--- a/de.blizzy.backup/src/de/blizzy/backup/Updater.java
+++ b/de.blizzy.backup/src/de/blizzy/backup/Updater.java
@@ -1,145 +1,147 @@
/*
blizzy's Backup - Easy to use personal file backup application
Copyright (C) 2011 Maik Schreiber
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.blizzy.backup;
import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;
import java.util.Date;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.operations.ProvisioningJob;
import org.eclipse.equinox.p2.operations.ProvisioningSession;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Shell;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
public class Updater {
private static final int VERSION_CHECK_INTERVAL = 7; // days
private boolean showDialogIfNoUpdatesAvailable;
private boolean forceCheck;
public Updater(boolean showDialogIfNoUpdatesAvailable, boolean forceCheck) {
this.showDialogIfNoUpdatesAvailable = showDialogIfNoUpdatesAvailable;
this.forceCheck = forceCheck;
}
public boolean update(Shell shell) throws Throwable {
final boolean[] restartNecessary = new boolean[1];
if (needsCheck()) {
final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
IRunnableWithProgress runnable = new IRunnableWithProgress() {
@SuppressWarnings("synthetic-access")
public void run(IProgressMonitor monitor) throws InvocationTargetException {
SubMonitor progress = SubMonitor.convert(monitor);
restartNecessary[0] = updateInJob(progress, pmd.getShell());
monitor.done();
}
};
try {
pmd.run(true, true, runnable);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
if (restartNecessary[0]) {
IDialogSettings settings = Utils.getSection("versionCheck"); //$NON-NLS-1$
settings.put("cleanupOldFeatures", true); //$NON-NLS-1$
}
return restartNecessary[0];
}
private boolean needsCheck() {
if (forceCheck) {
return true;
}
IDialogSettings settings = Utils.getSection("versionCheck"); //$NON-NLS-1$
String lastCheckTimeStr = settings.get("lastCheckTime"); //$NON-NLS-1$
if (lastCheckTimeStr == null) {
return true;
}
long lastCheckTime = Long.parseLong(lastCheckTimeStr);
Calendar next = Calendar.getInstance();
next.setTime(new Date(lastCheckTime));
next.add(Calendar.DAY_OF_YEAR, VERSION_CHECK_INTERVAL);
Calendar now = Calendar.getInstance();
return next.before(now) || next.equals(now);
}
private boolean updateInJob(SubMonitor progress, final Shell shell) {
progress.beginTask(Messages.CheckingForNewVersion, 2);
BundleContext bundleContext = BackupPlugin.getDefault().getBundle().getBundleContext();
ServiceReference ref = bundleContext.getServiceReference(IProvisioningAgent.SERVICE_NAME);
IProvisioningAgent agent = (IProvisioningAgent) bundleContext.getService(ref);
boolean restartNecessary = false;
ProvisioningSession session = new ProvisioningSession(agent);
final UpdateOperation op = new UpdateOperation(session);
IStatus status = op.resolveModal(progress.newChild(1));
resetCheckTimeout();
if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
if (showDialogIfNoUpdatesAvailable) {
shell.getDisplay().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(shell, Messages.Title_NoNewVersionAvailable, Messages.NoNewVersionAvailable);
}
});
}
} else if (status.isOK()) {
final boolean[] installUpdates = new boolean[1];
shell.getDisplay().syncExec(new Runnable() {
public void run() {
installUpdates[0] = MessageDialog.openConfirm(shell,
Messages.Title_NewVersionAvailable, Messages.NewVersionAvailable);
}
});
if (installUpdates[0]) {
ProvisioningJob job = op.getProvisioningJob(null);
status = job.runModal(progress.newChild(1));
if (status.isOK()) {
restartNecessary = true;
} else {
BackupPlugin.getDefault().getLog().log(status);
final IStatus myStatus = status;
shell.getDisplay().syncExec(new Runnable() {
public void run() {
ErrorDialog.openError(shell, Messages.Title_Error, null, myStatus);
}
});
}
}
+ } else {
+ BackupPlugin.getDefault().getLog().log(status);
}
return restartNecessary;
}
private void resetCheckTimeout() {
Utils.getSection("versionCheck").put("lastCheckTime", System.currentTimeMillis()); //$NON-NLS-1$//$NON-NLS-2$
}
}
| true | true | private boolean updateInJob(SubMonitor progress, final Shell shell) {
progress.beginTask(Messages.CheckingForNewVersion, 2);
BundleContext bundleContext = BackupPlugin.getDefault().getBundle().getBundleContext();
ServiceReference ref = bundleContext.getServiceReference(IProvisioningAgent.SERVICE_NAME);
IProvisioningAgent agent = (IProvisioningAgent) bundleContext.getService(ref);
boolean restartNecessary = false;
ProvisioningSession session = new ProvisioningSession(agent);
final UpdateOperation op = new UpdateOperation(session);
IStatus status = op.resolveModal(progress.newChild(1));
resetCheckTimeout();
if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
if (showDialogIfNoUpdatesAvailable) {
shell.getDisplay().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(shell, Messages.Title_NoNewVersionAvailable, Messages.NoNewVersionAvailable);
}
});
}
} else if (status.isOK()) {
final boolean[] installUpdates = new boolean[1];
shell.getDisplay().syncExec(new Runnable() {
public void run() {
installUpdates[0] = MessageDialog.openConfirm(shell,
Messages.Title_NewVersionAvailable, Messages.NewVersionAvailable);
}
});
if (installUpdates[0]) {
ProvisioningJob job = op.getProvisioningJob(null);
status = job.runModal(progress.newChild(1));
if (status.isOK()) {
restartNecessary = true;
} else {
BackupPlugin.getDefault().getLog().log(status);
final IStatus myStatus = status;
shell.getDisplay().syncExec(new Runnable() {
public void run() {
ErrorDialog.openError(shell, Messages.Title_Error, null, myStatus);
}
});
}
}
}
return restartNecessary;
}
| private boolean updateInJob(SubMonitor progress, final Shell shell) {
progress.beginTask(Messages.CheckingForNewVersion, 2);
BundleContext bundleContext = BackupPlugin.getDefault().getBundle().getBundleContext();
ServiceReference ref = bundleContext.getServiceReference(IProvisioningAgent.SERVICE_NAME);
IProvisioningAgent agent = (IProvisioningAgent) bundleContext.getService(ref);
boolean restartNecessary = false;
ProvisioningSession session = new ProvisioningSession(agent);
final UpdateOperation op = new UpdateOperation(session);
IStatus status = op.resolveModal(progress.newChild(1));
resetCheckTimeout();
if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
if (showDialogIfNoUpdatesAvailable) {
shell.getDisplay().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(shell, Messages.Title_NoNewVersionAvailable, Messages.NoNewVersionAvailable);
}
});
}
} else if (status.isOK()) {
final boolean[] installUpdates = new boolean[1];
shell.getDisplay().syncExec(new Runnable() {
public void run() {
installUpdates[0] = MessageDialog.openConfirm(shell,
Messages.Title_NewVersionAvailable, Messages.NewVersionAvailable);
}
});
if (installUpdates[0]) {
ProvisioningJob job = op.getProvisioningJob(null);
status = job.runModal(progress.newChild(1));
if (status.isOK()) {
restartNecessary = true;
} else {
BackupPlugin.getDefault().getLog().log(status);
final IStatus myStatus = status;
shell.getDisplay().syncExec(new Runnable() {
public void run() {
ErrorDialog.openError(shell, Messages.Title_Error, null, myStatus);
}
});
}
}
} else {
BackupPlugin.getDefault().getLog().log(status);
}
return restartNecessary;
}
|
diff --git a/name.abuchen.portfolio.ui/src/name/abuchen/portfolio/ui/dialogs/SecurityDeliveryDialog.java b/name.abuchen.portfolio.ui/src/name/abuchen/portfolio/ui/dialogs/SecurityDeliveryDialog.java
index f9e539c0..24279801 100644
--- a/name.abuchen.portfolio.ui/src/name/abuchen/portfolio/ui/dialogs/SecurityDeliveryDialog.java
+++ b/name.abuchen.portfolio.ui/src/name/abuchen/portfolio/ui/dialogs/SecurityDeliveryDialog.java
@@ -1,225 +1,225 @@
package name.abuchen.portfolio.ui.dialogs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import name.abuchen.portfolio.model.Client;
import name.abuchen.portfolio.model.Portfolio;
import name.abuchen.portfolio.model.PortfolioTransaction;
import name.abuchen.portfolio.model.PortfolioTransaction.Type;
import name.abuchen.portfolio.model.Security;
import name.abuchen.portfolio.model.Values;
import name.abuchen.portfolio.snapshot.ClientSnapshot;
import name.abuchen.portfolio.ui.Messages;
import name.abuchen.portfolio.ui.util.BindingHelper;
import name.abuchen.portfolio.ui.util.CurrencyToStringConverter;
import name.abuchen.portfolio.ui.util.StringToCurrencyConverter;
import name.abuchen.portfolio.util.Dates;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class SecurityDeliveryDialog extends AbstractDialog
{
static class Model extends BindingHelper.Model
{
private final PortfolioTransaction.Type type;
private Portfolio portfolio;
private Security security;
private long shares;
private long price;
private long fees;
private long total;
private Date date = Dates.today();
public Model(Client client, Portfolio portfolio, Type type)
{
super(client);
this.portfolio = portfolio;
this.type = type;
if (portfolio == null && !client.getPortfolios().isEmpty())
setPortfolio(client.getPortfolios().get(0));
if (security == null && !client.getSecurities().isEmpty())
setSecurity(client.getSecurities().get(0));
}
public PortfolioTransaction.Type getType()
{
return type;
}
public long getPrice()
{
return price;
}
private long calculatePrice()
{
return shares == 0 ? 0 : Math.max(0, (total - fees) * Values.Share.factor() / shares);
}
public Portfolio getPortfolio()
{
return portfolio;
}
public void setPortfolio(Portfolio portfolio)
{
firePropertyChange("portfolio", this.portfolio, this.portfolio = portfolio); //$NON-NLS-1$
}
public Security getSecurity()
{
return security;
}
public void setSecurity(Security security)
{
firePropertyChange("security", this.security, this.security = security); //$NON-NLS-1$
}
public long getShares()
{
return shares;
}
public void setShares(long shares)
{
firePropertyChange("shares", this.shares, this.shares = shares); //$NON-NLS-1$
firePropertyChange("price", this.price, this.price = calculatePrice()); //$NON-NLS-1$
}
public long getTotal()
{
return total;
}
public void setTotal(long total)
{
firePropertyChange("total", this.total, this.total = total); //$NON-NLS-1$
firePropertyChange("price", this.price, this.price = calculatePrice()); //$NON-NLS-1$
}
public long getFees()
{
return fees;
}
public void setFees(long fees)
{
firePropertyChange("fees", this.fees, this.fees = fees); //$NON-NLS-1$
firePropertyChange("price", this.price, this.price = calculatePrice()); //$NON-NLS-1$
}
public Date getDate()
{
return date;
}
public void setDate(Date date)
{
firePropertyChange("date", this.date, this.date = date); //$NON-NLS-1$
}
@Override
public void applyChanges()
{
if (security == null)
throw new UnsupportedOperationException(Messages.MsgMissingSecurity);
PortfolioTransaction t = new PortfolioTransaction();
t.setType(type);
t.setDate(date);
t.setSecurity(security);
t.setFees(fees);
t.setShares(shares);
t.setAmount(total);
portfolio.addTransaction(t);
}
}
public SecurityDeliveryDialog(Shell parentShell, Client client, Portfolio portfolio, PortfolioTransaction.Type type)
{
super(parentShell, type.toString(), new Model(client, portfolio, type));
if (!(type == PortfolioTransaction.Type.DELIVERY_INBOUND || type == PortfolioTransaction.Type.DELIVERY_OUTBOUND))
throw new UnsupportedOperationException();
}
@Override
protected void createFormElements(Composite editArea)
{
// security selection
List<Security> securities = new ArrayList<Security>();
if (((Model) getModel()).getType() == PortfolioTransaction.Type.DELIVERY_INBOUND)
{
for (Security s : getModel().getClient().getSecurities())
if (!s.isRetired())
securities.add(s);
}
else
{
securities.addAll(ClientSnapshot.create(getModel().getClient(), Dates.today()).getJointPortfolio()
.getPositionsBySecurity().keySet());
}
Collections.sort(securities, new Security.ByName());
bindings().bindComboViewer(editArea, Messages.ColumnSecurity, "security", new LabelProvider() //$NON-NLS-1$
{
@Override
public String getText(Object element)
{
return ((Security) element).getName();
}
}, securities.toArray());
// portfolio selection
bindings().bindComboViewer(editArea, Messages.ColumnPortfolio, "portfolio", new LabelProvider() //$NON-NLS-1$
{
@Override
public String getText(Object element)
{
return ((Portfolio) element).getName();
}
}, getModel().getClient().getPortfolios().toArray());
// shares
bindings().bindMandatorySharesInput(editArea, Messages.ColumnShares, "shares").setFocus(); //$NON-NLS-1$
// price
Label label = new Label(editArea, SWT.NONE);
label.setText(Messages.ColumnPrice);
Label lblPrice = new Label(editArea, SWT.BORDER | SWT.READ_ONLY | SWT.NO_FOCUS);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, false).applyTo(lblPrice);
getBindingContext().bindValue(
SWTObservables.observeText(lblPrice),
BeansObservables.observeValue(getModel(), "price"), //$NON-NLS-1$
new UpdateValueStrategy(false, UpdateValueStrategy.POLICY_UPDATE)
.setConverter(new StringToCurrencyConverter(Values.Amount)), //
new UpdateValueStrategy(false, UpdateValueStrategy.POLICY_UPDATE)
.setConverter(new CurrencyToStringConverter(Values.Amount)));
// fees
- bindings().bindMandatoryAmountInput(editArea, Messages.ColumnFees, "fees"); //$NON-NLS-1$
+ bindings().bindAmountInput(editArea, Messages.ColumnFees, "fees"); //$NON-NLS-1$
// total
bindings().bindMandatoryAmountInput(editArea, Messages.ColumnTotal, "total"); //$NON-NLS-1$
// date
bindings().bindDatePicker(editArea, Messages.ColumnDate, "date"); //$NON-NLS-1$
}
}
| true | true | protected void createFormElements(Composite editArea)
{
// security selection
List<Security> securities = new ArrayList<Security>();
if (((Model) getModel()).getType() == PortfolioTransaction.Type.DELIVERY_INBOUND)
{
for (Security s : getModel().getClient().getSecurities())
if (!s.isRetired())
securities.add(s);
}
else
{
securities.addAll(ClientSnapshot.create(getModel().getClient(), Dates.today()).getJointPortfolio()
.getPositionsBySecurity().keySet());
}
Collections.sort(securities, new Security.ByName());
bindings().bindComboViewer(editArea, Messages.ColumnSecurity, "security", new LabelProvider() //$NON-NLS-1$
{
@Override
public String getText(Object element)
{
return ((Security) element).getName();
}
}, securities.toArray());
// portfolio selection
bindings().bindComboViewer(editArea, Messages.ColumnPortfolio, "portfolio", new LabelProvider() //$NON-NLS-1$
{
@Override
public String getText(Object element)
{
return ((Portfolio) element).getName();
}
}, getModel().getClient().getPortfolios().toArray());
// shares
bindings().bindMandatorySharesInput(editArea, Messages.ColumnShares, "shares").setFocus(); //$NON-NLS-1$
// price
Label label = new Label(editArea, SWT.NONE);
label.setText(Messages.ColumnPrice);
Label lblPrice = new Label(editArea, SWT.BORDER | SWT.READ_ONLY | SWT.NO_FOCUS);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, false).applyTo(lblPrice);
getBindingContext().bindValue(
SWTObservables.observeText(lblPrice),
BeansObservables.observeValue(getModel(), "price"), //$NON-NLS-1$
new UpdateValueStrategy(false, UpdateValueStrategy.POLICY_UPDATE)
.setConverter(new StringToCurrencyConverter(Values.Amount)), //
new UpdateValueStrategy(false, UpdateValueStrategy.POLICY_UPDATE)
.setConverter(new CurrencyToStringConverter(Values.Amount)));
// fees
bindings().bindMandatoryAmountInput(editArea, Messages.ColumnFees, "fees"); //$NON-NLS-1$
// total
bindings().bindMandatoryAmountInput(editArea, Messages.ColumnTotal, "total"); //$NON-NLS-1$
// date
bindings().bindDatePicker(editArea, Messages.ColumnDate, "date"); //$NON-NLS-1$
}
| protected void createFormElements(Composite editArea)
{
// security selection
List<Security> securities = new ArrayList<Security>();
if (((Model) getModel()).getType() == PortfolioTransaction.Type.DELIVERY_INBOUND)
{
for (Security s : getModel().getClient().getSecurities())
if (!s.isRetired())
securities.add(s);
}
else
{
securities.addAll(ClientSnapshot.create(getModel().getClient(), Dates.today()).getJointPortfolio()
.getPositionsBySecurity().keySet());
}
Collections.sort(securities, new Security.ByName());
bindings().bindComboViewer(editArea, Messages.ColumnSecurity, "security", new LabelProvider() //$NON-NLS-1$
{
@Override
public String getText(Object element)
{
return ((Security) element).getName();
}
}, securities.toArray());
// portfolio selection
bindings().bindComboViewer(editArea, Messages.ColumnPortfolio, "portfolio", new LabelProvider() //$NON-NLS-1$
{
@Override
public String getText(Object element)
{
return ((Portfolio) element).getName();
}
}, getModel().getClient().getPortfolios().toArray());
// shares
bindings().bindMandatorySharesInput(editArea, Messages.ColumnShares, "shares").setFocus(); //$NON-NLS-1$
// price
Label label = new Label(editArea, SWT.NONE);
label.setText(Messages.ColumnPrice);
Label lblPrice = new Label(editArea, SWT.BORDER | SWT.READ_ONLY | SWT.NO_FOCUS);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, false).applyTo(lblPrice);
getBindingContext().bindValue(
SWTObservables.observeText(lblPrice),
BeansObservables.observeValue(getModel(), "price"), //$NON-NLS-1$
new UpdateValueStrategy(false, UpdateValueStrategy.POLICY_UPDATE)
.setConverter(new StringToCurrencyConverter(Values.Amount)), //
new UpdateValueStrategy(false, UpdateValueStrategy.POLICY_UPDATE)
.setConverter(new CurrencyToStringConverter(Values.Amount)));
// fees
bindings().bindAmountInput(editArea, Messages.ColumnFees, "fees"); //$NON-NLS-1$
// total
bindings().bindMandatoryAmountInput(editArea, Messages.ColumnTotal, "total"); //$NON-NLS-1$
// date
bindings().bindDatePicker(editArea, Messages.ColumnDate, "date"); //$NON-NLS-1$
}
|
diff --git a/src/main/java/com/slclassifieds/adsonline/web/HomeController.java b/src/main/java/com/slclassifieds/adsonline/web/HomeController.java
index 09ca72c..163b522 100644
--- a/src/main/java/com/slclassifieds/adsonline/web/HomeController.java
+++ b/src/main/java/com/slclassifieds/adsonline/web/HomeController.java
@@ -1,55 +1,55 @@
package com.slclassifieds.adsonline.web;
import java.util.Locale;
import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.slclassifieds.adsonline.dao.UserDao;
import com.slclassifieds.adsonline.dao.UserDaoImpl;
import com.slclassifieds.adsonline.model.User;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
private UserDao userDao;
@Autowired
public void setUserDao(UserDao userDaoImpl) {
this.userDao = userDaoImpl;
}
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
- return "head";
+ return "home";
}
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String homeMethod(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
return "home";
}
}
| true | true | public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
return "head";
}
| public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
return "home";
}
|
diff --git a/src/com/android/mms/MmsConfig.java b/src/com/android/mms/MmsConfig.java
index 6ec0a1c..1d1469f 100644
--- a/src/com/android/mms/MmsConfig.java
+++ b/src/com/android/mms/MmsConfig.java
@@ -1,147 +1,147 @@
/*
* Copyright (C) 2009 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.mms;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.net.Uri;
import android.util.Config;
import android.util.Log;
import com.android.internal.util.XmlUtils;
public class MmsConfig {
private static final String TAG = "MmsConfig";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
/**
* Whether to hide MMS functionality from the user (i.e. SMS only).
*/
private static int mMmsEnabled = -1; // an int so we can tell whether it's been inited
private static int mMaxMessageSize = 0;
private static String mUaProfUrl = null;
private static int mMaxImageHeight = 0;
private static int mMaxImageWidth = 0;
public static void init(Context context) {
if (LOCAL_LOGV) {
Log.v(TAG, "MmsConfig.init()");
}
loadMmsSettings(context);
}
public static boolean getMmsEnabled() {
return mMmsEnabled == 1 ? true : false;
}
public static int getMaxMessageSize() {
return mMaxMessageSize;
}
public static String getUaProfUrl() {
return mUaProfUrl;
}
public static int getMaxImageHeight() {
return mMaxImageHeight;
}
public static int getMaxImageWidth() {
return mMaxImageWidth;
}
private static void loadMmsSettings(Context context) {
XmlResourceParser parser = context.getResources()
.getXml(R.xml.mms_config);
try {
XmlUtils.beginDocument(parser, "mms_config");
while (true) {
XmlUtils.nextElement(parser);
String tag = parser.getName();
if (tag == null) {
break;
}
String name = parser.getAttributeName(0);
String value = parser.getAttributeValue(0);
String text = null;
if (parser.next() == XmlPullParser.TEXT) {
text = parser.getText();
}
if ("name".equalsIgnoreCase(name)) {
if ("bool".equals(tag)) {
// bool config tags go here
if ("enabledMMS".equalsIgnoreCase(value)) {
mMmsEnabled = "true".equalsIgnoreCase(text) ? 1 : 0;
}
} else if ("int".equals(tag)) {
// int config tags go here
if ("maxMessageSize".equalsIgnoreCase(value)) {
mMaxMessageSize = Integer.parseInt(text);
} else if ("maxImageHeight".equalsIgnoreCase(value)) {
mMaxImageHeight = Integer.parseInt(text);
} else if ("maxImageWidth".equalsIgnoreCase(value)) {
mMaxImageWidth = Integer.parseInt(text);
}
} else if ("string".equals(tag)) {
// string config tags go here
if ("uaProfUrl".equalsIgnoreCase(value)) {
mUaProfUrl = text;
}
}
}
}
} catch (XmlPullParserException e) {
} catch (NumberFormatException e) {
} catch (IOException e) {
} finally {
parser.close();
}
String errorStr = null;
if (mMmsEnabled == -1) {
errorStr = "enableMMS";
}
if (mMaxMessageSize == 0) {
errorStr = "maxMessageSize";
}
if (mMaxImageHeight == 0) {
errorStr = "maxImageHeight";
}
if (mMaxImageWidth == 0) {
errorStr = "maxImageWidth";
}
- if (mUaProfUrl == null) {
+ if (getMmsEnabled() && mUaProfUrl == null) {
errorStr = "uaProfUrl";
}
if (errorStr != null) {
String err =
String.format("MmsConfig.loadMmsSettings mms_config.xml missing %s setting",
errorStr);
Log.e(TAG, err);
throw new ContentRestrictionException(err);
}
}
}
| true | true | private static void loadMmsSettings(Context context) {
XmlResourceParser parser = context.getResources()
.getXml(R.xml.mms_config);
try {
XmlUtils.beginDocument(parser, "mms_config");
while (true) {
XmlUtils.nextElement(parser);
String tag = parser.getName();
if (tag == null) {
break;
}
String name = parser.getAttributeName(0);
String value = parser.getAttributeValue(0);
String text = null;
if (parser.next() == XmlPullParser.TEXT) {
text = parser.getText();
}
if ("name".equalsIgnoreCase(name)) {
if ("bool".equals(tag)) {
// bool config tags go here
if ("enabledMMS".equalsIgnoreCase(value)) {
mMmsEnabled = "true".equalsIgnoreCase(text) ? 1 : 0;
}
} else if ("int".equals(tag)) {
// int config tags go here
if ("maxMessageSize".equalsIgnoreCase(value)) {
mMaxMessageSize = Integer.parseInt(text);
} else if ("maxImageHeight".equalsIgnoreCase(value)) {
mMaxImageHeight = Integer.parseInt(text);
} else if ("maxImageWidth".equalsIgnoreCase(value)) {
mMaxImageWidth = Integer.parseInt(text);
}
} else if ("string".equals(tag)) {
// string config tags go here
if ("uaProfUrl".equalsIgnoreCase(value)) {
mUaProfUrl = text;
}
}
}
}
} catch (XmlPullParserException e) {
} catch (NumberFormatException e) {
} catch (IOException e) {
} finally {
parser.close();
}
String errorStr = null;
if (mMmsEnabled == -1) {
errorStr = "enableMMS";
}
if (mMaxMessageSize == 0) {
errorStr = "maxMessageSize";
}
if (mMaxImageHeight == 0) {
errorStr = "maxImageHeight";
}
if (mMaxImageWidth == 0) {
errorStr = "maxImageWidth";
}
if (mUaProfUrl == null) {
errorStr = "uaProfUrl";
}
if (errorStr != null) {
String err =
String.format("MmsConfig.loadMmsSettings mms_config.xml missing %s setting",
errorStr);
Log.e(TAG, err);
throw new ContentRestrictionException(err);
}
}
| private static void loadMmsSettings(Context context) {
XmlResourceParser parser = context.getResources()
.getXml(R.xml.mms_config);
try {
XmlUtils.beginDocument(parser, "mms_config");
while (true) {
XmlUtils.nextElement(parser);
String tag = parser.getName();
if (tag == null) {
break;
}
String name = parser.getAttributeName(0);
String value = parser.getAttributeValue(0);
String text = null;
if (parser.next() == XmlPullParser.TEXT) {
text = parser.getText();
}
if ("name".equalsIgnoreCase(name)) {
if ("bool".equals(tag)) {
// bool config tags go here
if ("enabledMMS".equalsIgnoreCase(value)) {
mMmsEnabled = "true".equalsIgnoreCase(text) ? 1 : 0;
}
} else if ("int".equals(tag)) {
// int config tags go here
if ("maxMessageSize".equalsIgnoreCase(value)) {
mMaxMessageSize = Integer.parseInt(text);
} else if ("maxImageHeight".equalsIgnoreCase(value)) {
mMaxImageHeight = Integer.parseInt(text);
} else if ("maxImageWidth".equalsIgnoreCase(value)) {
mMaxImageWidth = Integer.parseInt(text);
}
} else if ("string".equals(tag)) {
// string config tags go here
if ("uaProfUrl".equalsIgnoreCase(value)) {
mUaProfUrl = text;
}
}
}
}
} catch (XmlPullParserException e) {
} catch (NumberFormatException e) {
} catch (IOException e) {
} finally {
parser.close();
}
String errorStr = null;
if (mMmsEnabled == -1) {
errorStr = "enableMMS";
}
if (mMaxMessageSize == 0) {
errorStr = "maxMessageSize";
}
if (mMaxImageHeight == 0) {
errorStr = "maxImageHeight";
}
if (mMaxImageWidth == 0) {
errorStr = "maxImageWidth";
}
if (getMmsEnabled() && mUaProfUrl == null) {
errorStr = "uaProfUrl";
}
if (errorStr != null) {
String err =
String.format("MmsConfig.loadMmsSettings mms_config.xml missing %s setting",
errorStr);
Log.e(TAG, err);
throw new ContentRestrictionException(err);
}
}
|
diff --git a/sitestats-tool/src/java/org/sakaiproject/sitestats/tool/wicket/widget/Widget.java b/sitestats-tool/src/java/org/sakaiproject/sitestats/tool/wicket/widget/Widget.java
index d800278..d7eb99d 100644
--- a/sitestats-tool/src/java/org/sakaiproject/sitestats/tool/wicket/widget/Widget.java
+++ b/sitestats-tool/src/java/org/sakaiproject/sitestats/tool/wicket/widget/Widget.java
@@ -1,212 +1,213 @@
/**
* $URL:$
* $Id:$
*
* Copyright (c) 2006-2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.sitestats.tool.wicket.widget;
import java.util.List;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.PageParameters;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.link.StatelessLink;
import org.apache.wicket.markup.html.list.Loop;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.sakaiproject.sitestats.api.report.ReportDef;
import org.sakaiproject.sitestats.tool.wicket.components.AjaxLazyLoadFragment;
import org.sakaiproject.sitestats.tool.wicket.components.ExternalImage;
import org.sakaiproject.sitestats.tool.wicket.models.ReportDefModel;
import org.sakaiproject.sitestats.tool.wicket.pages.ReportDataPage;
/**
* @author Nuno Fernandes
*/
public class Widget extends Panel {
private static final long serialVersionUID = 1L;
private static final int MAX_TEXT_LENGTH = 16;
private String iconUrl = "";
private String title = "";
private List<WidgetMiniStat> widgetMiniStats = null;
private List<AbstractTab> tabs = null;
public Widget(String id, String iconUrl, String title, List<WidgetMiniStat> widgetMiniStats, List<AbstractTab> widgetTabs) {
super(id);
this.iconUrl = iconUrl;
this.title = title;
this.widgetMiniStats = widgetMiniStats;
this.tabs = widgetTabs;
}
@Override
protected void onBeforeRender() {
renderWidget();
super.onBeforeRender();
}
private void renderWidget() {
setRenderBodyOnly(true);
removeAll();
// Icon
add(new ExternalImage("icon", iconUrl));
// Title
add(new Label("title", title));
// Show more/less links
ExternalLink showMore = new ExternalLink("showMore", "#");
showMore.setOutputMarkupId(true);
add(showMore);
ExternalLink showLess = new ExternalLink("showLess", "#");
showLess.setOutputMarkupId(true);
add(showLess);
// Content details (middle)
WebMarkupContainer middle = new WebMarkupContainer("middle");
middle.setOutputMarkupId(true);
add(middle);
// MiniStats ajax load behavior
AjaxLazyLoadFragment ministatContainer = new AjaxLazyLoadFragment("ministatContainer") {
private static final long serialVersionUID = 12L;
@Override
public Fragment getLazyLoadFragment(String markupId) {
return Widget.this.getLazyLoadedMiniStats(markupId);
}
@Override
public Component getLoadingComponent(String markupId) {
StringBuilder loadingComp = new StringBuilder();
loadingComp.append("<div class=\"ministat load\">");
loadingComp.append(" <img src=\"");
loadingComp.append(RequestCycle.get().urlFor(AbstractDefaultAjaxBehavior.INDICATOR));
loadingComp.append("\"/>");
loadingComp.append("</div>");
return new Label(markupId, loadingComp.toString()).setEscapeModelStrings(false);
}
};
add(ministatContainer);
// Tabs
WidgetTabs widgetTabs = new WidgetTabs("widgetTabs", tabs, 0);
middle.add(widgetTabs);
// Links behaviors
String showMoreOnclick = "showMoreLess('#"+middle.getMarkupId()+"', '#"+showMore.getMarkupId()+"','#"+showLess.getMarkupId()+"');return false;";
showMore.add(new SimpleAttributeModifier("onclick", showMoreOnclick));
String showLessOnclick = "showMoreLess('#"+middle.getMarkupId()+"', '#"+showMore.getMarkupId()+"','#"+showLess.getMarkupId()+"');return false;";
showLess.add(new SimpleAttributeModifier("onclick", showLessOnclick));
}
private Fragment getLazyLoadedMiniStats(String markupId) {
Fragment ministatFragment = new Fragment(markupId, "ministatFragment", this);
int miniStatsCount = widgetMiniStats != null ? widgetMiniStats.size() : 0;
Loop miniStatsLoop = new Loop("ministat", miniStatsCount) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(LoopItem item) {
int index = item.getIteration();
WidgetMiniStat ms = widgetMiniStats.get(index);
// Value
WebMarkupContainer value = new WebMarkupContainer("value");
Label valueLabel = new Label("valueLabel", ms.getValue());
valueLabel.setRenderBodyOnly(true);
String tooltip = ms.getTooltip();
StringBuilder classes = new StringBuilder();
if(tooltip == null) {
classes.append("value");
}else{
classes.append("valueText");
value.add(new AttributeModifier("title", true, new Model(ms.getTooltip())));
}
if(ms.isWiderText()) {
if(ms.getValue().length() > MAX_TEXT_LENGTH) {
valueLabel.setModelObject(ms.getValue().substring(0, MAX_TEXT_LENGTH) + "...");
}
item.add(new AttributeModifier("class", true, new Model("ministat wider")));
}
value.add(new AttributeModifier("class", true, new Model(classes.toString())));
value.add(valueLabel);
item.add(value);
// Second value
Label secvalue = new Label("secvalue", ms.getSecondValue());
secvalue.setVisible(ms.getSecondValue() != null);
value.add(secvalue);
// Link
final ReportDef reportDefinition = ms.getReportDefinition();
Link link = new StatelessLink("report") {
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
String siteId = reportDefinition.getSiteId();
ReportDefModel reportDefModel = new ReportDefModel(reportDefinition);
setResponsePage(new ReportDataPage(reportDefModel, new PageParameters("siteId="+siteId), getWebPage()));
}
};
if(reportDefinition != null) {
link.add(new AttributeModifier("title", true, new ResourceModel("overview_show_report")));
}else if(ms instanceof WidgetMiniStatLink){
WidgetMiniStatLink msl = (WidgetMiniStatLink) ms;
final Page page = msl.getPageLink();
link = new StatelessLink("report") {
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
setResponsePage(page);
}
};
if(msl.getPageLinkTooltip() != null) {
link.add(new AttributeModifier("title", true, new Model(msl.getPageLinkTooltip())));
}
link.add(new AttributeModifier("class", true, new Model("extlink")));
}else{
link.setEnabled(false);
link.setRenderBodyOnly(true);
}
item.add(link);
// Label
Label label = new Label("label", ms.getLabel());
+ label.setRenderBodyOnly(true);
link.add(label);
}
};
ministatFragment.add(miniStatsLoop);
return ministatFragment;
}
}
| true | true | private Fragment getLazyLoadedMiniStats(String markupId) {
Fragment ministatFragment = new Fragment(markupId, "ministatFragment", this);
int miniStatsCount = widgetMiniStats != null ? widgetMiniStats.size() : 0;
Loop miniStatsLoop = new Loop("ministat", miniStatsCount) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(LoopItem item) {
int index = item.getIteration();
WidgetMiniStat ms = widgetMiniStats.get(index);
// Value
WebMarkupContainer value = new WebMarkupContainer("value");
Label valueLabel = new Label("valueLabel", ms.getValue());
valueLabel.setRenderBodyOnly(true);
String tooltip = ms.getTooltip();
StringBuilder classes = new StringBuilder();
if(tooltip == null) {
classes.append("value");
}else{
classes.append("valueText");
value.add(new AttributeModifier("title", true, new Model(ms.getTooltip())));
}
if(ms.isWiderText()) {
if(ms.getValue().length() > MAX_TEXT_LENGTH) {
valueLabel.setModelObject(ms.getValue().substring(0, MAX_TEXT_LENGTH) + "...");
}
item.add(new AttributeModifier("class", true, new Model("ministat wider")));
}
value.add(new AttributeModifier("class", true, new Model(classes.toString())));
value.add(valueLabel);
item.add(value);
// Second value
Label secvalue = new Label("secvalue", ms.getSecondValue());
secvalue.setVisible(ms.getSecondValue() != null);
value.add(secvalue);
// Link
final ReportDef reportDefinition = ms.getReportDefinition();
Link link = new StatelessLink("report") {
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
String siteId = reportDefinition.getSiteId();
ReportDefModel reportDefModel = new ReportDefModel(reportDefinition);
setResponsePage(new ReportDataPage(reportDefModel, new PageParameters("siteId="+siteId), getWebPage()));
}
};
if(reportDefinition != null) {
link.add(new AttributeModifier("title", true, new ResourceModel("overview_show_report")));
}else if(ms instanceof WidgetMiniStatLink){
WidgetMiniStatLink msl = (WidgetMiniStatLink) ms;
final Page page = msl.getPageLink();
link = new StatelessLink("report") {
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
setResponsePage(page);
}
};
if(msl.getPageLinkTooltip() != null) {
link.add(new AttributeModifier("title", true, new Model(msl.getPageLinkTooltip())));
}
link.add(new AttributeModifier("class", true, new Model("extlink")));
}else{
link.setEnabled(false);
link.setRenderBodyOnly(true);
}
item.add(link);
// Label
Label label = new Label("label", ms.getLabel());
link.add(label);
}
};
ministatFragment.add(miniStatsLoop);
return ministatFragment;
}
| private Fragment getLazyLoadedMiniStats(String markupId) {
Fragment ministatFragment = new Fragment(markupId, "ministatFragment", this);
int miniStatsCount = widgetMiniStats != null ? widgetMiniStats.size() : 0;
Loop miniStatsLoop = new Loop("ministat", miniStatsCount) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(LoopItem item) {
int index = item.getIteration();
WidgetMiniStat ms = widgetMiniStats.get(index);
// Value
WebMarkupContainer value = new WebMarkupContainer("value");
Label valueLabel = new Label("valueLabel", ms.getValue());
valueLabel.setRenderBodyOnly(true);
String tooltip = ms.getTooltip();
StringBuilder classes = new StringBuilder();
if(tooltip == null) {
classes.append("value");
}else{
classes.append("valueText");
value.add(new AttributeModifier("title", true, new Model(ms.getTooltip())));
}
if(ms.isWiderText()) {
if(ms.getValue().length() > MAX_TEXT_LENGTH) {
valueLabel.setModelObject(ms.getValue().substring(0, MAX_TEXT_LENGTH) + "...");
}
item.add(new AttributeModifier("class", true, new Model("ministat wider")));
}
value.add(new AttributeModifier("class", true, new Model(classes.toString())));
value.add(valueLabel);
item.add(value);
// Second value
Label secvalue = new Label("secvalue", ms.getSecondValue());
secvalue.setVisible(ms.getSecondValue() != null);
value.add(secvalue);
// Link
final ReportDef reportDefinition = ms.getReportDefinition();
Link link = new StatelessLink("report") {
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
String siteId = reportDefinition.getSiteId();
ReportDefModel reportDefModel = new ReportDefModel(reportDefinition);
setResponsePage(new ReportDataPage(reportDefModel, new PageParameters("siteId="+siteId), getWebPage()));
}
};
if(reportDefinition != null) {
link.add(new AttributeModifier("title", true, new ResourceModel("overview_show_report")));
}else if(ms instanceof WidgetMiniStatLink){
WidgetMiniStatLink msl = (WidgetMiniStatLink) ms;
final Page page = msl.getPageLink();
link = new StatelessLink("report") {
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
setResponsePage(page);
}
};
if(msl.getPageLinkTooltip() != null) {
link.add(new AttributeModifier("title", true, new Model(msl.getPageLinkTooltip())));
}
link.add(new AttributeModifier("class", true, new Model("extlink")));
}else{
link.setEnabled(false);
link.setRenderBodyOnly(true);
}
item.add(link);
// Label
Label label = new Label("label", ms.getLabel());
label.setRenderBodyOnly(true);
link.add(label);
}
};
ministatFragment.add(miniStatsLoop);
return ministatFragment;
}
|
diff --git a/src/net/java/sip/communicator/impl/gui/main/contactlist/SourceContactRightButtonMenu.java b/src/net/java/sip/communicator/impl/gui/main/contactlist/SourceContactRightButtonMenu.java
index 59bac1b4e..0401efe87 100644
--- a/src/net/java/sip/communicator/impl/gui/main/contactlist/SourceContactRightButtonMenu.java
+++ b/src/net/java/sip/communicator/impl/gui/main/contactlist/SourceContactRightButtonMenu.java
@@ -1,136 +1,136 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main.contactlist;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.main.call.*;
import net.java.sip.communicator.impl.gui.main.contactlist.contactsource.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.service.contactsource.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.swing.*;
/**
* The right button menu for external contact sources.
* @see ExternalContactSource
*/
public class SourceContactRightButtonMenu
extends JPopupMenu
{
private final SourceContact sourceContact;
/**
* Creates an instance of <tt>SourceContactRightButtonMenu</tt> by
* specifying the <tt>SourceContact</tt>, for which this menu is created.
* @param sourceContact the <tt>SourceContact</tt>, for which this menu is
* created
*/
public SourceContactRightButtonMenu(SourceContact sourceContact)
{
this.sourceContact = sourceContact;
this.initItems();
}
/**
* Initializes menu items.
*/
private void initItems()
{
ContactDetail cDetail = sourceContact
.getPreferredContactDetail(OperationSetBasicTelephony.class);
if (cDetail != null)
add(initCallMenu());
}
/**
* Initializes the call menu.
* @return the call menu
*/
private Component initCallMenu()
{
SIPCommMenu callContactMenu = new SIPCommMenu(
GuiActivator.getResources().getI18NString("service.gui.CALL"));
callContactMenu.setIcon(new ImageIcon(ImageLoader
.getImage(ImageLoader.CALL_16x16_ICON)));
Iterator<ContactDetail> details
= sourceContact.getContactDetails(OperationSetBasicTelephony.class)
.iterator();
while (details.hasNext())
{
final ContactDetail detail = details.next();
// add all the contacts that support telephony to the call menu
JMenuItem callContactItem = new JMenuItem();
- callContactItem.setName(detail.getContactAddress());
+ callContactItem.setText(detail.getContactAddress());
callContactItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
ProtocolProviderService protocolProvider
= detail.getPreferredProtocolProvider(
OperationSetBasicTelephony.class);
if (protocolProvider != null)
CallManager.createCall( protocolProvider,
detail.getContactAddress());
else
CallManager.createCall(detail.getContactAddress());
}
});
callContactMenu.add(callContactItem);
}
return callContactMenu;
}
// private Component initIMMenu()
// {
// SIPCommMenu callContactMenu = new SIPCommMenu(
// GuiActivator.getResources().getI18NString(
// "service.gui.SEND_MESSAGE"));
// callContactMenu.setIcon(new ImageIcon(ImageLoader
// .getImage(ImageLoader.SEND_MESSAGE_16x16_ICON)));
//
// Iterator<ContactDetail> details
// = sourceContact.getContactDetails(
// OperationSetBasicInstantMessaging.class).iterator();
//
// while (details.hasNext())
// {
// final ContactDetail detail = details.next();
// // add all the contacts that support telephony to the call menu
// JMenuItem callContactItem = new JMenuItem();
// callContactItem.setName(detail.getContactAddress());
// callContactItem.addActionListener(new ActionListener()
// {
// public void actionPerformed(ActionEvent e)
// {
// ProtocolProviderService protocolProvider
// = detail.getPreferredProtocolProvider(
// OperationSetBasicInstantMessaging.class);
//
// if (protocolProvider != null)
// CallManager.createCall( protocolProvider,
// detail.getContactAddress());
// else
// GuiActivator.getUIService().getChatWindowManager()
// .startChat(contactItem);
// }
// });
// callContactMenu.add(callContactItem);
// }
// return callContactMenu;
// }
}
| true | true | private Component initCallMenu()
{
SIPCommMenu callContactMenu = new SIPCommMenu(
GuiActivator.getResources().getI18NString("service.gui.CALL"));
callContactMenu.setIcon(new ImageIcon(ImageLoader
.getImage(ImageLoader.CALL_16x16_ICON)));
Iterator<ContactDetail> details
= sourceContact.getContactDetails(OperationSetBasicTelephony.class)
.iterator();
while (details.hasNext())
{
final ContactDetail detail = details.next();
// add all the contacts that support telephony to the call menu
JMenuItem callContactItem = new JMenuItem();
callContactItem.setName(detail.getContactAddress());
callContactItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
ProtocolProviderService protocolProvider
= detail.getPreferredProtocolProvider(
OperationSetBasicTelephony.class);
if (protocolProvider != null)
CallManager.createCall( protocolProvider,
detail.getContactAddress());
else
CallManager.createCall(detail.getContactAddress());
}
});
callContactMenu.add(callContactItem);
}
return callContactMenu;
}
| private Component initCallMenu()
{
SIPCommMenu callContactMenu = new SIPCommMenu(
GuiActivator.getResources().getI18NString("service.gui.CALL"));
callContactMenu.setIcon(new ImageIcon(ImageLoader
.getImage(ImageLoader.CALL_16x16_ICON)));
Iterator<ContactDetail> details
= sourceContact.getContactDetails(OperationSetBasicTelephony.class)
.iterator();
while (details.hasNext())
{
final ContactDetail detail = details.next();
// add all the contacts that support telephony to the call menu
JMenuItem callContactItem = new JMenuItem();
callContactItem.setText(detail.getContactAddress());
callContactItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
ProtocolProviderService protocolProvider
= detail.getPreferredProtocolProvider(
OperationSetBasicTelephony.class);
if (protocolProvider != null)
CallManager.createCall( protocolProvider,
detail.getContactAddress());
else
CallManager.createCall(detail.getContactAddress());
}
});
callContactMenu.add(callContactItem);
}
return callContactMenu;
}
|
diff --git a/mes-plugins/mes-plugins-material-flow/src/main/java/com/qcadoo/mes/materialFlow/MaterialFlowService.java b/mes-plugins/mes-plugins-material-flow/src/main/java/com/qcadoo/mes/materialFlow/MaterialFlowService.java
index a336b9c19a..4996053175 100644
--- a/mes-plugins/mes-plugins-material-flow/src/main/java/com/qcadoo/mes/materialFlow/MaterialFlowService.java
+++ b/mes-plugins/mes-plugins-material-flow/src/main/java/com/qcadoo/mes/materialFlow/MaterialFlowService.java
@@ -1,440 +1,438 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 0.4.10
*
* This file is part of Qcadoo.
*
* Qcadoo is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.materialFlow;
import static com.qcadoo.mes.basic.constants.BasicConstants.MODEL_PRODUCT;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.collect.Sets;
import com.qcadoo.mes.basic.constants.BasicConstants;
import com.qcadoo.mes.materialFlow.constants.MaterialFlowConstants;
import com.qcadoo.model.api.DataDefinition;
import com.qcadoo.model.api.DataDefinitionService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.search.SearchCriteriaBuilder;
import com.qcadoo.model.api.search.SearchOrders;
import com.qcadoo.model.api.search.SearchProjections;
import com.qcadoo.model.api.search.SearchRestrictions;
import com.qcadoo.model.api.search.SearchResult;
import com.qcadoo.view.api.ComponentState;
import com.qcadoo.view.api.ViewDefinitionState;
import com.qcadoo.view.api.components.FieldComponent;
import com.qcadoo.view.api.utils.NumberGeneratorService;
@Service
public class MaterialFlowService {
@Autowired
private DataDefinitionService dataDefinitionService;
@Autowired
private NumberGeneratorService numberGeneratorService;
public BigDecimal calculateShouldBeInStockArea(final Long stockAreas, final String product, final String forDate) {
BigDecimal countProductIn = BigDecimal.ZERO;
BigDecimal countProductOut = BigDecimal.ZERO;
BigDecimal countProduct = BigDecimal.ZERO;
Date lastCorrectionDate = null;
DataDefinition transferDataCorrection = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_STOCK_CORRECTION);
DataDefinition transferTo = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_TRANSFER);
DataDefinition transferFrom = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_TRANSFER);
- DataDefinition dataDefStockAreas = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
- MaterialFlowConstants.MODEL_STOCK_AREAS);
Long stockAreasId = stockAreas;
Long productId = Long.valueOf(product);
Entity resultDataCorrection = transferDataCorrection.find().add(SearchRestrictions.eq("stockAreas.id", stockAreas))
.add(SearchRestrictions.eq("product.id", productId)).addOrder(SearchOrders.desc("stockCorrectionDate"))
.setMaxResults(1).uniqueResult();
if (resultDataCorrection != null) {
lastCorrectionDate = (Date) resultDataCorrection.getField("stockCorrectionDate");
countProduct = (BigDecimal) resultDataCorrection.getField("found");
}
SearchResult resultTo = null;
SearchResult resultFrom = null;
if (lastCorrectionDate == null) {
resultTo = transferTo.find(
"where stockAreasTo = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate + "'")
.list();
resultFrom = transferFrom
.find("where stockAreasFrom = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate
+ "'").list();
} else {
resultTo = transferTo.find(
"where stockAreasTo = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate
+ "' and time > '" + lastCorrectionDate + "'").list();
resultFrom = transferFrom.find(
"where stockAreasFrom = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate
+ "' and time > '" + lastCorrectionDate + "'").list();
}
for (Entity e : resultTo.getEntities()) {
BigDecimal quantity = (BigDecimal) e.getField("quantity");
countProductIn = countProductIn.add(quantity);
}
for (Entity e : resultFrom.getEntities()) {
BigDecimal quantity = (BigDecimal) e.getField("quantity");
countProductOut = countProductOut.add(quantity);
}
if (lastCorrectionDate == null) {
countProductIn = countProductIn.subtract(countProductOut);
} else {
countProductIn = countProductIn.add(countProduct);
countProductIn = countProductIn.subtract(countProductOut);
}
if (countProductIn.compareTo(BigDecimal.ZERO) == -1) {
countProductIn = BigDecimal.ZERO;
}
return countProductIn;
}
public void refreshShouldBeInStockCorrectionDetail(final ViewDefinitionState state, final ComponentState componentState,
final String[] args) {
refreshShouldBeInStockCorrectionDetail(state);
}
public void refreshShouldBeInStockCorrectionDetail(final ViewDefinitionState state) {
FieldComponent stockAreas = (FieldComponent) state.getComponentByReference("stockAreas");
FieldComponent product = (FieldComponent) state.getComponentByReference("product");
FieldComponent date = (FieldComponent) state.getComponentByReference("stockCorrectionDate");
FieldComponent should = (FieldComponent) state.getComponentByReference("shouldBe");
if (stockAreas != null && product != null && date != null) {
if (stockAreas.getFieldValue() != null && product.getFieldValue() != null
&& !date.getFieldValue().toString().equals("")) {
Long stockAreasNumber = (Long) stockAreas.getFieldValue();
String productNumber = product.getFieldValue().toString();
String forDate = date.getFieldValue().toString();
BigDecimal shouldBe = calculateShouldBeInStockArea(stockAreasNumber, productNumber, forDate);
if (shouldBe != null && shouldBe != BigDecimal.ZERO) {
should.setFieldValue(shouldBe);
} else {
should.setFieldValue(BigDecimal.ZERO);
}
}
}
should.requestComponentUpdateState();
}
public void fillNumberFieldValue(final ViewDefinitionState view) {
if (view.getComponentByReference("number").getFieldValue() != null) {
return;
}
numberGeneratorService.generateAndInsertNumber(view, MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_TRANSFORMATIONS, "form", "number");
}
public void generateNumberForTransfer(final ViewDefinitionState state, final ComponentState componentState,
final String[] args) {
generateNumberAfterSelectingProduct(state, componentState, MaterialFlowConstants.MODEL_TRANSFER);
}
public void generateNumberForStockCorrection(final ViewDefinitionState state, final ComponentState componentState,
final String[] args) {
generateNumberAfterSelectingProduct(state, componentState, MaterialFlowConstants.MODEL_STOCK_CORRECTION);
}
public void generateNumberAfterSelectingProduct(final ViewDefinitionState state, final ComponentState componentState,
String tableToGenerateNumber) {
if (!(componentState instanceof FieldComponent)) {
throw new IllegalStateException("component is not FieldComponentState");
}
FieldComponent number = (FieldComponent) state.getComponentByReference("number");
FieldComponent productState = (FieldComponent) componentState;
if (!numberGeneratorService.checkIfShouldInsertNumber(state, "form", "number")) {
return;
}
if (productState.getFieldValue() != null) {
Entity product = getAreaById((Long) productState.getFieldValue());
if (product != null) {
String numberValue = product.getField("number")
+ "-"
+ numberGeneratorService
.generateNumber(MaterialFlowConstants.PLUGIN_IDENTIFIER, tableToGenerateNumber, 3);
number.setFieldValue(numberValue);
}
}
number.requestComponentUpdateState();
}
private Entity getAreaById(final Long productId) {
DataDefinition instructionDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT);
@SuppressWarnings("deprecation")
SearchCriteriaBuilder searchCriteria = instructionDD.find().setMaxResults(1).isIdEq(productId);
SearchResult searchResult = searchCriteria.list();
if (searchResult.getTotalNumberOfEntities() == 1) {
return searchResult.getEntities().get(0);
}
return null;
}
public void fillUnitFieldValue(final ViewDefinitionState view, final ComponentState componentState, final String[] args) {
fillUnitFieldValue(view);
}
public void fillUnitFieldValue(final ViewDefinitionState view) {
Long productId = (Long) view.getComponentByReference("product").getFieldValue();
if (productId == null) {
return;
}
Entity product = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, MODEL_PRODUCT).get(productId);
FieldComponent unitField = null;
String unit = product.getField("unit").toString();
for (String referenceName : Sets.newHashSet("quantityUNIT", "shouldBeUNIT", "foundUNIT")) {
unitField = (FieldComponent) view.getComponentByReference(referenceName);
if (unitField == null) {
continue;
}
unitField.setFieldValue(unit);
unitField.requestComponentUpdateState();
}
}
public Map<Entity, BigDecimal> calculateMaterialQuantitiesInStockArea(Entity materialsInStockAreas) {
List<Entity> stockAreas = new ArrayList<Entity>(materialsInStockAreas.getHasManyField("stockAreas"));
Map<Entity, BigDecimal> reportData = new HashMap<Entity, BigDecimal>();
for (Entity component : stockAreas) {
Entity stockArea = (Entity) component.getField("stockAreas");
Long stockAreaNumber = (Long) stockArea.getField("number");
List<Entity> products = getProductsSeenInStockArea(stockAreaNumber.toString());
String forDate = ((Date) materialsInStockAreas.getField("materialFlowForDate")).toString();
for (Entity product : products) {
BigDecimal quantity = calculateShouldBeInStockArea(stockAreaNumber, product.getStringField("number"), forDate);
if (reportData.containsKey(product)) {
reportData.put(product, reportData.get(product).add(quantity));
} else {
reportData.put(product, quantity);
}
}
}
return reportData;
}
public List<Entity> getProductsSeenInStockArea(String stockAreaNumber) {
DataDefinition dataDefStockAreas = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_STOCK_AREAS);
Long id = dataDefStockAreas.find("where number = '" + stockAreaNumber + "'").uniqueResult().getId();
DataDefinition dataDefProduct = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER_BASIC,
MaterialFlowConstants.MODEL_PRODUCT);
List<Entity> productsFromTransfers = dataDefProduct.find().createAlias("transfer", "t")
.addOrder(SearchOrders.asc("t.product.id"))
.setProjection(SearchProjections.distinct(SearchProjections.field("t.product")))
.add(SearchRestrictions.eqField("t.product.id", "id")).add(SearchRestrictions.eq("t.stockAreasTo.id", id)).list()
.getEntities();
List<Entity> productsFromStockCorrections = dataDefProduct.find().createAlias("stockCorrection", "sc")
.addOrder(SearchOrders.asc("sc.product.id"))
.setProjection(SearchProjections.distinct(SearchProjections.field("sc.product")))
.add(SearchRestrictions.eqField("sc.product.id", "id")).add(SearchRestrictions.eq("sc.stockAreas.id", id)).list()
.getEntities();
for (Entity product : productsFromStockCorrections) {
if (!productsFromTransfers.contains(product)) {
productsFromTransfers.add(product);
}
}
return productsFromTransfers;
}
public void fillTransferConsumptionDataFromTransformation(final ViewDefinitionState state,
final ComponentState componentState, final String[] args) {
String number = state.getComponentByReference("number").getFieldValue().toString();
componentState.performEvent(state, "save", new String[0]);
DataDefinition transferDataDefinition = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_TRANSFER);
Long id = transferDataDefinition.find("where number = '" + number + "'").uniqueResult().getId();
Entity transferCopy = transferDataDefinition.get(id);
Entity transformation = transferCopy.getBelongsToField("transformationsConsumption");
transferCopy.setField("type", "Consumption");
transferCopy.setField("time", transformation.getField("time"));
transferCopy.setField("stockAreasFrom", transformation.getField("stockAreasFrom"));
transferCopy.setField("staff", transformation.getField("staff"));
transferDataDefinition.save(transferCopy);
}
public void fillTransferProductionDataFromTransformation(final ViewDefinitionState state,
final ComponentState componentState, final String[] args) {
String number = state.getComponentByReference("number").getFieldValue().toString();
componentState.performEvent(state, "save", new String[0]);
DataDefinition transferDataDefinition = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_TRANSFER);
Long id = transferDataDefinition.find("where number = '" + number + "'").uniqueResult().getId();
Entity transferCopy = transferDataDefinition.get(id);
Entity transformation = transferCopy.getBelongsToField("transformationsProduction");
transferCopy.setField("type", "Production");
transferCopy.setField("time", transformation.getField("time"));
transferCopy.setField("stockAreasTo", transformation.getField("stockAreasTo"));
transferCopy.setField("staff", transformation.getField("staff"));
transferDataDefinition.save(transferCopy);
}
public void disableStockAreaFieldForParticularTransferType(final ViewDefinitionState state,
final ComponentState componentState, final String[] args) {
disableStockAreaFieldForParticularTransferType(state);
}
public void disableStockAreaFieldForParticularTransferType(final ViewDefinitionState state) {
if (state.getComponentByReference("type").getFieldValue() == null) {
return;
}
String type = state.getComponentByReference("type").getFieldValue().toString();
FieldComponent toStockArea = (FieldComponent) state.getComponentByReference("stockAreasTo");
FieldComponent fromStockArea = (FieldComponent) state.getComponentByReference("stockAreasFrom");
if (type.compareTo("Consumption") == 0) {
toStockArea.setEnabled(false);
toStockArea.setFieldValue("");
fromStockArea.setEnabled(true);
toStockArea.setRequired(false);
} else if (type.compareTo("Production") == 0) {
fromStockArea.setEnabled(false);
fromStockArea.setFieldValue("");
toStockArea.setEnabled(true);
toStockArea.setRequired(true);
} else {
toStockArea.setEnabled(true);
fromStockArea.setEnabled(true);
}
toStockArea.requestComponentUpdateState();
fromStockArea.requestComponentUpdateState();
}
public void fillDefaultStockAreaToFieldInTransformations(final ViewDefinitionState state,
final ComponentState componentState, final String[] args) {
FieldComponent stockAreaTo = (FieldComponent) state.getComponentByReference("stockAreasTo");
if (stockAreaTo.getFieldValue() == null) {
FieldComponent stockAreaFrom = (FieldComponent) state.getComponentByReference("stockAreasFrom");
stockAreaTo.setFieldValue(stockAreaFrom.getFieldValue());
}
stockAreaTo.requestComponentUpdateState();
}
public boolean validateTransfer(final DataDefinition dataDefinition, final Entity entity) {
if (entity.getField("transformationsConsumption") == null && entity.getField("transformationsProduction") == null) {
Entity stockAreasFrom = (Entity) (entity.getField("stockAreasFrom") != null ? entity.getField("stockAreasFrom")
: null);
Entity stockAreasTo = (Entity) (entity.getField("stockAreasTo") != null ? entity.getField("stockAreasTo") : null);
Date date = (Date) (entity.getField("time") != null ? entity.getField("time") : null);
String type = (entity.getStringField("type") != null ? entity.getStringField("type") : null);
boolean validate = true;
if (stockAreasFrom == null && stockAreasTo == null) {
entity.addError(dataDefinition.getField("stockAreasFrom"),
"materialFlow.validate.global.error.fillAtLeastOneStockAreas");
entity.addError(dataDefinition.getField("stockAreasTo"),
"materialFlow.validate.global.error.fillAtLeastOneStockAreas");
validate = false;
}
if (type == null) {
entity.addError(dataDefinition.getField("type"), "materialFlow.validate.global.error.fillType");
validate = false;
}
if (date == null) {
entity.addError(dataDefinition.getField("time"), "materialFlow.validate.global.error.fillDate");
validate = false;
}
return validate;
}
return true;
}
public void checkIfTransferHasTransformation(final ViewDefinitionState state) {
String number = (String) state.getComponentByReference("number").getFieldValue();
if (number == null) {
return;
}
Entity transfer = dataDefinitionService
.get(MaterialFlowConstants.PLUGIN_IDENTIFIER, MaterialFlowConstants.MODEL_TRANSFER)
.find("where number = '" + number + "'").uniqueResult();
if (transfer == null) {
return;
}
if (transfer.getBelongsToField("transformationsConsumption") != null
|| transfer.getBelongsToField("transformationsProduction") != null) {
FieldComponent type = (FieldComponent) state.getComponentByReference("type");
FieldComponent date = (FieldComponent) state.getComponentByReference("time");
FieldComponent stockAreasTo = (FieldComponent) state.getComponentByReference("stockAreasTo");
FieldComponent stockAreasFrom = (FieldComponent) state.getComponentByReference("stockAreasFrom");
FieldComponent staff = (FieldComponent) state.getComponentByReference("staff");
type.setEnabled(false);
date.setEnabled(false);
stockAreasTo.setEnabled(false);
stockAreasFrom.setEnabled(false);
staff.setEnabled(false);
}
}
}
| true | true | public BigDecimal calculateShouldBeInStockArea(final Long stockAreas, final String product, final String forDate) {
BigDecimal countProductIn = BigDecimal.ZERO;
BigDecimal countProductOut = BigDecimal.ZERO;
BigDecimal countProduct = BigDecimal.ZERO;
Date lastCorrectionDate = null;
DataDefinition transferDataCorrection = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_STOCK_CORRECTION);
DataDefinition transferTo = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_TRANSFER);
DataDefinition transferFrom = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_TRANSFER);
DataDefinition dataDefStockAreas = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_STOCK_AREAS);
Long stockAreasId = stockAreas;
Long productId = Long.valueOf(product);
Entity resultDataCorrection = transferDataCorrection.find().add(SearchRestrictions.eq("stockAreas.id", stockAreas))
.add(SearchRestrictions.eq("product.id", productId)).addOrder(SearchOrders.desc("stockCorrectionDate"))
.setMaxResults(1).uniqueResult();
if (resultDataCorrection != null) {
lastCorrectionDate = (Date) resultDataCorrection.getField("stockCorrectionDate");
countProduct = (BigDecimal) resultDataCorrection.getField("found");
}
SearchResult resultTo = null;
SearchResult resultFrom = null;
if (lastCorrectionDate == null) {
resultTo = transferTo.find(
"where stockAreasTo = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate + "'")
.list();
resultFrom = transferFrom
.find("where stockAreasFrom = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate
+ "'").list();
} else {
resultTo = transferTo.find(
"where stockAreasTo = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate
+ "' and time > '" + lastCorrectionDate + "'").list();
resultFrom = transferFrom.find(
"where stockAreasFrom = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate
+ "' and time > '" + lastCorrectionDate + "'").list();
}
for (Entity e : resultTo.getEntities()) {
BigDecimal quantity = (BigDecimal) e.getField("quantity");
countProductIn = countProductIn.add(quantity);
}
for (Entity e : resultFrom.getEntities()) {
BigDecimal quantity = (BigDecimal) e.getField("quantity");
countProductOut = countProductOut.add(quantity);
}
if (lastCorrectionDate == null) {
countProductIn = countProductIn.subtract(countProductOut);
} else {
countProductIn = countProductIn.add(countProduct);
countProductIn = countProductIn.subtract(countProductOut);
}
if (countProductIn.compareTo(BigDecimal.ZERO) == -1) {
countProductIn = BigDecimal.ZERO;
}
return countProductIn;
}
| public BigDecimal calculateShouldBeInStockArea(final Long stockAreas, final String product, final String forDate) {
BigDecimal countProductIn = BigDecimal.ZERO;
BigDecimal countProductOut = BigDecimal.ZERO;
BigDecimal countProduct = BigDecimal.ZERO;
Date lastCorrectionDate = null;
DataDefinition transferDataCorrection = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_STOCK_CORRECTION);
DataDefinition transferTo = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_TRANSFER);
DataDefinition transferFrom = dataDefinitionService.get(MaterialFlowConstants.PLUGIN_IDENTIFIER,
MaterialFlowConstants.MODEL_TRANSFER);
Long stockAreasId = stockAreas;
Long productId = Long.valueOf(product);
Entity resultDataCorrection = transferDataCorrection.find().add(SearchRestrictions.eq("stockAreas.id", stockAreas))
.add(SearchRestrictions.eq("product.id", productId)).addOrder(SearchOrders.desc("stockCorrectionDate"))
.setMaxResults(1).uniqueResult();
if (resultDataCorrection != null) {
lastCorrectionDate = (Date) resultDataCorrection.getField("stockCorrectionDate");
countProduct = (BigDecimal) resultDataCorrection.getField("found");
}
SearchResult resultTo = null;
SearchResult resultFrom = null;
if (lastCorrectionDate == null) {
resultTo = transferTo.find(
"where stockAreasTo = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate + "'")
.list();
resultFrom = transferFrom
.find("where stockAreasFrom = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate
+ "'").list();
} else {
resultTo = transferTo.find(
"where stockAreasTo = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate
+ "' and time > '" + lastCorrectionDate + "'").list();
resultFrom = transferFrom.find(
"where stockAreasFrom = '" + stockAreasId + "' and product = '" + product + "' and time <= '" + forDate
+ "' and time > '" + lastCorrectionDate + "'").list();
}
for (Entity e : resultTo.getEntities()) {
BigDecimal quantity = (BigDecimal) e.getField("quantity");
countProductIn = countProductIn.add(quantity);
}
for (Entity e : resultFrom.getEntities()) {
BigDecimal quantity = (BigDecimal) e.getField("quantity");
countProductOut = countProductOut.add(quantity);
}
if (lastCorrectionDate == null) {
countProductIn = countProductIn.subtract(countProductOut);
} else {
countProductIn = countProductIn.add(countProduct);
countProductIn = countProductIn.subtract(countProductOut);
}
if (countProductIn.compareTo(BigDecimal.ZERO) == -1) {
countProductIn = BigDecimal.ZERO;
}
return countProductIn;
}
|
diff --git a/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java b/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
index ffbdf9e8c..a81d294ee 100644
--- a/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
+++ b/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
@@ -1,1777 +1,1784 @@
/*
* 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.harmony.regex.tests.java.util.regex;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import junit.framework.TestCase;
import org.apache.harmony.testframework.serialization.SerializationTest;
import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
public class PatternTest extends TestCase {
String[] testPatterns = {
"(a|b)*abb",
"(1*2*3*4*)*567",
"(a|b|c|d)*aab",
"(1|2|3|4|5|6|7|8|9|0)(1|2|3|4|5|6|7|8|9|0)*",
"(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)*",
"(a|b)*(a|b)*A(a|b)*lice.*",
"(a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)(a|b|c|d|e|f|g|h|"
+ "i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)*(1|2|3|4|5|6|7|8|9|0)*|while|for|struct|if|do",
// BEGIN android-changed
// We don't have canonical equivalence.
// "x(?c)y", "x(?cc)y"
// "x(?:c)y"
// END android-changed
};
String[] testPatternsAlt = {
/*
* According to JavaDoc 2 and 3 oct digit sequences like \\o70\\o347
* should be OK, but test is failed for them
*/
"[ab]\\b\\\\o5\\xF9\\u1E7B\\t\\n\\f\\r\\a\\e[yz]",
"^\\p{Lower}*\\p{Upper}*\\p{ASCII}?\\p{Alpha}?\\p{Digit}*\\p{Alnum}\\p{Punct}\\p{Graph}\\p{Print}\\p{Blank}\\p{Cntrl}\\p{XDigit}\\p{Space}",
"$\\p{javaLowerCase}\\p{javaUpperCase}\\p{javaWhitespace}\\p{javaMirrored}",
"\\p{InGreek}\\p{Lu}\\p{Sc}\\P{InGreek}[\\p{L}&&[^\\p{Lu}]]" };
String[] wrongTestPatterns = { "\\o9A", "\\p{Lawer}", "\\xG0" };
final static int[] flagsSet = { Pattern.CASE_INSENSITIVE,
Pattern.MULTILINE, Pattern.DOTALL, Pattern.UNICODE_CASE
/* , Pattern.CANON_EQ */ };
/*
* Based on RI implenetation documents. Need to check this set regarding
* actual implementation.
*/
final static int[] wrongFlagsSet = { 256, 512, 1024 };
final static int DEFAULT_FLAGS = 0;
public void testMatcher() {
// some very simple test
Pattern p = Pattern.compile("a");
assertNotNull(p.matcher("bcde"));
assertNotSame(p.matcher("a"), p.matcher("a"));
}
public void testSplitCharSequenceint() {
// splitting CharSequence which ends with pattern
// bug6193
assertEquals(",,".split(",", 3).length, 3);
assertEquals(",,".split(",", 4).length, 3);
// bug6193
// bug5391
assertEquals(Pattern.compile("o").split("boo:and:foo", 5).length, 5);
assertEquals(Pattern.compile("b").split("ab", -1).length, 2);
// bug5391
String s[];
Pattern pat = Pattern.compile("x");
s = pat.split("zxx:zzz:zxx", 10);
assertEquals(s.length, 5);
s = pat.split("zxx:zzz:zxx", 3);
assertEquals(s.length, 3);
s = pat.split("zxx:zzz:zxx", -1);
assertEquals(s.length, 5);
s = pat.split("zxx:zzz:zxx", 0);
assertEquals(s.length, 3);
// other splitting
// negative limit
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", -1);
assertEquals(s.length, 5);
s = pat.split("", -1);
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("", -1);
assertEquals(s.length, 1);
s = pat.split("abccbadfe", -1);
assertEquals(s.length, 11);
// zero limit
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", 0);
assertEquals(s.length, 3);
s = pat.split("", 0);
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("", 0);
assertEquals(s.length, 1);
s = pat.split("abccbadfe", 0);
assertEquals(s.length, 10);
// positive limit
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", 12);
assertEquals(s.length, 5);
s = pat.split("", 6);
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("", 11);
assertEquals(s.length, 1);
s = pat.split("abccbadfe", 15);
assertEquals(s.length, 11);
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", 5);
assertEquals(s.length, 5);
s = pat.split("", 1);
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("", 1);
assertEquals(s.length, 1);
s = pat.split("abccbadfe", 11);
assertEquals(s.length, 11);
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", 3);
assertEquals(s.length, 3);
pat = Pattern.compile("");
s = pat.split("abccbadfe", 5);
assertEquals(s.length, 5);
}
public void testSplitCharSequence() {
String s[];
Pattern pat = Pattern.compile("b");
s = pat.split("abccbadfebb");
assertEquals(s.length, 3);
s = pat.split("");
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("");
assertEquals(s.length, 1);
s = pat.split("abccbadfe");
assertEquals(s.length, 10);
// bug6544
String s1 = "";
String[] arr = s1.split(":");
assertEquals(arr.length, 1);
// bug6544
}
public void testPattern() {
/* Positive assertion test. */
for (String aPattern : testPatterns) {
Pattern p = Pattern.compile(aPattern);
try {
assertTrue(p.pattern().equals(aPattern));
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void testCompile() {
/* Positive assertion test. */
for (String aPattern : testPatterns) {
try {
Pattern p = Pattern.compile(aPattern);
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
/* Positive assertion test with alternative templates. */
for (String aPattern : testPatternsAlt) {
try {
Pattern p = Pattern.compile(aPattern);
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
/* Negative assertion test. */
for (String aPattern : wrongTestPatterns) {
try {
Pattern p = Pattern.compile(aPattern);
fail("PatternSyntaxException is expected");
} catch (PatternSyntaxException pse) {
/* OKAY */
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void testFlags() {
String baseString;
String testString;
Pattern pat;
Matcher mat;
baseString = "((?i)|b)a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "(?i)a|b";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)a|b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "c|(?i)a|b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)a|(?s)b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)a|(?-i)b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "(?i)a|(?-i)c|b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "(?i)a|(?-i)c|(?i)b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)a|(?-i)b";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "((?i))a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "|(?i)|a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)((?s)a.)";
testString = "A\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)((?-i)a)";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "(?i)(?s:a.)";
testString = "A\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)fgh(?s:aa)";
testString = "fghAA";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)((?-i))a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc(?i)d";
testString = "ABCD";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "abcD";
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "a(?i)a(?-i)a(?i)a(?-i)a";
testString = "aAaAa";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "aAAAa";
mat = pat.matcher(testString);
assertFalse(mat.matches());
}
// BEGIN android-removed
// The flags() method should only return those flags that were explicitly
// passed during the compilation. The JDK also accepts the ones implicitly
// contained in the pattern, but ICU doesn't do this.
//
// public void testFlagsMethod() {
// String baseString;
// Pattern pat;
//
// /*
// * These tests are for compatibility with RI only. Logically we have to
// * return only flags specified during the compilation. For example
// * pat.flags() == 0 when we compile Pattern pat =
// * Pattern.compile("(?i)abc(?-i)"); but the whole expression is compiled
// * in a case insensitive manner. So there is little sense to do calls to
// * flags() now.
// */
// baseString = "(?-i)";
// pat = Pattern.compile(baseString);
//
// baseString = "(?idmsux)abc(?-i)vg(?-dmu)";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), Pattern.DOTALL | Pattern.COMMENTS);
//
// baseString = "(?idmsux)abc|(?-i)vg|(?-dmu)";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), Pattern.DOTALL | Pattern.COMMENTS);
//
// baseString = "(?is)a((?x)b.)";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
//
// baseString = "(?i)a((?-i))";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), Pattern.CASE_INSENSITIVE);
//
// baseString = "((?i)a)";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), 0);
//
// pat = Pattern.compile("(?is)abc");
// assertEquals(pat.flags(), Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
// }
//END android-removed
/*
* Check default flags when they are not specified in pattern. Based on RI
* since could not find that info
*/
public void testFlagsCompileDefault() {
for (String pat : testPatternsAlt) {
try {
Pattern p = Pattern.compile(pat);
assertEquals(p.flags(), DEFAULT_FLAGS);
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
/*
* Check that flags specified during compile are set properly This is a
* simple implementation that does not use flags combinations. Need to
* improve.
*/
public void testFlagsCompileValid() {
for (String pat : testPatternsAlt) {
for (int flags : flagsSet) {
try {
Pattern p = Pattern.compile(pat, flags);
assertEquals(p.flags(), flags);
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
}
public void testCompileStringint() {
/*
* these tests are needed to verify that appropriate exceptions are
* thrown
*/
String pattern = "b)a";
try {
Pattern.compile(pattern);
fail("Expected a PatternSyntaxException when compiling pattern: "
+ pattern);
} catch (PatternSyntaxException e) {
// pass
}
pattern = "bcde)a";
try {
Pattern.compile(pattern);
fail("Expected a PatternSyntaxException when compiling pattern: "
+ pattern);
} catch (PatternSyntaxException e) {
// pass
}
pattern = "bbg())a";
try {
Pattern pat = Pattern.compile(pattern);
fail("Expected a PatternSyntaxException when compiling pattern: "
+ pattern);
} catch (PatternSyntaxException e) {
// pass
}
pattern = "cdb(?i))a";
try {
Pattern pat = Pattern.compile(pattern);
fail("Expected a PatternSyntaxException when compiling pattern: "
+ pattern);
} catch (PatternSyntaxException e) {
// pass
}
/*
* This pattern should compile - HARMONY-2127
*/
// pattern = "x(?c)y";
// Pattern.compile(pattern);
/*
* this pattern doesn't match any string, but should be compiled anyway
*/
pattern = "(b\\1)a";
Pattern.compile(pattern);
}
/*
* Class under test for Pattern compile(String)
*/
public void testQuantCompileNeg() {
String[] patterns = { "5{,2}", "{5asd", "{hgdhg", "{5,hjkh", "{,5hdsh",
"{5,3shdfkjh}" };
for (String element : patterns) {
try {
Pattern.compile(element);
fail("PatternSyntaxException was expected, but compilation succeeds");
} catch (PatternSyntaxException pse) {
continue;
}
}
// Regression for HARMONY-1365
// BEGIN android-changed
// Original regex contained some illegal stuff. Changed it slightly,
// while maintaining the wicked character of this "mother of all
// regexes".
// String pattern = "(?![^\\<C\\f\\0146\\0270\\}&&[|\\02-\\x3E\\}|X-\\|]]{7,}+)[|\\\\\\x98\\<\\?\\u4FCFr\\,\\0025\\}\\004|\\0025-\\052\061]|(?<![|\\01-\\u829E])|(?<!\\p{Alpha})|^|(?-s:[^\\x15\\\\\\x24F\\a\\,\\a\\u97D8[\\x38\\a[\\0224-\\0306[^\\0020-\\u6A57]]]]??)(?uxix:[^|\\{\\[\\0367\\t\\e\\x8C\\{\\[\\074c\\]V[|b\\fu\\r\\0175\\<\\07f\\066s[^D-\\x5D]]])(?xx:^{5,}+)(?uuu)(?=^\\D)|(?!\\G)(?>\\G*?)(?![^|\\]\\070\\ne\\{\\t\\[\\053\\?\\\\\\x51\\a\\075\\0023-\\[&&[|\\022-\\xEA\\00-\\u41C2&&[^|a-\\xCC&&[^\\037\\uECB3\\u3D9A\\x31\\|\\<b\\0206\\uF2EC\\01m\\,\\ak\\a\\03&&\\p{Punct}]]]])(?-dxs:[|\\06-\\07|\\e-\\x63&&[|Tp\\u18A3\\00\\|\\xE4\\05\\061\\015\\0116C|\\r\\{\\}\\006\\xEA\\0367\\xC4\\01\\0042\\0267\\xBB\\01T\\}\\0100\\?[|\\[-\\u459B|\\x23\\x91\\rF\\0376[|\\?-\\x94\\0113-\\\\\\s]]]]{6}?)(?<=[^\\t-\\x42H\\04\\f\\03\\0172\\?i\\u97B6\\e\\f\\uDAC2])(?=\\B*+)(?>[^\\016\\r\\{\\,\\uA29D\\034\\02[\\02-\\[|\\t\\056\\uF599\\x62\\e\\<\\032\\uF0AC\\0026\\0205Q\\|\\\\\\06\\0164[|\\057-\\u7A98&&[\\061-g|\\|\\0276\\n\\042\\011\\e\\xE8\\x64B\\04\\u6D0EDW^\\p{Lower}]]]]?)(?<=[^\\n\\\\\\t\\u8E13\\,\\0114\\u656E\\xA5\\]&&[\\03-\\026|\\uF39D\\01\\{i\\u3BC2\\u14FE]])(?<=[^|\\uAE62\\054H\\|\\}&&^\\p{Space}])(?sxx)(?<=[\\f\\006\\a\\r\\xB4]*+)|(?x-xd:^{5}+)()";
String pattern = "(?![^\\<C\\f\\0146\\0270\\}&&[|\\02-\\x3E\\}|X-\\|]]{7,}+)[|\\\\\\x98\\<\\?\\u4FCFr\\,\\0025\\}\\004|\\0025-\\052\061]|(?<![|\\01-\\u829E])|(?<!\\p{Alpha})|^|(?-s:[^\\x15\\\\\\x24F\\a\\,\\a\\u97D8[\\x38\\a[\\0224-\\0306[^\\0020-\\u6A57]]]]??)(?uxix:[^|\\{\\[\\0367\\t\\e\\x8C\\{\\[\\074c\\]V[|b\\fu\\r\\0175\\<\\07f\\066s[^D-\\x5D]]])(?xx:^{5,}+)(?uuu)(?=^\\D)|(?!\\G)(?>\\.*?)(?![^|\\]\\070\\ne\\{\\t\\[\\053\\?\\\\\\x51\\a\\075\\0023-\\[&&[|\\022-\\xEA\\00-\\u41C2&&[^|a-\\xCC&&[^\\037\\uECB3\\u3D9A\\x31\\|\\<b\\0206\\uF2EC\\01m\\,\\ak\\a\\03&&\\p{Punct}]]]])(?-dxs:[|\\06-\\07|\\e-\\x63&&[|Tp\\u18A3\\00\\|\\xE4\\05\\061\\015\\0116C|\\r\\{\\}\\006\\xEA\\0367\\xC4\\01\\0042\\0267\\xBB\\01T\\}\\0100\\?[|\\[-\\u459B|\\x23\\x91\\rF\\0376[|\\?-\\x94\\0113-\\\\\\s]]]]{6}?)(?<=[^\\t-\\x42H\\04\\f\\03\\0172\\?i\\u97B6\\e\\f\\uDAC2])(?=\\.*+)(?>[^\\016\\r\\{\\,\\uA29D\\034\\02[\\02-\\[|\\t\\056\\uF599\\x62\\e\\<\\032\\uF0AC\\0026\\0205Q\\|\\\\\\06\\0164[|\\057-\\u7A98&&[\\061-g|\\|\\0276\\n\\042\\011\\e\\xE8\\x64B\\04\\u6D0EDW^\\p{Lower}]]]]?)(?<=[^\\n\\\\\\t\\u8E13\\,\\0114\\u656E\\xA5\\]&&[\\03-\\026|\\uF39D\\01\\{i\\u3BC2\\u14FE]])(?<=[^|\\uAE62\\054H\\|\\}&&^\\p{Space}])(?sxx)(?<=[\\f\\006\\a\\r\\xB4]{1,5})|(?x-xd:^{5}+)()";
// END android-changed
assertNotNull(Pattern.compile(pattern));
}
public void testQuantCompilePos() {
String[] patterns = {/* "(abc){1,3}", */"abc{2,}", "abc{5}" };
for (String element : patterns) {
Pattern.compile(element);
}
}
public void testQuantComposition() {
String pattern = "(a{1,3})aab";
java.util.regex.Pattern pat = java.util.regex.Pattern.compile(pattern);
java.util.regex.Matcher mat = pat.matcher("aaab");
mat.matches();
mat.start(1);
mat.group(1);
}
public void testMatches() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
{ "213567", "12324567", "1234567", "213213567",
"21312312312567", "444444567" },
{ "abcdaab", "aab", "abaab", "cdaab", "acbdadcbaab" },
{ "213234567", "3458", "0987654", "7689546432", "0398576",
"98432", "5" },
{
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ "ababbaAabababblice", "ababbaAliceababab", "ababbAabliceaaa",
"abbbAbbbliceaaa", "Alice" },
{ "a123", "bnxnvgds156", "for", "while", "if", "struct" },
{ "xy" }, { "xy" }, { "xcy" }
};
for (int i = 0; i < testPatterns.length; i++) {
for (int j = 0; j < posSeq[i].length; j++) {
assertTrue("Incorrect match: " + testPatterns[i] + " vs "
+ posSeq[i][j], Pattern.matches(testPatterns[i],
posSeq[i][j]));
}
}
}
public void testMatchesException() {
/* Negative assertion test. */
for (String aPattern : wrongTestPatterns) {
try {
Pattern.matches(aPattern, "Foo");
fail("PatternSyntaxException is expected");
} catch (PatternSyntaxException pse) {
/* OKAY */
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void testTimeZoneIssue() {
Pattern p = Pattern.compile("GMT(\\+|\\-)(\\d+)(:(\\d+))?");
Matcher m = p.matcher("GMT-9:45");
assertTrue(m.matches());
assertEquals("-", m.group(1));
assertEquals("9", m.group(2));
assertEquals(":45", m.group(3));
assertEquals("45", m.group(4));
}
// BEGIN android-changed
// Removed one pattern that is buggy on the JDK. We don't want to duplicate that.
public void testCompileRanges() {
String[] correctTestPatterns = { "[^]*abb]*", /* "[^a-d[^m-p]]*abb", */
"[a-d\\d]*abb", "[abc]*abb", "[a-e&&[de]]*abb", "[^abc]*abb",
"[a-e&&[^de]]*abb", "[a-z&&[^m-p]]*abb", "[a-d[m-p]]*abb",
"[a-zA-Z]*abb", "[+*?]*abb", "[^+*?]*abb" };
String[] inputSecuence = { "kkkk", /* "admpabb", */ "abcabcd124654abb",
"abcabccbacababb", "dededededededeedabb", "gfdhfghgdfghabb",
"accabacbcbaabb", "acbvfgtyabb", "adbcacdbmopabcoabb",
"jhfkjhaSDFGHJkdfhHNJMjkhfabb", "+*??+*abb", "sdfghjkabb" };
Pattern pat;
for (int i = 0; i < correctTestPatterns.length; i++) {
assertTrue("pattern: " + correctTestPatterns[i] + " input: "
+ inputSecuence[i], Pattern.matches(correctTestPatterns[i],
inputSecuence[i]));
}
String[] wrongInputSecuence = { "]", /* "admpkk", */ "abcabcd124k654abb",
"abwcabccbacababb", "abababdeababdeabb", "abcabcacbacbabb",
"acdcbecbaabb", "acbotyabb", "adbcaecdbmopabcoabb",
"jhfkjhaSDFGHJk;dfhHNJMjkhfabb", "+*?a?+*abb", "sdf+ghjkabb" };
for (int i = 0; i < correctTestPatterns.length; i++) {
assertFalse("pattern: " + correctTestPatterns[i] + " input: "
+ wrongInputSecuence[i], Pattern.matches(
correctTestPatterns[i], wrongInputSecuence[i]));
}
}
public void testRangesSpecialCases() {
String neg_patterns[] = { "[a-&&[b-c]]", "[a-\\w]", "[b-a]", "[]" };
for (String element : neg_patterns) {
try {
Pattern.compile(element);
fail("PatternSyntaxException was expected: " + element);
} catch (PatternSyntaxException pse) {
}
}
String pos_patterns[] = { "[-]+", "----", "[a-]+", "a-a-a-a-aa--",
"[\\w-a]+", "123-2312--aaa-213", "[a-]]+", "-]]]]]]]]]]]]]]]" };
for (int i = 0; i < pos_patterns.length; i++) {
String pat = pos_patterns[i++];
String inp = pos_patterns[i];
assertTrue("pattern: " + pat + " input: " + inp, Pattern.matches(
pat, inp));
}
}
// END android-changed
public void testZeroSymbols() {
assertTrue(Pattern.matches("[\0]*abb", "\0\0\0\0\0\0abb"));
}
public void testEscapes() {
Pattern pat = Pattern.compile("\\Q{]()*?");
Matcher mat = pat.matcher("{]()*?");
assertTrue(mat.matches());
}
public void testBug181() {
Pattern.compile("[\\t-\\r]");
}
public void testOrphanQuantifiers() {
try {
Pattern.compile("+++++");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testOrphanQuantifiers2() {
try {
Pattern pat = Pattern.compile("\\d+*");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testBug197() {
Object[] vals = { ":", new Integer(2),
new String[] { "boo", "and:foo" }, ":", new Integer(5),
new String[] { "boo", "and", "foo" }, ":", new Integer(-2),
new String[] { "boo", "and", "foo" }, ":", new Integer(3),
new String[] { "boo", "and", "foo" }, ":", new Integer(1),
new String[] { "boo:and:foo" }, "o", new Integer(5),
new String[] { "b", "", ":and:f", "", "" }, "o",
new Integer(4), new String[] { "b", "", ":and:f", "o" }, "o",
new Integer(-2), new String[] { "b", "", ":and:f", "", "" },
"o", new Integer(0), new String[] { "b", "", ":and:f" } };
for (int i = 0; i < vals.length / 3;) {
String[] res = Pattern.compile(vals[i++].toString()).split(
"boo:and:foo", ((Integer) vals[i++]).intValue());
String[] expectedRes = (String[]) vals[i++];
assertEquals(expectedRes.length, res.length);
for (int j = 0; j < expectedRes.length; j++) {
assertEquals(expectedRes[j], res[j]);
}
}
}
public void testURIPatterns() {
String URI_REGEXP_STR = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String SCHEME_REGEXP_STR = "^[a-zA-Z]{1}[\\w+-.]+$";
String REL_URI_REGEXP_STR = "^(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String IPV6_REGEXP_STR = "^[0-9a-fA-F\\:\\.]+(\\%\\w+)?$";
String IPV6_REGEXP_STR2 = "^\\[[0-9a-fA-F\\:\\.]+(\\%\\w+)?\\]$";
String IPV4_REGEXP_STR = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
String HOSTNAME_REGEXP_STR = "\\w+[\\w\\-\\.]*";
Pattern URI_REGEXP = Pattern.compile(URI_REGEXP_STR);
Pattern REL_URI_REGEXP = Pattern.compile(REL_URI_REGEXP_STR);
Pattern SCHEME_REGEXP = Pattern.compile(SCHEME_REGEXP_STR);
Pattern IPV4_REGEXP = Pattern.compile(IPV4_REGEXP_STR);
Pattern IPV6_REGEXP = Pattern.compile(IPV6_REGEXP_STR);
Pattern IPV6_REGEXP2 = Pattern.compile(IPV6_REGEXP_STR2);
Pattern HOSTNAME_REGEXP = Pattern.compile(HOSTNAME_REGEXP_STR);
}
public void testFindBoundaryCases1() {
Pattern pat = Pattern.compile(".*\n");
Matcher mat = pat.matcher("a\n");
mat.find();
assertEquals("a\n", mat.group());
}
public void testFindBoundaryCases2() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("aAa");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases3() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("a\naA\n");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases4() {
Pattern pat = Pattern.compile("A.*");
Matcher mat = pat.matcher("A\n");
mat.find();
assertEquals("A", mat.group());
}
public void testFindBoundaryCases5() {
Pattern pat = Pattern.compile(".*A.*");
Matcher mat = pat.matcher("\nA\naaa\nA\naaAaa\naaaA\n");
// Matcher mat = pat.matcher("\nA\n");
String[] res = { "A", "A", "aaAaa", "aaaA" };
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testFindBoundaryCases6() {
String[] res = { "", "a", "", "" };
Pattern pat = Pattern.compile(".*");
Matcher mat = pat.matcher("\na\n");
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testBackReferences() {
Pattern pat = Pattern.compile("(\\((\\w*):(.*):(\\2)\\))");
Matcher mat = pat
.matcher("(start1: word :start1)(start2: word :start2)");
int k = 1;
for (; mat.find(); k++) {
assertEquals("start" + k, mat.group(2));
assertEquals(" word ", mat.group(3));
assertEquals("start" + k, mat.group(4));
}
assertEquals(3, k);
pat = Pattern.compile(".*(.)\\1");
mat = pat.matcher("saa");
assertTrue(mat.matches());
}
public void testNewLine() {
Pattern pat = Pattern.compile("(^$)*\n", Pattern.MULTILINE);
Matcher mat = pat.matcher("\r\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(2, counter);
}
public void testFindGreedy() {
Pattern pat = Pattern.compile(".*aaa", Pattern.DOTALL);
Matcher mat = pat.matcher("aaaa\naaa\naaaaaa");
mat.matches();
assertEquals(15, mat.end());
}
public void testSerialization() throws Exception {
Pattern pat = Pattern.compile("a*bc");
SerializableAssert comparator = new SerializableAssert() {
public void assertDeserialized(Serializable initial,
Serializable deserialized) {
assertEquals(((Pattern) initial).toString(),
((Pattern) deserialized).toString());
}
};
SerializationTest.verifyGolden(this, pat, comparator);
SerializationTest.verifySelf(pat, comparator);
}
public void testSOLQuant() {
Pattern pat = Pattern.compile("$*", Pattern.MULTILINE);
Matcher mat = pat.matcher("\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(3, counter);
}
public void testIllegalEscape() {
try {
Pattern.compile("\\y");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testEmptyFamily() {
Pattern.compile("\\p{Lower}");
String a = "*";
}
public void testNonCaptConstr() {
// Flags
Pattern pat = Pattern.compile("(?i)b*(?-i)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
// Non-capturing groups
pat = Pattern.compile("(?i:b*)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
pat = Pattern
// 1 2 3 4 5 6 7 8 9 10 11
.compile("(?:-|(-?\\d+\\d\\d\\d))?(?:-|-(\\d\\d))?(?:-|-(\\d\\d))?(T)?(?:(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?)?(?:(?:((?:\\+|\\-)\\d\\d):(\\d\\d))|(Z))?");
Matcher mat = pat.matcher("-1234-21-31T41:51:61.789+71:81");
assertTrue(mat.matches());
assertEquals("-1234", mat.group(1));
assertEquals("21", mat.group(2));
assertEquals("31", mat.group(3));
assertEquals("T", mat.group(4));
assertEquals("41", mat.group(5));
assertEquals("51", mat.group(6));
assertEquals("61", mat.group(7));
assertEquals(".789", mat.group(8));
assertEquals("+71", mat.group(9));
assertEquals("81", mat.group(10));
// positive lookahead
pat = Pattern.compile(".*\\.(?=log$).*$");
assertTrue(pat.matcher("a.b.c.log").matches());
assertFalse(pat.matcher("a.b.c.log.").matches());
// negative lookahead
pat = Pattern.compile(".*\\.(?!log$).*$");
assertFalse(pat.matcher("abc.log").matches());
assertTrue(pat.matcher("abc.logg").matches());
// positive lookbehind
pat = Pattern.compile(".*(?<=abc)\\.log$");
assertFalse(pat.matcher("cde.log").matches());
assertTrue(pat.matcher("abc.log").matches());
// negative lookbehind
pat = Pattern.compile(".*(?<!abc)\\.log$");
assertTrue(pat.matcher("cde.log").matches());
assertFalse(pat.matcher("abc.log").matches());
// atomic group
pat = Pattern.compile("(?>a*)abb");
assertFalse(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a*)bb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a|aa)aabb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>aa|a)aabb");
assertFalse(pat.matcher("aaabb").matches());
// BEGIN android-removed
// Questionable constructs that ICU doesn't support.
// // quantifiers over look ahead
// pat = Pattern.compile(".*(?<=abc)*\\.log$");
// assertTrue(pat.matcher("cde.log").matches());
// pat = Pattern.compile(".*(?<=abc)+\\.log$");
// assertFalse(pat.matcher("cde.log").matches());
// END android-removed
}
public void testCorrectReplacementBackreferencedJointSet() {
Pattern pat = Pattern.compile("ab(a)*\\1");
pat = Pattern.compile("abc(cd)fg");
pat = Pattern.compile("aba*cd");
pat = Pattern.compile("ab(a)*+cd");
pat = Pattern.compile("ab(a)*?cd");
pat = Pattern.compile("ab(a)+cd");
pat = Pattern.compile(".*(.)\\1");
pat = Pattern.compile("ab((a)|c|d)e");
pat = Pattern.compile("abc((a(b))cd)");
pat = Pattern.compile("ab(a)++cd");
pat = Pattern.compile("ab(a)?(c)d");
pat = Pattern.compile("ab(a)?+cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a){1,3}?(c)d");
}
public void testCompilePatternWithTerminatorMark() {
Pattern pat = Pattern.compile("a\u0000\u0000cd");
Matcher mat = pat.matcher("a\u0000\u0000cd");
assertTrue(mat.matches());
}
public void testAlternations() {
String baseString = "|a|bc";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|bc|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|b|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(|b|cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b||cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|cd|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|c|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(?:|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a||||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "(?i-is)|a";
pat = Pattern.compile(baseString);
mat = pat.matcher("a");
assertTrue(mat.matches());
}
public void testMatchWithGroups() {
String baseString = "jwkerhjwehrkwjehrkwjhrwkjehrjwkehrjkwhrkwehrkwhrkwrhwkhrwkjehr";
String pattern = ".*(..).*\\1.*";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
baseString = "saa";
pattern = ".*(.)\\1";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
assertTrue(Pattern.compile(pattern).matcher(baseString).find());
}
public void testSplitEmptyCharSequence() {
String s1 = "";
String[] arr = s1.split(":");
assertEquals(arr.length, 1);
}
public void testSplitEndsWithPattern() {
assertEquals(",,".split(",", 3).length, 3);
assertEquals(",,".split(",", 4).length, 3);
assertEquals(Pattern.compile("o").split("boo:and:foo", 5).length, 5);
assertEquals(Pattern.compile("b").split("ab", -1).length, 2);
}
public void testCaseInsensitiveFlag() {
assertTrue(Pattern.matches("(?i-:AbC)", "ABC"));
}
public void testEmptyGroups() {
Pattern pat = Pattern.compile("ab(?>)cda");
Matcher mat = pat.matcher("abcda");
assertTrue(mat.matches());
pat = Pattern.compile("ab()");
mat = pat.matcher("ab");
assertTrue(mat.matches());
pat = Pattern.compile("abc(?:)(..)");
mat = pat.matcher("abcgf");
assertTrue(mat.matches());
}
public void testCompileNonCaptGroup() {
boolean isCompiled = false;
try {
// BEGIN android-change
// We don't have canonical equivalence.
Pattern pat = Pattern.compile("(?:)");
pat = Pattern.compile("(?:)", Pattern.DOTALL);
pat = Pattern.compile("(?:)", Pattern.CASE_INSENSITIVE);
pat = Pattern.compile("(?:)", Pattern.COMMENTS | Pattern.UNIX_LINES);
// END android-change
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testEmbeddedFlags() {
String baseString = "(?i)((?s)a)";
String testString = "A";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a.";
testString = "a\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc(?x:(?i)(?s)(?d)a.)";
testString = "abcA\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc((?x)d)(?i)(?s)a";
testString = "abcdA";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAltWithFlags() {
boolean isCompiled = false;
try {
Pattern pat = Pattern.compile("|(?i-xi)|()");
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testRestoreFlagsAfterGroup() {
String baseString = "abc((?x)d) a";
String testString = "abcd a";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
}
/*
* Verify if the Pattern support the following character classes:
* \p{javaLowerCase} \p{javaUpperCase} \p{javaWhitespace} \p{javaMirrored}
*/
public void testCompileCharacterClass() {
// Regression for HARMONY-606, 696
Pattern pattern = Pattern.compile("\\p{javaLowerCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUpperCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaWhitespace}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaMirrored}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDefined}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaIdentifierIgnorable}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaISOControl}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierStart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetter}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetterOrDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaSpaceChar}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaTitleCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierStart}");
assertNotNull(pattern);
}
/**
* s original test was fixed to pass on RI
*/
// BEGIN android-removed
// We don't have canonical equivalence.
// public void testCanonEqFlag() {
//
// /*
// * for decompositions see
// * http://www.unicode.org/Public/4.0-Update/UnicodeData-4.0.0.txt
// * http://www.unicode.org/reports/tr15/#Decomposition
// */
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "ab(a*)\\1";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a(abcdf)d";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "aabcdfd";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// // \u01E0 -> \u0226\u0304 ->\u0041\u0307\u0304
// // \u00CC -> \u0049\u0300
//
// /*
// * baseString = "\u01E0\u00CCcdb(ac)"; testString =
// * "\u0226\u0304\u0049\u0300cdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\u01E0cdb(a\u00CCc)";
// testString = "\u0041\u0307\u0304cdba\u0049\u0300c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\u00CC";
// testString = "a\u0049\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u0226\u0304cdb(ac\u0049\u0300)"; testString =
// * "\u01E0cdbac\u00CC"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u0041\u0307\u0304\u00CC)"; testString =
// * "cdb\u0226\u0304\u0049\u0300"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0[a-c]\u0049\u0300cdb(ac)"; testString =
// * "\u01E0b\u00CCcdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0|\u00CCcdb(ac)"; testString =
// * "\u0041\u0307\u0304"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u00CC?cdb(ac)*(\u01E0)*[a-c]"; testString =
// * "cdb\u0041\u0307\u0304b"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "a\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u00E0a");
// assertTrue(mat.find());
//
// /*
// * baseString = "\u7B20\uF9F8abc"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher("\uF9F8\uF9F8abc");
// * assertTrue(mat.matches());
// *
// * //\u01F9 -> \u006E\u0300 //\u00C3 -> \u0041\u0303
// *
// * baseString = "cdb(?:\u00C3\u006E\u0300)"; testString =
// * "cdb\u0041\u0303\u01F9"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * //\u014C -> \u004F\u0304 //\u0163 -> \u0074\u0327
// *
// * baseString = "cdb(?:\u0163\u004F\u0304)"; testString =
// * "cdb\u0074\u0327\u014C"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// // \u00E1->a\u0301
// // canonical ordering takes place \u0301\u0327 -> \u0327\u0301
// baseString = "c\u0327\u0301";
// testString = "c\u0301\u0327";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * Hangul decompositions
// */
// // \uD4DB->\u1111\u1171\u11B6
// // \uD21E->\u1110\u116D\u11B5
// // \uD264->\u1110\u1170
// // not Hangul:\u0453->\u0433\u0301
// baseString = "a\uD4DB\u1111\u1171\u11B6\uD264";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "\u0453c\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a\u1110\u116D\u11B5b\uD21Ebc";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// /*
// * baseString = "\uD4DB\uD21E\u1110\u1170cdb(ac)"; testString =
// * "\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// baseString = "\uD4DB\uD264cdb(a\uD21Ec)";
// testString = "\u1111\u1171\u11B6\u1110\u1170cdba\u1110\u116D\u11B5c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD4DB";
// testString = "a\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD21E";
// testString = "a\u1110\u116D\u11B5";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u1111\u1171\u11B6cdb(ac\u1110\u116D\u11B5)";
// * testString = "\uD4DBcdbac\uD21E"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u1111\u1171\u11B6\uD21E)"; testString =
// * "cdb\uD4DB\u1110\u116D\u11B5"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\uD4DB[a-c]\u1110\u116D\u11B5cdb(ac)"; testString =
// * "\uD4DBb\uD21Ecdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertFalse(mat.matches());
//
// baseString = "\u00CC?cdb(ac)*(\uD4DB)*[a-c]";
// testString = "cdb\u1111\u1171\u11B6b";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u1111\u1171\u11B6a");
// assertTrue(mat.find());
//
// baseString = "\u1111";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\uD4DBr");
// assertFalse(mat.find());
// }
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testIndexesCanonicalEq() {
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\u1111\u1171\u11B6awr");
// assertTrue(mat.find());
// assertEquals(mat.start(), 4);
// assertEquals(mat.end(), 7);
//
// /*
// * baseString = "\uD4DB\u1111\u1171\u11B6"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher("bcda\u1111\u1171\u11B6\uD4DBawr");
// * assertTrue(mat.find()); assertEquals(mat.start(), 4);
// * assertEquals(mat.end(), 8);
// *
// * baseString = "\uD4DB\uD21E\u1110\u1170"; testString =
// * "abcabc\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.find());
// * assertEquals(mat.start(), 6); assertEquals(mat.end(), 13);
// */}
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testCanonEqFlagWithSupplementaryCharacters() {
//
// /*
// * \u1D1BF->\u1D1BB\u1D16F->\u1D1B9\u1D165\u1D16F in UTF32
// * \uD834\uDDBF->\uD834\uDDBB\uD834\uDD6F
// * ->\uD834\uDDB9\uD834\uDD65\uD834\uDD6F in UTF16
// */
// String patString = "abc\uD834\uDDBFef";
// String testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// Pattern pat = Pattern.compile(patString, Pattern.CANON_EQ);
// Matcher mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// *
// * patString = "abc\uD834\uDDBB\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * patString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// /*
// * testSupplementary characters with no decomposition
// */
// /*
// * patString = "a\uD9A0\uDE8Ebc\uD834\uDDBB\uD834\uDD6Fe\uDE8Ef";
// * testString = "a\uD9A0\uDE8Ebc\uD834\uDDBFe\uDE8Ef"; pat =
// * Pattern.compile(patString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */}
// END android-removed
public void testRangesWithSurrogatesSupplementary() {
String patString = "[abc\uD8D2]";
String testString = "\uD8D2";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D2\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D2gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3&&[c\uD8D3]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3\uDBEE\uDF0C&&[c\uD8D3\uDBEE\uDF0C]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDBEE\uDF0C";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uDBFC]\uDDC2cd";
testString = "\uDBFC\uDDC2cd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "a\uDDC2cd";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testSequencesWithSurrogatesSupplementary() {
String patString = "abcd\uD8D3";
String testString = "abcd\uD8D3\uDFFC";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
// BEGIN android-changed
// This one really doesn't make sense, as the above is a corrupt surrogate.
// Even if it's matched by the JDK, it's more of a bug than of a behavior one
// might want to duplicate.
// assertFalse(mat.find());
// END android-changed
testString = "abcd\uD8D3abc";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "ab\uDBEFcd";
testString = "ab\uDBEFcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = "\uDFFCabcd";
testString = "\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "abc\uDFFCabcdecd";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "\uD8D3\uDFFCabcd";
testString = "abc\uD8D3\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
}
public void testPredefinedClassesWithSurrogatesSupplementary() {
String patString = "[123\\D]";
String testString = "a";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[123[^\\p{javaDigit}]]";
testString = "a";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// surrogate characters
patString = "\\p{Cs}";
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
/*
* see http://www.unicode.org/reports/tr18/#Supplementary_Characters we
* have to treat text as code points not code units. \\p{Cs} matches any
* surrogate character but here testString is a one code point
* consisting of two code units (two surrogate characters) so we find
* nothing
*/
// assertFalse(mat.find());
// swap low and high surrogates
testString = "\uDE27\uD916";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[\uD916\uDE271\uD91623&&[^\\p{Cs}]]";
testString = "1";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uD916";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
// \uD9A0\uDE8E=\u7828E
// \u78281=\uD9A0\uDE81
patString = "[a-\uD9A0\uDE8E]";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testDotConstructionWithSurrogatesSupplementary() {
String patString = ".";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\n";
mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = ".*\uDE81";
testString = "\uD9A0\uDE81\uD9A0\uDE81\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "\uD9A0\uDE81\uD9A0\uDE81\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = ".*";
testString = "\uD9A0\uDE81\n\uD9A0\uDE81\uD9A0\n\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void test_quoteLjava_lang_String() {
for (String aPattern : testPatterns) {
Pattern p = Pattern.compile(aPattern);
try {
assertEquals("quote was wrong for plain text", "\\Qtest\\E", p
.quote("test"));
assertEquals("quote was wrong for text with quote sign",
"\\Q\\Qtest\\E", p.quote("\\Qtest"));
assertEquals("quote was wrong for quotted text",
"\\Q\\Qtest\\E\\\\E\\Q\\E", p.quote("\\Qtest\\E"));
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void test_matcherLjava_lang_StringLjava_lang_CharSequence() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
{ "213567", "12324567", "1234567", "213213567",
"21312312312567", "444444567" },
{ "abcdaab", "aab", "abaab", "cdaab", "acbdadcbaab" },
{ "213234567", "3458", "0987654", "7689546432", "0398576",
"98432", "5" },
{
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ "ababbaAabababblice", "ababbaAliceababab", "ababbAabliceaaa",
"abbbAbbbliceaaa", "Alice" },
{ "a123", "bnxnvgds156", "for", "while", "if", "struct" },
{ "xy" }, { "xy" }, { "xcy" }
};
for (int i = 0; i < testPatterns.length; i++) {
for (int j = 0; j < posSeq[i].length; j++) {
assertTrue("Incorrect match: " + testPatterns[i] + " vs "
+ posSeq[i][j], Pattern.compile(testPatterns[i])
.matcher(posSeq[i][j]).matches());
}
}
}
public void testQuantifiersWithSurrogatesSupplementary() {
String patString = "\uD9A0\uDE81*abc";
String testString = "\uD9A0\uDE81\uD9A0\uDE81abc";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "abc";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAlternationsWithSurrogatesSupplementary() {
String patString = "\uDE81|\uD9A0\uDE81|\uD9A0";
String testString = "\uD9A0";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81\uD9A0";
mat = pat.matcher(testString);
assertFalse(mat.matches());
}
public void testGroupsWithSurrogatesSupplementary() {
//this pattern matches nothing
String patString = "(\uD9A0)\uDE81";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = "(\uD9A0)";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertFalse(mat.find());
}
/*
* Regression test for HARMONY-688
*/
public void testUnicodeCategoryWithSurrogatesSupplementary() {
Pattern p = Pattern.compile("\\p{javaLowerCase}");
Matcher matcher = p.matcher("\uD801\uDC28");
assertTrue(matcher.find());
}
public void testSplitEmpty() {
Pattern pat = Pattern.compile("");
String[] s = pat.split("", -1);
assertEquals(1, s.length);
assertEquals("", s[0]);
}
public void testToString() {
for (int i = 0; i < testPatterns.length; i++) {
Pattern p = Pattern.compile(testPatterns[i]);
assertEquals(testPatterns[i], p.toString());
}
}
+ // http://code.google.com/p/android/issues/detail?id=19308
+ public void test_hitEnd() {
+ Pattern p = Pattern.compile("^2(2[4-9]|3\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
+ Matcher m = p.matcher("224..");
+ boolean isPartialMatch = !m.matches() && m.hitEnd();
+ assertFalse(isPartialMatch);
+ }
}
| true | true | public void testBug197() {
Object[] vals = { ":", new Integer(2),
new String[] { "boo", "and:foo" }, ":", new Integer(5),
new String[] { "boo", "and", "foo" }, ":", new Integer(-2),
new String[] { "boo", "and", "foo" }, ":", new Integer(3),
new String[] { "boo", "and", "foo" }, ":", new Integer(1),
new String[] { "boo:and:foo" }, "o", new Integer(5),
new String[] { "b", "", ":and:f", "", "" }, "o",
new Integer(4), new String[] { "b", "", ":and:f", "o" }, "o",
new Integer(-2), new String[] { "b", "", ":and:f", "", "" },
"o", new Integer(0), new String[] { "b", "", ":and:f" } };
for (int i = 0; i < vals.length / 3;) {
String[] res = Pattern.compile(vals[i++].toString()).split(
"boo:and:foo", ((Integer) vals[i++]).intValue());
String[] expectedRes = (String[]) vals[i++];
assertEquals(expectedRes.length, res.length);
for (int j = 0; j < expectedRes.length; j++) {
assertEquals(expectedRes[j], res[j]);
}
}
}
public void testURIPatterns() {
String URI_REGEXP_STR = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String SCHEME_REGEXP_STR = "^[a-zA-Z]{1}[\\w+-.]+$";
String REL_URI_REGEXP_STR = "^(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String IPV6_REGEXP_STR = "^[0-9a-fA-F\\:\\.]+(\\%\\w+)?$";
String IPV6_REGEXP_STR2 = "^\\[[0-9a-fA-F\\:\\.]+(\\%\\w+)?\\]$";
String IPV4_REGEXP_STR = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
String HOSTNAME_REGEXP_STR = "\\w+[\\w\\-\\.]*";
Pattern URI_REGEXP = Pattern.compile(URI_REGEXP_STR);
Pattern REL_URI_REGEXP = Pattern.compile(REL_URI_REGEXP_STR);
Pattern SCHEME_REGEXP = Pattern.compile(SCHEME_REGEXP_STR);
Pattern IPV4_REGEXP = Pattern.compile(IPV4_REGEXP_STR);
Pattern IPV6_REGEXP = Pattern.compile(IPV6_REGEXP_STR);
Pattern IPV6_REGEXP2 = Pattern.compile(IPV6_REGEXP_STR2);
Pattern HOSTNAME_REGEXP = Pattern.compile(HOSTNAME_REGEXP_STR);
}
public void testFindBoundaryCases1() {
Pattern pat = Pattern.compile(".*\n");
Matcher mat = pat.matcher("a\n");
mat.find();
assertEquals("a\n", mat.group());
}
public void testFindBoundaryCases2() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("aAa");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases3() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("a\naA\n");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases4() {
Pattern pat = Pattern.compile("A.*");
Matcher mat = pat.matcher("A\n");
mat.find();
assertEquals("A", mat.group());
}
public void testFindBoundaryCases5() {
Pattern pat = Pattern.compile(".*A.*");
Matcher mat = pat.matcher("\nA\naaa\nA\naaAaa\naaaA\n");
// Matcher mat = pat.matcher("\nA\n");
String[] res = { "A", "A", "aaAaa", "aaaA" };
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testFindBoundaryCases6() {
String[] res = { "", "a", "", "" };
Pattern pat = Pattern.compile(".*");
Matcher mat = pat.matcher("\na\n");
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testBackReferences() {
Pattern pat = Pattern.compile("(\\((\\w*):(.*):(\\2)\\))");
Matcher mat = pat
.matcher("(start1: word :start1)(start2: word :start2)");
int k = 1;
for (; mat.find(); k++) {
assertEquals("start" + k, mat.group(2));
assertEquals(" word ", mat.group(3));
assertEquals("start" + k, mat.group(4));
}
assertEquals(3, k);
pat = Pattern.compile(".*(.)\\1");
mat = pat.matcher("saa");
assertTrue(mat.matches());
}
public void testNewLine() {
Pattern pat = Pattern.compile("(^$)*\n", Pattern.MULTILINE);
Matcher mat = pat.matcher("\r\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(2, counter);
}
public void testFindGreedy() {
Pattern pat = Pattern.compile(".*aaa", Pattern.DOTALL);
Matcher mat = pat.matcher("aaaa\naaa\naaaaaa");
mat.matches();
assertEquals(15, mat.end());
}
public void testSerialization() throws Exception {
Pattern pat = Pattern.compile("a*bc");
SerializableAssert comparator = new SerializableAssert() {
public void assertDeserialized(Serializable initial,
Serializable deserialized) {
assertEquals(((Pattern) initial).toString(),
((Pattern) deserialized).toString());
}
};
SerializationTest.verifyGolden(this, pat, comparator);
SerializationTest.verifySelf(pat, comparator);
}
public void testSOLQuant() {
Pattern pat = Pattern.compile("$*", Pattern.MULTILINE);
Matcher mat = pat.matcher("\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(3, counter);
}
public void testIllegalEscape() {
try {
Pattern.compile("\\y");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testEmptyFamily() {
Pattern.compile("\\p{Lower}");
String a = "*";
}
public void testNonCaptConstr() {
// Flags
Pattern pat = Pattern.compile("(?i)b*(?-i)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
// Non-capturing groups
pat = Pattern.compile("(?i:b*)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
pat = Pattern
// 1 2 3 4 5 6 7 8 9 10 11
.compile("(?:-|(-?\\d+\\d\\d\\d))?(?:-|-(\\d\\d))?(?:-|-(\\d\\d))?(T)?(?:(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?)?(?:(?:((?:\\+|\\-)\\d\\d):(\\d\\d))|(Z))?");
Matcher mat = pat.matcher("-1234-21-31T41:51:61.789+71:81");
assertTrue(mat.matches());
assertEquals("-1234", mat.group(1));
assertEquals("21", mat.group(2));
assertEquals("31", mat.group(3));
assertEquals("T", mat.group(4));
assertEquals("41", mat.group(5));
assertEquals("51", mat.group(6));
assertEquals("61", mat.group(7));
assertEquals(".789", mat.group(8));
assertEquals("+71", mat.group(9));
assertEquals("81", mat.group(10));
// positive lookahead
pat = Pattern.compile(".*\\.(?=log$).*$");
assertTrue(pat.matcher("a.b.c.log").matches());
assertFalse(pat.matcher("a.b.c.log.").matches());
// negative lookahead
pat = Pattern.compile(".*\\.(?!log$).*$");
assertFalse(pat.matcher("abc.log").matches());
assertTrue(pat.matcher("abc.logg").matches());
// positive lookbehind
pat = Pattern.compile(".*(?<=abc)\\.log$");
assertFalse(pat.matcher("cde.log").matches());
assertTrue(pat.matcher("abc.log").matches());
// negative lookbehind
pat = Pattern.compile(".*(?<!abc)\\.log$");
assertTrue(pat.matcher("cde.log").matches());
assertFalse(pat.matcher("abc.log").matches());
// atomic group
pat = Pattern.compile("(?>a*)abb");
assertFalse(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a*)bb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a|aa)aabb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>aa|a)aabb");
assertFalse(pat.matcher("aaabb").matches());
// BEGIN android-removed
// Questionable constructs that ICU doesn't support.
// // quantifiers over look ahead
// pat = Pattern.compile(".*(?<=abc)*\\.log$");
// assertTrue(pat.matcher("cde.log").matches());
// pat = Pattern.compile(".*(?<=abc)+\\.log$");
// assertFalse(pat.matcher("cde.log").matches());
// END android-removed
}
public void testCorrectReplacementBackreferencedJointSet() {
Pattern pat = Pattern.compile("ab(a)*\\1");
pat = Pattern.compile("abc(cd)fg");
pat = Pattern.compile("aba*cd");
pat = Pattern.compile("ab(a)*+cd");
pat = Pattern.compile("ab(a)*?cd");
pat = Pattern.compile("ab(a)+cd");
pat = Pattern.compile(".*(.)\\1");
pat = Pattern.compile("ab((a)|c|d)e");
pat = Pattern.compile("abc((a(b))cd)");
pat = Pattern.compile("ab(a)++cd");
pat = Pattern.compile("ab(a)?(c)d");
pat = Pattern.compile("ab(a)?+cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a){1,3}?(c)d");
}
public void testCompilePatternWithTerminatorMark() {
Pattern pat = Pattern.compile("a\u0000\u0000cd");
Matcher mat = pat.matcher("a\u0000\u0000cd");
assertTrue(mat.matches());
}
public void testAlternations() {
String baseString = "|a|bc";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|bc|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|b|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(|b|cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b||cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|cd|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|c|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(?:|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a||||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "(?i-is)|a";
pat = Pattern.compile(baseString);
mat = pat.matcher("a");
assertTrue(mat.matches());
}
public void testMatchWithGroups() {
String baseString = "jwkerhjwehrkwjehrkwjhrwkjehrjwkehrjkwhrkwehrkwhrkwrhwkhrwkjehr";
String pattern = ".*(..).*\\1.*";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
baseString = "saa";
pattern = ".*(.)\\1";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
assertTrue(Pattern.compile(pattern).matcher(baseString).find());
}
public void testSplitEmptyCharSequence() {
String s1 = "";
String[] arr = s1.split(":");
assertEquals(arr.length, 1);
}
public void testSplitEndsWithPattern() {
assertEquals(",,".split(",", 3).length, 3);
assertEquals(",,".split(",", 4).length, 3);
assertEquals(Pattern.compile("o").split("boo:and:foo", 5).length, 5);
assertEquals(Pattern.compile("b").split("ab", -1).length, 2);
}
public void testCaseInsensitiveFlag() {
assertTrue(Pattern.matches("(?i-:AbC)", "ABC"));
}
public void testEmptyGroups() {
Pattern pat = Pattern.compile("ab(?>)cda");
Matcher mat = pat.matcher("abcda");
assertTrue(mat.matches());
pat = Pattern.compile("ab()");
mat = pat.matcher("ab");
assertTrue(mat.matches());
pat = Pattern.compile("abc(?:)(..)");
mat = pat.matcher("abcgf");
assertTrue(mat.matches());
}
public void testCompileNonCaptGroup() {
boolean isCompiled = false;
try {
// BEGIN android-change
// We don't have canonical equivalence.
Pattern pat = Pattern.compile("(?:)");
pat = Pattern.compile("(?:)", Pattern.DOTALL);
pat = Pattern.compile("(?:)", Pattern.CASE_INSENSITIVE);
pat = Pattern.compile("(?:)", Pattern.COMMENTS | Pattern.UNIX_LINES);
// END android-change
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testEmbeddedFlags() {
String baseString = "(?i)((?s)a)";
String testString = "A";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a.";
testString = "a\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc(?x:(?i)(?s)(?d)a.)";
testString = "abcA\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc((?x)d)(?i)(?s)a";
testString = "abcdA";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAltWithFlags() {
boolean isCompiled = false;
try {
Pattern pat = Pattern.compile("|(?i-xi)|()");
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testRestoreFlagsAfterGroup() {
String baseString = "abc((?x)d) a";
String testString = "abcd a";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
}
/*
* Verify if the Pattern support the following character classes:
* \p{javaLowerCase} \p{javaUpperCase} \p{javaWhitespace} \p{javaMirrored}
*/
public void testCompileCharacterClass() {
// Regression for HARMONY-606, 696
Pattern pattern = Pattern.compile("\\p{javaLowerCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUpperCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaWhitespace}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaMirrored}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDefined}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaIdentifierIgnorable}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaISOControl}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierStart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetter}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetterOrDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaSpaceChar}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaTitleCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierStart}");
assertNotNull(pattern);
}
/**
* s original test was fixed to pass on RI
*/
// BEGIN android-removed
// We don't have canonical equivalence.
// public void testCanonEqFlag() {
//
// /*
// * for decompositions see
// * http://www.unicode.org/Public/4.0-Update/UnicodeData-4.0.0.txt
// * http://www.unicode.org/reports/tr15/#Decomposition
// */
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "ab(a*)\\1";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a(abcdf)d";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "aabcdfd";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// // \u01E0 -> \u0226\u0304 ->\u0041\u0307\u0304
// // \u00CC -> \u0049\u0300
//
// /*
// * baseString = "\u01E0\u00CCcdb(ac)"; testString =
// * "\u0226\u0304\u0049\u0300cdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\u01E0cdb(a\u00CCc)";
// testString = "\u0041\u0307\u0304cdba\u0049\u0300c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\u00CC";
// testString = "a\u0049\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u0226\u0304cdb(ac\u0049\u0300)"; testString =
// * "\u01E0cdbac\u00CC"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u0041\u0307\u0304\u00CC)"; testString =
// * "cdb\u0226\u0304\u0049\u0300"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0[a-c]\u0049\u0300cdb(ac)"; testString =
// * "\u01E0b\u00CCcdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0|\u00CCcdb(ac)"; testString =
// * "\u0041\u0307\u0304"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u00CC?cdb(ac)*(\u01E0)*[a-c]"; testString =
// * "cdb\u0041\u0307\u0304b"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "a\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u00E0a");
// assertTrue(mat.find());
//
// /*
// * baseString = "\u7B20\uF9F8abc"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher("\uF9F8\uF9F8abc");
// * assertTrue(mat.matches());
// *
// * //\u01F9 -> \u006E\u0300 //\u00C3 -> \u0041\u0303
// *
// * baseString = "cdb(?:\u00C3\u006E\u0300)"; testString =
// * "cdb\u0041\u0303\u01F9"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * //\u014C -> \u004F\u0304 //\u0163 -> \u0074\u0327
// *
// * baseString = "cdb(?:\u0163\u004F\u0304)"; testString =
// * "cdb\u0074\u0327\u014C"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// // \u00E1->a\u0301
// // canonical ordering takes place \u0301\u0327 -> \u0327\u0301
// baseString = "c\u0327\u0301";
// testString = "c\u0301\u0327";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * Hangul decompositions
// */
// // \uD4DB->\u1111\u1171\u11B6
// // \uD21E->\u1110\u116D\u11B5
// // \uD264->\u1110\u1170
// // not Hangul:\u0453->\u0433\u0301
// baseString = "a\uD4DB\u1111\u1171\u11B6\uD264";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "\u0453c\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a\u1110\u116D\u11B5b\uD21Ebc";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// /*
// * baseString = "\uD4DB\uD21E\u1110\u1170cdb(ac)"; testString =
// * "\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// baseString = "\uD4DB\uD264cdb(a\uD21Ec)";
// testString = "\u1111\u1171\u11B6\u1110\u1170cdba\u1110\u116D\u11B5c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD4DB";
// testString = "a\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD21E";
// testString = "a\u1110\u116D\u11B5";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u1111\u1171\u11B6cdb(ac\u1110\u116D\u11B5)";
// * testString = "\uD4DBcdbac\uD21E"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u1111\u1171\u11B6\uD21E)"; testString =
// * "cdb\uD4DB\u1110\u116D\u11B5"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\uD4DB[a-c]\u1110\u116D\u11B5cdb(ac)"; testString =
// * "\uD4DBb\uD21Ecdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertFalse(mat.matches());
//
// baseString = "\u00CC?cdb(ac)*(\uD4DB)*[a-c]";
// testString = "cdb\u1111\u1171\u11B6b";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u1111\u1171\u11B6a");
// assertTrue(mat.find());
//
// baseString = "\u1111";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\uD4DBr");
// assertFalse(mat.find());
// }
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testIndexesCanonicalEq() {
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\u1111\u1171\u11B6awr");
// assertTrue(mat.find());
// assertEquals(mat.start(), 4);
// assertEquals(mat.end(), 7);
//
// /*
// * baseString = "\uD4DB\u1111\u1171\u11B6"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher("bcda\u1111\u1171\u11B6\uD4DBawr");
// * assertTrue(mat.find()); assertEquals(mat.start(), 4);
// * assertEquals(mat.end(), 8);
// *
// * baseString = "\uD4DB\uD21E\u1110\u1170"; testString =
// * "abcabc\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.find());
// * assertEquals(mat.start(), 6); assertEquals(mat.end(), 13);
// */}
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testCanonEqFlagWithSupplementaryCharacters() {
//
// /*
// * \u1D1BF->\u1D1BB\u1D16F->\u1D1B9\u1D165\u1D16F in UTF32
// * \uD834\uDDBF->\uD834\uDDBB\uD834\uDD6F
// * ->\uD834\uDDB9\uD834\uDD65\uD834\uDD6F in UTF16
// */
// String patString = "abc\uD834\uDDBFef";
// String testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// Pattern pat = Pattern.compile(patString, Pattern.CANON_EQ);
// Matcher mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// *
// * patString = "abc\uD834\uDDBB\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * patString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// /*
// * testSupplementary characters with no decomposition
// */
// /*
// * patString = "a\uD9A0\uDE8Ebc\uD834\uDDBB\uD834\uDD6Fe\uDE8Ef";
// * testString = "a\uD9A0\uDE8Ebc\uD834\uDDBFe\uDE8Ef"; pat =
// * Pattern.compile(patString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */}
// END android-removed
public void testRangesWithSurrogatesSupplementary() {
String patString = "[abc\uD8D2]";
String testString = "\uD8D2";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D2\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D2gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3&&[c\uD8D3]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3\uDBEE\uDF0C&&[c\uD8D3\uDBEE\uDF0C]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDBEE\uDF0C";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uDBFC]\uDDC2cd";
testString = "\uDBFC\uDDC2cd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "a\uDDC2cd";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testSequencesWithSurrogatesSupplementary() {
String patString = "abcd\uD8D3";
String testString = "abcd\uD8D3\uDFFC";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
// BEGIN android-changed
// This one really doesn't make sense, as the above is a corrupt surrogate.
// Even if it's matched by the JDK, it's more of a bug than of a behavior one
// might want to duplicate.
// assertFalse(mat.find());
// END android-changed
testString = "abcd\uD8D3abc";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "ab\uDBEFcd";
testString = "ab\uDBEFcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = "\uDFFCabcd";
testString = "\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "abc\uDFFCabcdecd";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "\uD8D3\uDFFCabcd";
testString = "abc\uD8D3\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
}
public void testPredefinedClassesWithSurrogatesSupplementary() {
String patString = "[123\\D]";
String testString = "a";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[123[^\\p{javaDigit}]]";
testString = "a";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// surrogate characters
patString = "\\p{Cs}";
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
/*
* see http://www.unicode.org/reports/tr18/#Supplementary_Characters we
* have to treat text as code points not code units. \\p{Cs} matches any
* surrogate character but here testString is a one code point
* consisting of two code units (two surrogate characters) so we find
* nothing
*/
// assertFalse(mat.find());
// swap low and high surrogates
testString = "\uDE27\uD916";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[\uD916\uDE271\uD91623&&[^\\p{Cs}]]";
testString = "1";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uD916";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
// \uD9A0\uDE8E=\u7828E
// \u78281=\uD9A0\uDE81
patString = "[a-\uD9A0\uDE8E]";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testDotConstructionWithSurrogatesSupplementary() {
String patString = ".";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\n";
mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = ".*\uDE81";
testString = "\uD9A0\uDE81\uD9A0\uDE81\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "\uD9A0\uDE81\uD9A0\uDE81\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = ".*";
testString = "\uD9A0\uDE81\n\uD9A0\uDE81\uD9A0\n\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void test_quoteLjava_lang_String() {
for (String aPattern : testPatterns) {
Pattern p = Pattern.compile(aPattern);
try {
assertEquals("quote was wrong for plain text", "\\Qtest\\E", p
.quote("test"));
assertEquals("quote was wrong for text with quote sign",
"\\Q\\Qtest\\E", p.quote("\\Qtest"));
assertEquals("quote was wrong for quotted text",
"\\Q\\Qtest\\E\\\\E\\Q\\E", p.quote("\\Qtest\\E"));
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void test_matcherLjava_lang_StringLjava_lang_CharSequence() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
{ "213567", "12324567", "1234567", "213213567",
"21312312312567", "444444567" },
{ "abcdaab", "aab", "abaab", "cdaab", "acbdadcbaab" },
{ "213234567", "3458", "0987654", "7689546432", "0398576",
"98432", "5" },
{
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ "ababbaAabababblice", "ababbaAliceababab", "ababbAabliceaaa",
"abbbAbbbliceaaa", "Alice" },
{ "a123", "bnxnvgds156", "for", "while", "if", "struct" },
{ "xy" }, { "xy" }, { "xcy" }
};
for (int i = 0; i < testPatterns.length; i++) {
for (int j = 0; j < posSeq[i].length; j++) {
assertTrue("Incorrect match: " + testPatterns[i] + " vs "
+ posSeq[i][j], Pattern.compile(testPatterns[i])
.matcher(posSeq[i][j]).matches());
}
}
}
public void testQuantifiersWithSurrogatesSupplementary() {
String patString = "\uD9A0\uDE81*abc";
String testString = "\uD9A0\uDE81\uD9A0\uDE81abc";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "abc";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAlternationsWithSurrogatesSupplementary() {
String patString = "\uDE81|\uD9A0\uDE81|\uD9A0";
String testString = "\uD9A0";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81\uD9A0";
mat = pat.matcher(testString);
assertFalse(mat.matches());
}
public void testGroupsWithSurrogatesSupplementary() {
//this pattern matches nothing
String patString = "(\uD9A0)\uDE81";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = "(\uD9A0)";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertFalse(mat.find());
}
/*
* Regression test for HARMONY-688
*/
public void testUnicodeCategoryWithSurrogatesSupplementary() {
Pattern p = Pattern.compile("\\p{javaLowerCase}");
Matcher matcher = p.matcher("\uD801\uDC28");
assertTrue(matcher.find());
}
public void testSplitEmpty() {
Pattern pat = Pattern.compile("");
String[] s = pat.split("", -1);
assertEquals(1, s.length);
assertEquals("", s[0]);
}
public void testToString() {
for (int i = 0; i < testPatterns.length; i++) {
Pattern p = Pattern.compile(testPatterns[i]);
assertEquals(testPatterns[i], p.toString());
}
}
}
| public void testBug197() {
Object[] vals = { ":", new Integer(2),
new String[] { "boo", "and:foo" }, ":", new Integer(5),
new String[] { "boo", "and", "foo" }, ":", new Integer(-2),
new String[] { "boo", "and", "foo" }, ":", new Integer(3),
new String[] { "boo", "and", "foo" }, ":", new Integer(1),
new String[] { "boo:and:foo" }, "o", new Integer(5),
new String[] { "b", "", ":and:f", "", "" }, "o",
new Integer(4), new String[] { "b", "", ":and:f", "o" }, "o",
new Integer(-2), new String[] { "b", "", ":and:f", "", "" },
"o", new Integer(0), new String[] { "b", "", ":and:f" } };
for (int i = 0; i < vals.length / 3;) {
String[] res = Pattern.compile(vals[i++].toString()).split(
"boo:and:foo", ((Integer) vals[i++]).intValue());
String[] expectedRes = (String[]) vals[i++];
assertEquals(expectedRes.length, res.length);
for (int j = 0; j < expectedRes.length; j++) {
assertEquals(expectedRes[j], res[j]);
}
}
}
public void testURIPatterns() {
String URI_REGEXP_STR = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String SCHEME_REGEXP_STR = "^[a-zA-Z]{1}[\\w+-.]+$";
String REL_URI_REGEXP_STR = "^(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String IPV6_REGEXP_STR = "^[0-9a-fA-F\\:\\.]+(\\%\\w+)?$";
String IPV6_REGEXP_STR2 = "^\\[[0-9a-fA-F\\:\\.]+(\\%\\w+)?\\]$";
String IPV4_REGEXP_STR = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
String HOSTNAME_REGEXP_STR = "\\w+[\\w\\-\\.]*";
Pattern URI_REGEXP = Pattern.compile(URI_REGEXP_STR);
Pattern REL_URI_REGEXP = Pattern.compile(REL_URI_REGEXP_STR);
Pattern SCHEME_REGEXP = Pattern.compile(SCHEME_REGEXP_STR);
Pattern IPV4_REGEXP = Pattern.compile(IPV4_REGEXP_STR);
Pattern IPV6_REGEXP = Pattern.compile(IPV6_REGEXP_STR);
Pattern IPV6_REGEXP2 = Pattern.compile(IPV6_REGEXP_STR2);
Pattern HOSTNAME_REGEXP = Pattern.compile(HOSTNAME_REGEXP_STR);
}
public void testFindBoundaryCases1() {
Pattern pat = Pattern.compile(".*\n");
Matcher mat = pat.matcher("a\n");
mat.find();
assertEquals("a\n", mat.group());
}
public void testFindBoundaryCases2() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("aAa");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases3() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("a\naA\n");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases4() {
Pattern pat = Pattern.compile("A.*");
Matcher mat = pat.matcher("A\n");
mat.find();
assertEquals("A", mat.group());
}
public void testFindBoundaryCases5() {
Pattern pat = Pattern.compile(".*A.*");
Matcher mat = pat.matcher("\nA\naaa\nA\naaAaa\naaaA\n");
// Matcher mat = pat.matcher("\nA\n");
String[] res = { "A", "A", "aaAaa", "aaaA" };
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testFindBoundaryCases6() {
String[] res = { "", "a", "", "" };
Pattern pat = Pattern.compile(".*");
Matcher mat = pat.matcher("\na\n");
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testBackReferences() {
Pattern pat = Pattern.compile("(\\((\\w*):(.*):(\\2)\\))");
Matcher mat = pat
.matcher("(start1: word :start1)(start2: word :start2)");
int k = 1;
for (; mat.find(); k++) {
assertEquals("start" + k, mat.group(2));
assertEquals(" word ", mat.group(3));
assertEquals("start" + k, mat.group(4));
}
assertEquals(3, k);
pat = Pattern.compile(".*(.)\\1");
mat = pat.matcher("saa");
assertTrue(mat.matches());
}
public void testNewLine() {
Pattern pat = Pattern.compile("(^$)*\n", Pattern.MULTILINE);
Matcher mat = pat.matcher("\r\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(2, counter);
}
public void testFindGreedy() {
Pattern pat = Pattern.compile(".*aaa", Pattern.DOTALL);
Matcher mat = pat.matcher("aaaa\naaa\naaaaaa");
mat.matches();
assertEquals(15, mat.end());
}
public void testSerialization() throws Exception {
Pattern pat = Pattern.compile("a*bc");
SerializableAssert comparator = new SerializableAssert() {
public void assertDeserialized(Serializable initial,
Serializable deserialized) {
assertEquals(((Pattern) initial).toString(),
((Pattern) deserialized).toString());
}
};
SerializationTest.verifyGolden(this, pat, comparator);
SerializationTest.verifySelf(pat, comparator);
}
public void testSOLQuant() {
Pattern pat = Pattern.compile("$*", Pattern.MULTILINE);
Matcher mat = pat.matcher("\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(3, counter);
}
public void testIllegalEscape() {
try {
Pattern.compile("\\y");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testEmptyFamily() {
Pattern.compile("\\p{Lower}");
String a = "*";
}
public void testNonCaptConstr() {
// Flags
Pattern pat = Pattern.compile("(?i)b*(?-i)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
// Non-capturing groups
pat = Pattern.compile("(?i:b*)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
pat = Pattern
// 1 2 3 4 5 6 7 8 9 10 11
.compile("(?:-|(-?\\d+\\d\\d\\d))?(?:-|-(\\d\\d))?(?:-|-(\\d\\d))?(T)?(?:(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?)?(?:(?:((?:\\+|\\-)\\d\\d):(\\d\\d))|(Z))?");
Matcher mat = pat.matcher("-1234-21-31T41:51:61.789+71:81");
assertTrue(mat.matches());
assertEquals("-1234", mat.group(1));
assertEquals("21", mat.group(2));
assertEquals("31", mat.group(3));
assertEquals("T", mat.group(4));
assertEquals("41", mat.group(5));
assertEquals("51", mat.group(6));
assertEquals("61", mat.group(7));
assertEquals(".789", mat.group(8));
assertEquals("+71", mat.group(9));
assertEquals("81", mat.group(10));
// positive lookahead
pat = Pattern.compile(".*\\.(?=log$).*$");
assertTrue(pat.matcher("a.b.c.log").matches());
assertFalse(pat.matcher("a.b.c.log.").matches());
// negative lookahead
pat = Pattern.compile(".*\\.(?!log$).*$");
assertFalse(pat.matcher("abc.log").matches());
assertTrue(pat.matcher("abc.logg").matches());
// positive lookbehind
pat = Pattern.compile(".*(?<=abc)\\.log$");
assertFalse(pat.matcher("cde.log").matches());
assertTrue(pat.matcher("abc.log").matches());
// negative lookbehind
pat = Pattern.compile(".*(?<!abc)\\.log$");
assertTrue(pat.matcher("cde.log").matches());
assertFalse(pat.matcher("abc.log").matches());
// atomic group
pat = Pattern.compile("(?>a*)abb");
assertFalse(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a*)bb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a|aa)aabb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>aa|a)aabb");
assertFalse(pat.matcher("aaabb").matches());
// BEGIN android-removed
// Questionable constructs that ICU doesn't support.
// // quantifiers over look ahead
// pat = Pattern.compile(".*(?<=abc)*\\.log$");
// assertTrue(pat.matcher("cde.log").matches());
// pat = Pattern.compile(".*(?<=abc)+\\.log$");
// assertFalse(pat.matcher("cde.log").matches());
// END android-removed
}
public void testCorrectReplacementBackreferencedJointSet() {
Pattern pat = Pattern.compile("ab(a)*\\1");
pat = Pattern.compile("abc(cd)fg");
pat = Pattern.compile("aba*cd");
pat = Pattern.compile("ab(a)*+cd");
pat = Pattern.compile("ab(a)*?cd");
pat = Pattern.compile("ab(a)+cd");
pat = Pattern.compile(".*(.)\\1");
pat = Pattern.compile("ab((a)|c|d)e");
pat = Pattern.compile("abc((a(b))cd)");
pat = Pattern.compile("ab(a)++cd");
pat = Pattern.compile("ab(a)?(c)d");
pat = Pattern.compile("ab(a)?+cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a){1,3}?(c)d");
}
public void testCompilePatternWithTerminatorMark() {
Pattern pat = Pattern.compile("a\u0000\u0000cd");
Matcher mat = pat.matcher("a\u0000\u0000cd");
assertTrue(mat.matches());
}
public void testAlternations() {
String baseString = "|a|bc";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|bc|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|b|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(|b|cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b||cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|cd|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|c|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(?:|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a||||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "(?i-is)|a";
pat = Pattern.compile(baseString);
mat = pat.matcher("a");
assertTrue(mat.matches());
}
public void testMatchWithGroups() {
String baseString = "jwkerhjwehrkwjehrkwjhrwkjehrjwkehrjkwhrkwehrkwhrkwrhwkhrwkjehr";
String pattern = ".*(..).*\\1.*";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
baseString = "saa";
pattern = ".*(.)\\1";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
assertTrue(Pattern.compile(pattern).matcher(baseString).find());
}
public void testSplitEmptyCharSequence() {
String s1 = "";
String[] arr = s1.split(":");
assertEquals(arr.length, 1);
}
public void testSplitEndsWithPattern() {
assertEquals(",,".split(",", 3).length, 3);
assertEquals(",,".split(",", 4).length, 3);
assertEquals(Pattern.compile("o").split("boo:and:foo", 5).length, 5);
assertEquals(Pattern.compile("b").split("ab", -1).length, 2);
}
public void testCaseInsensitiveFlag() {
assertTrue(Pattern.matches("(?i-:AbC)", "ABC"));
}
public void testEmptyGroups() {
Pattern pat = Pattern.compile("ab(?>)cda");
Matcher mat = pat.matcher("abcda");
assertTrue(mat.matches());
pat = Pattern.compile("ab()");
mat = pat.matcher("ab");
assertTrue(mat.matches());
pat = Pattern.compile("abc(?:)(..)");
mat = pat.matcher("abcgf");
assertTrue(mat.matches());
}
public void testCompileNonCaptGroup() {
boolean isCompiled = false;
try {
// BEGIN android-change
// We don't have canonical equivalence.
Pattern pat = Pattern.compile("(?:)");
pat = Pattern.compile("(?:)", Pattern.DOTALL);
pat = Pattern.compile("(?:)", Pattern.CASE_INSENSITIVE);
pat = Pattern.compile("(?:)", Pattern.COMMENTS | Pattern.UNIX_LINES);
// END android-change
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testEmbeddedFlags() {
String baseString = "(?i)((?s)a)";
String testString = "A";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a.";
testString = "a\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc(?x:(?i)(?s)(?d)a.)";
testString = "abcA\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc((?x)d)(?i)(?s)a";
testString = "abcdA";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAltWithFlags() {
boolean isCompiled = false;
try {
Pattern pat = Pattern.compile("|(?i-xi)|()");
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testRestoreFlagsAfterGroup() {
String baseString = "abc((?x)d) a";
String testString = "abcd a";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
}
/*
* Verify if the Pattern support the following character classes:
* \p{javaLowerCase} \p{javaUpperCase} \p{javaWhitespace} \p{javaMirrored}
*/
public void testCompileCharacterClass() {
// Regression for HARMONY-606, 696
Pattern pattern = Pattern.compile("\\p{javaLowerCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUpperCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaWhitespace}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaMirrored}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDefined}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaIdentifierIgnorable}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaISOControl}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierStart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetter}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetterOrDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaSpaceChar}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaTitleCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierStart}");
assertNotNull(pattern);
}
/**
* s original test was fixed to pass on RI
*/
// BEGIN android-removed
// We don't have canonical equivalence.
// public void testCanonEqFlag() {
//
// /*
// * for decompositions see
// * http://www.unicode.org/Public/4.0-Update/UnicodeData-4.0.0.txt
// * http://www.unicode.org/reports/tr15/#Decomposition
// */
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "ab(a*)\\1";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a(abcdf)d";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "aabcdfd";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// // \u01E0 -> \u0226\u0304 ->\u0041\u0307\u0304
// // \u00CC -> \u0049\u0300
//
// /*
// * baseString = "\u01E0\u00CCcdb(ac)"; testString =
// * "\u0226\u0304\u0049\u0300cdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\u01E0cdb(a\u00CCc)";
// testString = "\u0041\u0307\u0304cdba\u0049\u0300c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\u00CC";
// testString = "a\u0049\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u0226\u0304cdb(ac\u0049\u0300)"; testString =
// * "\u01E0cdbac\u00CC"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u0041\u0307\u0304\u00CC)"; testString =
// * "cdb\u0226\u0304\u0049\u0300"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0[a-c]\u0049\u0300cdb(ac)"; testString =
// * "\u01E0b\u00CCcdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0|\u00CCcdb(ac)"; testString =
// * "\u0041\u0307\u0304"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u00CC?cdb(ac)*(\u01E0)*[a-c]"; testString =
// * "cdb\u0041\u0307\u0304b"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "a\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u00E0a");
// assertTrue(mat.find());
//
// /*
// * baseString = "\u7B20\uF9F8abc"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher("\uF9F8\uF9F8abc");
// * assertTrue(mat.matches());
// *
// * //\u01F9 -> \u006E\u0300 //\u00C3 -> \u0041\u0303
// *
// * baseString = "cdb(?:\u00C3\u006E\u0300)"; testString =
// * "cdb\u0041\u0303\u01F9"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * //\u014C -> \u004F\u0304 //\u0163 -> \u0074\u0327
// *
// * baseString = "cdb(?:\u0163\u004F\u0304)"; testString =
// * "cdb\u0074\u0327\u014C"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// // \u00E1->a\u0301
// // canonical ordering takes place \u0301\u0327 -> \u0327\u0301
// baseString = "c\u0327\u0301";
// testString = "c\u0301\u0327";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * Hangul decompositions
// */
// // \uD4DB->\u1111\u1171\u11B6
// // \uD21E->\u1110\u116D\u11B5
// // \uD264->\u1110\u1170
// // not Hangul:\u0453->\u0433\u0301
// baseString = "a\uD4DB\u1111\u1171\u11B6\uD264";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "\u0453c\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a\u1110\u116D\u11B5b\uD21Ebc";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// /*
// * baseString = "\uD4DB\uD21E\u1110\u1170cdb(ac)"; testString =
// * "\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// baseString = "\uD4DB\uD264cdb(a\uD21Ec)";
// testString = "\u1111\u1171\u11B6\u1110\u1170cdba\u1110\u116D\u11B5c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD4DB";
// testString = "a\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD21E";
// testString = "a\u1110\u116D\u11B5";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u1111\u1171\u11B6cdb(ac\u1110\u116D\u11B5)";
// * testString = "\uD4DBcdbac\uD21E"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u1111\u1171\u11B6\uD21E)"; testString =
// * "cdb\uD4DB\u1110\u116D\u11B5"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\uD4DB[a-c]\u1110\u116D\u11B5cdb(ac)"; testString =
// * "\uD4DBb\uD21Ecdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertFalse(mat.matches());
//
// baseString = "\u00CC?cdb(ac)*(\uD4DB)*[a-c]";
// testString = "cdb\u1111\u1171\u11B6b";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u1111\u1171\u11B6a");
// assertTrue(mat.find());
//
// baseString = "\u1111";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\uD4DBr");
// assertFalse(mat.find());
// }
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testIndexesCanonicalEq() {
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\u1111\u1171\u11B6awr");
// assertTrue(mat.find());
// assertEquals(mat.start(), 4);
// assertEquals(mat.end(), 7);
//
// /*
// * baseString = "\uD4DB\u1111\u1171\u11B6"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher("bcda\u1111\u1171\u11B6\uD4DBawr");
// * assertTrue(mat.find()); assertEquals(mat.start(), 4);
// * assertEquals(mat.end(), 8);
// *
// * baseString = "\uD4DB\uD21E\u1110\u1170"; testString =
// * "abcabc\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.find());
// * assertEquals(mat.start(), 6); assertEquals(mat.end(), 13);
// */}
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testCanonEqFlagWithSupplementaryCharacters() {
//
// /*
// * \u1D1BF->\u1D1BB\u1D16F->\u1D1B9\u1D165\u1D16F in UTF32
// * \uD834\uDDBF->\uD834\uDDBB\uD834\uDD6F
// * ->\uD834\uDDB9\uD834\uDD65\uD834\uDD6F in UTF16
// */
// String patString = "abc\uD834\uDDBFef";
// String testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// Pattern pat = Pattern.compile(patString, Pattern.CANON_EQ);
// Matcher mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// *
// * patString = "abc\uD834\uDDBB\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * patString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// /*
// * testSupplementary characters with no decomposition
// */
// /*
// * patString = "a\uD9A0\uDE8Ebc\uD834\uDDBB\uD834\uDD6Fe\uDE8Ef";
// * testString = "a\uD9A0\uDE8Ebc\uD834\uDDBFe\uDE8Ef"; pat =
// * Pattern.compile(patString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */}
// END android-removed
public void testRangesWithSurrogatesSupplementary() {
String patString = "[abc\uD8D2]";
String testString = "\uD8D2";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D2\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D2gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3&&[c\uD8D3]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3\uDBEE\uDF0C&&[c\uD8D3\uDBEE\uDF0C]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDBEE\uDF0C";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uDBFC]\uDDC2cd";
testString = "\uDBFC\uDDC2cd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "a\uDDC2cd";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testSequencesWithSurrogatesSupplementary() {
String patString = "abcd\uD8D3";
String testString = "abcd\uD8D3\uDFFC";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
// BEGIN android-changed
// This one really doesn't make sense, as the above is a corrupt surrogate.
// Even if it's matched by the JDK, it's more of a bug than of a behavior one
// might want to duplicate.
// assertFalse(mat.find());
// END android-changed
testString = "abcd\uD8D3abc";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "ab\uDBEFcd";
testString = "ab\uDBEFcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = "\uDFFCabcd";
testString = "\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "abc\uDFFCabcdecd";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "\uD8D3\uDFFCabcd";
testString = "abc\uD8D3\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
}
public void testPredefinedClassesWithSurrogatesSupplementary() {
String patString = "[123\\D]";
String testString = "a";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[123[^\\p{javaDigit}]]";
testString = "a";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// surrogate characters
patString = "\\p{Cs}";
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
/*
* see http://www.unicode.org/reports/tr18/#Supplementary_Characters we
* have to treat text as code points not code units. \\p{Cs} matches any
* surrogate character but here testString is a one code point
* consisting of two code units (two surrogate characters) so we find
* nothing
*/
// assertFalse(mat.find());
// swap low and high surrogates
testString = "\uDE27\uD916";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[\uD916\uDE271\uD91623&&[^\\p{Cs}]]";
testString = "1";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uD916";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
// \uD9A0\uDE8E=\u7828E
// \u78281=\uD9A0\uDE81
patString = "[a-\uD9A0\uDE8E]";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testDotConstructionWithSurrogatesSupplementary() {
String patString = ".";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\n";
mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = ".*\uDE81";
testString = "\uD9A0\uDE81\uD9A0\uDE81\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "\uD9A0\uDE81\uD9A0\uDE81\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = ".*";
testString = "\uD9A0\uDE81\n\uD9A0\uDE81\uD9A0\n\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void test_quoteLjava_lang_String() {
for (String aPattern : testPatterns) {
Pattern p = Pattern.compile(aPattern);
try {
assertEquals("quote was wrong for plain text", "\\Qtest\\E", p
.quote("test"));
assertEquals("quote was wrong for text with quote sign",
"\\Q\\Qtest\\E", p.quote("\\Qtest"));
assertEquals("quote was wrong for quotted text",
"\\Q\\Qtest\\E\\\\E\\Q\\E", p.quote("\\Qtest\\E"));
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void test_matcherLjava_lang_StringLjava_lang_CharSequence() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
{ "213567", "12324567", "1234567", "213213567",
"21312312312567", "444444567" },
{ "abcdaab", "aab", "abaab", "cdaab", "acbdadcbaab" },
{ "213234567", "3458", "0987654", "7689546432", "0398576",
"98432", "5" },
{
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ "ababbaAabababblice", "ababbaAliceababab", "ababbAabliceaaa",
"abbbAbbbliceaaa", "Alice" },
{ "a123", "bnxnvgds156", "for", "while", "if", "struct" },
{ "xy" }, { "xy" }, { "xcy" }
};
for (int i = 0; i < testPatterns.length; i++) {
for (int j = 0; j < posSeq[i].length; j++) {
assertTrue("Incorrect match: " + testPatterns[i] + " vs "
+ posSeq[i][j], Pattern.compile(testPatterns[i])
.matcher(posSeq[i][j]).matches());
}
}
}
public void testQuantifiersWithSurrogatesSupplementary() {
String patString = "\uD9A0\uDE81*abc";
String testString = "\uD9A0\uDE81\uD9A0\uDE81abc";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "abc";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAlternationsWithSurrogatesSupplementary() {
String patString = "\uDE81|\uD9A0\uDE81|\uD9A0";
String testString = "\uD9A0";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81\uD9A0";
mat = pat.matcher(testString);
assertFalse(mat.matches());
}
public void testGroupsWithSurrogatesSupplementary() {
//this pattern matches nothing
String patString = "(\uD9A0)\uDE81";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = "(\uD9A0)";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertFalse(mat.find());
}
/*
* Regression test for HARMONY-688
*/
public void testUnicodeCategoryWithSurrogatesSupplementary() {
Pattern p = Pattern.compile("\\p{javaLowerCase}");
Matcher matcher = p.matcher("\uD801\uDC28");
assertTrue(matcher.find());
}
public void testSplitEmpty() {
Pattern pat = Pattern.compile("");
String[] s = pat.split("", -1);
assertEquals(1, s.length);
assertEquals("", s[0]);
}
public void testToString() {
for (int i = 0; i < testPatterns.length; i++) {
Pattern p = Pattern.compile(testPatterns[i]);
assertEquals(testPatterns[i], p.toString());
}
}
// http://code.google.com/p/android/issues/detail?id=19308
public void test_hitEnd() {
Pattern p = Pattern.compile("^2(2[4-9]|3\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
Matcher m = p.matcher("224..");
boolean isPartialMatch = !m.matches() && m.hitEnd();
assertFalse(isPartialMatch);
}
}
|
diff --git a/com.sap.core.odata.processor.fit/src/main/java/com/sap/core/odata/processor/fit/JPAReferenceServiceFactory.java b/com.sap.core.odata.processor.fit/src/main/java/com/sap/core/odata/processor/fit/JPAReferenceServiceFactory.java
index 7256126d3..0503de3c2 100644
--- a/com.sap.core.odata.processor.fit/src/main/java/com/sap/core/odata/processor/fit/JPAReferenceServiceFactory.java
+++ b/com.sap.core.odata.processor.fit/src/main/java/com/sap/core/odata/processor/fit/JPAReferenceServiceFactory.java
@@ -1,43 +1,43 @@
package com.sap.core.odata.processor.fit;
import java.util.HashMap;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.sql.DataSource;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import com.sap.core.odata.processor.api.jpa.ODataJPAContext;
import com.sap.core.odata.processor.api.jpa.ODataJPAServiceFactory;
import com.sap.core.odata.processor.api.jpa.exception.ODataJPARuntimeException;
public class JPAReferenceServiceFactory extends ODataJPAServiceFactory{
private static final String PUNIT_NAME = "salesorderprocessing";
@Override
- public ODataJPAContext initializeJPAContext() throws ODataJPARuntimeException {
+ public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException {
DataSource ds = null;
try {
InitialContext ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DefaultDB");
} catch (NamingException e) {
e.printStackTrace();
}
Map<String, DataSource> properties = new HashMap<String, DataSource>();
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, ds);
//properties.put("eclipselink.target-database", "com.sap.persistence.platform.database.HDBPlatform");
ODataJPAContext oDataJPAContext= this.getODataJPAContext();
EntityManagerFactory emf = Persistence.createEntityManagerFactory(PUNIT_NAME,properties);
oDataJPAContext.setEntityManagerFactory(emf);
oDataJPAContext.setPersistenceUnitName(PUNIT_NAME);
return oDataJPAContext;
}
}
| true | true | public ODataJPAContext initializeJPAContext() throws ODataJPARuntimeException {
DataSource ds = null;
try {
InitialContext ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DefaultDB");
} catch (NamingException e) {
e.printStackTrace();
}
Map<String, DataSource> properties = new HashMap<String, DataSource>();
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, ds);
//properties.put("eclipselink.target-database", "com.sap.persistence.platform.database.HDBPlatform");
ODataJPAContext oDataJPAContext= this.getODataJPAContext();
EntityManagerFactory emf = Persistence.createEntityManagerFactory(PUNIT_NAME,properties);
oDataJPAContext.setEntityManagerFactory(emf);
oDataJPAContext.setPersistenceUnitName(PUNIT_NAME);
return oDataJPAContext;
}
| public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException {
DataSource ds = null;
try {
InitialContext ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DefaultDB");
} catch (NamingException e) {
e.printStackTrace();
}
Map<String, DataSource> properties = new HashMap<String, DataSource>();
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, ds);
//properties.put("eclipselink.target-database", "com.sap.persistence.platform.database.HDBPlatform");
ODataJPAContext oDataJPAContext= this.getODataJPAContext();
EntityManagerFactory emf = Persistence.createEntityManagerFactory(PUNIT_NAME,properties);
oDataJPAContext.setEntityManagerFactory(emf);
oDataJPAContext.setPersistenceUnitName(PUNIT_NAME);
return oDataJPAContext;
}
|
diff --git a/src/robot/subsystems/ChassisSubsystem.java b/src/robot/subsystems/ChassisSubsystem.java
index 11e0aaa..9399ffb 100644
--- a/src/robot/subsystems/ChassisSubsystem.java
+++ b/src/robot/subsystems/ChassisSubsystem.java
@@ -1,196 +1,196 @@
package robot.subsystems;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.Subsystem;
import robot.Constants;
import robot.EncoderAverager;
import robot.OutputStorage;
import robot.Pneumatic;
import robot.commands.CommandBase;
import robot.commands.TeleopDriveCommand;
import robot.parsable.ParsablePIDController;
public class ChassisSubsystem extends Subsystem {
public static final double INCHES_PER_ENCODER_COUNT = 92.5 / 1242.5385;
public static final double PID_DRIVE_PERCENT_TOLERANCE = 10.0;
public static final double PID_GYRO_ABSOLUTE_TOLERANCE = 2.0;
public static final double PID_COUNT_ABSOLUTE_TOLERANCE = 10.0;
Victor vicLeft = new Victor(Constants.LEFT_MOTOR_CHANNEL);
Victor vicRight = new Victor(Constants.RIGHT_MOTOR_CHANNEL);
Encoder encLeft = new Encoder(Constants.ENC_LEFT_ONE, Constants.ENC_LEFT_TWO, true);
Encoder encRight = new Encoder(Constants.ENC_RIGHT_ONE, Constants.ENC_RIGHT_TWO, true);
EncoderAverager encAverager = new EncoderAverager(encLeft, true, encRight, false, true); //Left is negative, use counts
public Pneumatic shifterPneumatic; //Pneumatics are initialized in CommandBase.java
OutputStorage leftOutputStorage = new OutputStorage();
OutputStorage rightOutputStorage = new OutputStorage();
RobotDrive robotDrive = new RobotDrive(leftOutputStorage, rightOutputStorage);
ParsablePIDController pidLeft = new ParsablePIDController("pidleft", 0.001, 0.0005, 0.0, encLeft, vicLeft);
ParsablePIDController pidRight = new ParsablePIDController("pidright", 0.001, 0.0005, 0.0, encRight, vicRight);
public ParsablePIDController pidGyro = new ParsablePIDController("pidgyro", 0.08, 0.0, 0.0, CommandBase.positioningSubsystem.positionGyro, new OutputStorage());
public ParsablePIDController pidCount = new ParsablePIDController("pidcount", 0.02, 0.0, 0.0, encAverager, new OutputStorage());
public ChassisSubsystem() {
encLeft.setPIDSourceParameter(Encoder.PIDSourceParameter.kRate);
encRight.setPIDSourceParameter(Encoder.PIDSourceParameter.kRate);
encLeft.start();
encRight.start();
pidLeft.setInputRange(-Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get(), Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get());
pidRight.setInputRange(-Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get(), Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get());
- pidGyro.setInputRange(Double.MIN_VALUE, Double.MAX_VALUE);
- pidCount.setInputRange(Double.MIN_VALUE, Double.MAX_VALUE);
+ pidGyro.setInputRange(-Double.MAX_VALUE, Double.MAX_VALUE);
+ pidCount.setInputRange(-Double.MAX_VALUE, Double.MAX_VALUE);
pidLeft.setOutputRange(-1.0, 1.0);
pidRight.setOutputRange(-1.0, 1.0);
pidGyro.setOutputRange(-1.0, 1.0);
pidCount.setOutputRange(-0.95, 0.95);
pidLeft.setPercentTolerance(PID_DRIVE_PERCENT_TOLERANCE);
pidRight.setPercentTolerance(PID_DRIVE_PERCENT_TOLERANCE);
pidGyro.setAbsoluteTolerance(PID_GYRO_ABSOLUTE_TOLERANCE);
pidCount.setAbsoluteTolerance(PID_COUNT_ABSOLUTE_TOLERANCE);
}
public void initDefaultCommand() {
setDefaultCommand(new TeleopDriveCommand());
}
public void disable() {
disablePID();
}
public void enable() {
encLeft.reset();
encRight.reset();
enablePID();
}
public boolean isEnabledPID() {
return pidLeft.isEnable() && pidRight.isEnable();
}
public boolean isEnabledPIDGyro() {
return pidGyro.isEnable();
}
public void disablePID() {
if (pidLeft.isEnable() || pidRight.isEnable()) {
pidLeft.disable();
pidRight.disable();
}
}
public void enablePID() {
if (!pidLeft.isEnable() || !pidRight.isEnable()) {
pidLeft.enable();
pidRight.enable();
}
}
public void disablePIDGyro() {
if (pidGyro.isEnable()) {
pidGyro.disable();
}
}
public void enablePIDGyro() {
if (!pidGyro.isEnable()) {
pidGyro.enable();
}
}
public void disablePIDCount() {
if (pidCount.isEnable()) {
pidCount.disable();
}
}
public void enablePIDCount() {
if (!pidCount.isEnable()) {
pidCount.enable();
}
}
public void drive(double speed, double rotation) {
robotDrive.arcadeDrive(speed, -rotation);
if (isEnabledPID()) {
if (getHighGear()) {
//High gear
pidLeft.setSetpoint(leftOutputStorage.get() * Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get());
pidRight.setSetpoint(rightOutputStorage.get() * Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get());
} else {
//Low gear
pidLeft.setSetpoint(leftOutputStorage.get() * Constants.CHASSIS_MAX_LOW_ENCODER_RATE.get());
pidRight.setSetpoint(rightOutputStorage.get() * Constants.CHASSIS_MAX_LOW_ENCODER_RATE.get());
}
} else {
vicLeft.set(leftOutputStorage.get());
vicRight.set(rightOutputStorage.get());
}
}
public void pidGyroRelativeSetpoint(double relativeAngle) {
pidGyro.setSetpoint(CommandBase.positioningSubsystem.positionGyro.getAngle() + relativeAngle);
}
public void pidGyroAbsoluteSetpoint(double absAngle) {
pidGyro.setSetpoint(absAngle);
}
public void pidCountRelativeSetpoint(double relativeCounts) {
pidCount.setSetpoint(encAverager.get() + relativeCounts);
}
public boolean pidGyroOnTarget() {
return pidGyro.onTarget();
}
public boolean pidCountOnTarget() {
return pidCount.onTarget();
}
public void shift(boolean value) {
shifterPneumatic.set(value);
}
public boolean getHighGear() {
return shifterPneumatic.get();
}
public double getAverageRate() {
return encAverager.getRate();
}
public int getAverageDistance() {
//Right counts - left counts because left counts are negative
return encAverager.get(); //Average rate
}
public boolean isMoving() {
//If we are above the threshold then we are moving
return Math.abs(getAverageRate()) > Constants.CHASSIS_ENCODER_MOVEMENT_THRESHOLD.get();
}
public void resetEncoders() {
encLeft.reset();
encRight.reset();
}
public void print() {
System.out.println("[" + this.getName() + "]");
System.out.println("encLeftRate: " + encLeft.getRate() + " encRightRate: " + encRight.getRate());
System.out.println("encLeft: " + encLeft.get() + " encRight: " + encRight.get());
System.out.println("averageEncoderRate: " + getAverageRate());
System.out.println("averageEncoderDistance: " + getAverageDistance());
System.out.println("PIDEnabled: " + isEnabledPID());
System.out.println("LeftOutputStorage: " + leftOutputStorage.get() + " RightOutputStorage: " + rightOutputStorage.get());
System.out.println("PIDLeft output: " + pidLeft.get() + " PIDRight output: " + pidRight.get());
System.out.println("PIDLeft setpoint: " + pidLeft.getSetpoint() + " PIDRight setpoint: " + pidRight.getSetpoint());
System.out.println("PIDGyro setpoint: " + pidGyro.getSetpoint() + " output: " + pidGyro.get());
System.out.println("PIDCount setpoint: " + pidCount.getSetpoint() + " output: " + pidCount.get());
}
}
| true | true | public ChassisSubsystem() {
encLeft.setPIDSourceParameter(Encoder.PIDSourceParameter.kRate);
encRight.setPIDSourceParameter(Encoder.PIDSourceParameter.kRate);
encLeft.start();
encRight.start();
pidLeft.setInputRange(-Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get(), Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get());
pidRight.setInputRange(-Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get(), Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get());
pidGyro.setInputRange(Double.MIN_VALUE, Double.MAX_VALUE);
pidCount.setInputRange(Double.MIN_VALUE, Double.MAX_VALUE);
pidLeft.setOutputRange(-1.0, 1.0);
pidRight.setOutputRange(-1.0, 1.0);
pidGyro.setOutputRange(-1.0, 1.0);
pidCount.setOutputRange(-0.95, 0.95);
pidLeft.setPercentTolerance(PID_DRIVE_PERCENT_TOLERANCE);
pidRight.setPercentTolerance(PID_DRIVE_PERCENT_TOLERANCE);
pidGyro.setAbsoluteTolerance(PID_GYRO_ABSOLUTE_TOLERANCE);
pidCount.setAbsoluteTolerance(PID_COUNT_ABSOLUTE_TOLERANCE);
}
| public ChassisSubsystem() {
encLeft.setPIDSourceParameter(Encoder.PIDSourceParameter.kRate);
encRight.setPIDSourceParameter(Encoder.PIDSourceParameter.kRate);
encLeft.start();
encRight.start();
pidLeft.setInputRange(-Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get(), Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get());
pidRight.setInputRange(-Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get(), Constants.CHASSIS_MAX_HIGH_ENCODER_RATE.get());
pidGyro.setInputRange(-Double.MAX_VALUE, Double.MAX_VALUE);
pidCount.setInputRange(-Double.MAX_VALUE, Double.MAX_VALUE);
pidLeft.setOutputRange(-1.0, 1.0);
pidRight.setOutputRange(-1.0, 1.0);
pidGyro.setOutputRange(-1.0, 1.0);
pidCount.setOutputRange(-0.95, 0.95);
pidLeft.setPercentTolerance(PID_DRIVE_PERCENT_TOLERANCE);
pidRight.setPercentTolerance(PID_DRIVE_PERCENT_TOLERANCE);
pidGyro.setAbsoluteTolerance(PID_GYRO_ABSOLUTE_TOLERANCE);
pidCount.setAbsoluteTolerance(PID_COUNT_ABSOLUTE_TOLERANCE);
}
|
diff --git a/src/java/com/sun/gluegen/ant/StaticGLGenTask.java b/src/java/com/sun/gluegen/ant/StaticGLGenTask.java
index 255ab8a1a..87619422c 100644
--- a/src/java/com/sun/gluegen/ant/StaticGLGenTask.java
+++ b/src/java/com/sun/gluegen/ant/StaticGLGenTask.java
@@ -1,303 +1,304 @@
package com.sun.gluegen.ant;
/*
* StaticGLGenTask.java
* Copyright (C) 2003 Rob Grzywinski ([email protected])
*
* Copying, distribution and use of this software in source and binary
* forms, with or without modification, is permitted provided that the
* following conditions are met:
*
* Distributions of source code must reproduce the copyright notice,
* this list of conditions and the following disclaimer in the source
* code header files; and Distributions of binary code must reproduce
* the copyright notice, this list of conditions and the following
* disclaimer in the documentation, Read me file, license file and/or
* other materials provided with the software distribution.
*
* The names of Sun Microsystems, Inc. ("Sun") and/or the copyright
* holder may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS," WITHOUT A WARRANTY OF ANY
* KIND. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, NON-INTERFERENCE, ACCURACY OF
* INFORMATIONAL CONTENT OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. THE
* COPYRIGHT HOLDER, SUN AND SUN'S LICENSORS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL THE
* COPYRIGHT HOLDER, SUN OR SUN'S LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
* CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
* REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGES. YOU ACKNOWLEDGE THAT THIS SOFTWARE IS NOT
* DESIGNED, LICENSED OR INTENDED FOR USE IN THE DESIGN, CONSTRUCTION,
* OPERATION OR MAINTENANCE OF ANY NUCLEAR FACILITY. THE COPYRIGHT
* HOLDER, SUN AND SUN'S LICENSORS DISCLAIM ANY EXPRESS OR IMPLIED
* WARRANTY OF FITNESS FOR SUCH USES.
*/
import java.io.IOException;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.LogStreamHandler;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PatternSet;
import org.apache.tools.ant.util.JavaEnvUtils;
/**
* <p>An <a href="http://ant.apache.org">ANT</a> {@link org.apache.tools.ant.Task}
* for using {@link com.sun.gluegen.opengl.BuildStaticGLInfo}.</p>
*
* <p>Usage:</p>
* <pre>
<staticglgen package="[generated files package]"
headers="[file pattern of GL headers]"
outputdir="[directory to output the generated files]" />
* </pre>
*
* @author Rob Grzywinski <a href="mailto:[email protected]">[email protected]</a>
*/
// FIXME: blow out javadoc
public class StaticGLGenTask extends Task
{
/**
* <p>The {@link com.sun.gluegen.opengl.BuildStaticGLInfo} classname.</p>
*/
private static final String GL_GEN = "com.sun.gluegen.opengl.BuildStaticGLInfo";
// =========================================================================
/**
* <p>The {@link org.apache.tools.ant.types.CommandlineJava} that is used
* to execute {@link com.sun.gluegen.opengl.BuildStaticGLInfo}.</p>
*/
private CommandlineJava glgenCommandline;
// =========================================================================
/**
* <p>The package name for the generated files.</p>
*/
private String packageName;
/**
* <p>The output directory.</p>
*/
private String outputDirectory;
/**
* <p>The {@link org.apache.tools.ant.types.FileSet} of GL headers.</p>
*/
private FileSet headerSet = new FileSet();
// =========================================================================
/**
* <p>Create and add the VM and classname to {@link org.apache.tools.ant.types.CommandlineJava}.</p>
*/
public StaticGLGenTask()
{
// create the CommandlineJava that will be used to call BuildStaticGLInfo
glgenCommandline = new CommandlineJava();
// set the VM and classname in the commandline
glgenCommandline.setVm(JavaEnvUtils.getJreExecutable("java"));
glgenCommandline.setClassname(GL_GEN);
}
// =========================================================================
// ANT getters and setters
/**
* <p>Set the package name for the generated files. This is called by ANT.</p>
*
* @param packageName the name of the package for the generated files
*/
public void setPackage(String packageName)
{
log( ("Setting package name to: " + packageName), Project.MSG_VERBOSE);
this.packageName = packageName;
}
/**
* <p>Set the output directory. This is called by ANT.</p>
*
* @param directory the output directory
*/
public void setOutputDir(String directory)
{
log( ("Setting output directory to: " + directory),
Project.MSG_VERBOSE);
this.outputDirectory = directory;
}
/**
* <p>Add a header file to the list. This is called by ANT for a nested
* element.</p>
*
* @return {@link org.apache.tools.ant.types.PatternSet.NameEntry}
*/
public PatternSet.NameEntry createHeader()
{
return headerSet.createInclude();
}
/**
* <p>Add a header file to the list. This is called by ANT for a nested
* element.</p>
*
* @return {@link org.apache.tools.ant.types.PatternSet.NameEntry}
*/
public PatternSet.NameEntry createHeadersFile()
{
return headerSet.createIncludesFile();
}
/**
* <p>Set the set of header patterns. Patterns may be separated by a comma
* or a space. This is called by ANT.</p>
*
* @param headers the string containing the header patterns
*/
public void setHeaders(String headers)
{
headerSet.setIncludes(headers);
}
/**
* <p>Add an optional classpath that defines the location of {@link com.sun.gluegen.opengl.BuildStaticGLInfo}
* and <code>BuildStaticGLInfo</code>'s dependencies.</p>
*
* @returns {@link org.apache.tools.ant.types.Path}
*/
public Path createClasspath()
{
return glgenCommandline.createClasspath(project).createPath();
}
// =========================================================================
/**
* <p>Run the task. This involves validating the set attributes, creating
* the command line to be executed and finally executing the command.</p>
*
* @see org.apache.tools.ant.Task#execute()
*/
public void execute()
throws BuildException
{
// validate that all of the required attributes have been set
validateAttributes();
// TODO: add logic to determine if the generated file needs to be
// regenerated
// add the attributes to the CommandlineJava
addAttributes();
log(glgenCommandline.describeCommand(), Project.MSG_VERBOSE);
// execute the command and throw on error
final int error = execute(glgenCommandline.getCommandline());
if(error == 1)
throw new BuildException( ("BuildStaticGLInfo returned: " + error), location);
}
/**
* <p>Ensure that the user specified all required arguments.</p>
*
* @throws BuildException if there are required arguments that are not
* present or not valid
*/
private void validateAttributes()
throws BuildException
{
// validate that the package name is set
if(!isValid(packageName))
throw new BuildException("Invalid package name: " + packageName);
// validate that the output directory is set
// TODO: switch to file and ensure that it exists
if(!isValid(outputDirectory))
throw new BuildException("Invalid output directory name: " + outputDirectory);
// TODO: validate that there are headers set
}
/**
* <p>Is the specified string valid? A valid string is non-<code>null</code>
* and has a non-zero length.</p>
*
* @param string the string to be tested for validity
* @return <code>true</code> if the string is valid. <code>false</code>
* otherwise.
*/
private boolean isValid(String string)
{
// check for null
if(string == null)
return false;
// ensure that the string has a non-zero length
// NOTE: must trim() to remove leading and trailing whitespace
if(string.trim().length() < 1)
return false;
// the string is valid
return true;
}
/**
* <p>Add all of the attributes to the command line. They have already
* been validated.</p>
*/
private void addAttributes()
{
// add the package name
glgenCommandline.createArgument().setValue(packageName);
// add the output directory name
glgenCommandline.createArgument().setValue(outputDirectory);
// add the header -files- from the FileSet
headerSet.setDir(getProject().getBaseDir());
DirectoryScanner directoryScanner = headerSet.getDirectoryScanner(getProject());
String[] directoryFiles = directoryScanner.getIncludedFiles();
for(int i=0; i<directoryFiles.length; i++)
{
glgenCommandline.createArgument().setValue(directoryFiles[i]);
}
}
/**
* <p>Execute {@link com.sun.gluegen.opengl.BuildStaticGLInfo} in a
* forked JVM.</p>
*
* @throws BuildException
*/
private int execute(String[] command)
throws BuildException
{
// create the object that will perform the command execution
Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO,
Project.MSG_WARN),
null);
// set the project and command line
execute.setAntRun(project);
execute.setCommandline(command);
+ execute.setWorkingDirectory( project.getBaseDir() );
// execute the command
try
{
return execute.execute();
} catch(IOException ioe)
{
throw new BuildException(ioe, location);
}
}
}
| true | true | private int execute(String[] command)
throws BuildException
{
// create the object that will perform the command execution
Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO,
Project.MSG_WARN),
null);
// set the project and command line
execute.setAntRun(project);
execute.setCommandline(command);
// execute the command
try
{
return execute.execute();
} catch(IOException ioe)
{
throw new BuildException(ioe, location);
}
}
| private int execute(String[] command)
throws BuildException
{
// create the object that will perform the command execution
Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO,
Project.MSG_WARN),
null);
// set the project and command line
execute.setAntRun(project);
execute.setCommandline(command);
execute.setWorkingDirectory( project.getBaseDir() );
// execute the command
try
{
return execute.execute();
} catch(IOException ioe)
{
throw new BuildException(ioe, location);
}
}
|
diff --git a/Curiosity/src/edu/kit/curiosity/behaviors/race/RaceFollowWall.java b/Curiosity/src/edu/kit/curiosity/behaviors/race/RaceFollowWall.java
index c9bcc37..69bf809 100644
--- a/Curiosity/src/edu/kit/curiosity/behaviors/race/RaceFollowWall.java
+++ b/Curiosity/src/edu/kit/curiosity/behaviors/race/RaceFollowWall.java
@@ -1,71 +1,71 @@
package edu.kit.curiosity.behaviors.race;
import lejos.nxt.UltrasonicSensor;
import lejos.robotics.navigation.DifferentialPilot;
import lejos.robotics.subsumption.Behavior;
import edu.kit.curiosity.Settings;
/**
* The class {@code FollowWall} describes the behavior to follow a wall.
*
* @author Team Curiosity
*/
public class RaceFollowWall implements Behavior {
private boolean suppressed = false;
private UltrasonicSensor sonic;
private DifferentialPilot pilot;
private int distanceToWall;
/**
* Constructs a new FollowWall Behavior.
*
* @param distance
* - the distance in which the wall is followed.
*/
public RaceFollowWall(int distance) {
distanceToWall = distance;
pilot = Settings.PILOT;
sonic = Settings.SONIC;
}
/**
* The Behavior takes control if the robot is not in the swamp
*/
@Override
public boolean takeControl() {
return (!Settings.atStart);
}
/**
* The robot moves along the Wall and turns to the right, if the wall is too
* far away.
*/
@Override
public void action() {
suppressed = false;
- Settings.readState = false;
+ Settings.readState = true;
System.out.println("Follow");
while (!suppressed && !((Settings.TOUCH_L.isPressed() || Settings.TOUCH_R.isPressed()))) {
if (sonic.getDistance() > (distanceToWall + 20)) {
pilot.arc(-15, -90, true);
} else if (sonic.getDistance() <= distanceToWall) {
pilot.arc(100, 20, true);
} else if (sonic.getDistance() > distanceToWall) {
pilot.arc(-100, -20, true);
}
}
// pilot.stop();
}
/**
* Initiates the cleanup when this Behavior is suppressed
*/
@Override
public void suppress() {
suppressed = true;
}
}
| true | true | public void action() {
suppressed = false;
Settings.readState = false;
System.out.println("Follow");
while (!suppressed && !((Settings.TOUCH_L.isPressed() || Settings.TOUCH_R.isPressed()))) {
if (sonic.getDistance() > (distanceToWall + 20)) {
pilot.arc(-15, -90, true);
} else if (sonic.getDistance() <= distanceToWall) {
pilot.arc(100, 20, true);
} else if (sonic.getDistance() > distanceToWall) {
pilot.arc(-100, -20, true);
}
}
// pilot.stop();
}
| public void action() {
suppressed = false;
Settings.readState = true;
System.out.println("Follow");
while (!suppressed && !((Settings.TOUCH_L.isPressed() || Settings.TOUCH_R.isPressed()))) {
if (sonic.getDistance() > (distanceToWall + 20)) {
pilot.arc(-15, -90, true);
} else if (sonic.getDistance() <= distanceToWall) {
pilot.arc(100, 20, true);
} else if (sonic.getDistance() > distanceToWall) {
pilot.arc(-100, -20, true);
}
}
// pilot.stop();
}
|
diff --git a/src/main/java/net/minecraft/src/GuiIngame.java b/src/main/java/net/minecraft/src/GuiIngame.java
index a5f6c629..a5f6e323 100644
--- a/src/main/java/net/minecraft/src/GuiIngame.java
+++ b/src/main/java/net/minecraft/src/GuiIngame.java
@@ -1,519 +1,520 @@
package net.minecraft.src;
import java.awt.Color;
import java.util.List;
import java.util.Random;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
// Spout Start
import org.lwjgl.opengl.GL11;
import org.spoutcraft.client.SpoutClient;
import org.spoutcraft.client.chunkcache.ChunkNetCache;
import org.spoutcraft.client.config.Configuration;
import org.spoutcraft.client.gui.minimap.ZanMinimap;
import org.spoutcraft.api.Spoutcraft;
import org.spoutcraft.api.gui.ChatTextBox;
import org.spoutcraft.api.gui.InGameHUD;
import org.spoutcraft.api.gui.ServerPlayerList;
import org.spoutcraft.api.player.ChatMessage;
// Spout End
public class GuiIngame extends Gui {
private static final RenderItem itemRenderer = new RenderItem();
// Spout Start - private to public static final
public static final Random rand = new Random();
// Spout End
private final Minecraft mc;
/** ChatGUI instance that retains all previous chat data */
private final GuiNewChat persistantChatGUI;
private int updateCounter = 0;
/** The string specifying which record music is playing */
private String recordPlaying = "";
/** How many ticks the record playing message will be displayed */
private int recordPlayingUpFor = 0;
private boolean recordIsPlaying = false;
/** Previous frame vignette brightness (slowly changes by 1% each frame) */
public float prevVignetteBrightness = 1.0F;
private int field_92017_k;
private ItemStack field_92016_l;
public GuiIngame(Minecraft par1Minecraft) {
this.mc = par1Minecraft;
this.persistantChatGUI = new GuiNewChat(par1Minecraft);
}
// Spout Start
private final ZanMinimap map = new ZanMinimap();
private static boolean needsUpdate = true;
public static void dirtySurvival() {
needsUpdate = true;
}
// Spout End
/**
* Render the ingame overlay with quick icon bar, ...
*/
// Spout Start - Most of function rewritten
// TODO: Rewrite again, it's in a horrible state, I'm surprised it works...
public void renderGameOverlay(float f, boolean flag, int i, int j) {
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
FontRenderer font = this.mc.fontRenderer;
this.mc.entityRenderer.setupOverlayRendering();
GL11.glEnable(GL11.GL_BLEND);
if (Minecraft.isFancyGraphicsEnabled()) {
this.renderVignette(this.mc.thePlayer.getBrightness(f), screenWidth, screenHeight);
} else {
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3);
if (this.mc.gameSettings.thirdPersonView == 0 && helmet != null && helmet.itemID == Block.pumpkin.blockID) {
this.renderPumpkinBlur(screenWidth, screenHeight);
}
if (!this.mc.thePlayer.isPotionActive(Potion.confusion)) {
float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * f;
if (var10 > 0.0F) {
this.renderPortalOverlay(var10, screenWidth, screenHeight);
}
}
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/gui.png"));
InventoryPlayer var11 = this.mc.thePlayer.inventory;
this.zLevel = -90.0F;
this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22);
this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/icons.png"));
GL11.glEnable(3042 /* GL_BLEND */);
GL11.glBlendFunc(775, 769);
this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042 /* GL_BLEND */);
GuiIngame.rand.setSeed((long) (this.updateCounter * 312871));
int var15;
int var17;
this.renderBossHealth();
// Better safe than sorry
SpoutClient.enableSandbox();
// Toggle visibility if needed
if (needsUpdate && mainScreen.getHealthBar().isVisible() == mc.playerController.isInCreativeMode()) {
mainScreen.toggleSurvivalHUD(!mc.playerController.isInCreativeMode());
}
needsUpdate = false;
// Hunger Bar Begin
mainScreen.getHungerBar().render();
// Hunger Bar End
// Armor Bar Begin
mainScreen.getArmorBar().render();
// Armor Bar End
// Health Bar Begin
mainScreen.getHealthBar().render();
// Health Bar End
// Bubble Bar Begin
mainScreen.getBubbleBar().render();
// Bubble Bar End
// Exp Bar Begin
mainScreen.getExpBar().render();
// Exp Bar End
SpoutClient.disableSandbox();
map.onRenderTick();
GL11.glDisable(GL11.GL_BLEND);
this.mc.mcProfiler.startSection("actionBar");
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
for (var15 = 0; var15 < 9; ++var15) {
int x = screenWidth / 2 - 90 + var15 * 20 + 2;
var17 = screenHeight - 16 - 3;
this.renderInventorySlot(var15, x, var17, f);
}
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
this.mc.mcProfiler.endSection();
float var33;
if (this.mc.thePlayer.getSleepTimer() > 0) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
var15 = this.mc.thePlayer.getSleepTimer();
float var26 = (float)var15 / 100.0F;
if (var26 > 1.0F) {
var26 = 1.0F - (float)(var15 - 100) / 10.0F;
}
var17 = (int)(220.0F * var26) << 24 | 1052704;
this.drawRect(0, 0, screenWidth, screenHeight, var17);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
}
SpoutClient.enableSandbox();
mainScreen.render();
SpoutClient.disableSandbox();
if (this.mc.gameSettings.showDebugInfo) {
this.mc.mcProfiler.startSection("debug");
GL11.glPushMatrix();
if (Configuration.getFastDebug() != 2) {
font.drawStringWithShadow("Minecraft 1.4.7 (" + this.mc.debug + ")", 2, 2, 16777215);
font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215);
font.drawStringWithShadow(this.mc.getEntityDebug(), 2, 22, 16777215);
font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215);
font.drawStringWithShadow(this.mc.getWorldProviderName(), 2, 42, 16777215);
long var41 = Runtime.getRuntime().maxMemory();
long var34 = Runtime.getRuntime().totalMemory();
long var42 = Runtime.getRuntime().freeMemory();
long var43 = var34 - var42;
String var45 = "Used memory: " + var43 * 100L / var41 + "% (" + var43 / 1024L / 1024L + "MB) of " + var41 / 1024L / 1024L + "MB";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 2, 14737632);
var45 = "Allocated memory: " + var34 * 100L / var41 + "% (" + var34 / 1024L / 1024L + "MB)";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 12, 14737632);
if(SpoutClient.getInstance().isCoordsCheat()) {
this.drawString(font, String.format("x: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posX)}), 2, 64, 14737632);
this.drawString(font, String.format("y: %.3f (feet pos, %.3f eyes pos)", new Object[] {Double.valueOf(this.mc.thePlayer.boundingBox.minY), Double.valueOf(this.mc.thePlayer.posY)}), 2, 72, 14737632);
this.drawString(font, String.format("z: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posZ)}), 2, 80, 14737632);
this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632);
}
int var47 = MathHelper.floor_double(this.mc.thePlayer.posX);
int var22 = MathHelper.floor_double(this.mc.thePlayer.posY);
int var233 = MathHelper.floor_double(this.mc.thePlayer.posZ);
if (this.mc.theWorld != null && this.mc.theWorld.blockExists(var47, var22, var233)) {
Chunk var48 = this.mc.theWorld.getChunkFromBlockCoords(var47, var233);
this.drawString(font, "lc: " + (var48.getTopFilledSegment() + 15) + " b: " + var48.getBiomeGenForWorldCoords(var47 & 15, var233 & 15, this.mc.theWorld.getWorldChunkManager()).biomeName + " bl: " + var48.getSavedLightValue(EnumSkyBlock.Block, var47 & 15, var22, var233 & 15) + " sl: " + var48.getSavedLightValue(EnumSkyBlock.Sky, var47 & 15, var22, var233 & 15) + " rl: " + var48.getBlockLightValue(var47 & 15, var22, var233 & 15, 0), 2, 96, 14737632);
}
this.drawString(font, String.format("ws: %.3f, fs: %.3f, g: %b", new Object[] {Float.valueOf(this.mc.thePlayer.capabilities.getWalkSpeed()), Float.valueOf(this.mc.thePlayer.capabilities.getFlySpeed()), Boolean.valueOf(this.mc.thePlayer.onGround)}), 2, 104, 14737632);
// Spout Start
boolean cacheInUse = ChunkNetCache.cacheInUse.get();
int y = 115;
font.drawStringWithShadow("Network Info", 2, y += 11, 0xFFFFFF);
if (!cacheInUse) {
font.drawStringWithShadow("Chunk Network Cache: Inactive", 22, y += 11, 0xE0E0E0);
} else {
font.drawStringWithShadow("Chunk Network Cache: Active", 22, y += 11, 0xE0E0E0);
font.drawStringWithShadow("Cache hit: " + ChunkNetCache.hitPercentage.get() + "%", 22, y += 10, 0xE0E0E0);
}
font.drawStringWithShadow("Average Cube Size: " + ChunkNetCache.averageChunkSize.get() / 10.0 + " bytes", 22, y += 10, 0xE0E0E0);
long logTime = System.currentTimeMillis() - ChunkNetCache.loggingStart.get();
long kbpsUp = (80000L * ChunkNetCache.totalPacketUp.get()) / 1024 / logTime;
long kbpsDown = (80000L * ChunkNetCache.totalPacketDown.get()) / 1024 / logTime;
font.drawStringWithShadow("Upstream: " + (kbpsUp / 10.0) + "kbps (" + (ChunkNetCache.totalPacketUp.get() / 1024) + "kB)", 22, y += 11, 0xE0E0E0);
font.drawStringWithShadow("Downstream: " + (kbpsDown / 10.0) + "kbps (" + (ChunkNetCache.totalPacketDown.get() / 1024) + "kB)", 22, y += 11, 0xE0E0E0);
// Spout End
} else {
font.drawStringWithShadow(Integer.toString(Minecraft.framesPerSecond), 4, 2, 0xFFE303);
}
+ this.mc.mcProfiler.endSection();
GL11.glPopMatrix();
if (this.recordPlayingUpFor > 0) {
this.mc.mcProfiler.startSection("overlayMessage");
var33 = (float)this.recordPlayingUpFor - f;
int var12 = (int)(var33 * 256.0F / 20.0F);
if (var12 > 255) {
var12 = 255;
}
if (var12 > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
int var13 = 16777215;
if (this.recordIsPlaying) {
var13 = Color.HSBtoRGB(var33 / 50.0F, 0.7F, 0.6F) & 16777215;
}
font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var13 + (var12 << 24));
GL11.glDisable(GL11.GL_BLEND);
GL11.glPopMatrix();
}
this.mc.mcProfiler.endSection();
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, (float)(screenHeight - 48), 0.0F);
this.mc.mcProfiler.startSection("chat");
this.persistantChatGUI.drawChat(this.updateCounter);
this.mc.mcProfiler.endSection();
GL11.glPopMatrix();
if (this.mc.gameSettings.keyBindPlayerList.pressed && (!this.mc.isIntegratedServerRunning() || this.mc.thePlayer.sendQueue.playerInfoList.size() > 1)) {
this.mc.mcProfiler.startSection("playerList");
NetClientHandler var37 = this.mc.thePlayer.sendQueue;
List var39 = var37.playerInfoList;
int var13 = var37.currentServerMaxPlayers;
int var40 = var13;
int var38;
for (var38 = 1; var40 > 20; var40 = (var13 + var38 - 1) / var38) {
++var38;
}
int var16 = 300 / var38;
if (var16 > 150) {
var16 = 150;
}
var17 = (screenWidth - var38 * var16) / 2;
byte var44 = 10;
drawRect(var17 - 1, var44 - 1, var17 + var16 * var38, var44 + 9 * var40, Integer.MIN_VALUE);
for (int var19 = 0; var19 < var13; ++var19) {
int var20 = var17 + var19 % var38 * var16;
int var47 = var44 + var19 / var38 * 9;
drawRect(var20, var47, var20 + var16 - 1, var47 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL11.GL_ALPHA_TEST);
if (var19 < var39.size()) {
GuiPlayerInfo var46 = (GuiPlayerInfo)var39.get(var19);
font.drawStringWithShadow(var46.name, var20, var47, 16777215);
this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png"));
byte var50 = 0;
boolean var48 = false;
byte var49;
if (var46.responseTime < 0) {
var49 = 5;
} else if (var46.responseTime < 150) {
var49 = 0;
} else if (var46.responseTime < 300) {
var49 = 1;
} else if (var46.responseTime < 600) {
var49 = 2;
} else if (var46.responseTime < 1000) {
var49 = 3;
} else {
var49 = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(var20 + var16 - 12, var47, 0 + var50 * 10, 176 + var49 * 8, 10, 8);
this.zLevel -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_ALPHA_TEST);
}
/**
* Renders dragon's (boss) health on the HUD
*/
private void renderBossHealth() {
if (BossStatus.bossName != null && BossStatus.statusBarLength > 0) {
--BossStatus.statusBarLength;
FontRenderer var1 = this.mc.fontRenderer;
ScaledResolution var2 = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int var3 = var2.getScaledWidth();
short var4 = 182;
int var5 = var3 / 2 - var4 / 2;
int var6 = (int)(BossStatus.healthScale * (float)(var4 + 1));
byte var7 = 12;
this.drawTexturedModalRect(var5, var7, 0, 74, var4, 5);
this.drawTexturedModalRect(var5, var7, 0, 74, var4, 5);
if (var6 > 0) {
this.drawTexturedModalRect(var5, var7, 0, 79, var6, 5);
}
String var8 = BossStatus.bossName;
var1.drawStringWithShadow(var8, var3 / 2 - var1.getStringWidth(var8) / 2, var7 - 10, 16777215);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.mc.renderEngine.getTexture("/gui/icons.png"));
}
}
private void renderPumpkinBlur(int par1, int par2) {
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(false);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.mc.renderEngine.getTexture("%blur%/misc/pumpkinblur.png"));
Tessellator var3 = Tessellator.instance;
var3.startDrawingQuads();
var3.addVertexWithUV(0.0D, (double)par2, -90.0D, 0.0D, 1.0D);
var3.addVertexWithUV((double)par1, (double)par2, -90.0D, 1.0D, 1.0D);
var3.addVertexWithUV((double)par1, 0.0D, -90.0D, 1.0D, 0.0D);
var3.addVertexWithUV(0.0D, 0.0D, -90.0D, 0.0D, 0.0D);
var3.draw();
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
/**
* Renders the vignette. Args: vignetteBrightness, width, height
*/
private void renderVignette(float par1, int par2, int par3) {
par1 = 1.0F - par1;
if (par1 < 0.0F) {
par1 = 0.0F;
}
if (par1 > 1.0F) {
par1 = 1.0F;
}
this.prevVignetteBrightness = (float)((double)this.prevVignetteBrightness + (double)(par1 - this.prevVignetteBrightness) * 0.01D);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(false);
GL11.glBlendFunc(GL11.GL_ZERO, GL11.GL_ONE_MINUS_SRC_COLOR);
GL11.glColor4f(this.prevVignetteBrightness, this.prevVignetteBrightness, this.prevVignetteBrightness, 1.0F);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.mc.renderEngine.getTexture("%blur%/misc/vignette.png"));
Tessellator var4 = Tessellator.instance;
var4.startDrawingQuads();
var4.addVertexWithUV(0.0D, (double)par3, -90.0D, 0.0D, 1.0D);
var4.addVertexWithUV((double)par2, (double)par3, -90.0D, 1.0D, 1.0D);
var4.addVertexWithUV((double)par2, 0.0D, -90.0D, 1.0D, 0.0D);
var4.addVertexWithUV(0.0D, 0.0D, -90.0D, 0.0D, 0.0D);
var4.draw();
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
/**
* Renders the portal overlay. Args: portalStrength, width, height
*/
private void renderPortalOverlay(float par1, int par2, int par3) {
if (par1 < 1.0F) {
par1 *= par1;
par1 *= par1;
par1 = par1 * 0.8F + 0.2F;
}
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(false);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1.0F, 1.0F, 1.0F, par1);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.mc.renderEngine.getTexture("/terrain.png"));
float var4 = (float)(Block.portal.blockIndexInTexture % 16) / 16.0F;
float var5 = (float)(Block.portal.blockIndexInTexture / 16) / 16.0F;
float var6 = (float)(Block.portal.blockIndexInTexture % 16 + 1) / 16.0F;
float var7 = (float)(Block.portal.blockIndexInTexture / 16 + 1) / 16.0F;
Tessellator var8 = Tessellator.instance;
var8.startDrawingQuads();
var8.addVertexWithUV(0.0D, (double)par3, -90.0D, (double)var4, (double)var7);
var8.addVertexWithUV((double)par2, (double)par3, -90.0D, (double)var6, (double)var7);
var8.addVertexWithUV((double)par2, 0.0D, -90.0D, (double)var6, (double)var5);
var8.addVertexWithUV(0.0D, 0.0D, -90.0D, (double)var4, (double)var5);
var8.draw();
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
/**
* Renders the specified item of the inventory slot at the specified location. Args: slot, x, y, partialTick
*/
private void renderInventorySlot(int par1, int par2, int par3, float par4) {
ItemStack var5 = this.mc.thePlayer.inventory.mainInventory[par1];
if (var5 != null) {
float var6 = (float)var5.animationsToGo - par4;
if (var6 > 0.0F) {
GL11.glPushMatrix();
float var7 = 1.0F + var6 / 5.0F;
GL11.glTranslatef((float)(par2 + 8), (float)(par3 + 12), 0.0F);
GL11.glScalef(1.0F / var7, (var7 + 1.0F) / 2.0F, 1.0F);
GL11.glTranslatef((float)(-(par2 + 8)), (float)(-(par3 + 12)), 0.0F);
}
itemRenderer.renderItemAndEffectIntoGUI(this.mc.fontRenderer, this.mc.renderEngine, var5, par2, par3);
if (var6 > 0.0F) {
GL11.glPopMatrix();
}
itemRenderer.renderItemOverlayIntoGUI(this.mc.fontRenderer, this.mc.renderEngine, var5, par2, par3);
}
}
/**
* The update tick for the ingame UI
*/
public void updateTick() {
if (this.recordPlayingUpFor > 0) {
--this.recordPlayingUpFor;
}
++this.updateCounter;
if (this.mc.thePlayer != null) {
ItemStack var1 = this.mc.thePlayer.inventory.getCurrentItem();
if (var1 == null) {
this.field_92017_k = 0;
} else if (this.field_92016_l != null && var1.itemID == this.field_92016_l.itemID && ItemStack.areItemStackTagsEqual(var1, this.field_92016_l) && (var1.isItemStackDamageable() || var1.getItemDamage() == this.field_92016_l.getItemDamage())) {
if (this.field_92017_k > 0) {
--this.field_92017_k;
}
} else {
this.field_92017_k = 40;
}
this.field_92016_l = var1;
}
}
public void setRecordPlayingMessage(String par1Str) {
this.recordPlaying = "Now playing: " + par1Str;
this.recordPlayingUpFor = 60;
this.recordIsPlaying = true;
}
/**
* returns a pointer to the persistant Chat GUI, containing all previous chat messages and such
*/
public GuiNewChat getChatGUI() {
return this.persistantChatGUI;
}
public int getUpdateCounter() {
return this.updateCounter;
}
}
| true | true | public void renderGameOverlay(float f, boolean flag, int i, int j) {
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
FontRenderer font = this.mc.fontRenderer;
this.mc.entityRenderer.setupOverlayRendering();
GL11.glEnable(GL11.GL_BLEND);
if (Minecraft.isFancyGraphicsEnabled()) {
this.renderVignette(this.mc.thePlayer.getBrightness(f), screenWidth, screenHeight);
} else {
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3);
if (this.mc.gameSettings.thirdPersonView == 0 && helmet != null && helmet.itemID == Block.pumpkin.blockID) {
this.renderPumpkinBlur(screenWidth, screenHeight);
}
if (!this.mc.thePlayer.isPotionActive(Potion.confusion)) {
float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * f;
if (var10 > 0.0F) {
this.renderPortalOverlay(var10, screenWidth, screenHeight);
}
}
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/gui.png"));
InventoryPlayer var11 = this.mc.thePlayer.inventory;
this.zLevel = -90.0F;
this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22);
this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/icons.png"));
GL11.glEnable(3042 /* GL_BLEND */);
GL11.glBlendFunc(775, 769);
this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042 /* GL_BLEND */);
GuiIngame.rand.setSeed((long) (this.updateCounter * 312871));
int var15;
int var17;
this.renderBossHealth();
// Better safe than sorry
SpoutClient.enableSandbox();
// Toggle visibility if needed
if (needsUpdate && mainScreen.getHealthBar().isVisible() == mc.playerController.isInCreativeMode()) {
mainScreen.toggleSurvivalHUD(!mc.playerController.isInCreativeMode());
}
needsUpdate = false;
// Hunger Bar Begin
mainScreen.getHungerBar().render();
// Hunger Bar End
// Armor Bar Begin
mainScreen.getArmorBar().render();
// Armor Bar End
// Health Bar Begin
mainScreen.getHealthBar().render();
// Health Bar End
// Bubble Bar Begin
mainScreen.getBubbleBar().render();
// Bubble Bar End
// Exp Bar Begin
mainScreen.getExpBar().render();
// Exp Bar End
SpoutClient.disableSandbox();
map.onRenderTick();
GL11.glDisable(GL11.GL_BLEND);
this.mc.mcProfiler.startSection("actionBar");
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
for (var15 = 0; var15 < 9; ++var15) {
int x = screenWidth / 2 - 90 + var15 * 20 + 2;
var17 = screenHeight - 16 - 3;
this.renderInventorySlot(var15, x, var17, f);
}
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
this.mc.mcProfiler.endSection();
float var33;
if (this.mc.thePlayer.getSleepTimer() > 0) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
var15 = this.mc.thePlayer.getSleepTimer();
float var26 = (float)var15 / 100.0F;
if (var26 > 1.0F) {
var26 = 1.0F - (float)(var15 - 100) / 10.0F;
}
var17 = (int)(220.0F * var26) << 24 | 1052704;
this.drawRect(0, 0, screenWidth, screenHeight, var17);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
}
SpoutClient.enableSandbox();
mainScreen.render();
SpoutClient.disableSandbox();
if (this.mc.gameSettings.showDebugInfo) {
this.mc.mcProfiler.startSection("debug");
GL11.glPushMatrix();
if (Configuration.getFastDebug() != 2) {
font.drawStringWithShadow("Minecraft 1.4.7 (" + this.mc.debug + ")", 2, 2, 16777215);
font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215);
font.drawStringWithShadow(this.mc.getEntityDebug(), 2, 22, 16777215);
font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215);
font.drawStringWithShadow(this.mc.getWorldProviderName(), 2, 42, 16777215);
long var41 = Runtime.getRuntime().maxMemory();
long var34 = Runtime.getRuntime().totalMemory();
long var42 = Runtime.getRuntime().freeMemory();
long var43 = var34 - var42;
String var45 = "Used memory: " + var43 * 100L / var41 + "% (" + var43 / 1024L / 1024L + "MB) of " + var41 / 1024L / 1024L + "MB";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 2, 14737632);
var45 = "Allocated memory: " + var34 * 100L / var41 + "% (" + var34 / 1024L / 1024L + "MB)";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 12, 14737632);
if(SpoutClient.getInstance().isCoordsCheat()) {
this.drawString(font, String.format("x: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posX)}), 2, 64, 14737632);
this.drawString(font, String.format("y: %.3f (feet pos, %.3f eyes pos)", new Object[] {Double.valueOf(this.mc.thePlayer.boundingBox.minY), Double.valueOf(this.mc.thePlayer.posY)}), 2, 72, 14737632);
this.drawString(font, String.format("z: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posZ)}), 2, 80, 14737632);
this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632);
}
int var47 = MathHelper.floor_double(this.mc.thePlayer.posX);
int var22 = MathHelper.floor_double(this.mc.thePlayer.posY);
int var233 = MathHelper.floor_double(this.mc.thePlayer.posZ);
if (this.mc.theWorld != null && this.mc.theWorld.blockExists(var47, var22, var233)) {
Chunk var48 = this.mc.theWorld.getChunkFromBlockCoords(var47, var233);
this.drawString(font, "lc: " + (var48.getTopFilledSegment() + 15) + " b: " + var48.getBiomeGenForWorldCoords(var47 & 15, var233 & 15, this.mc.theWorld.getWorldChunkManager()).biomeName + " bl: " + var48.getSavedLightValue(EnumSkyBlock.Block, var47 & 15, var22, var233 & 15) + " sl: " + var48.getSavedLightValue(EnumSkyBlock.Sky, var47 & 15, var22, var233 & 15) + " rl: " + var48.getBlockLightValue(var47 & 15, var22, var233 & 15, 0), 2, 96, 14737632);
}
this.drawString(font, String.format("ws: %.3f, fs: %.3f, g: %b", new Object[] {Float.valueOf(this.mc.thePlayer.capabilities.getWalkSpeed()), Float.valueOf(this.mc.thePlayer.capabilities.getFlySpeed()), Boolean.valueOf(this.mc.thePlayer.onGround)}), 2, 104, 14737632);
// Spout Start
boolean cacheInUse = ChunkNetCache.cacheInUse.get();
int y = 115;
font.drawStringWithShadow("Network Info", 2, y += 11, 0xFFFFFF);
if (!cacheInUse) {
font.drawStringWithShadow("Chunk Network Cache: Inactive", 22, y += 11, 0xE0E0E0);
} else {
font.drawStringWithShadow("Chunk Network Cache: Active", 22, y += 11, 0xE0E0E0);
font.drawStringWithShadow("Cache hit: " + ChunkNetCache.hitPercentage.get() + "%", 22, y += 10, 0xE0E0E0);
}
font.drawStringWithShadow("Average Cube Size: " + ChunkNetCache.averageChunkSize.get() / 10.0 + " bytes", 22, y += 10, 0xE0E0E0);
long logTime = System.currentTimeMillis() - ChunkNetCache.loggingStart.get();
long kbpsUp = (80000L * ChunkNetCache.totalPacketUp.get()) / 1024 / logTime;
long kbpsDown = (80000L * ChunkNetCache.totalPacketDown.get()) / 1024 / logTime;
font.drawStringWithShadow("Upstream: " + (kbpsUp / 10.0) + "kbps (" + (ChunkNetCache.totalPacketUp.get() / 1024) + "kB)", 22, y += 11, 0xE0E0E0);
font.drawStringWithShadow("Downstream: " + (kbpsDown / 10.0) + "kbps (" + (ChunkNetCache.totalPacketDown.get() / 1024) + "kB)", 22, y += 11, 0xE0E0E0);
// Spout End
} else {
font.drawStringWithShadow(Integer.toString(Minecraft.framesPerSecond), 4, 2, 0xFFE303);
}
GL11.glPopMatrix();
if (this.recordPlayingUpFor > 0) {
this.mc.mcProfiler.startSection("overlayMessage");
var33 = (float)this.recordPlayingUpFor - f;
int var12 = (int)(var33 * 256.0F / 20.0F);
if (var12 > 255) {
var12 = 255;
}
if (var12 > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
int var13 = 16777215;
if (this.recordIsPlaying) {
var13 = Color.HSBtoRGB(var33 / 50.0F, 0.7F, 0.6F) & 16777215;
}
font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var13 + (var12 << 24));
GL11.glDisable(GL11.GL_BLEND);
GL11.glPopMatrix();
}
this.mc.mcProfiler.endSection();
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, (float)(screenHeight - 48), 0.0F);
this.mc.mcProfiler.startSection("chat");
this.persistantChatGUI.drawChat(this.updateCounter);
this.mc.mcProfiler.endSection();
GL11.glPopMatrix();
if (this.mc.gameSettings.keyBindPlayerList.pressed && (!this.mc.isIntegratedServerRunning() || this.mc.thePlayer.sendQueue.playerInfoList.size() > 1)) {
this.mc.mcProfiler.startSection("playerList");
NetClientHandler var37 = this.mc.thePlayer.sendQueue;
List var39 = var37.playerInfoList;
int var13 = var37.currentServerMaxPlayers;
int var40 = var13;
int var38;
for (var38 = 1; var40 > 20; var40 = (var13 + var38 - 1) / var38) {
++var38;
}
int var16 = 300 / var38;
if (var16 > 150) {
var16 = 150;
}
var17 = (screenWidth - var38 * var16) / 2;
byte var44 = 10;
drawRect(var17 - 1, var44 - 1, var17 + var16 * var38, var44 + 9 * var40, Integer.MIN_VALUE);
for (int var19 = 0; var19 < var13; ++var19) {
int var20 = var17 + var19 % var38 * var16;
int var47 = var44 + var19 / var38 * 9;
drawRect(var20, var47, var20 + var16 - 1, var47 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL11.GL_ALPHA_TEST);
if (var19 < var39.size()) {
GuiPlayerInfo var46 = (GuiPlayerInfo)var39.get(var19);
font.drawStringWithShadow(var46.name, var20, var47, 16777215);
this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png"));
byte var50 = 0;
boolean var48 = false;
byte var49;
if (var46.responseTime < 0) {
var49 = 5;
} else if (var46.responseTime < 150) {
var49 = 0;
} else if (var46.responseTime < 300) {
var49 = 1;
} else if (var46.responseTime < 600) {
var49 = 2;
} else if (var46.responseTime < 1000) {
var49 = 3;
} else {
var49 = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(var20 + var16 - 12, var47, 0 + var50 * 10, 176 + var49 * 8, 10, 8);
this.zLevel -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_ALPHA_TEST);
}
| public void renderGameOverlay(float f, boolean flag, int i, int j) {
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
FontRenderer font = this.mc.fontRenderer;
this.mc.entityRenderer.setupOverlayRendering();
GL11.glEnable(GL11.GL_BLEND);
if (Minecraft.isFancyGraphicsEnabled()) {
this.renderVignette(this.mc.thePlayer.getBrightness(f), screenWidth, screenHeight);
} else {
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3);
if (this.mc.gameSettings.thirdPersonView == 0 && helmet != null && helmet.itemID == Block.pumpkin.blockID) {
this.renderPumpkinBlur(screenWidth, screenHeight);
}
if (!this.mc.thePlayer.isPotionActive(Potion.confusion)) {
float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * f;
if (var10 > 0.0F) {
this.renderPortalOverlay(var10, screenWidth, screenHeight);
}
}
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/gui.png"));
InventoryPlayer var11 = this.mc.thePlayer.inventory;
this.zLevel = -90.0F;
this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22);
this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/icons.png"));
GL11.glEnable(3042 /* GL_BLEND */);
GL11.glBlendFunc(775, 769);
this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042 /* GL_BLEND */);
GuiIngame.rand.setSeed((long) (this.updateCounter * 312871));
int var15;
int var17;
this.renderBossHealth();
// Better safe than sorry
SpoutClient.enableSandbox();
// Toggle visibility if needed
if (needsUpdate && mainScreen.getHealthBar().isVisible() == mc.playerController.isInCreativeMode()) {
mainScreen.toggleSurvivalHUD(!mc.playerController.isInCreativeMode());
}
needsUpdate = false;
// Hunger Bar Begin
mainScreen.getHungerBar().render();
// Hunger Bar End
// Armor Bar Begin
mainScreen.getArmorBar().render();
// Armor Bar End
// Health Bar Begin
mainScreen.getHealthBar().render();
// Health Bar End
// Bubble Bar Begin
mainScreen.getBubbleBar().render();
// Bubble Bar End
// Exp Bar Begin
mainScreen.getExpBar().render();
// Exp Bar End
SpoutClient.disableSandbox();
map.onRenderTick();
GL11.glDisable(GL11.GL_BLEND);
this.mc.mcProfiler.startSection("actionBar");
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableGUIStandardItemLighting();
for (var15 = 0; var15 < 9; ++var15) {
int x = screenWidth / 2 - 90 + var15 * 20 + 2;
var17 = screenHeight - 16 - 3;
this.renderInventorySlot(var15, x, var17, f);
}
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
this.mc.mcProfiler.endSection();
float var33;
if (this.mc.thePlayer.getSleepTimer() > 0) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
var15 = this.mc.thePlayer.getSleepTimer();
float var26 = (float)var15 / 100.0F;
if (var26 > 1.0F) {
var26 = 1.0F - (float)(var15 - 100) / 10.0F;
}
var17 = (int)(220.0F * var26) << 24 | 1052704;
this.drawRect(0, 0, screenWidth, screenHeight, var17);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
}
SpoutClient.enableSandbox();
mainScreen.render();
SpoutClient.disableSandbox();
if (this.mc.gameSettings.showDebugInfo) {
this.mc.mcProfiler.startSection("debug");
GL11.glPushMatrix();
if (Configuration.getFastDebug() != 2) {
font.drawStringWithShadow("Minecraft 1.4.7 (" + this.mc.debug + ")", 2, 2, 16777215);
font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215);
font.drawStringWithShadow(this.mc.getEntityDebug(), 2, 22, 16777215);
font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215);
font.drawStringWithShadow(this.mc.getWorldProviderName(), 2, 42, 16777215);
long var41 = Runtime.getRuntime().maxMemory();
long var34 = Runtime.getRuntime().totalMemory();
long var42 = Runtime.getRuntime().freeMemory();
long var43 = var34 - var42;
String var45 = "Used memory: " + var43 * 100L / var41 + "% (" + var43 / 1024L / 1024L + "MB) of " + var41 / 1024L / 1024L + "MB";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 2, 14737632);
var45 = "Allocated memory: " + var34 * 100L / var41 + "% (" + var34 / 1024L / 1024L + "MB)";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 12, 14737632);
if(SpoutClient.getInstance().isCoordsCheat()) {
this.drawString(font, String.format("x: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posX)}), 2, 64, 14737632);
this.drawString(font, String.format("y: %.3f (feet pos, %.3f eyes pos)", new Object[] {Double.valueOf(this.mc.thePlayer.boundingBox.minY), Double.valueOf(this.mc.thePlayer.posY)}), 2, 72, 14737632);
this.drawString(font, String.format("z: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posZ)}), 2, 80, 14737632);
this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632);
}
int var47 = MathHelper.floor_double(this.mc.thePlayer.posX);
int var22 = MathHelper.floor_double(this.mc.thePlayer.posY);
int var233 = MathHelper.floor_double(this.mc.thePlayer.posZ);
if (this.mc.theWorld != null && this.mc.theWorld.blockExists(var47, var22, var233)) {
Chunk var48 = this.mc.theWorld.getChunkFromBlockCoords(var47, var233);
this.drawString(font, "lc: " + (var48.getTopFilledSegment() + 15) + " b: " + var48.getBiomeGenForWorldCoords(var47 & 15, var233 & 15, this.mc.theWorld.getWorldChunkManager()).biomeName + " bl: " + var48.getSavedLightValue(EnumSkyBlock.Block, var47 & 15, var22, var233 & 15) + " sl: " + var48.getSavedLightValue(EnumSkyBlock.Sky, var47 & 15, var22, var233 & 15) + " rl: " + var48.getBlockLightValue(var47 & 15, var22, var233 & 15, 0), 2, 96, 14737632);
}
this.drawString(font, String.format("ws: %.3f, fs: %.3f, g: %b", new Object[] {Float.valueOf(this.mc.thePlayer.capabilities.getWalkSpeed()), Float.valueOf(this.mc.thePlayer.capabilities.getFlySpeed()), Boolean.valueOf(this.mc.thePlayer.onGround)}), 2, 104, 14737632);
// Spout Start
boolean cacheInUse = ChunkNetCache.cacheInUse.get();
int y = 115;
font.drawStringWithShadow("Network Info", 2, y += 11, 0xFFFFFF);
if (!cacheInUse) {
font.drawStringWithShadow("Chunk Network Cache: Inactive", 22, y += 11, 0xE0E0E0);
} else {
font.drawStringWithShadow("Chunk Network Cache: Active", 22, y += 11, 0xE0E0E0);
font.drawStringWithShadow("Cache hit: " + ChunkNetCache.hitPercentage.get() + "%", 22, y += 10, 0xE0E0E0);
}
font.drawStringWithShadow("Average Cube Size: " + ChunkNetCache.averageChunkSize.get() / 10.0 + " bytes", 22, y += 10, 0xE0E0E0);
long logTime = System.currentTimeMillis() - ChunkNetCache.loggingStart.get();
long kbpsUp = (80000L * ChunkNetCache.totalPacketUp.get()) / 1024 / logTime;
long kbpsDown = (80000L * ChunkNetCache.totalPacketDown.get()) / 1024 / logTime;
font.drawStringWithShadow("Upstream: " + (kbpsUp / 10.0) + "kbps (" + (ChunkNetCache.totalPacketUp.get() / 1024) + "kB)", 22, y += 11, 0xE0E0E0);
font.drawStringWithShadow("Downstream: " + (kbpsDown / 10.0) + "kbps (" + (ChunkNetCache.totalPacketDown.get() / 1024) + "kB)", 22, y += 11, 0xE0E0E0);
// Spout End
} else {
font.drawStringWithShadow(Integer.toString(Minecraft.framesPerSecond), 4, 2, 0xFFE303);
}
this.mc.mcProfiler.endSection();
GL11.glPopMatrix();
if (this.recordPlayingUpFor > 0) {
this.mc.mcProfiler.startSection("overlayMessage");
var33 = (float)this.recordPlayingUpFor - f;
int var12 = (int)(var33 * 256.0F / 20.0F);
if (var12 > 255) {
var12 = 255;
}
if (var12 > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
int var13 = 16777215;
if (this.recordIsPlaying) {
var13 = Color.HSBtoRGB(var33 / 50.0F, 0.7F, 0.6F) & 16777215;
}
font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var13 + (var12 << 24));
GL11.glDisable(GL11.GL_BLEND);
GL11.glPopMatrix();
}
this.mc.mcProfiler.endSection();
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, (float)(screenHeight - 48), 0.0F);
this.mc.mcProfiler.startSection("chat");
this.persistantChatGUI.drawChat(this.updateCounter);
this.mc.mcProfiler.endSection();
GL11.glPopMatrix();
if (this.mc.gameSettings.keyBindPlayerList.pressed && (!this.mc.isIntegratedServerRunning() || this.mc.thePlayer.sendQueue.playerInfoList.size() > 1)) {
this.mc.mcProfiler.startSection("playerList");
NetClientHandler var37 = this.mc.thePlayer.sendQueue;
List var39 = var37.playerInfoList;
int var13 = var37.currentServerMaxPlayers;
int var40 = var13;
int var38;
for (var38 = 1; var40 > 20; var40 = (var13 + var38 - 1) / var38) {
++var38;
}
int var16 = 300 / var38;
if (var16 > 150) {
var16 = 150;
}
var17 = (screenWidth - var38 * var16) / 2;
byte var44 = 10;
drawRect(var17 - 1, var44 - 1, var17 + var16 * var38, var44 + 9 * var40, Integer.MIN_VALUE);
for (int var19 = 0; var19 < var13; ++var19) {
int var20 = var17 + var19 % var38 * var16;
int var47 = var44 + var19 / var38 * 9;
drawRect(var20, var47, var20 + var16 - 1, var47 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL11.GL_ALPHA_TEST);
if (var19 < var39.size()) {
GuiPlayerInfo var46 = (GuiPlayerInfo)var39.get(var19);
font.drawStringWithShadow(var46.name, var20, var47, 16777215);
this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png"));
byte var50 = 0;
boolean var48 = false;
byte var49;
if (var46.responseTime < 0) {
var49 = 5;
} else if (var46.responseTime < 150) {
var49 = 0;
} else if (var46.responseTime < 300) {
var49 = 1;
} else if (var46.responseTime < 600) {
var49 = 2;
} else if (var46.responseTime < 1000) {
var49 = 3;
} else {
var49 = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(var20 + var16 - 12, var47, 0 + var50 * 10, 176 + var49 * 8, 10, 8);
this.zLevel -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_ALPHA_TEST);
}
|
diff --git a/fsm-editor/src/com/mxgraph/examples/swing/editor/scxml/SCXMLGraph.java b/fsm-editor/src/com/mxgraph/examples/swing/editor/scxml/SCXMLGraph.java
index 3796e5f..2e0f577 100755
--- a/fsm-editor/src/com/mxgraph/examples/swing/editor/scxml/SCXMLGraph.java
+++ b/fsm-editor/src/com/mxgraph/examples/swing/editor/scxml/SCXMLGraph.java
@@ -1,811 +1,808 @@
package com.mxgraph.examples.swing.editor.scxml;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import com.mxgraph.examples.config.SCXMLConstraints.RestrictedState;
import com.mxgraph.examples.config.SCXMLConstraints.RestrictedState.PossibleEvent;
import com.mxgraph.examples.swing.SCXMLGraphEditor;
import com.mxgraph.examples.swing.SCXMLGraphEditor.EditorStatus;
import com.mxgraph.examples.swing.editor.fileimportexport.SCXMLEdge;
import com.mxgraph.examples.swing.editor.fileimportexport.SCXMLImportExport;
import com.mxgraph.examples.swing.editor.fileimportexport.SCXMLNode;
import com.mxgraph.examples.swing.editor.utils.XMLUtils;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.model.mxICell;
import com.mxgraph.model.mxIGraphModel;
import com.mxgraph.util.StringUtils;
import com.mxgraph.util.mxEvent;
import com.mxgraph.util.mxEventObject;
import com.mxgraph.util.mxPoint;
import com.mxgraph.util.mxRectangle;
import com.mxgraph.util.mxResources;
import com.mxgraph.view.mxCellState;
import com.mxgraph.view.mxGraph;
/**
* A graph that creates new edges from a given template edge.
*/
public class SCXMLGraph extends mxGraph
{
/**
* Holds the shared number formatter.
*
* @see NumberFormat#getInstance()
*/
public static final NumberFormat numberFormat = NumberFormat.getInstance();
private SCXMLGraphEditor editor;
private HashSet<Object> immovable=new HashSet<Object>();
private HashSet<Object> undeletable=new HashSet<Object>();
private HashSet<Object> uneditable=new HashSet<Object>();
private HashSet<mxCell> outsourced=new HashSet<mxCell>();
private HashMap<mxCell,HashSet<mxCell>> original2clones=new HashMap<mxCell, HashSet<mxCell>>();
private HashMap<String,SCXMLImportExport> ourced=new HashMap<String, SCXMLImportExport>();
public void addToOutsourced(mxCell n) {
assert(((SCXMLNode)n.getValue()).isOutsourcedNode());
outsourced.add(n);
}
public void removeFromOutsourced(mxCell n) {
outsourced.remove(n);
}
public HashSet<mxCell> getOutsourcedNodes() {
return outsourced;
}
public HashMap<mxCell,HashSet<mxCell>> getOriginal2Clones() {
return original2clones;
}
public void clearOutsourcedIndex() {
outsourced.clear();
}
public void setCellAsMovable(Object cell,Boolean m) {
if (m) immovable.remove(cell);
else immovable.add(cell);
}
public void setCellAsDeletable(Object cell,Boolean d) {
if (d) undeletable.remove(cell);
else undeletable.add(cell);
}
public void setCellAsEditable(Object cell,boolean e) {
if (e) uneditable.remove(cell);
else uneditable.add(cell);
}
public void setCellAsConnectable(Object cell,boolean c) {
if (cell instanceof mxCell) ((mxCell) cell).setConnectable(c);
}
@Override
public mxRectangle getPaintBounds(Object[] cells)
{
return getBoundsForCells(cells, false, true, true);
}
@Override
public boolean isCellFoldable(Object cell, boolean collapse)
{
return isSwimlane(cell);
}
@Override
public boolean isValidDropTarget(Object cell, Object[] cells)
{
return (cell != null) && isSwimlane(cell);
}
@Override
public String validateCell(Object cell, Hashtable<Object, Object> context)
{
EditorStatus status=getEditor().getStatus();
SCXMLGraphComponent gc = getEditor().getGraphComponent();
String warnings="";
if (isCellEditable(cell) && (status==EditorStatus.EDITING)) {
if (model.isVertex(cell)) {
mxCell node=(mxCell)cell;
mxICell parent=node.getParent();
if ((parent!=null) && (parent.getValue() instanceof SCXMLNode)) {
mxCellState stateChild = view.getState(cell);
//mxCellState stateParent = view.getState(parent);
//System.out.println(node+" "+parent+" "+stateChild+" "+stateParent);
Object container=gc.getCellAt((int)stateChild.getCenterX(), (int)stateChild.getCenterY(),true,null,cell,true);
//System.out.println(container);
if (container!=parent) warnings+=node+" is not graphically contained in its parent "+parent+".\n";
}
SCXMLNode nodeValue = (SCXMLNode)node.getValue();
String nodeValueID=nodeValue.getID();
if (nodeValueID.matches(".*[\\s]+.*")) warnings+="node name contains spaces.\n";
// check if the executable content is parsable xml
String error=XMLUtils.isParsableXMLString(nodeValue.getOnEntry());
if (error!=null) warnings+="OnEntry content of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getOnExit());
if (error!=null) warnings+="OnExit content of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getOnInitialEntry());
if (error!=null) warnings+="On initial content of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getDoneData());
if (error!=null) warnings+="Done data of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getDatamodel());
if (error!=null) warnings+="Data model of node "+nodeValueID+" caused a parser error: "+error+"\n";
if (!nodeValue.isOutsourcedNode()) {
// check if the namespace has been included
String SCXMLid=nodeValueID;
int pos=SCXMLid.indexOf(':');
boolean namespaceGood=true;
String namespace="";
if (pos>0) {
namespaceGood=false;
namespace=SCXMLid.substring(0,pos);
mxIGraphModel model = getModel();
mxCell root = SCXMLImportExport.followUniqueDescendantLineTillSCXMLValueIsFound(model);
SCXMLNode rootValue=(SCXMLNode) root.getValue();
String[] namespaces=rootValue.getNamespace().split("\n");
Pattern p = Pattern.compile("^[\\s]*xmlns:([^\\s=:]+)[\\s]*=.*$");
for(String ns:namespaces) {
Matcher m = p.matcher(ns);
if (m.matches() && (m.groupCount()==1)) {
ns=m.group(1);
if (namespace.equals(ns)) {
namespaceGood=true;
break;
}
}
}
}
if (!namespaceGood) warnings+="Namespace '"+namespace+"' is used but not defined.\n";
}
if (!StringUtils.isEmptyString(nodeValueID)) {
SCXMLNode parentValue=null;
if (parent==null || ((parentValue=(SCXMLNode)parent.getValue())==null) || !parentValue.getFake() || !nodeValueID.equals(SCXMLNode.ROOTID)) {
if (gc.isSCXMLNodeAlreadyThere(nodeValue)) warnings+="duplicated node name: "+nodeValueID+"\n";
else gc.addSCXMLNode(nodeValue,node);
}
}
if (nodeValue.isClusterNode()) {
int numInitialChildren=0;
int numOutGoingTransitions=0;
int numChildren=node.getChildCount();
for (int i=0;i<numChildren;i++) {
mxCell c=(mxCell) node.getChildAt(i);
if (c.isVertex()) {
SCXMLNode cValue = (SCXMLNode)c.getValue();
if (cValue.isInitial()) {
numInitialChildren++;
}
if ((numInitialChildren>0) && nodeValue.isParallel()) warnings+="Parallel nodes ("+nodeValueID+") don't support a child marked as intiial.\n";
if (numInitialChildren>1) warnings+="More than 1 children of "+nodeValueID+" is marked as initial.\n";
} else {
if (nodeValue.isHistoryNode()) {
if (c.getSource().equals(node)) {
numOutGoingTransitions++;
if (numOutGoingTransitions>1) warnings+="History node '"+nodeValueID+"' has more than 1 outgoing transition.\n";
if (!StringUtils.isEmptyString(((SCXMLEdge)c.getValue()).getCondition()) ||
!StringUtils.isEmptyString(((SCXMLEdge)c.getValue()).getEvent())) {
warnings+="Outgoing transition of history node has non null event or condition.\n";
}
}
}
}
}
}
} else if (model.isEdge(cell)) {
// check that source and target have non null SCXML ids.
mxCell edge=(mxCell)cell;
SCXMLEdge edgeValue=(SCXMLEdge) edge.getValue();
if ((edge.getSource()==null) || (edge.getTarget()==null)) warnings+="unconnected edge.\n";
String error=XMLUtils.isParsableXMLString(edgeValue.getExe());
SCXMLNode source=(SCXMLNode)edge.getSource().getValue();
SCXMLNode target=(SCXMLNode)edge.getTarget().getValue();
if (error!=null) warnings+="Executable content of one edge from "+source.getID()+" to "+target.getID()+" caused a parser error: "+error+"\n";
if (StringUtils.isEmptyString(source.getID()) || StringUtils.isEmptyString(target.getID())) {
warnings+="target and source of a transition must have not empty name.\n";
}
Object lca = model.getNearestCommonAncestor(edge.getSource(), edge.getTarget());
if (lca!=null && lca instanceof mxCell) {
SCXMLNode scxmlLCA = (SCXMLNode) ((mxCell)lca).getValue();
if (scxmlLCA.isParallel()) warnings+=source.getID()+" and "+target.getID()+" are (descendats of) siblings of a parallel node ("+scxmlLCA.getID()+").";
}
String edgeEventName = edgeValue.getEvent();
- //event name can not be null
- if (edgeEventName==null || edgeEventName.isEmpty()) {
- warnings += "Event can not be null!";
- } else if (source.isRestricted()){
- //check that edge event is allowed by the restriction on the source node
+ //check that edge event is allowed by the restriction on the source node
+ if (source.isRestricted()){
boolean isEventPossible = false;
for(PossibleEvent possibleEvent: source.getPossibleEvents()){
if (possibleEvent.getName().equals(edgeEventName)) {
isEventPossible = true;
}
}
if (!isEventPossible) {
warnings += "Invalid event from " + source.getID() + " to " + target.getID() + "!";
}
}
}
}
if (StringUtils.isEmptyString(warnings)) return null;
else return warnings;
}
@Override
public boolean isCellMovable(Object cell)
{
return isCellsMovable() && !isCellLocked(cell) && !immovable.contains(cell);
}
@Override
public boolean isCellDeletable(Object cell)
{
return isCellsDeletable() && !undeletable.contains(cell);
}
@Override
public boolean isCellEditable(Object cell) {
return isCellsEditable() && !uneditable.contains(cell);
}
@Override
public RootStrength vertexShouldBeRoot(Object cell, Object parent,boolean invert) {
if (cell instanceof mxCell) {
mxCell c=(mxCell)cell;
Object v=c.getValue();
if ((v!=null) && (v instanceof SCXMLNode)) {
return new RootStrength((invert)?((SCXMLNode)v).isFinal():((SCXMLNode)v).isInitial(),0);
} else return super.vertexShouldBeRoot(cell, parent, invert);
} else return super.vertexShouldBeRoot(cell, parent, invert);
}
@Override
public Object insertEdge(Object parent, String id, Object value,Object source, Object target)
{
//System.out.println("insert edge: parent:"+parent+" value:"+value+" source:"+source+" target:"+target);
try {
int size=getAllOutgoingEdges(source).length;
if (value==null) {
value=getEditor().getCurrentFileIO().buildEdgeValue();
} else if (!(value instanceof SCXMLEdge)) {
System.out.println("WARNING: non NULL and non SCXMLEdge value passed for new edge (insertEdge in SCXMLGraph)");
value=getEditor().getCurrentFileIO().buildEdgeValue();
}
updateConnectionOfSCXMLEdge((SCXMLEdge) value,source,target,null);
if (((SCXMLEdge)value).getOrder()==null) ((SCXMLEdge)value).setOrder(size);
Object edge = insertEdge(parent, ((SCXMLEdge)value).getInternalID(), value, source, target, "");
setCellStyle(((SCXMLEdge) value).getStyle((mxCell) edge),edge);
return edge;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void askToUseThisEdgeValue(Object clone, Object otherEdgeValue) {
int answer = JOptionPane.showConfirmDialog(editor, mxResources.get("createAsNewTargetForMultitarget"),mxResources.get("edgeCreationOption"),JOptionPane.YES_NO_OPTION);
if (answer==JOptionPane.YES_OPTION) {
model.setValue(clone, otherEdgeValue);
} else {
SCXMLEdge value=(SCXMLEdge) model.getValue(clone);
value.getSCXMLTargets().clear();
}
}
@Override
public Object[] cloneCells(Object[] cells, boolean allowInvalidEdges,Map<Object,Object> mapping)
{
Object[] clones = null;
if (cells != null)
{
Collection<Object> tmp = new LinkedHashSet<Object>(cells.length);
tmp.addAll(Arrays.asList(cells));
if (!tmp.isEmpty())
{
double scale = view.getScale();
mxPoint trans = view.getTranslate();
clones = model.cloneCells(cells, true,mapping);
for (int i = 0; i < cells.length; i++)
{
Object newValue = ((SCXMLImportExport)getEditor().getCurrentFileIO()).cloneValue(((mxCell)clones[i]).getValue());
((mxCell)clones[i]).setValue(newValue);
if (!allowInvalidEdges
&& model.isEdge(clones[i])
&& getEdgeValidationError(clones[i], model
.getTerminal(clones[i], true), model
.getTerminal(clones[i], false)) != null)
{
clones[i] = null;
}
else
{
mxGeometry g = model.getGeometry(clones[i]);
if (g != null)
{
mxCellState state = view.getState(cells[i]);
mxCellState pstate = view.getState(model
.getParent(cells[i]));
if (state != null && pstate != null)
{
double dx = pstate.getOrigin().getX();
double dy = pstate.getOrigin().getY();
if (model.isEdge(clones[i]))
{
// Checks if the source is cloned or sets the terminal point
Object src = model.getTerminal(cells[i],
true);
while (src != null && !tmp.contains(src))
{
src = model.getParent(src);
}
if (src == null)
{
mxPoint pt = state.getAbsolutePoint(0);
g.setTerminalPoint(new mxPoint(pt
.getX()
/ scale - trans.getX(), pt
.getY()
/ scale - trans.getY()), true);
}
// Checks if the target is cloned or sets the terminal point
Object trg = model.getTerminal(cells[i],
false);
while (trg != null && !tmp.contains(trg))
{
trg = model.getParent(trg);
}
if (trg == null)
{
mxPoint pt = state
.getAbsolutePoint(state
.getAbsolutePointCount() - 1);
g.setTerminalPoint(new mxPoint(pt
.getX()
/ scale - trans.getX(), pt
.getY()
/ scale - trans.getY()), false);
}
// Translates the control points
List<mxPoint> points = g.getPoints();
if (points != null)
{
Iterator<mxPoint> it = points
.iterator();
while (it.hasNext())
{
mxPoint pt = it.next();
pt.setX(pt.getX() + dx);
pt.setY(pt.getY() + dy);
}
}
}
else
{
g.setX(g.getX() + dx);
g.setY(g.getY() + dy);
}
}
}
}
}
}
else
{
clones = new Object[] {};
}
}
return clones;
}
@Override
public void cellsRemoved(Object[] cells)
{
if (cells != null && cells.length > 0)
{
double scale = view.getScale();
mxPoint tr = view.getTranslate();
model.beginUpdate();
try
{
Collection<Object> cellSet = new HashSet<Object>();
cellSet.addAll(Arrays.asList(cells));
for (int i = 0; i < cells.length; i++)
{
mxCell cell=(mxCell) cells[i];
// Disconnects edges which are not in cells
Object[] edges = getConnections(cell);
for (int j = 0; j < edges.length; j++)
{
if (!cellSet.contains(edges[j]))
{
mxGeometry geo = model.getGeometry(edges[j]);
if (geo != null)
{
mxCellState state = view.getState(edges[j]);
if (state != null)
{
geo = (mxGeometry) geo.clone();
boolean source = view.getVisibleTerminal(
edges[j], true) == cell;
int n = (source) ? 0 : state
.getAbsolutePointCount() - 1;
mxPoint pt = state.getAbsolutePoint(n);
geo.setTerminalPoint(new mxPoint(pt.getX()
/ scale - tr.getX(), pt.getY()
/ scale - tr.getY()), source);
model.setTerminal(edges[j], null, source);
model.setGeometry(edges[j], geo);
}
}
}
}
model.remove(cell);
if (cell.isEdge()) {
// check if this edge has a source with other outgoing edges and
// the source is not going to be deleted. In that case reorder the
// remaining outgoing edges closing the potential hole that
// removing this edge may be causing.
mxCell source=(mxCell) cell.getSource();
if (!cellSet.contains(source) && getAllOutgoingEdges(source).length>0) {
SCXMLChangeHandler.addStateOfNodeInCurrentEdit(source, model);
reOrderOutgoingEdges(source);
}
// if deleted edge was part of multitarget edge, remove the target pointed by this deleted edge.
Collection<Object> siblings = getEditor().getGraphComponent().getSiblingsOfCell(cell);
if (siblings.size()>1) {
SCXMLEdge edgeValue = (SCXMLEdge) cell.getValue();
SCXMLNode targetNode=(SCXMLNode) cell.getTarget().getValue();
assert(edgeValue.getSCXMLTargets().contains(targetNode.getID()));
edgeValue.getSCXMLTargets().remove(targetNode.getID());
}
}
}
fireEvent(new mxEventObject(mxEvent.CELLS_REMOVED, "cells",cells));
}
finally
{
model.endUpdate();
}
}
}
public void reOrderOutgoingEdges(mxCell source) {
HashMap<Integer,ArrayList<SCXMLEdge>> pos=new HashMap<Integer, ArrayList<SCXMLEdge>>();
int min=0,max=0;
for(Object s:getAllOutgoingEdges(source)) {
mxCell c=(mxCell) s;
SCXMLEdge v = (SCXMLEdge) c.getValue();
int o=v.getOrder();
ArrayList<SCXMLEdge> l = pos.get(o);
if (l==null) pos.put(o, l=new ArrayList<SCXMLEdge>());
l.add(v);
if (o<min) min=o;
if (o>max) max=o;
}
int neworder=0;
for(int i=min;i<=max;i++) {
if (pos.containsKey(i)) {
for (SCXMLEdge e:pos.get(i)) {
e.setOrder(neworder++);
}
}
}
}
@Override
public Object connectCell(Object edge, Object terminal, boolean source)
{
//System.out.println("connect cell: edge:"+edge+" terminal:"+terminal+" source:"+source);
model.beginUpdate();
try
{
SCXMLChangeHandler.addStateOfEdgeInCurrentEdit((mxCell) edge, model);
SCXMLGraphComponent gc = (SCXMLGraphComponent) getEditor().getGraphComponent();
Collection<Object> siblings = gc.getSiblingsOfCell(edge);
if (siblings.size()>1) {
if (source) {
JOptionPane.showMessageDialog(editor,
"Detaching edge from multitarget edge.",
mxResources.get("warning"),
JOptionPane.WARNING_MESSAGE);
SCXMLEdge oldValue=(SCXMLEdge) ((mxCell)edge).getValue();
SCXMLEdge newValue = (SCXMLEdge) ((SCXMLImportExport)getEditor().getCurrentFileIO()).cloneValue(oldValue);
((mxCell)edge).setValue(newValue);
SCXMLNode targetNodeValue=(SCXMLNode) model.getValue(model.getTerminal(edge, false));
oldValue.getSCXMLTargets().remove(targetNodeValue.getID());
ArrayList<String> targets = newValue.getSCXMLTargets();
targets.clear();
targets.add(targetNodeValue.getID());
}
}
// connect edge to new terminal (source or target)
Object previous = model.getTerminal(edge, source);
cellConnected(edge, terminal, source);
fireEvent(new mxEventObject(mxEvent.CONNECT_CELL, "edge", edge,
"terminal", terminal, "source", source, "previous",
previous));
// update the order of edges in case we move the source of an edge from one node to another.
if (source) {
SCXMLChangeHandler.addStateOfNodeInCurrentEdit((mxCell) previous, model);
reOrderOutgoingEdges((mxCell) previous);
SCXMLChangeHandler.addStateOfNodeInCurrentEdit((mxCell) terminal, model);
reOrderOutgoingEdges((mxCell) terminal);
}
SCXMLEdge edgeValue=(SCXMLEdge) ((mxCell)edge).getValue();
// Synchronize the source and targets stored in the value of the modified edge with the graphical properties here updated.
updateConnectionOfSCXMLEdge(edgeValue,(source)?terminal:null,(source)?null:terminal,previous);
// update edge style
setCellStyle(edgeValue.getStyle((mxCell) edge),edge);
} catch (Exception e) {
e.printStackTrace();
} finally {
model.endUpdate();
}
return edge;
}
private void updateConnectionOfSCXMLEdge(SCXMLEdge value, Object source, Object target, Object previous) throws Exception {
//System.out.println("update connectiopn: value:"+value+" source:"+source+" target:"+target+" previous:"+previous);
String sourceID=null,targetID=null;
if (source!=null) {
sourceID=((SCXMLNode)((mxCell)source).getValue()).getID();
value.setSCXMLSource(sourceID);
}
if (target!=null) {
targetID=((SCXMLNode)((mxCell)target).getValue()).getID();
if (previous==null) {
// add a target to an edge (new edge without any previous target)
ArrayList<String> targets = value.getSCXMLTargets();
if (!targets.contains(targetID)) value.getSCXMLTargets().add(targetID);
} else {
// update an edge belonging to a multitarget edge
String previousTargetID=((SCXMLNode)((mxCell)previous).getValue()).getID();
if (!value.getSCXMLTargets().contains(previousTargetID)) throw new Exception("updateConnectionOfSCXMLEdge: Error while moving target of edge with multiple targets. Old target not found.");
value.getSCXMLTargets().remove(previousTargetID);
value.getSCXMLTargets().add(targetID);
}
}
}
public void setEditor(SCXMLGraphEditor scxmlGraphEditor) {
this.editor=scxmlGraphEditor;
}
public SCXMLGraphEditor getEditor() {
return this.editor;
}
public mxCell findCellContainingAllOtherCells() {
return null;
}
@Override
public String convertValueToString(Object cell)
{
Object v = model.getValue(cell);
if (v instanceof SCXMLNode) {
SCXMLNode node=((SCXMLNode)v);
if (!StringUtils.isEmptyString(node.getName()))
return node.getID()+"["+node.getName()+"]";
else
return node.getID();
} else if (v instanceof SCXMLEdge) {
SCXMLEdge edge=((SCXMLEdge)v);
return edge.getEvent();
} else {
return "";
}
}
/**
* Holds the edge to be used as a template for inserting new edges.
*/
protected Object edgeTemplate;
/**
* Custom graph that defines the alternate edge style to be used when
* the middle control point of edges is double clicked (flipped).
*/
public SCXMLGraph()
{
setAlternateEdgeStyle("edgeStyle=mxEdgeStyle.ElbowConnector;elbow=vertical");
setAutoSizeCells(true);
setAllowLoops(true);
}
/**
* Sets the edge template to be used to inserting edges.
*/
public void setEdgeTemplate(Object template)
{
edgeTemplate = template;
}
/**
* Prints out some useful information about the cell in the tooltip.
*/
public String getToolTipForCell(Object cell)
{
String tip = null;
if (cell instanceof mxCell) {
if (((mxCell)cell).isEdge()) {
tip="<html>";
SCXMLEdge v=(SCXMLEdge) ((mxCell)cell).getValue();
tip+="order: "+v.getOrder()+"<br>";
tip+="event: "+v.getEvent()+"<br>";
tip+="condition: <pre>"+XMLUtils.escapeStringForXML(v.getCondition())+"</pre><br>";
tip+="exe: <pre>"+XMLUtils.escapeStringForXML(v.getExe())+"</pre><br>";
tip += "</html>";
} else if (((mxCell)cell).isVertex()) {
SCXMLNode v=(SCXMLNode) ((mxCell)cell).getValue();
String src=v.getOutsourcedLocation();
if (!StringUtils.isEmptyString(src)) {
tip="<html>";
tip+="src: "+src+"<br>";
tip+="type: "+v.getSRC().getType()+"<br>";
tip += "</html>";
} else {
String tipBody="";
if (v.isRestricted()) {
tipBody += "Restrictions:<br><pre>";
for(RestrictedState restriction: v.getRestrictedStates()){
tipBody += restriction.getName() + "<br>";
}
tipBody += "</pre><br>";
}
if (v.isInitial()) tipBody+="onInitialEntry: <pre>"+XMLUtils.escapeStringForXML(v.getOnInitialEntry())+"</pre><br>";
String onEntry = v.getOnEntry();
if ((onEntry!=null) && (!(onEntry.isEmpty()))) {
tipBody+="onEntry:<br><pre>"+XMLUtils.escapeStringForXML(onEntry)+"</pre><br>";
}
String onExit = v.getOnExit();
if ((onExit!=null) && (!(onExit.isEmpty()))) {
tipBody+="onExit:<br><pre>"+XMLUtils.escapeStringForXML(onExit)+"</pre><br>";
}
if (v.isFinal()) tipBody+="exitData: "+v.getDoneData()+"<br>";
if (!tipBody.isEmpty()) {
tip = "<html>";
tip += tipBody;
tip += "</html>";
}
}
}
}
return tip;
}
// public String getToolTipForCell(Object cell)
// {
// String tip = "<html>";
// mxGeometry geo = getModel().getGeometry(cell);
// mxCellState state = getView().getState(cell);
//
// if (getModel().isEdge(cell))
// {
// tip += "points={";
//
// if (geo != null)
// {
// List<mxPoint> points = geo.getPoints();
//
// if (points != null)
// {
// Iterator<mxPoint> it = points.iterator();
//
// while (it.hasNext())
// {
// mxPoint point = it.next();
// tip += "[x=" + numberFormat.format(point.getX())
// + ",y=" + numberFormat.format(point.getY())
// + "],";
// }
//
// tip = tip.substring(0, tip.length() - 1);
// }
// }
//
// tip += "}<br>";
// tip += "absPoints={";
//
// if (state != null)
// {
//
// for (int i = 0; i < state.getAbsolutePointCount(); i++)
// {
// mxPoint point = state.getAbsolutePoint(i);
// tip += "[x=" + numberFormat.format(point.getX())
// + ",y=" + numberFormat.format(point.getY())
// + "],";
// }
//
// tip = tip.substring(0, tip.length() - 1);
// }
//
// tip += "}";
// }
// else
// {
// tip += "geo=[";
//
// if (geo != null)
// {
// tip += "x=" + numberFormat.format(geo.getX()) + ",y="
// + numberFormat.format(geo.getY()) + ",width="
// + numberFormat.format(geo.getWidth()) + ",height="
// + numberFormat.format(geo.getHeight());
// }
//
// tip += "]<br>";
// tip += "state=[";
//
// if (state != null)
// {
// tip += "x=" + numberFormat.format(state.getX()) + ",y="
// + numberFormat.format(state.getY()) + ",width="
// + numberFormat.format(state.getWidth())
// + ",height="
// + numberFormat.format(state.getHeight());
// }
//
// tip += "]";
// }
//
// mxPoint trans = getView().getTranslate();
//
// tip += "<br>scale=" + numberFormat.format(getView().getScale())
// + ", translate=[x=" + numberFormat.format(trans.getX())
// + ",y=" + numberFormat.format(trans.getY()) + "]";
// tip += "</html>";
//
// return tip;
// }
/**
* Overrides the method to use the currently selected edge template for
* new edges.
*
* @param graph
* @param parent
* @param id
* @param value
* @param source
* @param target
* @param style
* @return
*/
public Object createEdge(Object parent, String id, Object value,
Object source, Object target, String style)
{
if (edgeTemplate != null)
{
mxCell edge = (mxCell) cloneCells(new Object[] { edgeTemplate })[0];
edge.setId(id);
return edge;
}
return super.createEdge(parent, id, value, source, target, style);
}
public void clearUndeletable(){
undeletable.clear();
}
}
| true | true | public String validateCell(Object cell, Hashtable<Object, Object> context)
{
EditorStatus status=getEditor().getStatus();
SCXMLGraphComponent gc = getEditor().getGraphComponent();
String warnings="";
if (isCellEditable(cell) && (status==EditorStatus.EDITING)) {
if (model.isVertex(cell)) {
mxCell node=(mxCell)cell;
mxICell parent=node.getParent();
if ((parent!=null) && (parent.getValue() instanceof SCXMLNode)) {
mxCellState stateChild = view.getState(cell);
//mxCellState stateParent = view.getState(parent);
//System.out.println(node+" "+parent+" "+stateChild+" "+stateParent);
Object container=gc.getCellAt((int)stateChild.getCenterX(), (int)stateChild.getCenterY(),true,null,cell,true);
//System.out.println(container);
if (container!=parent) warnings+=node+" is not graphically contained in its parent "+parent+".\n";
}
SCXMLNode nodeValue = (SCXMLNode)node.getValue();
String nodeValueID=nodeValue.getID();
if (nodeValueID.matches(".*[\\s]+.*")) warnings+="node name contains spaces.\n";
// check if the executable content is parsable xml
String error=XMLUtils.isParsableXMLString(nodeValue.getOnEntry());
if (error!=null) warnings+="OnEntry content of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getOnExit());
if (error!=null) warnings+="OnExit content of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getOnInitialEntry());
if (error!=null) warnings+="On initial content of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getDoneData());
if (error!=null) warnings+="Done data of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getDatamodel());
if (error!=null) warnings+="Data model of node "+nodeValueID+" caused a parser error: "+error+"\n";
if (!nodeValue.isOutsourcedNode()) {
// check if the namespace has been included
String SCXMLid=nodeValueID;
int pos=SCXMLid.indexOf(':');
boolean namespaceGood=true;
String namespace="";
if (pos>0) {
namespaceGood=false;
namespace=SCXMLid.substring(0,pos);
mxIGraphModel model = getModel();
mxCell root = SCXMLImportExport.followUniqueDescendantLineTillSCXMLValueIsFound(model);
SCXMLNode rootValue=(SCXMLNode) root.getValue();
String[] namespaces=rootValue.getNamespace().split("\n");
Pattern p = Pattern.compile("^[\\s]*xmlns:([^\\s=:]+)[\\s]*=.*$");
for(String ns:namespaces) {
Matcher m = p.matcher(ns);
if (m.matches() && (m.groupCount()==1)) {
ns=m.group(1);
if (namespace.equals(ns)) {
namespaceGood=true;
break;
}
}
}
}
if (!namespaceGood) warnings+="Namespace '"+namespace+"' is used but not defined.\n";
}
if (!StringUtils.isEmptyString(nodeValueID)) {
SCXMLNode parentValue=null;
if (parent==null || ((parentValue=(SCXMLNode)parent.getValue())==null) || !parentValue.getFake() || !nodeValueID.equals(SCXMLNode.ROOTID)) {
if (gc.isSCXMLNodeAlreadyThere(nodeValue)) warnings+="duplicated node name: "+nodeValueID+"\n";
else gc.addSCXMLNode(nodeValue,node);
}
}
if (nodeValue.isClusterNode()) {
int numInitialChildren=0;
int numOutGoingTransitions=0;
int numChildren=node.getChildCount();
for (int i=0;i<numChildren;i++) {
mxCell c=(mxCell) node.getChildAt(i);
if (c.isVertex()) {
SCXMLNode cValue = (SCXMLNode)c.getValue();
if (cValue.isInitial()) {
numInitialChildren++;
}
if ((numInitialChildren>0) && nodeValue.isParallel()) warnings+="Parallel nodes ("+nodeValueID+") don't support a child marked as intiial.\n";
if (numInitialChildren>1) warnings+="More than 1 children of "+nodeValueID+" is marked as initial.\n";
} else {
if (nodeValue.isHistoryNode()) {
if (c.getSource().equals(node)) {
numOutGoingTransitions++;
if (numOutGoingTransitions>1) warnings+="History node '"+nodeValueID+"' has more than 1 outgoing transition.\n";
if (!StringUtils.isEmptyString(((SCXMLEdge)c.getValue()).getCondition()) ||
!StringUtils.isEmptyString(((SCXMLEdge)c.getValue()).getEvent())) {
warnings+="Outgoing transition of history node has non null event or condition.\n";
}
}
}
}
}
}
} else if (model.isEdge(cell)) {
// check that source and target have non null SCXML ids.
mxCell edge=(mxCell)cell;
SCXMLEdge edgeValue=(SCXMLEdge) edge.getValue();
if ((edge.getSource()==null) || (edge.getTarget()==null)) warnings+="unconnected edge.\n";
String error=XMLUtils.isParsableXMLString(edgeValue.getExe());
SCXMLNode source=(SCXMLNode)edge.getSource().getValue();
SCXMLNode target=(SCXMLNode)edge.getTarget().getValue();
if (error!=null) warnings+="Executable content of one edge from "+source.getID()+" to "+target.getID()+" caused a parser error: "+error+"\n";
if (StringUtils.isEmptyString(source.getID()) || StringUtils.isEmptyString(target.getID())) {
warnings+="target and source of a transition must have not empty name.\n";
}
Object lca = model.getNearestCommonAncestor(edge.getSource(), edge.getTarget());
if (lca!=null && lca instanceof mxCell) {
SCXMLNode scxmlLCA = (SCXMLNode) ((mxCell)lca).getValue();
if (scxmlLCA.isParallel()) warnings+=source.getID()+" and "+target.getID()+" are (descendats of) siblings of a parallel node ("+scxmlLCA.getID()+").";
}
String edgeEventName = edgeValue.getEvent();
//event name can not be null
if (edgeEventName==null || edgeEventName.isEmpty()) {
warnings += "Event can not be null!";
} else if (source.isRestricted()){
//check that edge event is allowed by the restriction on the source node
boolean isEventPossible = false;
for(PossibleEvent possibleEvent: source.getPossibleEvents()){
if (possibleEvent.getName().equals(edgeEventName)) {
isEventPossible = true;
}
}
if (!isEventPossible) {
warnings += "Invalid event from " + source.getID() + " to " + target.getID() + "!";
}
}
}
}
if (StringUtils.isEmptyString(warnings)) return null;
else return warnings;
}
| public String validateCell(Object cell, Hashtable<Object, Object> context)
{
EditorStatus status=getEditor().getStatus();
SCXMLGraphComponent gc = getEditor().getGraphComponent();
String warnings="";
if (isCellEditable(cell) && (status==EditorStatus.EDITING)) {
if (model.isVertex(cell)) {
mxCell node=(mxCell)cell;
mxICell parent=node.getParent();
if ((parent!=null) && (parent.getValue() instanceof SCXMLNode)) {
mxCellState stateChild = view.getState(cell);
//mxCellState stateParent = view.getState(parent);
//System.out.println(node+" "+parent+" "+stateChild+" "+stateParent);
Object container=gc.getCellAt((int)stateChild.getCenterX(), (int)stateChild.getCenterY(),true,null,cell,true);
//System.out.println(container);
if (container!=parent) warnings+=node+" is not graphically contained in its parent "+parent+".\n";
}
SCXMLNode nodeValue = (SCXMLNode)node.getValue();
String nodeValueID=nodeValue.getID();
if (nodeValueID.matches(".*[\\s]+.*")) warnings+="node name contains spaces.\n";
// check if the executable content is parsable xml
String error=XMLUtils.isParsableXMLString(nodeValue.getOnEntry());
if (error!=null) warnings+="OnEntry content of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getOnExit());
if (error!=null) warnings+="OnExit content of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getOnInitialEntry());
if (error!=null) warnings+="On initial content of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getDoneData());
if (error!=null) warnings+="Done data of node "+nodeValueID+" caused a parser error: "+error+"\n";
error=XMLUtils.isParsableXMLString(nodeValue.getDatamodel());
if (error!=null) warnings+="Data model of node "+nodeValueID+" caused a parser error: "+error+"\n";
if (!nodeValue.isOutsourcedNode()) {
// check if the namespace has been included
String SCXMLid=nodeValueID;
int pos=SCXMLid.indexOf(':');
boolean namespaceGood=true;
String namespace="";
if (pos>0) {
namespaceGood=false;
namespace=SCXMLid.substring(0,pos);
mxIGraphModel model = getModel();
mxCell root = SCXMLImportExport.followUniqueDescendantLineTillSCXMLValueIsFound(model);
SCXMLNode rootValue=(SCXMLNode) root.getValue();
String[] namespaces=rootValue.getNamespace().split("\n");
Pattern p = Pattern.compile("^[\\s]*xmlns:([^\\s=:]+)[\\s]*=.*$");
for(String ns:namespaces) {
Matcher m = p.matcher(ns);
if (m.matches() && (m.groupCount()==1)) {
ns=m.group(1);
if (namespace.equals(ns)) {
namespaceGood=true;
break;
}
}
}
}
if (!namespaceGood) warnings+="Namespace '"+namespace+"' is used but not defined.\n";
}
if (!StringUtils.isEmptyString(nodeValueID)) {
SCXMLNode parentValue=null;
if (parent==null || ((parentValue=(SCXMLNode)parent.getValue())==null) || !parentValue.getFake() || !nodeValueID.equals(SCXMLNode.ROOTID)) {
if (gc.isSCXMLNodeAlreadyThere(nodeValue)) warnings+="duplicated node name: "+nodeValueID+"\n";
else gc.addSCXMLNode(nodeValue,node);
}
}
if (nodeValue.isClusterNode()) {
int numInitialChildren=0;
int numOutGoingTransitions=0;
int numChildren=node.getChildCount();
for (int i=0;i<numChildren;i++) {
mxCell c=(mxCell) node.getChildAt(i);
if (c.isVertex()) {
SCXMLNode cValue = (SCXMLNode)c.getValue();
if (cValue.isInitial()) {
numInitialChildren++;
}
if ((numInitialChildren>0) && nodeValue.isParallel()) warnings+="Parallel nodes ("+nodeValueID+") don't support a child marked as intiial.\n";
if (numInitialChildren>1) warnings+="More than 1 children of "+nodeValueID+" is marked as initial.\n";
} else {
if (nodeValue.isHistoryNode()) {
if (c.getSource().equals(node)) {
numOutGoingTransitions++;
if (numOutGoingTransitions>1) warnings+="History node '"+nodeValueID+"' has more than 1 outgoing transition.\n";
if (!StringUtils.isEmptyString(((SCXMLEdge)c.getValue()).getCondition()) ||
!StringUtils.isEmptyString(((SCXMLEdge)c.getValue()).getEvent())) {
warnings+="Outgoing transition of history node has non null event or condition.\n";
}
}
}
}
}
}
} else if (model.isEdge(cell)) {
// check that source and target have non null SCXML ids.
mxCell edge=(mxCell)cell;
SCXMLEdge edgeValue=(SCXMLEdge) edge.getValue();
if ((edge.getSource()==null) || (edge.getTarget()==null)) warnings+="unconnected edge.\n";
String error=XMLUtils.isParsableXMLString(edgeValue.getExe());
SCXMLNode source=(SCXMLNode)edge.getSource().getValue();
SCXMLNode target=(SCXMLNode)edge.getTarget().getValue();
if (error!=null) warnings+="Executable content of one edge from "+source.getID()+" to "+target.getID()+" caused a parser error: "+error+"\n";
if (StringUtils.isEmptyString(source.getID()) || StringUtils.isEmptyString(target.getID())) {
warnings+="target and source of a transition must have not empty name.\n";
}
Object lca = model.getNearestCommonAncestor(edge.getSource(), edge.getTarget());
if (lca!=null && lca instanceof mxCell) {
SCXMLNode scxmlLCA = (SCXMLNode) ((mxCell)lca).getValue();
if (scxmlLCA.isParallel()) warnings+=source.getID()+" and "+target.getID()+" are (descendats of) siblings of a parallel node ("+scxmlLCA.getID()+").";
}
String edgeEventName = edgeValue.getEvent();
//check that edge event is allowed by the restriction on the source node
if (source.isRestricted()){
boolean isEventPossible = false;
for(PossibleEvent possibleEvent: source.getPossibleEvents()){
if (possibleEvent.getName().equals(edgeEventName)) {
isEventPossible = true;
}
}
if (!isEventPossible) {
warnings += "Invalid event from " + source.getID() + " to " + target.getID() + "!";
}
}
}
}
if (StringUtils.isEmptyString(warnings)) return null;
else return warnings;
}
|
diff --git a/LunchList/src/csci498/abajwa/lunchlist/EditPreferences.java b/LunchList/src/csci498/abajwa/lunchlist/EditPreferences.java
index 9a6eaf7..b2b7bb0 100644
--- a/LunchList/src/csci498/abajwa/lunchlist/EditPreferences.java
+++ b/LunchList/src/csci498/abajwa/lunchlist/EditPreferences.java
@@ -1,60 +1,60 @@
package csci498.abajwa.lunchlist;
import android.content.ComponentName;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
public class EditPreferences extends PreferenceActivity {
SharedPreferences prefs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
@Override
public void onResume() {
super.onResume();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(onChange);
}
@Override
public void onPause() {
prefs.unregisterOnSharedPreferenceChangeListener(onChange);
super.onPause();
}
SharedPreferences.OnSharedPreferenceChangeListener onChange = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (getString(R.string.alarm).equals(key)) {
boolean enabled = prefs.getBoolean(key, false);
- int flag = (enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER);
+ int flag = (enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
ComponentName component = new ComponentName(EditPreferences.this, OnBootReceiver.class);
getPackageManager().setComponentEnabledSetting(component, flag, PackageManager.DONT_KILL_APP);
if (enabled) {
OnBootReceiver.setAlarm(EditPreferences.this);
}
else {
OnBootReceiver.cancelAlarm(EditPreferences.this);
}
}
else if (getString(R.string.alarm_time).equals(key)) {
OnBootReceiver.cancelAlarm(EditPreferences.this);
OnBootReceiver.setAlarm(EditPreferences.this);
}
}
};
}
| true | true | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (getString(R.string.alarm).equals(key)) {
boolean enabled = prefs.getBoolean(key, false);
int flag = (enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER);
ComponentName component = new ComponentName(EditPreferences.this, OnBootReceiver.class);
getPackageManager().setComponentEnabledSetting(component, flag, PackageManager.DONT_KILL_APP);
if (enabled) {
OnBootReceiver.setAlarm(EditPreferences.this);
}
else {
OnBootReceiver.cancelAlarm(EditPreferences.this);
}
}
else if (getString(R.string.alarm_time).equals(key)) {
OnBootReceiver.cancelAlarm(EditPreferences.this);
OnBootReceiver.setAlarm(EditPreferences.this);
}
}
| public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (getString(R.string.alarm).equals(key)) {
boolean enabled = prefs.getBoolean(key, false);
int flag = (enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
ComponentName component = new ComponentName(EditPreferences.this, OnBootReceiver.class);
getPackageManager().setComponentEnabledSetting(component, flag, PackageManager.DONT_KILL_APP);
if (enabled) {
OnBootReceiver.setAlarm(EditPreferences.this);
}
else {
OnBootReceiver.cancelAlarm(EditPreferences.this);
}
}
else if (getString(R.string.alarm_time).equals(key)) {
OnBootReceiver.cancelAlarm(EditPreferences.this);
OnBootReceiver.setAlarm(EditPreferences.this);
}
}
|
diff --git a/tizzit-common/src/main/java/org/tizzit/util/spring/httpinvoker/StreamSupportingHttpInvokerServiceExporter.java b/tizzit-common/src/main/java/org/tizzit/util/spring/httpinvoker/StreamSupportingHttpInvokerServiceExporter.java
index 6f093229..a6865df7 100644
--- a/tizzit-common/src/main/java/org/tizzit/util/spring/httpinvoker/StreamSupportingHttpInvokerServiceExporter.java
+++ b/tizzit-common/src/main/java/org/tizzit/util/spring/httpinvoker/StreamSupportingHttpInvokerServiceExporter.java
@@ -1,396 +1,402 @@
/**
* Copyright (c) 2009 Juwi MacMillan Group 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 org.tizzit.util.spring.httpinvoker;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.BufferedOutputStream;
import java.io.ObjectOutputStream;
import java.io.FilterOutputStream;
import java.io.FilterInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;
import org.springframework.remoting.support.RemoteInvocation;
import org.springframework.remoting.support.RemoteInvocationResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Extends <code>HttpInvokerServiceExporter</code> to allow
* <code>InputStream</code> parameters to remote service methods and
* <code>InputStream</code> return values from remote service methods. See
* the documentation for
* <code>StreamSupportingHttpInvokerProxyFactoryBean</code> for important
* restrictions and usage information. Also see
* <code>HttpInvokerServiceExporter</code> for general usage of the exporter
* facility.
*
* @author Andy DePue
* @since 1.2.3
* @see StreamSupportingHttpInvokerProxyFactoryBean
* @see HttpInvokerServiceExporter
*/
public class StreamSupportingHttpInvokerServiceExporter
extends HttpInvokerServiceExporter
{
private static final Log log = LogFactory.getLog(StreamSupportingHttpInvokerServiceExporter.class);
private boolean emptyInputStreamParameterBeforeReturn = false;
//
// METHODS FROM CLASS HttpInvokerServiceExporter
//
protected RemoteInvocation readRemoteInvocation(final HttpServletRequest request, final InputStream is)
throws IOException, ClassNotFoundException
{
final RemoteInvocation ret = super.readRemoteInvocation(request, new StreamSupportingHttpInvokerRequestExecutor.CloseShieldedInputStream(is));
boolean closeIs = true;
if(ret instanceof StreamSupportingRemoteInvocation) {
final StreamSupportingRemoteInvocation ssri = (StreamSupportingRemoteInvocation)ret;
if(ssri.getInputStreamParam() >= 0 && !ssri.isInputStreamParamNull()) {
ssri.getArguments()[ssri.getInputStreamParam()] = new ParameterInputStream(is);
closeIs = false;
}
}
if(closeIs) {
is.close();
}
return ret;
}
protected void writeRemoteInvocationResult(final HttpServletRequest request,
final HttpServletResponse response,
final RemoteInvocationResult result)
throws IOException
{
if(hasStreamResult(result)) {
response.setContentType(StreamSupportingHttpInvokerRequestExecutor.CONTENT_TYPE_SERIALIZED_OBJECT_WITH_STREAM);
} else {
response.setContentType(CONTENT_TYPE_SERIALIZED_OBJECT);
}
writeRemoteInvocationResult(request, response, result, response.getOutputStream());
}
protected void writeRemoteInvocationResult(final HttpServletRequest request,
final HttpServletResponse response,
final RemoteInvocationResult result,
final OutputStream os)
throws IOException
{
if(hasStreamResult(result)) {
final OutputStream decoratedOut = decorateOutputStream(request, response, os);
response.setHeader("Transfer-Encoding", "chunked");
try {
// We want to be able to close the ObjectOutputStream in order to
// properly flush and clear it out, but we don't want it closing
// our underlying OutputStream.
final ObjectOutputStream oos = new ObjectOutputStream(new CloseShieldedOutputStream(new BufferedOutputStream(decoratedOut, 4096)));
try {
doWriteRemoteInvocationResult(result, oos);
oos.flush();
} finally {
oos.close();
}
doWriteReturnInputStream((StreamSupportingRemoteInvocationResult)result, decoratedOut);
} finally {
decoratedOut.close();
}
} else {
super.writeRemoteInvocationResult(request, response, result, os);
}
}
protected RemoteInvocationResult invokeAndCreateResult(final RemoteInvocation invocation, final Object targetObject)
{
try {
final Object value = invoke(invocation, targetObject);
if(invocation instanceof StreamSupportingRemoteInvocation) {
final Boolean closedInputStreamParam = getParameterInputStreamClosedFlag(invocation);
if(value instanceof InputStream) {
return new StreamSupportingRemoteInvocationResult((InputStream)value, closedInputStreamParam);
} else {
return new StreamSupportingRemoteInvocationResult(value, closedInputStreamParam);
}
} else {
return new RemoteInvocationResult(value);
}
} catch (Throwable ex) {
if(invocation instanceof StreamSupportingRemoteInvocation) {
return new StreamSupportingRemoteInvocationResult(ex, getParameterInputStreamClosedFlag(invocation));
- } else {
- return new RemoteInvocationResult(ex);
+ } else {
+ if(log.isWarnEnabled()){
+ log.warn(ex.getCause().getMessage());
+ }
+ if(log.isDebugEnabled()){
+ log.debug(ex);
+ }
+ return new RemoteInvocationResult(new Exception(ex.getMessage()));
}
} finally {
final ParameterInputStream pi = getParameterInputStreamFrom(invocation);
if(pi != null) {
try {
pi.doRealClose(getEmptyInputStreamParameterBeforeReturn());
} catch(IOException e) {
log.warn("Error while attempting to close InputStream parameter for RemoteInvocation '" + invocation + "'", e);
}
}
}
}
//
// HELPER METHODS
//
/**
* See {@link #setEmptyInputStreamParameterBeforeReturn(boolean)}.
*
* @return <code>true</code> if any InputStream parameter should be
* "emptied" before sending the response to the client.
* @see #setEmptyInputStreamParameterBeforeReturn(boolean)
*/
public boolean getEmptyInputStreamParameterBeforeReturn()
{
return this.emptyInputStreamParameterBeforeReturn;
}
/**
* Determines if this servlet should "empty" any InputStream parameter to a
* service method before returning to the client. This is provided as a
* workaround for some servlet containers in order to ensure that if an
* exception is thrown or the service method returns before the InputStream
* parameter is read that the client will not block trying to send the
* remaining InputStream to the server. This means that in the face of an
* exception or early return from a method that the client will still finish
* uploading all of its data before it becomes aware of the situation,
* taking up unnecessary time and bandwidth. Because of this, a better
* solution should be found to this problem in the future. This property
* defaults to <code>false</code>.
*
* @param emptyInputStreamParameterBeforeReturn
*
*
* @see #getEmptyInputStreamParameterBeforeReturn()
*/
public void setEmptyInputStreamParameterBeforeReturn(final boolean emptyInputStreamParameterBeforeReturn)
{
this.emptyInputStreamParameterBeforeReturn = emptyInputStreamParameterBeforeReturn;
}
protected boolean hasStreamResult(final RemoteInvocationResult result)
{
return result instanceof StreamSupportingRemoteInvocationResult &&
((StreamSupportingRemoteInvocationResult)result).getHasReturnStream();
}
protected void doWriteReturnInputStream(final StreamSupportingRemoteInvocationResult result, final OutputStream unbufferedChunkedOut)
throws IOException
{
// We use the unbuffered chunked out with a custom buffer for optimum
// performance - partly because we can't be sure that the returned
// InputStream is itself buffered.
final InputStream isResult = result.getServerSideInputStream();
if(isResult != null) {
try {
final byte[] buffer = new byte[4096];
int read;
while((read = isResult.read(buffer)) != -1) {
unbufferedChunkedOut.write(buffer, 0, read);
}
} finally {
result.setServerSideInputStream(null);
isResult.close();
}
}
}
protected ParameterInputStream getParameterInputStreamFrom(final RemoteInvocation invocation)
{
if(invocation instanceof StreamSupportingRemoteInvocation) {
final StreamSupportingRemoteInvocation ssri = (StreamSupportingRemoteInvocation)invocation;
if(ssri.getInputStreamParam() >= 0 && !ssri.isInputStreamParamNull()) {
return (ParameterInputStream)ssri.getArguments()[ssri.getInputStreamParam()];
}
}
return null;
}
protected Boolean getParameterInputStreamClosedFlag(final RemoteInvocation invocation)
{
final ParameterInputStream pi = getParameterInputStreamFrom(invocation);
if(pi != null) {
return pi.isClosed() ? Boolean.TRUE : Boolean.FALSE;
} else {
return null;
}
}
/**
* Shields an underlying OutputStream from being closed.
*/
public static class CloseShieldedOutputStream extends FilterOutputStream
{
public CloseShieldedOutputStream(final OutputStream out)
{
super(out);
}
public void close() throws IOException
{
flush();
}
}
/**
* Tracks if an InputStream parameter is closed by a service method, if
* any input method threw an exception during operation, and if the
* service method read the InputStream to the end-of-stream. Also provides
* the ability to optionally read an InputStream to end-of-stream if the
* service method did not.
*/
public static class ParameterInputStream extends FilterInputStream
{
private boolean fullyRead = false;
private boolean erroredOut = false;
private boolean closed = false;
public ParameterInputStream(final InputStream in)
{
super(in);
}
public boolean isFullyRead()
{
return this.fullyRead;
}
public boolean isErroredOut()
{
return this.erroredOut;
}
public boolean isClosed()
{
return this.closed;
}
public void doRealClose(final boolean emptyStream) throws IOException
{
if(!isClosed()) {
if(log.isDebugEnabled()) log.debug("Service method failed to close InputStream parameter from remote invocation. Will perform the close anyway.");
}
if(!isFullyRead() && emptyStream && !isErroredOut()) {
final byte[] buf = new byte[4096];
//noinspection StatementWithEmptyBody
while(read(buf) != -1) ;
}
super.close();
}
protected int checkEos(final int read)
{
if(read == -1) {
this.fullyRead = true;
}
return read;
}
protected IOException checkException(final IOException ioe)
{
this.erroredOut = true;
return ioe;
}
protected void assertOpen() throws IOException
{
if(this.closed) {
throw new IOException("Stream closed");
}
}
//
// METHODS FROM CLASS FilterInputStream
//
public int read() throws IOException
{
assertOpen();
try {
return checkEos(super.read());
} catch(IOException e) {
throw checkException(e);
}
}
public int read(byte b[]) throws IOException
{
assertOpen();
try {
return checkEos(super.read(b));
} catch(IOException e) {
throw checkException(e);
}
}
public int read(byte b[], int off, int len) throws IOException
{
assertOpen();
try {
return checkEos(super.read(b, off, len));
} catch(IOException e) {
throw checkException(e);
}
}
public long skip(long n) throws IOException
{
assertOpen();
try {
return super.skip(n);
} catch(IOException e) {
throw checkException(e);
}
}
public int available() throws IOException
{
assertOpen();
try {
return super.available();
} catch(IOException e) {
throw checkException(e);
}
}
public void close() throws IOException
{
// Close will happen later.
this.closed = true;
}
}
}
| true | true | protected RemoteInvocationResult invokeAndCreateResult(final RemoteInvocation invocation, final Object targetObject)
{
try {
final Object value = invoke(invocation, targetObject);
if(invocation instanceof StreamSupportingRemoteInvocation) {
final Boolean closedInputStreamParam = getParameterInputStreamClosedFlag(invocation);
if(value instanceof InputStream) {
return new StreamSupportingRemoteInvocationResult((InputStream)value, closedInputStreamParam);
} else {
return new StreamSupportingRemoteInvocationResult(value, closedInputStreamParam);
}
} else {
return new RemoteInvocationResult(value);
}
} catch (Throwable ex) {
if(invocation instanceof StreamSupportingRemoteInvocation) {
return new StreamSupportingRemoteInvocationResult(ex, getParameterInputStreamClosedFlag(invocation));
} else {
return new RemoteInvocationResult(ex);
}
} finally {
final ParameterInputStream pi = getParameterInputStreamFrom(invocation);
if(pi != null) {
try {
pi.doRealClose(getEmptyInputStreamParameterBeforeReturn());
} catch(IOException e) {
log.warn("Error while attempting to close InputStream parameter for RemoteInvocation '" + invocation + "'", e);
}
}
}
}
| protected RemoteInvocationResult invokeAndCreateResult(final RemoteInvocation invocation, final Object targetObject)
{
try {
final Object value = invoke(invocation, targetObject);
if(invocation instanceof StreamSupportingRemoteInvocation) {
final Boolean closedInputStreamParam = getParameterInputStreamClosedFlag(invocation);
if(value instanceof InputStream) {
return new StreamSupportingRemoteInvocationResult((InputStream)value, closedInputStreamParam);
} else {
return new StreamSupportingRemoteInvocationResult(value, closedInputStreamParam);
}
} else {
return new RemoteInvocationResult(value);
}
} catch (Throwable ex) {
if(invocation instanceof StreamSupportingRemoteInvocation) {
return new StreamSupportingRemoteInvocationResult(ex, getParameterInputStreamClosedFlag(invocation));
} else {
if(log.isWarnEnabled()){
log.warn(ex.getCause().getMessage());
}
if(log.isDebugEnabled()){
log.debug(ex);
}
return new RemoteInvocationResult(new Exception(ex.getMessage()));
}
} finally {
final ParameterInputStream pi = getParameterInputStreamFrom(invocation);
if(pi != null) {
try {
pi.doRealClose(getEmptyInputStreamParameterBeforeReturn());
} catch(IOException e) {
log.warn("Error while attempting to close InputStream parameter for RemoteInvocation '" + invocation + "'", e);
}
}
}
}
|
diff --git a/common/src/org/bedework/synch/SynchEngine.java b/common/src/org/bedework/synch/SynchEngine.java
index a0b4cad..bfaf5ff 100644
--- a/common/src/org/bedework/synch/SynchEngine.java
+++ b/common/src/org/bedework/synch/SynchEngine.java
@@ -1,878 +1,878 @@
/* ********************************************************************
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig 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.bedework.synch;
import org.bedework.http.client.dav.DavClient;
import org.bedework.synch.cnctrs.Connector;
import org.bedework.synch.cnctrs.Connector.NotificationBatch;
import org.bedework.synch.cnctrs.ConnectorInstance;
import org.bedework.synch.db.ConnectorConfig;
import org.bedework.synch.db.Subscription;
import org.bedework.synch.db.SynchConfig;
import org.bedework.synch.db.SynchDb;
import org.bedework.synch.exception.SynchException;
import org.bedework.synch.wsmessages.SynchEndType;
import edu.rpi.cmt.calendar.XcalUtil.TzGetter;
import edu.rpi.cmt.security.PwEncryptionIntf;
import edu.rpi.cmt.timezones.Timezones;
import edu.rpi.cmt.timezones.TimezonesImpl;
import edu.rpi.sss.util.Util;
import net.fortuna.ical4j.model.TimeZone;
import org.apache.log4j.Logger;
import org.oasis_open.docs.ws_calendar.ns.soap.StatusType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/** Synch processor.
* <p>The synch processor manages subscriptions made by a subscriber to a target.
* Such a subscription might be one way or two way.
*
* <p>There are two ends to a subscription handled by connectors. The connectors
* implement a standard interface which provides sufficient information for the
* synch process.
*
* <p>Synchronization is triggered either when a change takes place - through
* some sort of push-notification or periodically.
*
* <p>For example, we might have a one way subscription from bedework to
* exchange. Exchange will post notifications to the synch engine which will
* then resynch the modified entity.
*
* <p>Alternatively we might have a subscription to a file which we refresh each
* day at 4am.
*
* <p>A subscription may be in the following states:<ul>
* <li>dormant - that is there is no current activity, for
* example a file subscription with a periodic update,</li>
* <li>active - there is some active connection associated with it, for example,
* an Exchange push subscription waiting for a notification</li>
* <li>processing - for example, an Exchange push subscription which is
* processing a notification</li>
* <li>unsubscribing - the user has asked to unsubscribe but there is some
* activity we are waiting for<li>
* </ul>
*
* <p>Interactions with the calendars is carried out through an interface which
* assumes the CalWs-SOAP protocol. Messages and responses are of that form
* though the actual implementation may not use the protocol if the target does
* not support it. For example we convert CalWs-SOAP interactions into ExchangeWS.
*
* --------------------- ignore below ----------------------------------------
*
* <p>This process manages the setting up of push-subscriptions with the exchange
* service and provides support for the resulting call-back from Exchange. There
* will be one instance of this object to handle the tables we create and
* manipulate.
*
* <p>There will be multiple threads calling the various methods. Push
* subscriptions work more or less as follows:<ul>
* <li>Subscribe to exchange giving a url to call back to. Set a refresh period</li>
* <li>Exchange calls back even if there is no change - effectively polling us</li>
* <li>If we don't respond Exchange doubles the wait period and tries again</li>
* <li>Repeats that a few times then gives up</li>
* <li>If we do respond will call again at the specified rate</li>
* <li>No unsubscribe - wait for a ping then respond with unsubscribe</li>
* </ul>
*
* <p>At startup we ask for the back end system to tell us what the subscription
* are and we spend some time setting those up.
*
* <p>We also provide a way for the system to tell us about new (un)subscribe
* requests. While starting up we need to queue these as they may be unsubscribes
* for a subscribe in the startup list.
*
* <p>Shutdown ought to wait for the remote systems to ping us for every outstanding
* subscription. That ought to be fairly quick.
*
* @author Mike Douglass
*/
public class SynchEngine extends TzGetter {
protected transient Logger log;
private final boolean debug;
private static String appname = "Synch";
private transient PwEncryptionIntf pwEncrypt;
/* Map of currently active notification subscriptions. These are subscriptions
* for which we get change messages from the remote system(s).
*/
private final Map<String, Subscription> activeSubs =
new HashMap<String, Subscription>();
private boolean starting;
private boolean running;
private boolean stopping;
private Configurator config;
private static Object getSyncherLock = new Object();
private static SynchEngine syncher;
private Timezones timezones;
static TzGetter tzgetter;
private SynchlingPool synchlingPool;
private SynchTimer synchTimer;
private BlockingQueue<Notification> notificationInQueue;
/* Where we keep subscriptions that come in while we are starting */
private List<Subscription> subsList;
private SynchDb db;
private Map<String, Connector> connectorMap = new HashMap<String, Connector>();
/* Some counts */
private StatLong notificationsCt = new StatLong("notifications");
private StatLong notificationsAddWt = new StatLong("notifications add wait");
/** This process handles startup notifications and (un)subscriptions.
*
*/
private class NotificationInThread extends Thread {
long lastTrace;
/**
*/
public NotificationInThread() {
super("NotifyIn");
}
@Override
public void run() {
while (true) {
if (debug) {
trace("About to wait for notification");
}
try {
Notification note = notificationInQueue.take();
if (note == null) {
continue;
}
if (debug) {
trace("Received notification");
}
if ((note.getSub() != null) && note.getSub().getDeleted()) {
// Drop it
if (debug) {
trace("Dropping deleted notification");
}
continue;
}
notificationsCt.inc();
Synchling sl = null;
try {
/* Get a synchling from the pool */
while (true) {
if (stopping) {
return;
}
sl = synchlingPool.getNoException();
if (sl != null) {
break;
}
}
/* The synchling needs to be running it's own thread. */
StatusType st = handleNotification(sl, note);
if (st == StatusType.WARNING) {
/* Back on the queue - these need to be flagged so we don't get an
* endless loop - perhaps we need a delay queue
*/
notificationInQueue.put(note);
}
} finally {
synchlingPool.add(sl);
}
/* If this is a poll kind then we should add it to a poll queue
*/
// XXX Add it to poll queue
} catch (InterruptedException ie) {
warn("Notification handler shutting down");
break;
} catch (Throwable t) {
if (debug) {
error(t);
} else {
// Try not to flood the log with error traces
long now = System.currentTimeMillis();
if ((now - lastTrace) > (30 * 1000)) {
error(t);
lastTrace = now;
} else {
error(t.getMessage());
}
}
}
}
}
}
private static NotificationInThread notifyInHandler;
/** Constructor
*
* @param exintf
*/
private SynchEngine() throws SynchException {
debug = getLogger().isDebugEnabled();
System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump",
String.valueOf(debug));
}
/**
* @return the syncher
* @throws SynchException
*/
public static SynchEngine getSyncher() throws SynchException {
if (syncher != null) {
return syncher;
}
synchronized (getSyncherLock) {
if (syncher != null) {
return syncher;
}
syncher = new SynchEngine();
return syncher;
}
}
/** Set before calling getSyncher
*
* @param val
*/
public static void setAppname(final String val) {
appname = val;
}
/**
* @return appname
*/
public static String getAppname() {
return appname;
}
/** Get a timezone object given the id. This will return transient objects
* registered in the timezone directory
*
* @param id
* @return TimeZone with id or null
* @throws Throwable
*/
@Override
public TimeZone getTz(final String id) throws Throwable {
return getSyncher().timezones.getTimeZone(id);
}
/**
* @return a getter for timezones
*/
public static TzGetter getTzGetter() {
return tzgetter;
}
/** Start synch process.
*
* @throws SynchException
*/
public void start() throws SynchException {
try {
if (starting || running) {
warn("Start called when already starting or running");
return;
}
synchronized (this) {
subsList = null;
starting = true;
}
db = new SynchDb();
config = new Configurator(db);
timezones = new TimezonesImpl();
timezones.init(config.getSynchConfig().getTimezonesURI());
tzgetter = this;
- DavClient.setDefaultMaxPerHost(20);
+ //DavClient.setDefaultMaxPerHost(20);
DavClient.setDefaultMaxPerRoute(20);
synchlingPool = new SynchlingPool();
synchlingPool.start(this,
config.getSynchConfig().getSynchlingPoolSize(),
config.getSynchConfig().getSynchlingPoolTimeout());
notificationInQueue = new ArrayBlockingQueue<Notification>(100);
info("**************************************************");
info("Starting synch");
info(" callback URI: " + config.getSynchConfig().getCallbackURI());
info("**************************************************");
if (config.getSynchConfig().getKeystore() != null) {
System.setProperty("javax.net.ssl.trustStore", config.getSynchConfig().getKeystore());
System.setProperty("javax.net.ssl.trustStorePassword", "bedework");
}
Set<ConnectorConfig> connectors = config.getSynchConfig().getConnectors();
String callbackUriBase = config.getSynchConfig().getCallbackURI();
/* Register the connectors and start them */
for (ConnectorConfig conf: connectors) {
String cnctrId = conf.getName();
info("Register and start connector " + cnctrId);
registerConnector(cnctrId, conf);
Connector conn = getConnector(cnctrId);
conn.start(cnctrId,
conf,
callbackUriBase + cnctrId + "/",
this);
while (!conn.isStarted()) {
/* Wait for it to start */
synchronized (this) {
this.wait(250);
}
if (conn.isFailed()) {
error("Connector " + cnctrId + " failed to start");
break;
}
}
}
synchTimer = new SynchTimer(this);
/* Get the list of subscriptions from our database and process them.
* While starting, new subscribe requests get added to the list.
*/
notifyInHandler = new NotificationInThread();
notifyInHandler.start();
try {
db.open();
List<Subscription> startList = db.getAll();
db.close();
startup:
while (starting) {
if (debug) {
trace("startList has " + startList.size() + " subscriptions");
}
for (Subscription sub: startList) {
setConnectors(sub);
reschedule(sub);
}
synchronized (this) {
if (subsList == null) {
// Nothing came in as we started
starting = false;
if (stopping) {
break startup;
}
running = true;
break;
}
startList = subsList;
subsList = null;
}
}
} finally {
if ((db != null) && db.isOpen()) {
db.close();
}
}
info("**************************************************");
info("Synch started");
info("**************************************************");
} catch (SynchException se) {
error(se);
starting = false;
running = false;
throw se;
} catch (Throwable t) {
error(t);
starting = false;
running = false;
throw new SynchException(t);
}
}
/** Reschedule a subscription for updates.
*
* @param sub
* @throws SynchException
*/
public void reschedule(final Subscription sub) throws SynchException {
if (debug) {
trace("reschedule subscription " + sub);
}
if (sub.polling()) {
synchTimer.schedule(sub, sub.nextRefresh());
return;
}
// XXX start up the add to active subs
activeSubs.put(sub.getSubscriptionId(), sub);
}
/**
* @return true if we're running
*/
public boolean getRunning() {
return running;
}
/**
* @return stats for synch service bean
*/
public List<Stat> getStats() {
List<Stat> stats = new ArrayList<Stat>();
stats.addAll(synchlingPool.getStats());
stats.addAll(synchTimer.getStats());
stats.add(notificationsCt);
stats.add(notificationsAddWt);
return stats;
}
/** Stop synch process.
*
*/
public void stop() {
if (stopping) {
return;
}
stopping = true;
/* Call stop on each connector
*/
for (Connector conn: getConnectors()) {
info("Stopping connector " + conn.getId());
try {
conn.stop();
} catch (Throwable t) {
if (debug) {
error(t);
} else {
error(t.getMessage());
}
}
}
info("Connectors stopped");
if (synchlingPool != null) {
synchlingPool.stop();
}
syncher = null;
info("**************************************************");
info("Synch shutdown complete");
info("**************************************************");
}
/**
* @param note
* @throws SynchException
*/
public void handleNotification(final Notification note) throws SynchException {
try {
while (true) {
if (stopping) {
return;
}
if (notificationInQueue.offer(note, 5, TimeUnit.SECONDS)) {
break;
}
}
} catch (InterruptedException ie) {
}
}
/**
* @return config object
* @throws SynchException
*/
public SynchConfig getConfig() throws SynchException {
return config.getSynchConfig();
}
/**
* @throws SynchException
*/
public void updateConfig() throws SynchException {
config.updateSynchConfig();
}
/**
* @param val
* @return decrypted string
* @throws SynchException
*/
public String decrypt(final String val) throws SynchException {
try {
return getEncrypter().decrypt(val);
} catch (SynchException se) {
throw se;
} catch (Throwable t) {
throw new SynchException(t);
}
}
/**
* @return en/decryptor
* @throws SynchException
*/
public PwEncryptionIntf getEncrypter() throws SynchException {
if (pwEncrypt != null) {
return pwEncrypt;
}
try {
String pwEncryptClass = "edu.rpi.cmt.security.PwEncryptionDefault";
//String pwEncryptClass = getSysparsHandler().get().getPwEncryptClass();
pwEncrypt = (PwEncryptionIntf)Util.getObject(pwEncryptClass,
PwEncryptionIntf.class);
pwEncrypt.init(config.getSynchConfig().getPrivKeys(),
config.getSynchConfig().getPubKeys());
return pwEncrypt;
} catch (SynchException se) {
throw se;
} catch (Throwable t) {
t.printStackTrace();
throw new SynchException(t);
}
}
/** Gets an instance and implants it in the subscription object.
* @param sub
* @param end
* @return ConnectorInstance or throws Exception
* @throws SynchException
*/
public ConnectorInstance getConnectorInstance(final Subscription sub,
final SynchEndType end) throws SynchException {
ConnectorInstance cinst;
Connector conn;
if (end == SynchEndType.A) {
cinst = sub.getEndAConnInst();
conn = sub.getEndAConn();
} else {
cinst = sub.getEndBConnInst();
conn = sub.getEndBConn();
}
if (cinst != null) {
return cinst;
}
if (conn == null) {
throw new SynchException("No connector for " + sub + "(" + end + ")");
}
cinst = conn.getConnectorInstance(sub, end);
if (cinst == null) {
throw new SynchException("No connector instance for " + sub +
"(" + end + ")");
}
if (end == SynchEndType.A) {
sub.setEndAConnInst(cinst);
} else {
sub.setEndBConnInst(cinst);
}
return cinst;
}
/** When we start up a new subscription we implant a Connector in the object.
*
* @param sub
* @throws SynchException
*/
public void setConnectors(final Subscription sub) throws SynchException {
String connectorId = sub.getEndAConnectorInfo().getConnectorId();
Connector conn = getConnector(connectorId);
if (conn == null) {
throw new SynchException("No connector for " + sub + "(" +
SynchEndType.A + ")");
}
sub.setEndAConn(conn);
connectorId = sub.getEndBConnectorInfo().getConnectorId();
conn = getConnector(connectorId);
if (conn == null) {
throw new SynchException("No connector for " + sub + "(" +
SynchEndType.B + ")");
}
sub.setEndBConn(conn);
}
private Collection<Connector> getConnectors() {
return connectorMap.values();
}
/** Return a registered connector with the given id.
*
* @param id
* @return connector or null.
*/
public Connector getConnector(final String id) {
return connectorMap.get(id);
}
/**
* @return registered ids.
*/
public Set<String> getConnectorIds() {
return connectorMap.keySet();
}
private void registerConnector(final String id,
final ConnectorConfig conf) throws SynchException {
try {
Class cl = Class.forName(conf.getClassName());
if (connectorMap.containsKey(id)) {
throw new SynchException("Connector " + id + " already registered");
}
Connector c = (Connector)cl.newInstance();
connectorMap.put(id, c);
} catch (Throwable t) {
throw new SynchException(t);
}
}
/** Processes a batch of notifications. This must be done in a timely manner
* as a request is usually hanging on this.
*
* @param notes
* @throws SynchException
*/
public void handleNotifications(
final NotificationBatch<Notification> notes) throws SynchException {
for (Notification note: notes.getNotifications()) {
db.open();
Synchling sl = null;
try {
if (note.getSub() != null) {
sl = synchlingPool.get();
handleNotification(sl, note);
}
} finally {
db.close();
if (sl != null) {
synchlingPool.add(sl);
}
}
}
return;
}
@SuppressWarnings("unchecked")
private StatusType handleNotification(final Synchling sl,
final Notification note) throws SynchException {
StatusType st = sl.handleNotification(note);
Subscription sub = note.getSub();
if (!sub.getMissingTarget()) {
return st;
}
if (sub.getErrorCt() > config.getSynchConfig().getMissingTargetRetries()) {
deleteSubscription(sub);
info("Subscription deleted after missing target retries exhausted: " + sub);
}
return st;
}
/* ====================================================================
* db methods
* ==================================================================== */
/**
* @param id
* @return subscription
* @throws SynchException
*/
public Subscription getSubscription(final String id) throws SynchException {
boolean opened = db.open();
try {
return db.get(id);
} finally {
if (opened) {
// It's a one-shot
db.close();
}
}
}
/**
* @param sub
* @throws SynchException
*/
public void addSubscription(final Subscription sub) throws SynchException {
db.add(sub);
sub.resetChanged();
}
/**
* @param sub
* @throws SynchException
*/
public void updateSubscription(final Subscription sub) throws SynchException {
boolean opened = db.open();
try {
db.update(sub);
sub.resetChanged();
} finally {
if (opened) {
// It's a one-shot
db.close();
}
}
}
/**
* @param sub
* @throws SynchException
*/
public void deleteSubscription(final Subscription sub) throws SynchException {
db.delete(sub);
}
/** Find any subscription that matches this one. There can only be one with
* the same endpoints
*
* @param sub
* @return matching subscriptions
* @throws SynchException
*/
public Subscription find(final Subscription sub) throws SynchException {
boolean opened = db.open();
try {
return db.find(sub);
} finally {
if (opened) {
// It's a one-shot
db.close();
}
}
}
/* ====================================================================
* private methods
* ==================================================================== */
private Logger getLogger() {
if (log == null) {
log = Logger.getLogger(this.getClass());
}
return log;
}
private void trace(final String msg) {
getLogger().debug(msg);
}
private void warn(final String msg) {
getLogger().warn(msg);
}
private void error(final String msg) {
getLogger().error(msg);
}
private void error(final Throwable t) {
getLogger().error(this, t);
}
private void info(final String msg) {
getLogger().info(msg);
}
}
| true | true | public void start() throws SynchException {
try {
if (starting || running) {
warn("Start called when already starting or running");
return;
}
synchronized (this) {
subsList = null;
starting = true;
}
db = new SynchDb();
config = new Configurator(db);
timezones = new TimezonesImpl();
timezones.init(config.getSynchConfig().getTimezonesURI());
tzgetter = this;
DavClient.setDefaultMaxPerHost(20);
DavClient.setDefaultMaxPerRoute(20);
synchlingPool = new SynchlingPool();
synchlingPool.start(this,
config.getSynchConfig().getSynchlingPoolSize(),
config.getSynchConfig().getSynchlingPoolTimeout());
notificationInQueue = new ArrayBlockingQueue<Notification>(100);
info("**************************************************");
info("Starting synch");
info(" callback URI: " + config.getSynchConfig().getCallbackURI());
info("**************************************************");
if (config.getSynchConfig().getKeystore() != null) {
System.setProperty("javax.net.ssl.trustStore", config.getSynchConfig().getKeystore());
System.setProperty("javax.net.ssl.trustStorePassword", "bedework");
}
Set<ConnectorConfig> connectors = config.getSynchConfig().getConnectors();
String callbackUriBase = config.getSynchConfig().getCallbackURI();
/* Register the connectors and start them */
for (ConnectorConfig conf: connectors) {
String cnctrId = conf.getName();
info("Register and start connector " + cnctrId);
registerConnector(cnctrId, conf);
Connector conn = getConnector(cnctrId);
conn.start(cnctrId,
conf,
callbackUriBase + cnctrId + "/",
this);
while (!conn.isStarted()) {
/* Wait for it to start */
synchronized (this) {
this.wait(250);
}
if (conn.isFailed()) {
error("Connector " + cnctrId + " failed to start");
break;
}
}
}
synchTimer = new SynchTimer(this);
/* Get the list of subscriptions from our database and process them.
* While starting, new subscribe requests get added to the list.
*/
notifyInHandler = new NotificationInThread();
notifyInHandler.start();
try {
db.open();
List<Subscription> startList = db.getAll();
db.close();
startup:
while (starting) {
if (debug) {
trace("startList has " + startList.size() + " subscriptions");
}
for (Subscription sub: startList) {
setConnectors(sub);
reschedule(sub);
}
synchronized (this) {
if (subsList == null) {
// Nothing came in as we started
starting = false;
if (stopping) {
break startup;
}
running = true;
break;
}
startList = subsList;
subsList = null;
}
}
} finally {
if ((db != null) && db.isOpen()) {
db.close();
}
}
info("**************************************************");
info("Synch started");
info("**************************************************");
} catch (SynchException se) {
error(se);
starting = false;
running = false;
throw se;
} catch (Throwable t) {
error(t);
starting = false;
running = false;
throw new SynchException(t);
}
}
| public void start() throws SynchException {
try {
if (starting || running) {
warn("Start called when already starting or running");
return;
}
synchronized (this) {
subsList = null;
starting = true;
}
db = new SynchDb();
config = new Configurator(db);
timezones = new TimezonesImpl();
timezones.init(config.getSynchConfig().getTimezonesURI());
tzgetter = this;
//DavClient.setDefaultMaxPerHost(20);
DavClient.setDefaultMaxPerRoute(20);
synchlingPool = new SynchlingPool();
synchlingPool.start(this,
config.getSynchConfig().getSynchlingPoolSize(),
config.getSynchConfig().getSynchlingPoolTimeout());
notificationInQueue = new ArrayBlockingQueue<Notification>(100);
info("**************************************************");
info("Starting synch");
info(" callback URI: " + config.getSynchConfig().getCallbackURI());
info("**************************************************");
if (config.getSynchConfig().getKeystore() != null) {
System.setProperty("javax.net.ssl.trustStore", config.getSynchConfig().getKeystore());
System.setProperty("javax.net.ssl.trustStorePassword", "bedework");
}
Set<ConnectorConfig> connectors = config.getSynchConfig().getConnectors();
String callbackUriBase = config.getSynchConfig().getCallbackURI();
/* Register the connectors and start them */
for (ConnectorConfig conf: connectors) {
String cnctrId = conf.getName();
info("Register and start connector " + cnctrId);
registerConnector(cnctrId, conf);
Connector conn = getConnector(cnctrId);
conn.start(cnctrId,
conf,
callbackUriBase + cnctrId + "/",
this);
while (!conn.isStarted()) {
/* Wait for it to start */
synchronized (this) {
this.wait(250);
}
if (conn.isFailed()) {
error("Connector " + cnctrId + " failed to start");
break;
}
}
}
synchTimer = new SynchTimer(this);
/* Get the list of subscriptions from our database and process them.
* While starting, new subscribe requests get added to the list.
*/
notifyInHandler = new NotificationInThread();
notifyInHandler.start();
try {
db.open();
List<Subscription> startList = db.getAll();
db.close();
startup:
while (starting) {
if (debug) {
trace("startList has " + startList.size() + " subscriptions");
}
for (Subscription sub: startList) {
setConnectors(sub);
reschedule(sub);
}
synchronized (this) {
if (subsList == null) {
// Nothing came in as we started
starting = false;
if (stopping) {
break startup;
}
running = true;
break;
}
startList = subsList;
subsList = null;
}
}
} finally {
if ((db != null) && db.isOpen()) {
db.close();
}
}
info("**************************************************");
info("Synch started");
info("**************************************************");
} catch (SynchException se) {
error(se);
starting = false;
running = false;
throw se;
} catch (Throwable t) {
error(t);
starting = false;
running = false;
throw new SynchException(t);
}
}
|
diff --git a/ui-fw/src/main/java/org/intalio/tempo/uiframework/actions/TasksAction.java b/ui-fw/src/main/java/org/intalio/tempo/uiframework/actions/TasksAction.java
index 1bf573a1..47a9edd0 100644
--- a/ui-fw/src/main/java/org/intalio/tempo/uiframework/actions/TasksAction.java
+++ b/ui-fw/src/main/java/org/intalio/tempo/uiframework/actions/TasksAction.java
@@ -1,158 +1,159 @@
/**
* Copyright (c) 2005-2006 Intalio 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
*
* Contributors:
* Intalio inc. - initial API and implementation
*
* $Id: XFormsManager.java 2764 2006-03-16 18:34:41Z ozenzin $
* $Log:$
*/
package org.intalio.tempo.uiframework.actions;
import java.net.URISyntaxException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import org.intalio.tempo.uiframework.Configuration;
import org.intalio.tempo.uiframework.Constants;
import org.intalio.tempo.uiframework.UIFWApplicationState;
import org.intalio.tempo.uiframework.URIUtils;
import org.intalio.tempo.uiframework.forms.FormManager;
import org.intalio.tempo.uiframework.forms.FormManagerBroker;
import org.intalio.tempo.uiframework.model.TaskHolder;
import org.intalio.tempo.web.ApplicationState;
import org.intalio.tempo.web.controller.Action;
import org.intalio.tempo.web.controller.ActionError;
import org.intalio.tempo.workflow.auth.AuthException;
import org.intalio.tempo.workflow.task.Notification;
import org.intalio.tempo.workflow.task.PATask;
import org.intalio.tempo.workflow.task.PIPATask;
import org.intalio.tempo.workflow.task.Task;
import org.intalio.tempo.workflow.task.TaskState;
import org.intalio.tempo.workflow.tms.ITaskManagementService;
import org.intalio.tempo.workflow.tms.client.RemoteTMSFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
@SuppressWarnings("unchecked")
public class TasksAction extends Action {
private static final Logger _log = LoggerFactory.getLogger(TasksAction.class);
private final Collection<Task> _tasks = new ArrayList<Task>();
private final Collection<TaskHolder<PATask>> _activityTasks = new ArrayList<TaskHolder<PATask>>();
private final Collection<TaskHolder<Notification>> _notifications = new ArrayList<TaskHolder<Notification>>();
private final Collection<TaskHolder<PIPATask>> _initTasks = new ArrayList<TaskHolder<PIPATask>>();
private void initLists() throws RemoteException, AuthException {
_log.info("Parsing task list for UI-FW");
FormManager fmanager = FormManagerBroker.getInstance().getFormManager();
String peopleActivityUrl = resoleUrl(fmanager.getPeopleActivityURL());
String notificationURL = resoleUrl(fmanager.getNotificationURL());
String peopleInitiatedProcessURL = resoleUrl(fmanager.getPeopleInitiatedProcessURL());
for (Object task : _tasks) {
+ _log.info(((Task)task).getID() + ":"+ task.getClass().getName());
if (task instanceof Notification) {
Notification notification = (Notification) task;
if (!TaskState.COMPLETED.equals(notification.getState())) {
_notifications.add(new TaskHolder<Notification>(notification, notificationURL));
}
} else if (task instanceof PATask) {
PATask paTask = (PATask) task;
if (!TaskState.COMPLETED.equals(paTask.getState())) {
_activityTasks.add(new TaskHolder<PATask>(paTask, peopleActivityUrl));
}
} else if (task instanceof PIPATask) {
PIPATask pipaTask = (PIPATask) task;
_initTasks.add(new TaskHolder<PIPATask>(pipaTask, peopleInitiatedProcessURL));
} else {
_log.info("Ignoring task of class:" + task.getClass().getName());
}
}
}
private String resoleUrl(String url) {
try {
url = URIUtils.resolveURI(_request, url);
if (_log.isDebugEnabled())
_log.debug("Found URL:" + url);
} catch (URISyntaxException ex) {
_log.error("Invalid URL for peopleActivityUrl", ex);
}
return url;
}
protected ITaskManagementService getTMS(String participantToken) throws RemoteException {
String endpoint = resoleUrl(Configuration.getInstance().getServiceEndpoint());
return new RemoteTMSFactory(endpoint, participantToken).getService();
}
protected String getParticipantToken() {
ApplicationState state = ApplicationState.getCurrentInstance(_request);
return state.getCurrentUser().getToken();
}
public void retrieveTasks() {
try {
String pToken = getParticipantToken();
ITaskManagementService taskManager = getTMS(pToken);
if (_log.isDebugEnabled()) {
_log.debug("Try to get Task List for participant token " + pToken);
}
Task[] tasks = taskManager.getTaskList();
if (_log.isDebugEnabled()) {
_log.debug("Task list of size " + tasks.length + " is retrieved for participant token " + pToken);
}
_tasks.addAll(Arrays.asList(tasks));
} catch (Exception ex) {
_errors.add(new ActionError(-1, null, "com_intalio_bpms_workflow_tasks_retrieve_error", null, ActionError
.getStackTrace(ex), null, null));
_log.error("Error while retrieving task list", ex);
}
}
@Override
public ModelAndView execute() {
retrieveTasks();
try {
initLists();
} catch (Exception ex) {
_log.error("Error during TasksAction execute()", ex);
}
String updateFlag = _request.getParameter("update");
// udateFlag==true -> auto update
if (updateFlag != null && updateFlag.equals("true")) {
return new ModelAndView("updates", createModel());
} else {
return new ModelAndView(Constants.TASKS_VIEW, createModel());
}
}
public ModelAndView getErrorView() {
return new ModelAndView(Constants.TASKS_VIEW, createModel());
}
protected void fillModel(Map model) {
super.fillModel(model);
UIFWApplicationState state = ApplicationState.getCurrentInstance(_request);
model.put("activityTasks", _activityTasks);
model.put("notifications", _notifications);
model.put("initTasks", _initTasks);
model.put("participantToken", state.getCurrentUser().getToken());
model.put("currentUser", state.getCurrentUser().getName());
}
}
| true | true | private void initLists() throws RemoteException, AuthException {
_log.info("Parsing task list for UI-FW");
FormManager fmanager = FormManagerBroker.getInstance().getFormManager();
String peopleActivityUrl = resoleUrl(fmanager.getPeopleActivityURL());
String notificationURL = resoleUrl(fmanager.getNotificationURL());
String peopleInitiatedProcessURL = resoleUrl(fmanager.getPeopleInitiatedProcessURL());
for (Object task : _tasks) {
if (task instanceof Notification) {
Notification notification = (Notification) task;
if (!TaskState.COMPLETED.equals(notification.getState())) {
_notifications.add(new TaskHolder<Notification>(notification, notificationURL));
}
} else if (task instanceof PATask) {
PATask paTask = (PATask) task;
if (!TaskState.COMPLETED.equals(paTask.getState())) {
_activityTasks.add(new TaskHolder<PATask>(paTask, peopleActivityUrl));
}
} else if (task instanceof PIPATask) {
PIPATask pipaTask = (PIPATask) task;
_initTasks.add(new TaskHolder<PIPATask>(pipaTask, peopleInitiatedProcessURL));
} else {
_log.info("Ignoring task of class:" + task.getClass().getName());
}
}
}
| private void initLists() throws RemoteException, AuthException {
_log.info("Parsing task list for UI-FW");
FormManager fmanager = FormManagerBroker.getInstance().getFormManager();
String peopleActivityUrl = resoleUrl(fmanager.getPeopleActivityURL());
String notificationURL = resoleUrl(fmanager.getNotificationURL());
String peopleInitiatedProcessURL = resoleUrl(fmanager.getPeopleInitiatedProcessURL());
for (Object task : _tasks) {
_log.info(((Task)task).getID() + ":"+ task.getClass().getName());
if (task instanceof Notification) {
Notification notification = (Notification) task;
if (!TaskState.COMPLETED.equals(notification.getState())) {
_notifications.add(new TaskHolder<Notification>(notification, notificationURL));
}
} else if (task instanceof PATask) {
PATask paTask = (PATask) task;
if (!TaskState.COMPLETED.equals(paTask.getState())) {
_activityTasks.add(new TaskHolder<PATask>(paTask, peopleActivityUrl));
}
} else if (task instanceof PIPATask) {
PIPATask pipaTask = (PIPATask) task;
_initTasks.add(new TaskHolder<PIPATask>(pipaTask, peopleInitiatedProcessURL));
} else {
_log.info("Ignoring task of class:" + task.getClass().getName());
}
}
}
|
diff --git a/app/controllers/Organismes.java b/app/controllers/Organismes.java
index 12c5ef2..d50d353 100644
--- a/app/controllers/Organismes.java
+++ b/app/controllers/Organismes.java
@@ -1,258 +1,259 @@
package controllers;
import models.*;
import notifier.Mails;
import play.Logger;
import play.data.validation.Required;
import play.data.validation.Valid;
import play.modules.search.Query;
import play.modules.search.Search;
import play.mvc.Scope;
import java.util.List;
import java.util.Map;
/**
* Controller to manage organisme pages.
*/
public class Organismes extends AbstractController {
/**
* Display the last version of an organisme.
*
* @param id
*/
public static void show(Long id) {
OrganismeMaster master = OrganismeMaster.findById(id);
notFoundIfNull(master);
Organisme organisme = master.getLastVersion();
render(id, organisme);
}
/**
* Display the organisme form for edition (or creation).
*
* @param id
*/
public static void edit(Long id) {
// only authenticated user can edit
isValidUser();
// retrieve object
Organisme organisme = null;
if (id != null) {
OrganismeMaster master = OrganismeMaster.findById(id);
notFoundIfNull(master);
organisme = master.getLastVersion();
}
// depends objects
List<OrganismeType> types = OrganismeType.findAll();
List<OrganismeActivite> activites = OrganismeActivite.findAll();
List<OrganismeNbSalarie> nbSalaries = OrganismeNbSalarie.findAll();
// render
render(id, organisme, types, activites, nbSalaries);
}
/**
* Save the organisme.
*
* @param id
* @param organisme
*/
public static void save(Long id, @Valid Organisme organisme, @Required Boolean cgu, Boolean participez) {
// only authenticated user can save
isValidUser();
// is it valid ?
if (validation.hasErrors()) {
params.flash();
validation.keep();
edit(id);
}
// retrieve organisme master or create it
OrganismeMaster master = new OrganismeMaster();
if (id != null) {
master = OrganismeMaster.findById(id);
}
else{
master.save();
}
// don't remove the old logo
if(organisme.logo == null){
+ if(master.getLastVersion() != null)
organisme.logo = master.getLastVersion().logo;
}
organisme.master = master;
organisme.save();
master.save();
// send alert for admin
if(!hasAdminRight()){
Mails.organisme(master, getCurrentUser(), participez);
}
// redirect user to show
show(master.id);
}
/**
* Display the history of the organisme.
*
* @param id
*/
public static void history(Long id) {
// only for admin
isAdminUser();
// retrieve organisme master
OrganismeMaster master = OrganismeMaster.findById(id);
notFoundIfNull(master);
render(master);
}
/**
* Display the version of the organisme.
*
* @param id
*/
public static void version(Long id) {
// only for admin
isAdminUser();
// retrive organisme
Organisme organisme = Organisme.findById(id);
notFoundIfNull(organisme);
render("@show", organisme, organisme.master.id);
}
/**
* Compare two version
*
* @param from
* @param to
*/
public static void compare(Long from, Long to) {
// only for admin
isAdminUser();
// retrive organisme
Organisme organismeFrom = Organisme.findById(from);
Organisme organismeTo = Organisme.findById(to);
// depends objects
List<OrganismeType> types = OrganismeType.findAll();
List<OrganismeActivite> activites = OrganismeActivite.findAll();
List<OrganismeNbSalarie> nbSalaries = OrganismeNbSalarie.findAll();
render(organismeFrom, organismeTo, types, activites, nbSalaries);
}
/**
* Produce a RSS of last ten updated/created organisation.
*/
public static void rss() {
List<OrganismeMaster> masters = OrganismeMaster.findAll();
response.contentType = "application/rss+xml";
render(masters);
}
/**
* Produce a CSV of all organisation items.
*/
public static void csv() {
response.contentType = "text/csv";
response.setHeader("Content-Disposition", "attachment;filename=organismes.csv");
renderText(OrganismeMaster.toCsv());
}
/**
* Render the logo of an organisme.
*
* @param id
*/
public static void logo(Long id) {
// retrieve organisme master or create it
OrganismeMaster master = OrganismeMaster.findById(id);
notFoundIfNull(master);
Organisme organisme = master.getLastVersion();
notFoundIfNull(organisme.logo);
response.setContentTypeIfNotSet(organisme.logo.type());
renderBinary(organisme.logo.get());
}
public static void search(String query, List<Long> typologies, List<String> deps, Integer page) {
if(page == null){
page = 1;
}
Map<String, Object> result = OrganismeMaster.search(query, typologies, deps, page);
List<OrganismeMaster> organismes = (List<OrganismeMaster>) result.get(OrganismeMaster.MAP_RESULT_LIST);
Integer nbItems = (Integer) result.get(OrganismeMaster.MAP_RESULT_NB);
Long nbTotal = Long.valueOf(OrganismeMaster.count());
// populate render
List<OrganismeType> types = OrganismeType.findAll();
render(query, typologies, deps, types, organismes, page, nbItems, nbTotal);
}
/**
* Render the admin interface for organisme (list all or search)
*/
public static void admin(String search) {
isAdminUser();
List<OrganismeMaster> organismes = OrganismeMaster.findAll();
render(organismes);
}
/**
* Admin action to delete on organisme.
*
* @param id
*/
public static void delete(Long id) {
isAdminUser();
OrganismeMaster organisme = OrganismeMaster.findById(id);
notFoundIfNull(organisme);
organisme.delete();
admin(null);
}
/**
* Admin action to set partenaire.
*
* @param id
*/
public static void partenaire(Long id, Boolean isPartenaire) {
isAdminUser();
OrganismeMaster organisme = OrganismeMaster.findById(id);
if (isPartenaire) {
organisme.isPartenaire = Boolean.TRUE;
} else {
organisme.isPartenaire = Boolean.FALSE;
}
organisme.save();
admin(null);
}
/**
* View to list all partenaires.
*/
public static void partenaires() {
List<OrganismeMaster> partenaires = OrganismeMaster.getAllPartenaires();
render(partenaires);
}
}
| true | true | public static void save(Long id, @Valid Organisme organisme, @Required Boolean cgu, Boolean participez) {
// only authenticated user can save
isValidUser();
// is it valid ?
if (validation.hasErrors()) {
params.flash();
validation.keep();
edit(id);
}
// retrieve organisme master or create it
OrganismeMaster master = new OrganismeMaster();
if (id != null) {
master = OrganismeMaster.findById(id);
}
else{
master.save();
}
// don't remove the old logo
if(organisme.logo == null){
organisme.logo = master.getLastVersion().logo;
}
organisme.master = master;
organisme.save();
master.save();
// send alert for admin
if(!hasAdminRight()){
Mails.organisme(master, getCurrentUser(), participez);
}
// redirect user to show
show(master.id);
}
| public static void save(Long id, @Valid Organisme organisme, @Required Boolean cgu, Boolean participez) {
// only authenticated user can save
isValidUser();
// is it valid ?
if (validation.hasErrors()) {
params.flash();
validation.keep();
edit(id);
}
// retrieve organisme master or create it
OrganismeMaster master = new OrganismeMaster();
if (id != null) {
master = OrganismeMaster.findById(id);
}
else{
master.save();
}
// don't remove the old logo
if(organisme.logo == null){
if(master.getLastVersion() != null)
organisme.logo = master.getLastVersion().logo;
}
organisme.master = master;
organisme.save();
master.save();
// send alert for admin
if(!hasAdminRight()){
Mails.organisme(master, getCurrentUser(), participez);
}
// redirect user to show
show(master.id);
}
|
diff --git a/src/com/cooliris/media/Gallery.java b/src/com/cooliris/media/Gallery.java
index 0ea80dd..a18e330 100644
--- a/src/com/cooliris/media/Gallery.java
+++ b/src/com/cooliris/media/Gallery.java
@@ -1,441 +1,446 @@
package com.cooliris.media;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.TimeZone;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.MediaStore.Images;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
import android.media.MediaScannerConnection;
import com.cooliris.cache.CacheService;
import com.cooliris.wallpaper.RandomDataSource;
import com.cooliris.wallpaper.Slideshow;
public final class Gallery extends Activity {
public static final TimeZone CURRENT_TIME_ZONE = TimeZone.getDefault();
public static float PIXEL_DENSITY = 0.0f;
public static final int CROP_MSG_INTERNAL = 100;
private static final String TAG = "Gallery";
private static final int CROP_MSG = 10;
private RenderView mRenderView = null;
private GridLayer mGridLayer;
private final Handler mHandler = new Handler();
private ReverseGeocoder mReverseGeocoder;
private boolean mPause;
private MediaScannerConnection mConnection;
private WakeLock mWakeLock;
private HashMap<String, Boolean> mAccountsEnabled = new HashMap<String, Boolean>();
private boolean mDockSlideshow = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final boolean imageManagerHasStorage = ImageManager.hasStorage();
boolean slideshowIntent = false;
if (isViewIntent()) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
slideshowIntent = extras.getBoolean("slideshow", false);
}
}
if (isViewIntent() && getIntent().getData().equals(Images.Media.EXTERNAL_CONTENT_URI)
&& slideshowIntent) {
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
finish();
} else {
Slideshow slideshow = new Slideshow(this);
slideshow.setDataSource(new RandomDataSource());
setContentView(slideshow);
mDockSlideshow = true;
}
return;
}
if (PIXEL_DENSITY == 0.0f) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
PIXEL_DENSITY = metrics.density;
}
mReverseGeocoder = new ReverseGeocoder(this);
mRenderView = new RenderView(this);
mGridLayer = new GridLayer(this, (int) (96.0f * PIXEL_DENSITY), (int) (72.0f * PIXEL_DENSITY), new GridLayoutInterface(4),
mRenderView);
mRenderView.setRootLayer(mGridLayer);
setContentView(mRenderView);
Thread t = new Thread() {
public void run() {
int numRetries = 25;
if (!imageManagerHasStorage) {
showToast(getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG);
do {
--numRetries;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
;
}
} while (numRetries > 0 && !ImageManager.hasStorage());
}
final boolean imageManagerHasStorageAfterDelay = ImageManager.hasStorage();
CacheService.computeDirtySets(Gallery.this);
CacheService.startCache(Gallery.this, false);
final boolean isCacheReady = CacheService.isCacheReady(false);
// Creating the DataSource objects.
final PicasaDataSource picasaDataSource = new PicasaDataSource(Gallery.this);
final LocalDataSource localDataSource = new LocalDataSource(Gallery.this);
final ConcatenatedDataSource combinedDataSource = new ConcatenatedDataSource(localDataSource, picasaDataSource);
// Depending upon the intent, we assign the right dataSource.
if (!isPickIntent() && !isViewIntent()) {
if (imageManagerHasStorageAfterDelay) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
if (!isCacheReady && imageManagerHasStorageAfterDelay) {
showToast(getResources().getString(R.string.loading_new), Toast.LENGTH_LONG);
}
} else if (!isViewIntent()) {
final Intent intent = getIntent();
if (intent != null) {
- final String type = intent.resolveType(Gallery.this);
+ String type = intent.resolveType(Gallery.this);
+ if (type == null) {
+ // By default, we include images
+ type = "image/*";
+ }
boolean includeImages = isImageType(type);
boolean includeVideos = isVideoType(type);
((LocalDataSource) localDataSource).setMimeFilter(!includeImages, !includeVideos);
if (includeImages) {
if (imageManagerHasStorageAfterDelay) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
} else {
mGridLayer.setDataSource(localDataSource);
}
mGridLayer.setPickIntent(true);
if (!imageManagerHasStorageAfterDelay) {
showToast(getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG);
} else {
showToast(getResources().getString(R.string.pick_prompt), Toast.LENGTH_LONG);
}
}
} else {
// View intent for images.
- Uri uri = getIntent().getData();
- boolean slideshow = getIntent().getBooleanExtra("slideshow", false);
+ final Intent intent = getIntent();
+ Uri uri = intent.getData();
+ boolean slideshow = intent.getBooleanExtra("slideshow", false);
final SingleDataSource singleDataSource = new SingleDataSource(Gallery.this, uri.toString(), slideshow);
final ConcatenatedDataSource singleCombinedDataSource = new ConcatenatedDataSource(singleDataSource, picasaDataSource);
mGridLayer.setDataSource(singleCombinedDataSource);
mGridLayer.setViewIntent(true, Utils.getBucketNameFromUri(uri));
if (singleDataSource.isSingleImage()) {
mGridLayer.setSingleImage(false);
} else if (slideshow) {
mGridLayer.setSingleImage(true);
mGridLayer.startSlideshow();
}
}
}
};
t.start();
//We record the set of enabled accounts for picasa.
mAccountsEnabled = PicasaDataSource.getAccountStatus(this);
Log.i(TAG, "onCreate");
}
private void showToast(final String string, final int duration) {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(Gallery.this, string, duration).show();
}
});
}
public ReverseGeocoder getReverseGeocoder() {
return mReverseGeocoder;
}
public Handler getHandler() {
return mHandler;
}
@Override
public void onRestart() {
super.onRestart();
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
if (mDockSlideshow) {
if (mWakeLock != null) {
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
}
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "GridView.Slideshow.All");
mWakeLock.acquire();
return;
}
if (ImageManager.hasStorage()) {
CacheService.computeDirtySets(this);
CacheService.startCache(this, false);
}
if (mRenderView != null) {
mRenderView.onResume();
}
if (mPause) {
// We check to see if the authenticated accounts have changed, and
// if so, reload the datasource.
HashMap<String, Boolean> accountsEnabled = PicasaDataSource.getAccountStatus(this);
String[] keys = new String[accountsEnabled.size()];
keys = accountsEnabled.keySet().toArray(keys);
int numKeys = keys.length;
for (int i = 0; i < numKeys; ++i) {
String key = keys[i];
boolean newValue = accountsEnabled.get(key).booleanValue();
boolean oldValue = false;
Boolean oldValObj = mAccountsEnabled.get(key);
if (oldValObj != null) {
oldValue = oldValObj.booleanValue();
}
if (oldValue != newValue) {
// Reload the datasource.
if (mGridLayer != null)
mGridLayer.setDataSource(mGridLayer.getDataSource());
break;
}
}
mAccountsEnabled = accountsEnabled;
mPause = false;
}
}
@Override
public void onPause() {
super.onPause();
if (mRenderView != null)
mRenderView.onPause();
if (mWakeLock != null) {
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
mWakeLock = null;
}
mPause = true;
}
public boolean isPaused() {
return mPause;
}
@Override
public void onStop() {
super.onStop();
if (mGridLayer != null)
mGridLayer.stop();
if (mReverseGeocoder != null) {
mReverseGeocoder.flushCache();
}
LocalDataSource.sThumbnailCache.flush();
LocalDataSource.sThumbnailCacheVideo.flush();
PicasaDataSource.sThumbnailCache.flush();
CacheService.startCache(this, true);
}
@Override
public void onDestroy() {
// Force GLThread to exit.
setContentView(R.layout.main);
if (mGridLayer != null) {
DataSource dataSource = mGridLayer.getDataSource();
if (dataSource != null) {
dataSource.shutdown();
}
mGridLayer.shutdown();
}
if (mReverseGeocoder != null)
mReverseGeocoder.shutdown();
if (mRenderView != null) {
mRenderView.shutdown();
mRenderView = null;
}
mGridLayer = null;
super.onDestroy();
Log.i(TAG, "onDestroy");
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mGridLayer != null) {
mGridLayer.markDirty(30);
}
if (mRenderView != null)
mRenderView.requestRender();
Log.i(TAG, "onConfigurationChanged");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mRenderView != null) {
return mRenderView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
} else {
return super.onKeyDown(keyCode, event);
}
}
private boolean isPickIntent() {
String action = getIntent().getAction();
return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action));
}
private boolean isViewIntent() {
String action = getIntent().getAction();
return Intent.ACTION_VIEW.equals(action);
}
private boolean isImageType(String type) {
return type.equals("vnd.android.cursor.dir/image") || type.equals("image/*");
}
private boolean isVideoType(String type) {
return type.equals("vnd.android.cursor.dir/video") || type.equals("video/*");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CROP_MSG: {
if (resultCode == RESULT_OK) {
setResult(resultCode, data);
finish();
}
break;
}
case CROP_MSG_INTERNAL: {
// We cropped an image, we must try to set the focus of the camera
// to that image.
if (resultCode == RESULT_OK) {
String contentUri = data.getAction();
if (mGridLayer != null) {
mGridLayer.focusItem(contentUri);
}
}
break;
}
}
}
@Override
public void onLowMemory() {
if (mRenderView != null) {
mRenderView.handleLowMemory();
}
}
public void launchCropperOrFinish(final MediaItem item) {
final Bundle myExtras = getIntent().getExtras();
String cropValue = myExtras != null ? myExtras.getString("crop") : null;
final String contentUri = item.mContentUri;
if (cropValue != null) {
Bundle newExtras = new Bundle();
if (cropValue.equals("circle")) {
newExtras.putString("circleCrop", "true");
}
Intent cropIntent = new Intent();
cropIntent.setData(Uri.parse(contentUri));
cropIntent.setClass(this, CropImage.class);
cropIntent.putExtras(newExtras);
// Pass through any extras that were passed in.
cropIntent.putExtras(myExtras);
startActivityForResult(cropIntent, CROP_MSG);
} else {
if (contentUri.startsWith("http://")) {
// This is a http uri, we must save it locally first and
// generate a content uri from it.
final ProgressDialog dialog = ProgressDialog.show(this, this.getResources().getString(R.string.initializing),
getResources().getString(R.string.running_face_detection), true, false);
if (contentUri != null) {
MediaScannerConnection.MediaScannerConnectionClient client = new MediaScannerConnection.MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
if (mConnection != null) {
try {
final String path = UriTexture.writeHttpDataInDirectory(Gallery.this, contentUri,
LocalDataSource.DOWNLOAD_BUCKET_NAME);
if (path != null) {
mConnection.scanFile(path, item.mMimeType);
} else {
shutdown("");
}
} catch (Exception e) {
shutdown("");
}
}
}
public void onScanCompleted(String path, Uri uri) {
shutdown(uri.toString());
}
public void shutdown(String uri) {
dialog.dismiss();
performReturn(myExtras, uri.toString());
if (mConnection != null) {
mConnection.disconnect();
}
}
};
MediaScannerConnection connection = new MediaScannerConnection(Gallery.this, client);
connection.connect();
mConnection = connection;
}
} else {
performReturn(myExtras, contentUri);
}
}
}
private void performReturn(Bundle myExtras, String contentUri) {
Intent result = new Intent(null, Uri.parse(contentUri));
if (myExtras != null && myExtras.getBoolean("return-data")) {
// The size of a transaction should be below 100K.
Bitmap bitmap = null;
try {
bitmap = UriTexture.createFromUri(this, contentUri, 1024, 1024, 0, null);
} catch (IOException e) {
;
} catch (URISyntaxException e) {
;
}
if (bitmap != null) {
result.putExtra("data", bitmap);
}
}
setResult(RESULT_OK, result);
finish();
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final boolean imageManagerHasStorage = ImageManager.hasStorage();
boolean slideshowIntent = false;
if (isViewIntent()) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
slideshowIntent = extras.getBoolean("slideshow", false);
}
}
if (isViewIntent() && getIntent().getData().equals(Images.Media.EXTERNAL_CONTENT_URI)
&& slideshowIntent) {
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
finish();
} else {
Slideshow slideshow = new Slideshow(this);
slideshow.setDataSource(new RandomDataSource());
setContentView(slideshow);
mDockSlideshow = true;
}
return;
}
if (PIXEL_DENSITY == 0.0f) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
PIXEL_DENSITY = metrics.density;
}
mReverseGeocoder = new ReverseGeocoder(this);
mRenderView = new RenderView(this);
mGridLayer = new GridLayer(this, (int) (96.0f * PIXEL_DENSITY), (int) (72.0f * PIXEL_DENSITY), new GridLayoutInterface(4),
mRenderView);
mRenderView.setRootLayer(mGridLayer);
setContentView(mRenderView);
Thread t = new Thread() {
public void run() {
int numRetries = 25;
if (!imageManagerHasStorage) {
showToast(getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG);
do {
--numRetries;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
;
}
} while (numRetries > 0 && !ImageManager.hasStorage());
}
final boolean imageManagerHasStorageAfterDelay = ImageManager.hasStorage();
CacheService.computeDirtySets(Gallery.this);
CacheService.startCache(Gallery.this, false);
final boolean isCacheReady = CacheService.isCacheReady(false);
// Creating the DataSource objects.
final PicasaDataSource picasaDataSource = new PicasaDataSource(Gallery.this);
final LocalDataSource localDataSource = new LocalDataSource(Gallery.this);
final ConcatenatedDataSource combinedDataSource = new ConcatenatedDataSource(localDataSource, picasaDataSource);
// Depending upon the intent, we assign the right dataSource.
if (!isPickIntent() && !isViewIntent()) {
if (imageManagerHasStorageAfterDelay) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
if (!isCacheReady && imageManagerHasStorageAfterDelay) {
showToast(getResources().getString(R.string.loading_new), Toast.LENGTH_LONG);
}
} else if (!isViewIntent()) {
final Intent intent = getIntent();
if (intent != null) {
final String type = intent.resolveType(Gallery.this);
boolean includeImages = isImageType(type);
boolean includeVideos = isVideoType(type);
((LocalDataSource) localDataSource).setMimeFilter(!includeImages, !includeVideos);
if (includeImages) {
if (imageManagerHasStorageAfterDelay) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
} else {
mGridLayer.setDataSource(localDataSource);
}
mGridLayer.setPickIntent(true);
if (!imageManagerHasStorageAfterDelay) {
showToast(getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG);
} else {
showToast(getResources().getString(R.string.pick_prompt), Toast.LENGTH_LONG);
}
}
} else {
// View intent for images.
Uri uri = getIntent().getData();
boolean slideshow = getIntent().getBooleanExtra("slideshow", false);
final SingleDataSource singleDataSource = new SingleDataSource(Gallery.this, uri.toString(), slideshow);
final ConcatenatedDataSource singleCombinedDataSource = new ConcatenatedDataSource(singleDataSource, picasaDataSource);
mGridLayer.setDataSource(singleCombinedDataSource);
mGridLayer.setViewIntent(true, Utils.getBucketNameFromUri(uri));
if (singleDataSource.isSingleImage()) {
mGridLayer.setSingleImage(false);
} else if (slideshow) {
mGridLayer.setSingleImage(true);
mGridLayer.startSlideshow();
}
}
}
};
t.start();
//We record the set of enabled accounts for picasa.
mAccountsEnabled = PicasaDataSource.getAccountStatus(this);
Log.i(TAG, "onCreate");
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final boolean imageManagerHasStorage = ImageManager.hasStorage();
boolean slideshowIntent = false;
if (isViewIntent()) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
slideshowIntent = extras.getBoolean("slideshow", false);
}
}
if (isViewIntent() && getIntent().getData().equals(Images.Media.EXTERNAL_CONTENT_URI)
&& slideshowIntent) {
if (!imageManagerHasStorage) {
Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
finish();
} else {
Slideshow slideshow = new Slideshow(this);
slideshow.setDataSource(new RandomDataSource());
setContentView(slideshow);
mDockSlideshow = true;
}
return;
}
if (PIXEL_DENSITY == 0.0f) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
PIXEL_DENSITY = metrics.density;
}
mReverseGeocoder = new ReverseGeocoder(this);
mRenderView = new RenderView(this);
mGridLayer = new GridLayer(this, (int) (96.0f * PIXEL_DENSITY), (int) (72.0f * PIXEL_DENSITY), new GridLayoutInterface(4),
mRenderView);
mRenderView.setRootLayer(mGridLayer);
setContentView(mRenderView);
Thread t = new Thread() {
public void run() {
int numRetries = 25;
if (!imageManagerHasStorage) {
showToast(getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG);
do {
--numRetries;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
;
}
} while (numRetries > 0 && !ImageManager.hasStorage());
}
final boolean imageManagerHasStorageAfterDelay = ImageManager.hasStorage();
CacheService.computeDirtySets(Gallery.this);
CacheService.startCache(Gallery.this, false);
final boolean isCacheReady = CacheService.isCacheReady(false);
// Creating the DataSource objects.
final PicasaDataSource picasaDataSource = new PicasaDataSource(Gallery.this);
final LocalDataSource localDataSource = new LocalDataSource(Gallery.this);
final ConcatenatedDataSource combinedDataSource = new ConcatenatedDataSource(localDataSource, picasaDataSource);
// Depending upon the intent, we assign the right dataSource.
if (!isPickIntent() && !isViewIntent()) {
if (imageManagerHasStorageAfterDelay) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
if (!isCacheReady && imageManagerHasStorageAfterDelay) {
showToast(getResources().getString(R.string.loading_new), Toast.LENGTH_LONG);
}
} else if (!isViewIntent()) {
final Intent intent = getIntent();
if (intent != null) {
String type = intent.resolveType(Gallery.this);
if (type == null) {
// By default, we include images
type = "image/*";
}
boolean includeImages = isImageType(type);
boolean includeVideos = isVideoType(type);
((LocalDataSource) localDataSource).setMimeFilter(!includeImages, !includeVideos);
if (includeImages) {
if (imageManagerHasStorageAfterDelay) {
mGridLayer.setDataSource(combinedDataSource);
} else {
mGridLayer.setDataSource(picasaDataSource);
}
} else {
mGridLayer.setDataSource(localDataSource);
}
mGridLayer.setPickIntent(true);
if (!imageManagerHasStorageAfterDelay) {
showToast(getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG);
} else {
showToast(getResources().getString(R.string.pick_prompt), Toast.LENGTH_LONG);
}
}
} else {
// View intent for images.
final Intent intent = getIntent();
Uri uri = intent.getData();
boolean slideshow = intent.getBooleanExtra("slideshow", false);
final SingleDataSource singleDataSource = new SingleDataSource(Gallery.this, uri.toString(), slideshow);
final ConcatenatedDataSource singleCombinedDataSource = new ConcatenatedDataSource(singleDataSource, picasaDataSource);
mGridLayer.setDataSource(singleCombinedDataSource);
mGridLayer.setViewIntent(true, Utils.getBucketNameFromUri(uri));
if (singleDataSource.isSingleImage()) {
mGridLayer.setSingleImage(false);
} else if (slideshow) {
mGridLayer.setSingleImage(true);
mGridLayer.startSlideshow();
}
}
}
};
t.start();
//We record the set of enabled accounts for picasa.
mAccountsEnabled = PicasaDataSource.getAccountStatus(this);
Log.i(TAG, "onCreate");
}
|
diff --git a/classes/com/sapienter/jbilling/server/provisioning/ExternalProvisioning.java b/classes/com/sapienter/jbilling/server/provisioning/ExternalProvisioning.java
index d8e0e8d6..1a35f2da 100644
--- a/classes/com/sapienter/jbilling/server/provisioning/ExternalProvisioning.java
+++ b/classes/com/sapienter/jbilling/server/provisioning/ExternalProvisioning.java
@@ -1,283 +1,283 @@
/*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2008 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling 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.
jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sapienter.jbilling.server.provisioning;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.common.SessionInternalError;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskException;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskManager;
import com.sapienter.jbilling.server.provisioning.config.Command;
import com.sapienter.jbilling.server.provisioning.config.Field;
import com.sapienter.jbilling.server.provisioning.config.Processor;
import com.sapienter.jbilling.server.provisioning.config.Provisioning;
import com.sapienter.jbilling.server.provisioning.config.Request;
import com.sapienter.jbilling.server.provisioning.task.IExternalProvisioning;
import com.sapienter.jbilling.server.util.Constants;
import com.sapienter.jbilling.server.util.Context;
/**
* Logic for external provisioning module. Receives a command from the
* commands rules task via JMS. The configuration file
* jbilling-provisioning.xml is used to map this command to command
* strings for specific external provisioning processors. Publishes
* results in a JMS topic.
*/
public class ExternalProvisioning {
private static final Logger LOG = Logger.getLogger(
ExternalProvisioning.class);
private static final String TOPIC_NAME =
"provisioning_commands_reply_topic";
private TopicConnection conn = null;
private TopicPublisher topic = null;
private TopicSession session = null;
private MapMessage message;
/**
* Receives and processes a command message from the command rules task.
* This method is called through the ProvisioningProcessSessionBean
* so that it runs in a transaction. ExternalProvisioningMDB is
* the class that actually receives the message.
*/
public void onMessage(Message myMessage) {
try {
setupTopic();
message = (MapMessage) myMessage;
Provisioning config = (Provisioning) Context.getBean(
Context.Name.PROVISIONING);
List<Command> commandsConfig = config.getCommands();
String command = message.getStringProperty("command");
// find command config
for(Command commandConfig : commandsConfig) {
if (command.equals(commandConfig.getId())) {
LOG.debug("Found a command configuration");
processCommand(commandConfig);
break; // no more configurations for this command?
}
}
} catch (Exception e) {
throw new SessionInternalError(e);
} finally {
closeTopic();
}
}
/**
* Processes a command according to the given configuration.
*/
private void processCommand(Command config)
throws JMSException, PluggableTaskException {
// process fields
List<Field> fieldConfig = config.getFields();
Map<String, String> fields = new HashMap<String, String>();
for (Field field : fieldConfig) {
String value = message.getStringProperty(field.getName());
if (value == null) {
value = field.getDefaultValue();
}
fields.put(field.getName(), value);
}
// call each configured processor
for (Processor processor : config.getProcessors()) {
PluggableTaskManager<IExternalProvisioning> taskManager = new
PluggableTaskManager<IExternalProvisioning>(
message.getIntProperty("entityId"),
Constants.PLUGGABLE_TASK_EXTERNAL_PROVISIONING);
IExternalProvisioning task = taskManager.getNextClass();
while (task != null) {
if (task.getId().equals(processor.getId())) {
callProcessor(task, processor, fields,
message.getStringProperty("id"));
break;
}
task = taskManager.getNextClass();
}
if (task == null) {
throw new SessionInternalError("Couldn't find external " +
"provisioining task with id: " + processor.getId());
}
}
}
/**
* Processes each request to the given external provisioning task
* as specified by the processor configuration.
*/
private void callProcessor(IExternalProvisioning task,
Processor processor, Map<String, String> fields, String id)
throws JMSException {
List<Request> requests = processor.getRequests();
Collections.sort(requests); // sort by order
for (Request request : requests) {
LOG.debug("Submit string pattern: " + request.getSubmit());
// insert fields into submit string
StringBuilder submit = new StringBuilder(request.getSubmit());
boolean keepLooking = true;
while (keepLooking) {
int barStartIndex = submit.indexOf("|");
int barEndIndex = submit.indexOf("|", barStartIndex + 1);
if (barStartIndex == -1) {
keepLooking = false;
} else if (barEndIndex == -1) {
throw new SessionInternalError("Mismatched '|' in submit " +
"string. Index: " + barStartIndex);
} else {
String fieldName = submit.substring(barStartIndex + 1,
barEndIndex);
String fieldValue = fields.get(fieldName);
LOG.debug("Replacing field name '" + fieldName +
"' with value '" + fieldValue + "'");
submit.replace(barStartIndex, barEndIndex + 1, fieldValue);
}
}
String submitString = submit.toString();
LOG.debug("Command string: " + submitString);
// call external provisioning processor task
String error = null;
Map<String, Object> result = null;
try {
result = task.sendRequest(id, submitString);
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.close();
LOG.error("External provisioning processor error: " +
e.getMessage() + "\n" + sw.toString());
error = e.toString();
}
// post message if required
if (request.getPostResult()) {
postResults(result, error);
}
// only continue with other requests if correct result
String continueOnType = request.getContinueOnType();
- if (continueOnType != null && !result.get("result").equals(
- continueOnType)) {
+ if (continueOnType != null && (result == null ||
+ !result.get("result").equals(continueOnType))) {
LOG.debug("Skipping other results.");
break;
}
}
}
/**
* Posts results of external provisioning processing tasks.
*/
private void postResults(Map<String, Object> results, String error)
throws JMSException {
MapMessage replyMessage = session.createMapMessage();
// add the original properties (names prefixed with 'in_')
Enumeration originalPropNames = message.getPropertyNames();
while (originalPropNames.hasMoreElements()) {
String propName = (String) originalPropNames.nextElement();
Object propValue = message.getObjectProperty(propName);
replyMessage.setObjectProperty("in_" + propName, propValue);
}
if (error == null) {
// add the properties returned by the processor
Set<Map.Entry<String, Object>> entrySet = results.entrySet();
for (Map.Entry<String, Object> entry : entrySet) {
replyMessage.setObjectProperty("out_" + entry.getKey(),
entry.getValue());
}
} else {
// there was an error
replyMessage.setStringProperty("out_result", "unavailable");
replyMessage.setStringProperty("exception", error);
}
// send the message
topic.publish(replyMessage);
}
/**
* Sets up the JMS topic.
*/
public void setupTopic() throws JMSException, NamingException {
InitialContext iniCtx = new InitialContext();
TopicConnectionFactory tcf = (TopicConnectionFactory)
iniCtx.lookup("ConnectionFactory");
conn = tcf.createTopicConnection();
session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
conn.start();
topic = session.createPublisher((Topic) iniCtx.lookup("topic/" +
TOPIC_NAME));
}
/**
* Closes the JMS topic.
*/
public void closeTopic() {
try {
if (topic != null) {
topic.close();
}
if (session != null) {
session.close();
}
if (conn != null) {
conn.close();
}
} catch(JMSException jmse) {
}
}
}
| true | true | private void callProcessor(IExternalProvisioning task,
Processor processor, Map<String, String> fields, String id)
throws JMSException {
List<Request> requests = processor.getRequests();
Collections.sort(requests); // sort by order
for (Request request : requests) {
LOG.debug("Submit string pattern: " + request.getSubmit());
// insert fields into submit string
StringBuilder submit = new StringBuilder(request.getSubmit());
boolean keepLooking = true;
while (keepLooking) {
int barStartIndex = submit.indexOf("|");
int barEndIndex = submit.indexOf("|", barStartIndex + 1);
if (barStartIndex == -1) {
keepLooking = false;
} else if (barEndIndex == -1) {
throw new SessionInternalError("Mismatched '|' in submit " +
"string. Index: " + barStartIndex);
} else {
String fieldName = submit.substring(barStartIndex + 1,
barEndIndex);
String fieldValue = fields.get(fieldName);
LOG.debug("Replacing field name '" + fieldName +
"' with value '" + fieldValue + "'");
submit.replace(barStartIndex, barEndIndex + 1, fieldValue);
}
}
String submitString = submit.toString();
LOG.debug("Command string: " + submitString);
// call external provisioning processor task
String error = null;
Map<String, Object> result = null;
try {
result = task.sendRequest(id, submitString);
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.close();
LOG.error("External provisioning processor error: " +
e.getMessage() + "\n" + sw.toString());
error = e.toString();
}
// post message if required
if (request.getPostResult()) {
postResults(result, error);
}
// only continue with other requests if correct result
String continueOnType = request.getContinueOnType();
if (continueOnType != null && !result.get("result").equals(
continueOnType)) {
LOG.debug("Skipping other results.");
break;
}
}
}
| private void callProcessor(IExternalProvisioning task,
Processor processor, Map<String, String> fields, String id)
throws JMSException {
List<Request> requests = processor.getRequests();
Collections.sort(requests); // sort by order
for (Request request : requests) {
LOG.debug("Submit string pattern: " + request.getSubmit());
// insert fields into submit string
StringBuilder submit = new StringBuilder(request.getSubmit());
boolean keepLooking = true;
while (keepLooking) {
int barStartIndex = submit.indexOf("|");
int barEndIndex = submit.indexOf("|", barStartIndex + 1);
if (barStartIndex == -1) {
keepLooking = false;
} else if (barEndIndex == -1) {
throw new SessionInternalError("Mismatched '|' in submit " +
"string. Index: " + barStartIndex);
} else {
String fieldName = submit.substring(barStartIndex + 1,
barEndIndex);
String fieldValue = fields.get(fieldName);
LOG.debug("Replacing field name '" + fieldName +
"' with value '" + fieldValue + "'");
submit.replace(barStartIndex, barEndIndex + 1, fieldValue);
}
}
String submitString = submit.toString();
LOG.debug("Command string: " + submitString);
// call external provisioning processor task
String error = null;
Map<String, Object> result = null;
try {
result = task.sendRequest(id, submitString);
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.close();
LOG.error("External provisioning processor error: " +
e.getMessage() + "\n" + sw.toString());
error = e.toString();
}
// post message if required
if (request.getPostResult()) {
postResults(result, error);
}
// only continue with other requests if correct result
String continueOnType = request.getContinueOnType();
if (continueOnType != null && (result == null ||
!result.get("result").equals(continueOnType))) {
LOG.debug("Skipping other results.");
break;
}
}
}
|
diff --git a/cdi/tests/org.jboss.tools.cdi.seam3.bot.test/src/org/jboss/tools/cdi/seam3/bot/test/tests/InterfaceAndAbstractValidationTest.java b/cdi/tests/org.jboss.tools.cdi.seam3.bot.test/src/org/jboss/tools/cdi/seam3/bot/test/tests/InterfaceAndAbstractValidationTest.java
index 679af022d..d877e20f3 100644
--- a/cdi/tests/org.jboss.tools.cdi.seam3.bot.test/src/org/jboss/tools/cdi/seam3/bot/test/tests/InterfaceAndAbstractValidationTest.java
+++ b/cdi/tests/org.jboss.tools.cdi.seam3.bot.test/src/org/jboss/tools/cdi/seam3/bot/test/tests/InterfaceAndAbstractValidationTest.java
@@ -1,93 +1,93 @@
/*******************************************************************************
* Copyright (c) 2010-2012 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.cdi.seam3.bot.test.tests;
import org.eclipse.core.resources.IMarker;
import org.jboss.tools.cdi.bot.test.CDIConstants;
import org.jboss.tools.cdi.seam3.bot.test.base.Seam3TestBase;
import org.jboss.tools.cdi.seam3.bot.test.util.SeamLibrary;
import org.jboss.tools.ui.bot.ext.Timing;
import org.jboss.tools.ui.bot.ext.helper.MarkerHelper;
import org.junit.After;
import org.junit.Test;
/**
*
* @author jjankovi
*
*/
public class InterfaceAndAbstractValidationTest extends Seam3TestBase {
@After
public void cleanWS() {
projectExplorer.deleteAllProjects();
}
@Test
public void testInterfaceValidation() {
/* import test project */
String projectName = "interface1";
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1);
bot.sleep(Timing.time3S()); // necessary to CDI Validation computation
/* get markers for beans.xml */
IMarker[] markers = getMarkersForResource(CDIConstants.BEANS_XML, projectName,
CDIConstants.WEBCONTENT, CDIConstants.WEB_INF);
/* assert expected count */
assertExpectedCount(markers.length ,1);
/* assert message contains expected value */
assertMessageContainsExpectedValue(MarkerHelper.getMarkerMessage(markers[0]),
- "Interface ", "cannot be configured as a bean");
+ "Abstract type", "cannot be configured as a bean");
}
@Test
public void testAbstractTypeValidation() {
/* import test project */
String projectName = "abstract1";
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1);
bot.sleep(Timing.time3S()); // necessary to CDI Validation computation
/* get markers for beans.xml */
IMarker[] markers = getMarkersForResource(CDIConstants.BEANS_XML, projectName,
CDIConstants.WEBCONTENT, CDIConstants.WEB_INF);
/* assert expected count */
assertExpectedCount(markers.length ,1);
/* assert message contains expected value */
assertMessageContainsExpectedValue(MarkerHelper.getMarkerMessage(markers[0]),
"Abstract type", "cannot be configured as a bean");
}
private void assertMessageContainsExpectedValue(String message,
String... expectedValues) {
for (String value : expectedValues) {
assertContains(value, message);
}
}
private IMarker[] getMarkersForResource(String resource, String ... path) {
MarkerHelper markerHelper = new MarkerHelper(resource, path);
return markerHelper.getMarkers();
}
private void assertExpectedCount(int realCount, int expectedCount) {
assertTrue("Expected count: " + expectedCount + " real count: " + realCount,
realCount == expectedCount);
}
}
| true | true | public void testInterfaceValidation() {
/* import test project */
String projectName = "interface1";
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1);
bot.sleep(Timing.time3S()); // necessary to CDI Validation computation
/* get markers for beans.xml */
IMarker[] markers = getMarkersForResource(CDIConstants.BEANS_XML, projectName,
CDIConstants.WEBCONTENT, CDIConstants.WEB_INF);
/* assert expected count */
assertExpectedCount(markers.length ,1);
/* assert message contains expected value */
assertMessageContainsExpectedValue(MarkerHelper.getMarkerMessage(markers[0]),
"Interface ", "cannot be configured as a bean");
}
| public void testInterfaceValidation() {
/* import test project */
String projectName = "interface1";
importSeam3ProjectWithLibrary(projectName, SeamLibrary.SOLDER_3_1);
bot.sleep(Timing.time3S()); // necessary to CDI Validation computation
/* get markers for beans.xml */
IMarker[] markers = getMarkersForResource(CDIConstants.BEANS_XML, projectName,
CDIConstants.WEBCONTENT, CDIConstants.WEB_INF);
/* assert expected count */
assertExpectedCount(markers.length ,1);
/* assert message contains expected value */
assertMessageContainsExpectedValue(MarkerHelper.getMarkerMessage(markers[0]),
"Abstract type", "cannot be configured as a bean");
}
|
diff --git a/src/plugins/WebOfTrust/OwnIdentity.java b/src/plugins/WebOfTrust/OwnIdentity.java
index 2d759902..0af8c398 100644
--- a/src/plugins/WebOfTrust/OwnIdentity.java
+++ b/src/plugins/WebOfTrust/OwnIdentity.java
@@ -1,248 +1,255 @@
/* This code is part of WoT, a plugin for Freenet. It is distributed
* under the GNU General Public License, version 2 (or at your option
* any later version). See http://www.gnu.org/ for details of the GPL. */
package plugins.WebOfTrust;
import java.net.MalformedURLException;
import java.util.Date;
import plugins.WebOfTrust.exceptions.InvalidParameterException;
import freenet.keys.FreenetURI;
import freenet.support.CurrentTimeUTC;
import freenet.support.Logger;
/**
* A local Identity (it belongs to the user)
*
* @author xor ([email protected])
* @author Julien Cornuwel ([email protected])
*/
public final class OwnIdentity extends Identity {
protected FreenetURI mInsertURI;
protected Date mLastInsertDate;
/**
* Creates a new OwnIdentity with the given parameters.
*
* @param insertURI A {@link FreenetURI} used to insert this OwnIdentity in Freenet
* @param nickName The nickName of this OwnIdentity
* @param publishTrustList Whether this OwnIdentity publishes its trustList or not
* @throws InvalidParameterException If a given parameter is invalid
* @throws MalformedURLException If insertURI isn't a valid insert URI.
*/
public OwnIdentity (WebOfTrust myWoT, FreenetURI insertURI, String nickName, boolean publishTrustList) throws InvalidParameterException, MalformedURLException {
- super(myWoT, insertURI.deriveRequestURIFromInsertURI(), nickName, publishTrustList);
+ super(myWoT,
+ // If we don't set a document name, we will get "java.net.MalformedURLException: SSK URIs must have a document name (to avoid ambiguity)"
+ // when calling FreenetURI.deriveRequestURIFromInsertURI().
+ // To make sure the code works, I have copypasted the URI normalization code which we have been using anyway instead of only
+ // adding a .setDocName() - I remember that it was tricky to get code which properly normalizes ALL existing URIs which
+ // people shove into WOT
+ insertURI.setKeyType("USK").setDocName(WebOfTrust.WOT_NAME).setMetaString(null).deriveRequestURIFromInsertURI(),
+ nickName, publishTrustList);
// This is already done by super()
// setEdition(0);
if(!insertURI.isUSK() && !insertURI.isSSK())
throw new InvalidParameterException("Identity URI keytype not supported: " + insertURI);
// initializeTransient() was not called yet so we must use mRequestURI.getEdition() instead of this.getEdition()
mInsertURI = insertURI.setKeyType("USK").setDocName(WebOfTrust.WOT_NAME).setSuggestedEdition(mRequestURI.getEdition()).setMetaString(null);
// Notice: Check that mInsertURI really is a insert URI is NOT necessary, FreenetURI.deriveRequestURIFromInsertURI() did that already for us.
// InsertableUSK.createInsertable(mInsertURI, false);
mLastInsertDate = new Date(0);
// Must be set to "fetched" to prevent the identity fetcher from trying to fetch the current edition and to make the identity inserter
// actually insert the identity. It won't insert it if the current edition is not marked as fetched to prevent inserts when restoring an
// own identity.
mCurrentEditionFetchState = FetchState.Fetched;
// Don't check for mNickname == null to allow restoring of own identities
}
/**
* Creates a new OwnIdentity with the given parameters.
* insertURI and requestURI are converted from String to {@link FreenetURI}
*
* @param insertURI A String representing the key needed to insert this OwnIdentity in Freenet
* @param nickName The nickName of this OwnIdentity
* @param publishTrustList Whether this OwnIdentity publishes its trustList or not
* @throws InvalidParameterException If a given parameter is invalid
* @throws MalformedURLException If insertURI is not a valid FreenetURI or a request URI instead of an insert URI.
*/
public OwnIdentity(WebOfTrust myWoT, String insertURI, String nickName, boolean publishTrustList) throws InvalidParameterException, MalformedURLException {
this(myWoT, new FreenetURI(insertURI), nickName, publishTrustList);
}
/**
* Whether this OwnIdentity needs to be inserted or not.
* We insert OwnIdentities when they have been modified AND at least once every three days.
* @return Whether this OwnIdentity needs to be inserted or not
*/
public final boolean needsInsert() {
// If the current edition was fetched successfully OR if parsing of it failed, we may insert a new one
// We may NOT insert a new one if it was not fetched: The identity might be in restore-mode
if(getCurrentEditionFetchState() == FetchState.NotFetched)
return false;
return (getLastChangeDate().after(getLastInsertDate()) ||
(CurrentTimeUTC.getInMillis() - getLastInsertDate().getTime()) > IdentityInserter.MAX_UNCHANGED_TINE_BEFORE_REINSERT);
}
/**
* @return This OwnIdentity's insertURI
*/
public final FreenetURI getInsertURI() {
checkedActivate(1);
checkedActivate(mInsertURI, 2);
return mInsertURI;
}
@Override
protected final void setEdition(long edition) throws InvalidParameterException {
super.setEdition(edition);
checkedActivate(1);
mCurrentEditionFetchState = FetchState.Fetched;
checkedActivate(mInsertURI, 2);
if(edition > mInsertURI.getEdition()) {
mInsertURI = mInsertURI.setSuggestedEdition(edition);
updated();
}
}
/**
* Only needed for normal identities.
*/
@Override
protected final void markForRefetch() {
return;
}
/**
* Sets the edition to the given edition and marks it for re-fetching. Used for restoring own identities.
*/
protected final void restoreEdition(long edition) throws InvalidParameterException {
setEdition(edition);
checkedActivate(1);
mCurrentEditionFetchState = FetchState.NotFetched;
}
/**
* Get the Date of last insertion of this OwnIdentity, in UTC, null if it was not inserted yet.
*/
public final Date getLastInsertDate() {
checkedActivate(1); // Date is a db4o primitive type so 1 is enough
return (Date)mLastInsertDate.clone();
}
/**
* Sets the last insertion date of this OwnIdentity to current time in UTC.
*/
protected final void updateLastInsertDate() {
checkedActivate(1); // Date is a db4o primitive type so 1 is enough
mLastInsertDate = CurrentTimeUTC.get();
}
/**
* Checks whether two OwnIdentity objects are equal.
* This checks <b>all</b> properties of the identities <b>excluding</b> the {@link Date} properties.
*/
public final boolean equals(Object obj) {
if(!super.equals(obj))
return false;
if(!(obj instanceof OwnIdentity))
return false;
OwnIdentity other = (OwnIdentity)obj;
if(!getInsertURI().equals(other.getInsertURI()))
return false;
return true;
}
/**
* Clones this OwnIdentity. Does <b>not</b> clone the {@link Date} attributes, they are initialized to the current time!
*/
public final OwnIdentity clone() {
try {
OwnIdentity clone = new OwnIdentity(mWebOfTrust, getInsertURI(), getNickname(), doesPublishTrustList());
checkedActivate(4); // For performance only
clone.mCurrentEditionFetchState = getCurrentEditionFetchState();
clone.setNewEditionHint(getLatestEditionHint());
clone.setContexts(getContexts());
clone.setProperties(getProperties());
return clone;
} catch(InvalidParameterException e) {
throw new RuntimeException(e);
} catch (MalformedURLException e) {
/* This should never happen since we checked when this object was created */
Logger.error(this, "Caugth MalformedURLException in clone()", e);
throw new IllegalStateException(e);
}
}
/**
* Stores this identity in the database without committing the transaction
* You must synchronize on the WoT, on the identity and then on the database when using this function!
*/
protected final void storeWithoutCommit() {
try {
// 4 is the maximal depth of all getter functions. You have to adjust this when introducing new member variables.
checkedActivate(4);
checkedStore(mInsertURI);
// checkedStore(mLastInsertDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */
}
catch(RuntimeException e) {
checkedRollbackAndThrow(e);
}
super.storeWithoutCommit(); // Not in the try{} so we don't do checkedRollbackAndThrow twice
}
protected final void deleteWithoutCommit() {
try {
// 4 is the maximal depth of all getter functions. You have to adjust this when introducing new member variables.
checkedActivate(4);
mInsertURI.removeFrom(mDB);
// checkedDelete(mLastInsertDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */
}
catch(RuntimeException e) {
checkedRollbackAndThrow(e);
}
super.deleteWithoutCommit(); // Not in the try{} so we don't do checkedRollbackAndThrow twice
}
public void startupDatabaseIntegrityTest() {
checkedActivate(4);
super.startupDatabaseIntegrityTest();
if(mInsertURI == null)
throw new NullPointerException("mInsertURI==null");
try {
if(!mInsertURI.deriveRequestURIFromInsertURI().equals(mRequestURI))
throw new IllegalStateException("Insert and request URI do not fit together!");
} catch (MalformedURLException e) {
throw new IllegalStateException("mInsertURI is not an insert URI!");
}
if(mLastInsertDate == null)
throw new NullPointerException("mLastInsertDate==null");
if(mLastInsertDate.after(CurrentTimeUTC.get()))
throw new IllegalStateException("mLastInsertDate is in the future: " + mLastInsertDate);
}
}
| true | true | public OwnIdentity (WebOfTrust myWoT, FreenetURI insertURI, String nickName, boolean publishTrustList) throws InvalidParameterException, MalformedURLException {
super(myWoT, insertURI.deriveRequestURIFromInsertURI(), nickName, publishTrustList);
// This is already done by super()
// setEdition(0);
if(!insertURI.isUSK() && !insertURI.isSSK())
throw new InvalidParameterException("Identity URI keytype not supported: " + insertURI);
// initializeTransient() was not called yet so we must use mRequestURI.getEdition() instead of this.getEdition()
mInsertURI = insertURI.setKeyType("USK").setDocName(WebOfTrust.WOT_NAME).setSuggestedEdition(mRequestURI.getEdition()).setMetaString(null);
// Notice: Check that mInsertURI really is a insert URI is NOT necessary, FreenetURI.deriveRequestURIFromInsertURI() did that already for us.
// InsertableUSK.createInsertable(mInsertURI, false);
mLastInsertDate = new Date(0);
// Must be set to "fetched" to prevent the identity fetcher from trying to fetch the current edition and to make the identity inserter
// actually insert the identity. It won't insert it if the current edition is not marked as fetched to prevent inserts when restoring an
// own identity.
mCurrentEditionFetchState = FetchState.Fetched;
// Don't check for mNickname == null to allow restoring of own identities
}
| public OwnIdentity (WebOfTrust myWoT, FreenetURI insertURI, String nickName, boolean publishTrustList) throws InvalidParameterException, MalformedURLException {
super(myWoT,
// If we don't set a document name, we will get "java.net.MalformedURLException: SSK URIs must have a document name (to avoid ambiguity)"
// when calling FreenetURI.deriveRequestURIFromInsertURI().
// To make sure the code works, I have copypasted the URI normalization code which we have been using anyway instead of only
// adding a .setDocName() - I remember that it was tricky to get code which properly normalizes ALL existing URIs which
// people shove into WOT
insertURI.setKeyType("USK").setDocName(WebOfTrust.WOT_NAME).setMetaString(null).deriveRequestURIFromInsertURI(),
nickName, publishTrustList);
// This is already done by super()
// setEdition(0);
if(!insertURI.isUSK() && !insertURI.isSSK())
throw new InvalidParameterException("Identity URI keytype not supported: " + insertURI);
// initializeTransient() was not called yet so we must use mRequestURI.getEdition() instead of this.getEdition()
mInsertURI = insertURI.setKeyType("USK").setDocName(WebOfTrust.WOT_NAME).setSuggestedEdition(mRequestURI.getEdition()).setMetaString(null);
// Notice: Check that mInsertURI really is a insert URI is NOT necessary, FreenetURI.deriveRequestURIFromInsertURI() did that already for us.
// InsertableUSK.createInsertable(mInsertURI, false);
mLastInsertDate = new Date(0);
// Must be set to "fetched" to prevent the identity fetcher from trying to fetch the current edition and to make the identity inserter
// actually insert the identity. It won't insert it if the current edition is not marked as fetched to prevent inserts when restoring an
// own identity.
mCurrentEditionFetchState = FetchState.Fetched;
// Don't check for mNickname == null to allow restoring of own identities
}
|
diff --git a/tests/src/android/webkit/cts/CtsTestServer.java b/tests/src/android/webkit/cts/CtsTestServer.java
index 0d786fd7..87b3d1dd 100644
--- a/tests/src/android/webkit/cts/CtsTestServer.java
+++ b/tests/src/android/webkit/cts/CtsTestServer.java
@@ -1,696 +1,697 @@
/*
* Copyright (C) 2009 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 android.webkit.cts;
import org.apache.harmony.luni.util.Base64;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.RequestLine;
import org.apache.http.StatusLine;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.impl.cookie.DateUtils;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
/**
* Simple http test server for testing webkit client functionality.
*/
public class CtsTestServer {
private static final String TAG = "CtsTestServer";
private static final int SERVER_PORT = 4444;
private static final int SSL_SERVER_PORT = 4445;
public static final String FAVICON_PATH = "/favicon.ico";
public static final String USERAGENT_PATH = "/useragent.html";
public static final String ASSET_PREFIX = "/assets/";
public static final String FAVICON_ASSET_PATH = ASSET_PREFIX + "webkit/favicon.png";
public static final String REDIRECT_PREFIX = "/redirect";
public static final String DELAY_PREFIX = "/delayed";
public static final String BINARY_PREFIX = "/binary";
public static final String COOKIE_PREFIX = "/cookie";
public static final String AUTH_PREFIX = "/auth";
public static final String SHUTDOWN_PREFIX = "/shutdown";
public static final int DELAY_MILLIS = 2000;
public static final String AUTH_REALM = "Android CTS";
public static final String AUTH_USER = "cts";
public static final String AUTH_PASS = "secret";
// base64 encoded credentials "cts:secret" used for basic authentication
public static final String AUTH_CREDENTIALS = "Basic Y3RzOnNlY3JldA==";
public static final String MESSAGE_401 = "401 unauthorized";
public static final String MESSAGE_403 = "403 forbidden";
public static final String MESSAGE_404 = "404 not found";
private static CtsTestServer sInstance;
private static Hashtable<Integer, String> sReasons;
private ServerThread mServerThread;
private String mServerUri;
private AssetManager mAssets;
private Context mContext;
private boolean mSsl;
private MimeTypeMap mMap;
private String mLastQuery;
private int mRequestCount;
private long mDocValidity;
private long mDocAge;
/**
* Create and start a local HTTP server instance.
* @param context The application context to use for fetching assets.
* @throws IOException
*/
public CtsTestServer(Context context) throws Exception {
this(context, false);
}
public static String getReasonString(int status) {
if (sReasons == null) {
sReasons = new Hashtable<Integer, String>();
sReasons.put(HttpStatus.SC_UNAUTHORIZED, "Unauthorized");
sReasons.put(HttpStatus.SC_NOT_FOUND, "Not Found");
sReasons.put(HttpStatus.SC_FORBIDDEN, "Forbidden");
sReasons.put(HttpStatus.SC_MOVED_TEMPORARILY, "Moved Temporarily");
}
return sReasons.get(status);
}
/**
* Create and start a local HTTP server instance.
* @param context The application context to use for fetching assets.
* @param ssl True if the server should be using secure sockets.
* @throws Exception
*/
public CtsTestServer(Context context, boolean ssl) throws Exception {
if (sInstance != null) {
// attempt to start a new instance while one is still running
// shut down the old instance first
sInstance.shutdown();
}
sInstance = this;
mContext = context;
mAssets = mContext.getAssets();
mSsl = ssl;
if (mSsl) {
mServerUri = "https://localhost:" + SSL_SERVER_PORT;
} else {
mServerUri = "http://localhost:" + SERVER_PORT;
}
mMap = MimeTypeMap.getSingleton();
mServerThread = new ServerThread(this, mSsl);
mServerThread.start();
}
/**
* Terminate the http server.
*/
public void shutdown() {
try {
// Avoid a deadlock between two threads where one is trying to call
// close() and the other one is calling accept() by sending a GET
// request for shutdown and having the server's one thread
// sequentially call accept() and close().
URL url = new URL(mServerUri + SHUTDOWN_PREFIX);
URLConnection connection = openConnection(url);
connection.connect();
// Read the input from the stream to send the request.
InputStream is = connection.getInputStream();
is.close();
// Block until the server thread is done shutting down.
mServerThread.join();
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (KeyManagementException e) {
throw new IllegalStateException(e);
}
sInstance = null;
}
private URLConnection openConnection(URL url)
throws IOException, NoSuchAlgorithmException, KeyManagementException {
if (mSsl) {
// Install hostname verifiers and trust managers that don't do
// anything in order to get around the client not trusting
// the test server due to a lack of certificates.
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setHostnameVerifier(new CtsHostnameVerifier());
SSLContext context = SSLContext.getInstance("TLS");
CtsTrustManager trustManager = new CtsTrustManager();
context.init(null, new CtsTrustManager[] {trustManager}, null);
connection.setSSLSocketFactory(context.getSocketFactory());
return connection;
} else {
return url.openConnection();
}
}
/**
* {@link X509TrustManager} that trusts everybody. This is used so that
* the client calling {@link CtsTestServer#shutdown()} can issue a request
* for shutdown by blindly trusting the {@link CtsTestServer}'s
* credentials.
*/
private static class CtsTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) {
// Trust the CtSTestServer...
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
// Trust the CtSTestServer...
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
/**
* {@link HostnameVerifier} that verifies everybody. This permits
* the client to trust the web server and call
* {@link CtsTestServer#shutdown()}.
*/
private static class CtsHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
/**
* Return the URI that points to the server root.
*/
public String getBaseUri() {
return mServerUri;
}
/**
* Return the absolute URL that refers to the given asset.
* @param path The path of the asset. See {@link AssetManager#open(String)}
*/
public String getAssetUrl(String path) {
StringBuilder sb = new StringBuilder(getBaseUri());
sb.append(ASSET_PREFIX);
sb.append(path);
return sb.toString();
}
/**
* Return an artificially delayed absolute URL that refers to the given asset. This can be
* used to emulate a slow HTTP server or connection.
* @param path The path of the asset. See {@link AssetManager#open(String)}
*/
public String getDelayedAssetUrl(String path) {
StringBuilder sb = new StringBuilder(getBaseUri());
sb.append(DELAY_PREFIX);
sb.append(ASSET_PREFIX);
sb.append(path);
return sb.toString();
}
/**
* Return an absolute URL that refers to the given asset and is protected by
* HTTP authentication.
* @param path The path of the asset. See {@link AssetManager#open(String)}
*/
public String getAuthAssetUrl(String path) {
StringBuilder sb = new StringBuilder(getBaseUri());
sb.append(AUTH_PREFIX);
sb.append(ASSET_PREFIX);
sb.append(path);
return sb.toString();
}
/**
* Return an absolute URL that indirectly refers to the given asset.
* When a client fetches this URL, the server will respond with a temporary redirect (302)
* referring to the absolute URL of the given asset.
* @param path The path of the asset. See {@link AssetManager#open(String)}
*/
public String getRedirectingAssetUrl(String path) {
return getRedirectingAssetUrl(path, 1);
}
/**
* Return an absolute URL that indirectly refers to the given asset.
* When a client fetches this URL, the server will respond with a temporary redirect (302)
* referring to the absolute URL of the given asset.
* @param path The path of the asset. See {@link AssetManager#open(String)}
* @param numRedirects The number of redirects required to reach the given asset.
*/
public String getRedirectingAssetUrl(String path, int numRedirects) {
StringBuilder sb = new StringBuilder(getBaseUri());
for (int i = 0; i < numRedirects; i++) {
sb.append(REDIRECT_PREFIX);
}
sb.append(ASSET_PREFIX);
sb.append(path);
return sb.toString();
}
public String getBinaryUrl(String mimeType, int contentLength) {
StringBuilder sb = new StringBuilder(getBaseUri());
sb.append(BINARY_PREFIX);
sb.append("?type=");
sb.append(mimeType);
sb.append("&length=");
sb.append(contentLength);
return sb.toString();
}
public String getCookieUrl(String path) {
StringBuilder sb = new StringBuilder(getBaseUri());
sb.append(COOKIE_PREFIX);
sb.append("/");
sb.append(path);
return sb.toString();
}
public String getUserAgentUrl() {
StringBuilder sb = new StringBuilder(getBaseUri());
sb.append(USERAGENT_PATH);
return sb.toString();
}
public String getLastRequestUrl() {
return mLastQuery;
}
public int getRequestCount() {
return mRequestCount;
}
/**
* Set the validity of any future responses in milliseconds. If this is set to a non-zero
* value, the server will include a "Expires" header.
* @param timeMillis The time, in milliseconds, for which any future response will be valid.
*/
public void setDocumentValidity(long timeMillis) {
mDocValidity = timeMillis;
}
/**
* Set the age of documents served. If this is set to a non-zero value, the server will include
* a "Last-Modified" header calculated from the value.
* @param timeMillis The age, in milliseconds, of any document served in the future.
*/
public void setDocumentAge(long timeMillis) {
mDocAge = timeMillis;
}
/**
* Generate a response to the given request.
* @throws InterruptedException
*/
private HttpResponse getResponse(HttpRequest request) throws InterruptedException {
RequestLine requestLine = request.getRequestLine();
HttpResponse response = null;
mRequestCount += 1;
Log.i(TAG, requestLine.getMethod() + ": " + requestLine.getUri());
String uriString = requestLine.getUri();
mLastQuery = uriString;
URI uri = URI.create(uriString);
String path = uri.getPath();
if (path.equals(FAVICON_PATH)) {
path = FAVICON_ASSET_PATH;
}
if (path.startsWith(DELAY_PREFIX)) {
try {
Thread.sleep(DELAY_MILLIS);
} catch (InterruptedException ignored) {
// ignore
}
path = path.substring(DELAY_PREFIX.length());
}
if (path.startsWith(AUTH_PREFIX)) {
// authentication required
Header[] auth = request.getHeaders("Authorization");
if (auth.length > 0) {
if (auth[0].getValue().equals(AUTH_CREDENTIALS)) {
// fall through and serve content
path = path.substring(AUTH_PREFIX.length());
} else {
// incorrect password
response = createResponse(HttpStatus.SC_FORBIDDEN);
}
} else {
// request authorization
response = createResponse(HttpStatus.SC_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\"");
}
}
if (path.startsWith(BINARY_PREFIX)) {
List <NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
int length = 0;
String mimeType = null;
try {
for (NameValuePair pair : args) {
String name = pair.getName();
if (name.equals("type")) {
mimeType = pair.getValue();
} else if (name.equals("length")) {
length = Integer.parseInt(pair.getValue());
}
}
if (length > 0 && mimeType != null) {
ByteArrayEntity entity = new ByteArrayEntity(new byte[length]);
entity.setContentType(mimeType);
response = createResponse(HttpStatus.SC_OK);
response.setEntity(entity);
response.addHeader("Content-Disposition", "attachment; filename=test.bin");
} else {
// fall through, return 404 at the end
}
} catch (Exception e) {
// fall through, return 404 at the end
Log.w(TAG, e);
}
} else if (path.startsWith(ASSET_PREFIX)) {
path = path.substring(ASSET_PREFIX.length());
// request for an asset file
try {
InputStream in = mAssets.open(path);
response = createResponse(HttpStatus.SC_OK);
InputStreamEntity entity = new InputStreamEntity(in, in.available());
String mimeType =
mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path));
if (mimeType == null) {
mimeType = "text/html";
}
entity.setContentType(mimeType);
response.setEntity(entity);
+ response.setHeader("Content-Length", "" + entity.getContentLength());
} catch (IOException e) {
response = null;
// fall through, return 404 at the end
}
} else if (path.startsWith(REDIRECT_PREFIX)) {
response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length());
Log.i(TAG, "Redirecting to: " + location);
response.addHeader("Location", location);
} else if (path.startsWith(COOKIE_PREFIX)) {
/*
* Return a page with a title containing a list of all incoming cookies,
* separated by '|' characters. If a numeric 'count' value is passed in a cookie,
* return a cookie with the value incremented by 1. Otherwise, return a cookie
* setting 'count' to 0.
*/
response = createResponse(HttpStatus.SC_OK);
Header[] cookies = request.getHeaders("Cookie");
Pattern p = Pattern.compile("count=(\\d+)");
StringBuilder cookieString = new StringBuilder(100);
int count = 0;
for (Header cookie : cookies) {
String value = cookie.getValue();
if (cookieString.length() > 0) {
cookieString.append("|");
}
cookieString.append(value);
Matcher m = p.matcher(value);
if (m.find()) {
count = Integer.parseInt(m.group(1)) + 1;
}
}
response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX);
response.setEntity(createEntity("<html><head><title>" + cookieString +
"</title></head><body>" + cookieString + "</body></html>"));
} else if (path.equals(USERAGENT_PATH)) {
response = createResponse(HttpStatus.SC_OK);
Header agentHeader = request.getFirstHeader("User-Agent");
String agent = "";
if (agentHeader != null) {
agent = agentHeader.getValue();
}
response.setEntity(createEntity("<html><head><title>" + agent + "</title></head>" +
"<body>" + agent + "</body></html>"));
} else if (path.equals(SHUTDOWN_PREFIX)) {
response = createResponse(HttpStatus.SC_OK);
// We cannot close the socket here, because we need to respond.
// Status must be set to OK, or else the test will fail due to
// a RunTimeException.
}
if (response == null) {
response = createResponse(HttpStatus.SC_NOT_FOUND);
}
StatusLine sl = response.getStatusLine();
Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
setDateHeaders(response);
return response;
}
private void setDateHeaders(HttpResponse response) {
long time = System.currentTimeMillis();
if (mDocValidity != 0) {
String expires =
DateUtils.formatDate(new Date(time + mDocValidity), DateUtils.PATTERN_RFC1123);
response.addHeader("Expires", expires);
}
if (mDocAge != 0) {
String modified =
DateUtils.formatDate(new Date(time - mDocAge), DateUtils.PATTERN_RFC1123);
response.addHeader("Last-Modified", modified);
}
response.addHeader("Date", DateUtils.formatDate(new Date(), DateUtils.PATTERN_RFC1123));
}
/**
* Create an empty response with the given status.
*/
private HttpResponse createResponse(int status) {
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, status, null);
// Fill in error reason. Avoid use of the ReasonPhraseCatalog, which is Locale-dependent.
String reason = getReasonString(status);
if (reason != null) {
StringBuffer buf = new StringBuffer("<html><head><title>");
buf.append(reason);
buf.append("</title></head><body>");
buf.append(reason);
buf.append("</body></html>");
response.setEntity(createEntity(buf.toString()));
}
return response;
}
/**
* Create a string entity for the given content.
*/
private StringEntity createEntity(String content) {
try {
StringEntity entity = new StringEntity(content);
entity.setContentType("text/html");
return entity;
} catch (UnsupportedEncodingException e) {
Log.w(TAG, e);
}
return null;
}
private static class ServerThread extends Thread {
private CtsTestServer mServer;
private ServerSocket mSocket;
private boolean mIsSsl;
private boolean mIsCancelled;
private SSLContext mSslContext;
/**
* Defines the keystore contents for the server, BKS version. Holds just a
* single self-generated key. The subject name is "Test Server".
*/
private static final String SERVER_KEYS_BKS =
"AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
"MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
"MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
"BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
"MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
"VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
"cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
"DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
"zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
"9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
"hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
"yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
"4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
"MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
"vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
"P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
"MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
"J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
"rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
"V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
"OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
"bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
"1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
"k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
private String PASSWORD = "android";
/**
* Loads a keystore from a base64-encoded String. Returns the KeyManager[]
* for the result.
*/
private KeyManager[] getKeyManagers() throws Exception {
byte[] bytes = Base64.decode(SERVER_KEYS_BKS.getBytes());
InputStream inputStream = new ByteArrayInputStream(bytes);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(inputStream, PASSWORD.toCharArray());
inputStream.close();
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
return keyManagerFactory.getKeyManagers();
}
public ServerThread(CtsTestServer server, boolean ssl) throws Exception {
super("ServerThread");
mServer = server;
mIsSsl = ssl;
int retry = 3;
while (true) {
try {
if (mIsSsl) {
mSslContext = SSLContext.getInstance("TLS");
mSslContext.init(getKeyManagers(), null, null);
mSocket = mSslContext.getServerSocketFactory().createServerSocket(
SSL_SERVER_PORT);
} else {
mSocket = new ServerSocket(SERVER_PORT);
}
return;
} catch (IOException e) {
Log.w(TAG, e);
if (--retry == 0) {
throw e;
}
// sleep in case server socket is still being closed
Thread.sleep(1000);
}
}
}
public void run() {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
while (!mIsCancelled) {
try {
Socket socket = mSocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, params);
// Determine whether we need to shutdown early before
// parsing the response since conn.close() will crash
// for SSL requests due to UnsupportedOperationException.
HttpRequest request = conn.receiveRequestHeader();
if (isShutdownRequest(request)) {
mIsCancelled = true;
}
HttpResponse response = mServer.getResponse(request);
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
conn.close();
} catch (IOException e) {
// normal during shutdown, ignore
Log.w(TAG, e);
} catch (HttpException e) {
Log.w(TAG, e);
} catch (InterruptedException e) {
Log.w(TAG, e);
} catch (UnsupportedOperationException e) {
// DefaultHttpServerConnection's close() throws an
// UnsupportedOperationException.
Log.w(TAG, e);
}
}
try {
mSocket.close();
} catch (IOException ignored) {
// safe to ignore
}
}
private boolean isShutdownRequest(HttpRequest request) {
RequestLine requestLine = request.getRequestLine();
String uriString = requestLine.getUri();
URI uri = URI.create(uriString);
String path = uri.getPath();
return path.equals(SHUTDOWN_PREFIX);
}
}
}
| true | true | private HttpResponse getResponse(HttpRequest request) throws InterruptedException {
RequestLine requestLine = request.getRequestLine();
HttpResponse response = null;
mRequestCount += 1;
Log.i(TAG, requestLine.getMethod() + ": " + requestLine.getUri());
String uriString = requestLine.getUri();
mLastQuery = uriString;
URI uri = URI.create(uriString);
String path = uri.getPath();
if (path.equals(FAVICON_PATH)) {
path = FAVICON_ASSET_PATH;
}
if (path.startsWith(DELAY_PREFIX)) {
try {
Thread.sleep(DELAY_MILLIS);
} catch (InterruptedException ignored) {
// ignore
}
path = path.substring(DELAY_PREFIX.length());
}
if (path.startsWith(AUTH_PREFIX)) {
// authentication required
Header[] auth = request.getHeaders("Authorization");
if (auth.length > 0) {
if (auth[0].getValue().equals(AUTH_CREDENTIALS)) {
// fall through and serve content
path = path.substring(AUTH_PREFIX.length());
} else {
// incorrect password
response = createResponse(HttpStatus.SC_FORBIDDEN);
}
} else {
// request authorization
response = createResponse(HttpStatus.SC_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\"");
}
}
if (path.startsWith(BINARY_PREFIX)) {
List <NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
int length = 0;
String mimeType = null;
try {
for (NameValuePair pair : args) {
String name = pair.getName();
if (name.equals("type")) {
mimeType = pair.getValue();
} else if (name.equals("length")) {
length = Integer.parseInt(pair.getValue());
}
}
if (length > 0 && mimeType != null) {
ByteArrayEntity entity = new ByteArrayEntity(new byte[length]);
entity.setContentType(mimeType);
response = createResponse(HttpStatus.SC_OK);
response.setEntity(entity);
response.addHeader("Content-Disposition", "attachment; filename=test.bin");
} else {
// fall through, return 404 at the end
}
} catch (Exception e) {
// fall through, return 404 at the end
Log.w(TAG, e);
}
} else if (path.startsWith(ASSET_PREFIX)) {
path = path.substring(ASSET_PREFIX.length());
// request for an asset file
try {
InputStream in = mAssets.open(path);
response = createResponse(HttpStatus.SC_OK);
InputStreamEntity entity = new InputStreamEntity(in, in.available());
String mimeType =
mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path));
if (mimeType == null) {
mimeType = "text/html";
}
entity.setContentType(mimeType);
response.setEntity(entity);
} catch (IOException e) {
response = null;
// fall through, return 404 at the end
}
} else if (path.startsWith(REDIRECT_PREFIX)) {
response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length());
Log.i(TAG, "Redirecting to: " + location);
response.addHeader("Location", location);
} else if (path.startsWith(COOKIE_PREFIX)) {
/*
* Return a page with a title containing a list of all incoming cookies,
* separated by '|' characters. If a numeric 'count' value is passed in a cookie,
* return a cookie with the value incremented by 1. Otherwise, return a cookie
* setting 'count' to 0.
*/
response = createResponse(HttpStatus.SC_OK);
Header[] cookies = request.getHeaders("Cookie");
Pattern p = Pattern.compile("count=(\\d+)");
StringBuilder cookieString = new StringBuilder(100);
int count = 0;
for (Header cookie : cookies) {
String value = cookie.getValue();
if (cookieString.length() > 0) {
cookieString.append("|");
}
cookieString.append(value);
Matcher m = p.matcher(value);
if (m.find()) {
count = Integer.parseInt(m.group(1)) + 1;
}
}
response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX);
response.setEntity(createEntity("<html><head><title>" + cookieString +
"</title></head><body>" + cookieString + "</body></html>"));
} else if (path.equals(USERAGENT_PATH)) {
response = createResponse(HttpStatus.SC_OK);
Header agentHeader = request.getFirstHeader("User-Agent");
String agent = "";
if (agentHeader != null) {
agent = agentHeader.getValue();
}
response.setEntity(createEntity("<html><head><title>" + agent + "</title></head>" +
"<body>" + agent + "</body></html>"));
} else if (path.equals(SHUTDOWN_PREFIX)) {
response = createResponse(HttpStatus.SC_OK);
// We cannot close the socket here, because we need to respond.
// Status must be set to OK, or else the test will fail due to
// a RunTimeException.
}
if (response == null) {
response = createResponse(HttpStatus.SC_NOT_FOUND);
}
StatusLine sl = response.getStatusLine();
Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
setDateHeaders(response);
return response;
}
| private HttpResponse getResponse(HttpRequest request) throws InterruptedException {
RequestLine requestLine = request.getRequestLine();
HttpResponse response = null;
mRequestCount += 1;
Log.i(TAG, requestLine.getMethod() + ": " + requestLine.getUri());
String uriString = requestLine.getUri();
mLastQuery = uriString;
URI uri = URI.create(uriString);
String path = uri.getPath();
if (path.equals(FAVICON_PATH)) {
path = FAVICON_ASSET_PATH;
}
if (path.startsWith(DELAY_PREFIX)) {
try {
Thread.sleep(DELAY_MILLIS);
} catch (InterruptedException ignored) {
// ignore
}
path = path.substring(DELAY_PREFIX.length());
}
if (path.startsWith(AUTH_PREFIX)) {
// authentication required
Header[] auth = request.getHeaders("Authorization");
if (auth.length > 0) {
if (auth[0].getValue().equals(AUTH_CREDENTIALS)) {
// fall through and serve content
path = path.substring(AUTH_PREFIX.length());
} else {
// incorrect password
response = createResponse(HttpStatus.SC_FORBIDDEN);
}
} else {
// request authorization
response = createResponse(HttpStatus.SC_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\"");
}
}
if (path.startsWith(BINARY_PREFIX)) {
List <NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
int length = 0;
String mimeType = null;
try {
for (NameValuePair pair : args) {
String name = pair.getName();
if (name.equals("type")) {
mimeType = pair.getValue();
} else if (name.equals("length")) {
length = Integer.parseInt(pair.getValue());
}
}
if (length > 0 && mimeType != null) {
ByteArrayEntity entity = new ByteArrayEntity(new byte[length]);
entity.setContentType(mimeType);
response = createResponse(HttpStatus.SC_OK);
response.setEntity(entity);
response.addHeader("Content-Disposition", "attachment; filename=test.bin");
} else {
// fall through, return 404 at the end
}
} catch (Exception e) {
// fall through, return 404 at the end
Log.w(TAG, e);
}
} else if (path.startsWith(ASSET_PREFIX)) {
path = path.substring(ASSET_PREFIX.length());
// request for an asset file
try {
InputStream in = mAssets.open(path);
response = createResponse(HttpStatus.SC_OK);
InputStreamEntity entity = new InputStreamEntity(in, in.available());
String mimeType =
mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path));
if (mimeType == null) {
mimeType = "text/html";
}
entity.setContentType(mimeType);
response.setEntity(entity);
response.setHeader("Content-Length", "" + entity.getContentLength());
} catch (IOException e) {
response = null;
// fall through, return 404 at the end
}
} else if (path.startsWith(REDIRECT_PREFIX)) {
response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length());
Log.i(TAG, "Redirecting to: " + location);
response.addHeader("Location", location);
} else if (path.startsWith(COOKIE_PREFIX)) {
/*
* Return a page with a title containing a list of all incoming cookies,
* separated by '|' characters. If a numeric 'count' value is passed in a cookie,
* return a cookie with the value incremented by 1. Otherwise, return a cookie
* setting 'count' to 0.
*/
response = createResponse(HttpStatus.SC_OK);
Header[] cookies = request.getHeaders("Cookie");
Pattern p = Pattern.compile("count=(\\d+)");
StringBuilder cookieString = new StringBuilder(100);
int count = 0;
for (Header cookie : cookies) {
String value = cookie.getValue();
if (cookieString.length() > 0) {
cookieString.append("|");
}
cookieString.append(value);
Matcher m = p.matcher(value);
if (m.find()) {
count = Integer.parseInt(m.group(1)) + 1;
}
}
response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX);
response.setEntity(createEntity("<html><head><title>" + cookieString +
"</title></head><body>" + cookieString + "</body></html>"));
} else if (path.equals(USERAGENT_PATH)) {
response = createResponse(HttpStatus.SC_OK);
Header agentHeader = request.getFirstHeader("User-Agent");
String agent = "";
if (agentHeader != null) {
agent = agentHeader.getValue();
}
response.setEntity(createEntity("<html><head><title>" + agent + "</title></head>" +
"<body>" + agent + "</body></html>"));
} else if (path.equals(SHUTDOWN_PREFIX)) {
response = createResponse(HttpStatus.SC_OK);
// We cannot close the socket here, because we need to respond.
// Status must be set to OK, or else the test will fail due to
// a RunTimeException.
}
if (response == null) {
response = createResponse(HttpStatus.SC_NOT_FOUND);
}
StatusLine sl = response.getStatusLine();
Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
setDateHeaders(response);
return response;
}
|
diff --git a/src/main/java/net/croxis/plugins/lift/Elevator.java b/src/main/java/net/croxis/plugins/lift/Elevator.java
index aefb4e9..46ea05c 100644
--- a/src/main/java/net/croxis/plugins/lift/Elevator.java
+++ b/src/main/java/net/croxis/plugins/lift/Elevator.java
@@ -1,104 +1,109 @@
package net.croxis.plugins.lift;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeMap;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
public class Elevator {
public HashSet<Block> baseBlocks = new HashSet<Block>();
public TreeMap <Integer, Floor> floormap = new TreeMap<Integer, Floor>();//Index is y value
public TreeMap <Integer, Floor> floormap2 = new TreeMap<Integer, Floor>();//Index is floor value
private TreeMap <World, TreeMap<Integer, Floor>> worldFloorMap= new TreeMap <World, TreeMap<Integer, Floor>>();
public HashSet<LivingEntity> passengers = new HashSet<LivingEntity>();
public int destinationY = 0;//Destination y coordinate
public HashSet<Block> glassBlocks = new HashSet<Block>();
public int taskid = 0;
public Floor destFloor = null;
public Floor startFloor = null;
public boolean goingUp = false;
public HashSet<Chunk> chunks = new HashSet<Chunk>();
public HashMap<LivingEntity, Location> holders = new HashMap<LivingEntity, Location>();
public Material baseBlockType = Material.IRON_BLOCK;
public double speed = 0.5;
public void clear(){
baseBlocks.clear();
floormap.clear();
floormap2.clear();
worldFloorMap.clear();
passengers.clear();
glassBlocks.clear();
}
public TreeMap <Integer, Floor> getFloormap(){
return floormap;
}
public TreeMap <Integer, Floor> getFloormap2(){
return floormap2;
}
public Floor getFloorFromY(int y){
return floormap.get(y);
}
public Floor getFloorFromN(int n){
return floormap2.get(n);
}
public boolean isInShaft(Entity entity){
for (Block block : baseBlocks){
Location inside = block.getLocation();
Location loc = entity.getLocation();
- if ((loc.getX() < inside.getX() + 1.0D) &&
+ /*if ((loc.getX() < inside.getX() + 1.0D) &&
(loc.getX() > inside.getX() - 1.0D) &&
(loc.getY() >= inside.getY() - 1.0D) &&
(loc.getY() <= floormap2.get(floormap2.lastKey()).getY()) &&
(loc.getZ() < inside.getZ() + 1.0D) &&
(loc.getZ() > inside.getZ() - 1.0D))
+ return true;*/
+ if (loc.getBlockX() == block.getX() &&
+ (loc.getY() >= inside.getY() - 1.0D) &&
+ (loc.getY() <= floormap2.get(floormap2.lastKey()).getY()) &&
+ loc.getBlockZ() == block.getZ())
return true;
}
return false;
}
public boolean isInShaftAtFloor(Entity entity, Floor floor){
if (isInShaft(entity)){
if (entity.getLocation().getY() >= floor.getY() - 1 && entity.getLocation().getY() <= floor.getY())
return true;
}
return false;
}
public void addPassenger(LivingEntity entity){
passengers.add(entity);
}
public void setPassengers(ArrayList<LivingEntity> entities){
passengers.clear();
passengers.addAll(entities);
}
public HashSet<LivingEntity> getPassengers(){
return passengers;
}
public int getTotalFloors(){
return floormap2.size();
}
public boolean isInLift(Player player){
return passengers.contains(player);
}
}
| false | true | public boolean isInShaft(Entity entity){
for (Block block : baseBlocks){
Location inside = block.getLocation();
Location loc = entity.getLocation();
if ((loc.getX() < inside.getX() + 1.0D) &&
(loc.getX() > inside.getX() - 1.0D) &&
(loc.getY() >= inside.getY() - 1.0D) &&
(loc.getY() <= floormap2.get(floormap2.lastKey()).getY()) &&
(loc.getZ() < inside.getZ() + 1.0D) &&
(loc.getZ() > inside.getZ() - 1.0D))
return true;
}
return false;
}
| public boolean isInShaft(Entity entity){
for (Block block : baseBlocks){
Location inside = block.getLocation();
Location loc = entity.getLocation();
/*if ((loc.getX() < inside.getX() + 1.0D) &&
(loc.getX() > inside.getX() - 1.0D) &&
(loc.getY() >= inside.getY() - 1.0D) &&
(loc.getY() <= floormap2.get(floormap2.lastKey()).getY()) &&
(loc.getZ() < inside.getZ() + 1.0D) &&
(loc.getZ() > inside.getZ() - 1.0D))
return true;*/
if (loc.getBlockX() == block.getX() &&
(loc.getY() >= inside.getY() - 1.0D) &&
(loc.getY() <= floormap2.get(floormap2.lastKey()).getY()) &&
loc.getBlockZ() == block.getZ())
return true;
}
return false;
}
|
diff --git a/sch-kp-web/src/main/java/hu/sch/web/kp/pages/svie/SvieAccount.java b/sch-kp-web/src/main/java/hu/sch/web/kp/pages/svie/SvieAccount.java
index c8c8cd17..a3c2c4d2 100644
--- a/sch-kp-web/src/main/java/hu/sch/web/kp/pages/svie/SvieAccount.java
+++ b/sch-kp-web/src/main/java/hu/sch/web/kp/pages/svie/SvieAccount.java
@@ -1,173 +1,174 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hu.sch.web.kp.pages.svie;
import hu.sch.domain.Membership;
import hu.sch.domain.SvieMembershipType;
import hu.sch.domain.SvieStatus;
import hu.sch.domain.User;
import hu.sch.services.SvieManagerLocal;
import hu.sch.web.components.ConfirmationBoxRenderer;
import hu.sch.web.components.customlinks.SvieRegPdfLink;
import hu.sch.web.kp.templates.SecuredPageTemplate;
import java.util.List;
import javax.ejb.EJB;
import org.apache.log4j.Logger;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
/**
*
* @author aldaris
*/
public final class SvieAccount extends SecuredPageTemplate {
@EJB(name = "SvieManagerBean")
SvieManagerLocal svieManager;
private static Logger log = Logger.getLogger(SvieAccount.class);
private final User user = getUser();
public SvieAccount() {
createNavbarWithSupportId(34);
//ha még nem SVIE tag, akkor továbbítjuk a SVIE regisztrációs oldalra.
if (user == null) {
getSession().error("A SVIE tagsághoz először létre kell hoznod egy közösségi profilt");
throw new RestartResponseException(getApplication().getHomePage());
}
if (user.getSvieMembershipType().equals(SvieMembershipType.NEMTAG)) {
throw new RestartResponseAtInterceptPageException(new SvieRegistration(user));
}
setHeaderLabelText("SVIE tagság beállításai");
add(new FeedbackPanel("pagemessages"));
+ add(new Label("sviestatusLabel", user.getSvieStatus().toString()));
OrdinalFragment ordFragment = new OrdinalFragment("ordinalFragment", "ordinalPanel");
AdvocateFragment advFragment = new AdvocateFragment("advocateFragment", "advocatePanel");
ordFragment.setVisible(false);
advFragment.setVisible(false);
add(ordFragment, advFragment);
if (user.getSvieMembershipType().equals(SvieMembershipType.RENDESTAG)) {
ordFragment.setVisible(true);
} else if (user.getSvieMembershipType().equals(SvieMembershipType.PARTOLOTAG)) {
advFragment.setVisible(true);
}
SvieRegPdfLink regPdfLink = new SvieRegPdfLink("pdfLink", user);
if (!user.getSvieStatus().equals(SvieStatus.FELDOLGOZASALATT)) {
regPdfLink.setVisible(false);
}
add(regPdfLink);
Link<Void> deleteSvieMs = new Link<Void>("deleteSvieMembership") {
@Override
public void onClick() {
svieManager.endMembership(user);
getSession().info("A SVIE tagságodat sikeresen megszüntetted");
setResponsePage(getApplication().getHomePage());
}
};
deleteSvieMs.add(new ConfirmationBoxRenderer("Biztosan meg szeretnéd szüntetni a SVIE tagságod?"));
add(deleteSvieMs);
}
private class OrdinalFragment extends Fragment {
public OrdinalFragment(String id, String markupId) {
super(id, markupId, null, null);
add(new Label("formLabel", "Elsődleges kör kiválasztása"));
Form<User> form = new Form<User>("form") {
@Override
protected void onSubmit() {
if (user.getSviePrimaryMembership() != null) {
svieManager.updatePrimaryMembership(user);
getSession().info("Elsődleges kör sikeresen kiválasztva");
setResponsePage(SvieAccount.class);
}
}
};
form.setModel(new CompoundPropertyModel<User>(user));
IModel<List<Membership>> groupNames = new LoadableDetachableModel<List<Membership>>() {
@Override
protected List<Membership> load() {
return svieManager.getSvieMembershipsForUser(user);
}
};
ListChoice listChoice = new ListChoice("sviePrimaryMembership", groupNames);
listChoice.setChoiceRenderer(new GroupNameChoices());
listChoice.setNullValid(false);
listChoice.setRequired(true);
form.add(listChoice);
add(form);
Link<Void> ordinalToAdvocate = new Link<Void>("ordinalToAdvocate") {
@Override
public void onClick() {
svieManager.OrdinalToAdvocate(user);
getSession().info("Sikeresen pártoló taggá váltál");
setResponsePage(SvieAccount.class);
}
};
ordinalToAdvocate.add(new ConfirmationBoxRenderer("Biztosan pártoló taggá szeretnél válni?"));
add(ordinalToAdvocate);
if (!user.getSvieStatus().equals(SvieStatus.ELFOGADVA)) {
ordinalToAdvocate.setVisible(false);
}
}
}
private class AdvocateFragment extends Fragment {
public AdvocateFragment(String id, String markupId) {
super(id, markupId, null, null);
List<Membership> ms = svieManager.getSvieMembershipsForUser(user);
Link<Void> advocateToOrdinal = new Link<Void>("advocateToOrdinal") {
@Override
public void onClick() {
svieManager.advocateToOrdinal(user);
getSession().info("Rendes taggá válás kezdeményezése sikeresen megtörtént");
setResponsePage(SvieAccount.class);
}
};
if (ms.isEmpty()) {
advocateToOrdinal.setVisible(false);
}
add(advocateToOrdinal);
}
}
private class GroupNameChoices implements IChoiceRenderer<Object> {
public Object getDisplayValue(Object object) {
Membership ms = (Membership) object;
return ms.getGroup().getName();
}
public String getIdValue(Object object, int index) {
Membership ms = (Membership) object;
return ms.getId().toString();
}
}
}
| true | true | public SvieAccount() {
createNavbarWithSupportId(34);
//ha még nem SVIE tag, akkor továbbítjuk a SVIE regisztrációs oldalra.
if (user == null) {
getSession().error("A SVIE tagsághoz először létre kell hoznod egy közösségi profilt");
throw new RestartResponseException(getApplication().getHomePage());
}
if (user.getSvieMembershipType().equals(SvieMembershipType.NEMTAG)) {
throw new RestartResponseAtInterceptPageException(new SvieRegistration(user));
}
setHeaderLabelText("SVIE tagság beállításai");
add(new FeedbackPanel("pagemessages"));
OrdinalFragment ordFragment = new OrdinalFragment("ordinalFragment", "ordinalPanel");
AdvocateFragment advFragment = new AdvocateFragment("advocateFragment", "advocatePanel");
ordFragment.setVisible(false);
advFragment.setVisible(false);
add(ordFragment, advFragment);
if (user.getSvieMembershipType().equals(SvieMembershipType.RENDESTAG)) {
ordFragment.setVisible(true);
} else if (user.getSvieMembershipType().equals(SvieMembershipType.PARTOLOTAG)) {
advFragment.setVisible(true);
}
SvieRegPdfLink regPdfLink = new SvieRegPdfLink("pdfLink", user);
if (!user.getSvieStatus().equals(SvieStatus.FELDOLGOZASALATT)) {
regPdfLink.setVisible(false);
}
add(regPdfLink);
Link<Void> deleteSvieMs = new Link<Void>("deleteSvieMembership") {
@Override
public void onClick() {
svieManager.endMembership(user);
getSession().info("A SVIE tagságodat sikeresen megszüntetted");
setResponsePage(getApplication().getHomePage());
}
};
deleteSvieMs.add(new ConfirmationBoxRenderer("Biztosan meg szeretnéd szüntetni a SVIE tagságod?"));
add(deleteSvieMs);
}
| public SvieAccount() {
createNavbarWithSupportId(34);
//ha még nem SVIE tag, akkor továbbítjuk a SVIE regisztrációs oldalra.
if (user == null) {
getSession().error("A SVIE tagsághoz először létre kell hoznod egy közösségi profilt");
throw new RestartResponseException(getApplication().getHomePage());
}
if (user.getSvieMembershipType().equals(SvieMembershipType.NEMTAG)) {
throw new RestartResponseAtInterceptPageException(new SvieRegistration(user));
}
setHeaderLabelText("SVIE tagság beállításai");
add(new FeedbackPanel("pagemessages"));
add(new Label("sviestatusLabel", user.getSvieStatus().toString()));
OrdinalFragment ordFragment = new OrdinalFragment("ordinalFragment", "ordinalPanel");
AdvocateFragment advFragment = new AdvocateFragment("advocateFragment", "advocatePanel");
ordFragment.setVisible(false);
advFragment.setVisible(false);
add(ordFragment, advFragment);
if (user.getSvieMembershipType().equals(SvieMembershipType.RENDESTAG)) {
ordFragment.setVisible(true);
} else if (user.getSvieMembershipType().equals(SvieMembershipType.PARTOLOTAG)) {
advFragment.setVisible(true);
}
SvieRegPdfLink regPdfLink = new SvieRegPdfLink("pdfLink", user);
if (!user.getSvieStatus().equals(SvieStatus.FELDOLGOZASALATT)) {
regPdfLink.setVisible(false);
}
add(regPdfLink);
Link<Void> deleteSvieMs = new Link<Void>("deleteSvieMembership") {
@Override
public void onClick() {
svieManager.endMembership(user);
getSession().info("A SVIE tagságodat sikeresen megszüntetted");
setResponsePage(getApplication().getHomePage());
}
};
deleteSvieMs.add(new ConfirmationBoxRenderer("Biztosan meg szeretnéd szüntetni a SVIE tagságod?"));
add(deleteSvieMs);
}
|
diff --git a/bundles/binding/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/HttpUtil.java b/bundles/binding/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/HttpUtil.java
index ae62ec5e..716c48af 100644
--- a/bundles/binding/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/HttpUtil.java
+++ b/bundles/binding/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/HttpUtil.java
@@ -1,195 +1,196 @@
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2011, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.binding.http.internal;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Some common methods to be used in both HTTP-In-Binding and HTTP-Out-Binding
*
* @author Thomas.Eichstaedt-Engelen
* @since 0.6.0
*/
public class HttpUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
/** {@link Pattern} which matches the credentials out of an URL */
private static final Pattern URL_CREDENTIALS_PATTERN = Pattern.compile("http://(.*?):(.*?)@.*");
/**
* Excutes the given <code>url</code> with the given <code>httpMethod</code>
*
* @param httpMethod the HTTP method to use
* @param url the url to execute (in milliseconds)
* @param timeout the socket timeout to wait for data
*
* @return the response body or <code>NULL</code> when the request went wrong
*/
public static String executeUrl(String httpMethod, String url, int timeout) {
HttpClient client = new HttpClient();
HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(timeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
Credentials credentials = extractCredentials(url);
if (credentials != null) {
+ client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, credentials);
}
if (logger.isDebugEnabled()) {
try {
logger.debug("About to execute '" + method.getURI().toString() + "'");
} catch (URIException e) {
logger.debug(e.getLocalizedMessage());
}
}
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
logger.warn("Method failed: " + method.getStatusLine());
}
String responseBody = method.getResponseBodyAsString();
if (!responseBody.isEmpty()) {
logger.debug(responseBody);
}
return responseBody;
}
catch (HttpException he) {
logger.error("Fatal protocol violation: ", he);
}
catch (IOException e) {
logger.error("Fatal transport error: {}", e.toString());
}
finally {
method.releaseConnection();
}
return null;
}
/**
* Extracts username and password from the given <code>url</code>. A valid
* url to extract {@link Credentials} from looks like:
* <pre>
* http://username:[email protected]
* </pre>
*
* @param url the URL to extract {@link Credentials} from
*
* @return the exracted Credentials or <code>null</code> if the given
* <code>url</code> does not contain credentials
*/
protected static Credentials extractCredentials(String url) {
Matcher matcher = URL_CREDENTIALS_PATTERN.matcher(url);
if (matcher.matches()) {
matcher.reset();
String username = "";
String password = "";
while (matcher.find()) {
username = matcher.group(1);
password = matcher.group(2);
}
Credentials credentials =
new UsernamePasswordCredentials(username, password);
return credentials;
}
return null;
}
/**
* Factory method to create a {@link HttpMethod}-object according to the
* given String <code>httpMethod</codde>
*
* @param httpMethodString the name of the {@link HttpMethod} to create
* @param url
*
* @return an object of type {@link GetMethod}, {@link PutMethod},
* {@link PostMethod} or {@link DeleteMethod}
* @throws IllegalArgumentException if <code>httpMethod</code> is none of
* <code>GET</code>, <code>PUT</code>, <code>POST</POST> or <code>DELETE</code>
*/
public static HttpMethod createHttpMethod(String httpMethodString, String url) {
if ("GET".equals(httpMethodString)) {
return new GetMethod(url);
}
else if ("PUT".equals(httpMethodString)) {
return new PutMethod(url);
}
else if ("POST".equals(httpMethodString)) {
return new PostMethod(url);
}
else if ("DELETE".equals(httpMethodString)) {
return new DeleteMethod(url);
}
else {
throw new IllegalArgumentException("given httpMethod '" + httpMethodString + "' is unknown");
}
}
}
| true | true | public static String executeUrl(String httpMethod, String url, int timeout) {
HttpClient client = new HttpClient();
HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(timeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
Credentials credentials = extractCredentials(url);
if (credentials != null) {
client.getState().setCredentials(AuthScope.ANY, credentials);
}
if (logger.isDebugEnabled()) {
try {
logger.debug("About to execute '" + method.getURI().toString() + "'");
} catch (URIException e) {
logger.debug(e.getLocalizedMessage());
}
}
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
logger.warn("Method failed: " + method.getStatusLine());
}
String responseBody = method.getResponseBodyAsString();
if (!responseBody.isEmpty()) {
logger.debug(responseBody);
}
return responseBody;
}
catch (HttpException he) {
logger.error("Fatal protocol violation: ", he);
}
catch (IOException e) {
logger.error("Fatal transport error: {}", e.toString());
}
finally {
method.releaseConnection();
}
return null;
}
| public static String executeUrl(String httpMethod, String url, int timeout) {
HttpClient client = new HttpClient();
HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(timeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
Credentials credentials = extractCredentials(url);
if (credentials != null) {
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, credentials);
}
if (logger.isDebugEnabled()) {
try {
logger.debug("About to execute '" + method.getURI().toString() + "'");
} catch (URIException e) {
logger.debug(e.getLocalizedMessage());
}
}
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
logger.warn("Method failed: " + method.getStatusLine());
}
String responseBody = method.getResponseBodyAsString();
if (!responseBody.isEmpty()) {
logger.debug(responseBody);
}
return responseBody;
}
catch (HttpException he) {
logger.error("Fatal protocol violation: ", he);
}
catch (IOException e) {
logger.error("Fatal transport error: {}", e.toString());
}
finally {
method.releaseConnection();
}
return null;
}
|
diff --git a/src/com/dmdirc/util/validators/ColourValidator.java b/src/com/dmdirc/util/validators/ColourValidator.java
index a4489ec..106dbdc 100644
--- a/src/com/dmdirc/util/validators/ColourValidator.java
+++ b/src/com/dmdirc/util/validators/ColourValidator.java
@@ -1,40 +1,40 @@
/*
* Copyright (c) 2006-2010 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.util.validators;
/**
* Validates that the value is a valid IRC colour (hex or mIRC).
*
* @since 0.6.5
* @author chris
*/
public class ColourValidator extends RegexStringValidator implements Validator<String> {
/**
* Creates a new colour validator.
*/
public ColourValidator() {
- super("^[0-9]|1[0-5]|[A-F0-9]{6}$", "Must be a valid colour");
+ super("^[0-9]|1[0-5]|(?i)[A-F0-9]{6}$", "Must be a valid colour");
}
}
| true | true | public ColourValidator() {
super("^[0-9]|1[0-5]|[A-F0-9]{6}$", "Must be a valid colour");
}
| public ColourValidator() {
super("^[0-9]|1[0-5]|(?i)[A-F0-9]{6}$", "Must be a valid colour");
}
|
diff --git a/src/org/jruby/parser/LocalNamesElement.java b/src/org/jruby/parser/LocalNamesElement.java
index e6e257a58..278521410 100644
--- a/src/org/jruby/parser/LocalNamesElement.java
+++ b/src/org/jruby/parser/LocalNamesElement.java
@@ -1,152 +1,154 @@
/*
* LocalVariableNames.java - description
* Created on 25.02.2002, 21:34:15
*
* Copyright (C) 2001, 2002 Jan Arne Petersen
* Jan Arne Petersen <[email protected]>
*
* JRuby - http://jruby.sourceforge.net
*
* This file is part of JRuby
*
* JRuby 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.
*
* JRuby 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 JRuby; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jruby.parser;
import java.util.*;
import org.jruby.util.collections.*;
/**
*
* @author jpetersen
* @version $Revision$
*/
public class LocalNamesElement implements StackElement {
private LocalNamesElement next;
private List localNames;
private int blockLevel;
/**
* @see StackElement#getNext()
*/
public StackElement getNext() {
return next;
}
/**
* @see StackElement#setNext(StackElement)
*/
public void setNext(StackElement newNext) {
this.next = (LocalNamesElement) newNext;
}
/**
* Returns true if there was already an assignment to a local
* variable named name, false otherwise.
*
* MRI: cf local_id
* @param name The name of the local variable.
* @return true if there was already an assignment to a local
* variable named id.
*/
public boolean isLocalRegistered(String name) {
if (localNames == null) {
return false;
} else {
return localNames.contains(name);
}
}
/**
* Returns the index of the local variable 'name' in the table
* of registered variable names.
*
* If name is not registered yet, register the variable name.
*
* If name == null returns the count of registered variable names.
* MRI: cf local_cnt
* @todo: this method is often used for its side effect (for registering a name)
* it should either be renamed or an other method without a return and with
* a better name should be used for this. the getLocalIndex name makes one
* believe the main purpose of this method is getting something while the
* result is often ignored.
*@param name The name of the local variable
*@return The index in the table of registered variable names.
*/
public int getLocalIndex(String name) {
if (name == null) {
return localNames != null ? localNames.size() : 0;
} else if (localNames == null) {
return registerLocal(name);
}
int index = localNames.indexOf(name);
if (index != -1) {
return index;
}
return registerLocal(name);
}
/**
* Register the local variable name 'name' in the table
* of registered variable names.
* Returns the index of the added local variable name in the table.
*
* MRI: cf local_append
*@param name The name of the local variable.
*@return The index of the local variable name in the table.
*/
public int registerLocal(String name) {
if (localNames == null) {
localNames = new ArrayList();
localNames.add("_");
localNames.add("~");
- if (name.equals("_")) {
- return 0;
- } else if (name.equals("~")) {
- return 1;
+ if (name != null) {
+ if (name.equals("_")) {
+ return 0;
+ } else if (name.equals("~")) {
+ return 1;
+ }
}
}
localNames.add(name);
return localNames.size() - 1;
}
/**
* Gets the localNames.
* @return Returns a List
*/
public List getLocalNames() {
return localNames != null ? localNames : Collections.EMPTY_LIST;
}
/**
* Sets the localNames.
* @param localNames The localNames to set
*/
public void setLocalNames(List localNames) {
this.localNames = localNames;
}
public boolean isInBlock() {
return blockLevel > 0;
}
public void changeBlockLevel(int change) {
blockLevel = blockLevel + change;
}
}
| true | true | public int registerLocal(String name) {
if (localNames == null) {
localNames = new ArrayList();
localNames.add("_");
localNames.add("~");
if (name.equals("_")) {
return 0;
} else if (name.equals("~")) {
return 1;
}
}
localNames.add(name);
return localNames.size() - 1;
}
| public int registerLocal(String name) {
if (localNames == null) {
localNames = new ArrayList();
localNames.add("_");
localNames.add("~");
if (name != null) {
if (name.equals("_")) {
return 0;
} else if (name.equals("~")) {
return 1;
}
}
}
localNames.add(name);
return localNames.size() - 1;
}
|
diff --git a/src/org/openstreetmap/fma/jtiledownloader/views/main/inputpanel/BBoxLatLonPanel.java b/src/org/openstreetmap/fma/jtiledownloader/views/main/inputpanel/BBoxLatLonPanel.java
index 3ec6a9e..d84c368 100644
--- a/src/org/openstreetmap/fma/jtiledownloader/views/main/inputpanel/BBoxLatLonPanel.java
+++ b/src/org/openstreetmap/fma/jtiledownloader/views/main/inputpanel/BBoxLatLonPanel.java
@@ -1,373 +1,373 @@
/*
* Copyright 2008, Friedrich Maier
* Copyright 2010, Sven Strickroth <[email protected]>
*
* This file is part of JTileDownloader.
*
* JTileDownloader 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.
*
* JTileDownloader 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 (see file COPYING.txt) of the GNU
* General Public License along with JTileDownloader.
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.openstreetmap.fma.jtiledownloader.views.main.inputpanel;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.openstreetmap.fma.jtiledownloader.config.AppConfiguration;
import org.openstreetmap.fma.jtiledownloader.config.DownloadConfigurationBBoxLatLon;
import org.openstreetmap.fma.jtiledownloader.config.DownloadConfigurationSaverIf;
import org.openstreetmap.fma.jtiledownloader.tilelist.TileList;
import org.openstreetmap.fma.jtiledownloader.tilelist.TileListBBoxLatLon;
import org.openstreetmap.fma.jtiledownloader.views.main.MainPanel;
import org.openstreetmap.fma.jtiledownloader.views.main.slippymap.SlippyMapChooser;
import org.openstreetmap.fma.jtiledownloader.views.main.slippymap.SlippyMapChooserWindow;
/**
*
*/
public class BBoxLatLonPanel
extends InputPanel
{
private static final long serialVersionUID = 1L;
private static final String COMPONENT_MINLAT = "MIN_LAT";
private static final String COMPONENT_MINLON = "MIN_LON";
private static final String COMPONENT_MAXLAT = "MAX_LAT";
private static final String COMPONENT_MAXLON = "MAX_LON";
private TileListBBoxLatLon _tileList = new TileListBBoxLatLon();
private JLabel _labelMinLat = new JLabel("Min. Latitude:");
private JTextField _textMinLat = new JTextField();
private JLabel _labelMinLon = new JLabel("Min. Longitude:");
private JTextField _textMinLon = new JTextField();
private JLabel _labelMaxLat = new JLabel("Max. Latitude:");
private JTextField _textMaxLat = new JTextField();
private JLabel _labelMaxLon = new JLabel("Max. Longitude:");
private JTextField _textMaxLon = new JTextField();
private JButton _buttonSlippyMapChooser = new JButton("Slippy Map chooser");
private DownloadConfigurationBBoxLatLon _downloadConfig;
private SlippyMapChooser changeListener = null;
private SlippyMapChooserWindow smc = null;
/**
* @param mainPanel
*/
public BBoxLatLonPanel(MainPanel mainPanel)
{
super(mainPanel);
createPanel();
initializePanel();
loadConfig(AppConfiguration.getInstance());
}
/**
* @see org.openstreetmap.fma.jtiledownloader.views.main.inputpanel.InputPanel#getJobType()
*/
@Override
public String getJobType()
{
return DownloadConfigurationBBoxLatLon.ID;
}
@Override
public void loadConfig(DownloadConfigurationSaverIf configurationSaver)
{
_downloadConfig = new DownloadConfigurationBBoxLatLon();
configurationSaver.loadDownloadConfig(_downloadConfig);
_textMinLat.setText("" + _downloadConfig.getMinLat());
_textMinLon.setText("" + _downloadConfig.getMinLon());
_textMaxLat.setText("" + _downloadConfig.getMaxLat());
_textMaxLon.setText("" + _downloadConfig.getMaxLon());
}
/**
*
*/
private void initializePanel()
{
_textMinLat.setName(COMPONENT_MINLAT);
_textMinLat.addFocusListener(new MyFocusListener());
_textMinLon.setName(COMPONENT_MINLON);
_textMinLon.addFocusListener(new MyFocusListener());
_textMaxLat.setName(COMPONENT_MAXLAT);
_textMaxLat.addFocusListener(new MyFocusListener());
_textMaxLon.setName(COMPONENT_MAXLON);
_textMaxLon.addFocusListener(new MyFocusListener());
_buttonSlippyMapChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
boolean isOk = false;
if (AppConfiguration.getInstance().isSlippyMap_NoDownload())
{
- JOptionPane.showMessageDialog(null, "SlippyMap will use \"" + AppConfiguration.getInstance().getOutputFolder() + "\" as local read-only-cache folder and will only display tiles which are already there (regardless of the selected tile-provider).");
+ JOptionPane.showMessageDialog(null, "SlippyMap will use \"" + _mainPanel.getOutputfolder() + "\" as local read-only-cache folder and will only display tiles which are already there (regardless of the selected tile-provider).");
isOk=true;
}
else if (!AppConfiguration.getInstance().isSlippyMap_SaveTiles())
{
- JOptionPane.showMessageDialog(null, "SlippyMap will use \"" + AppConfiguration.getInstance().getOutputFolder() + "\" as local read-only-cache folder and will load missing tiles from tile provider \"" + _mainPanel.getSelectedTileProvider().getName() + "\" w/o saving them to the output-folder.");
+ JOptionPane.showMessageDialog(null, "SlippyMap will use \"" + _mainPanel.getOutputfolder() + "\" as local read-only-cache folder and will load missing tiles from tile provider \"" + _mainPanel.getSelectedTileProvider().getName() + "\" w/o saving them to the output-folder.");
isOk=true;
}
- if (isOk || (AppConfiguration.getInstance().isSlippyMap_SaveTiles() && JOptionPane.showConfirmDialog(null, "SlippyMap will use \"" + AppConfiguration.getInstance().getOutputFolder() + "\" as local cache/download-folder and tileprovider \"" + _mainPanel.getSelectedTileProvider().getName() + "\".\nDo you want to continue?", "JTileDownloader SlippyMap", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
+ if (isOk || (AppConfiguration.getInstance().isSlippyMap_SaveTiles() && JOptionPane.showConfirmDialog(null, "SlippyMap will use \"" + _mainPanel.getOutputfolder() + "\" as local cache/download-folder and tileprovider \"" + _mainPanel.getSelectedTileProvider().getName() + "\".\nDo you want to continue?", "JTileDownloader SlippyMap", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
{
if (smc == null)
{
- smc = new SlippyMapChooserWindow((BBoxLatLonPanel) ((Component) arg0.getSource()).getParent(), _mainPanel.getSelectedTileProvider(), AppConfiguration.getInstance().getOutputFolder());
+ smc = new SlippyMapChooserWindow((BBoxLatLonPanel) ((Component) arg0.getSource()).getParent(), _mainPanel.getSelectedTileProvider(), _mainPanel.getOutputfolder());
}
smc.getSlippyMapChooser().setSaveTiles(AppConfiguration.getInstance().isSlippyMap_SaveTiles());
smc.getSlippyMapChooser().setNoDownload(AppConfiguration.getInstance().isSlippyMap_NoDownload());
- smc.getSlippyMapChooser().setDirectory(AppConfiguration.getInstance().getOutputFolder());
+ smc.getSlippyMapChooser().setDirectory(_mainPanel.getOutputfolder());
smc.getSlippyMapChooser().setTileProvider(_mainPanel.getSelectedTileProvider());
smc.setVisible(true);
}
}
});
}
/**
*
*/
private void createPanel()
{
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets = new Insets(5, 5, 0, 5);
constraints.gridwidth = GridBagConstraints.RELATIVE;
add(_labelMinLat, constraints);
constraints.gridwidth = GridBagConstraints.REMAINDER;
add(_textMinLat, constraints);
constraints.gridwidth = GridBagConstraints.RELATIVE;
add(_labelMaxLat, constraints);
constraints.gridwidth = GridBagConstraints.REMAINDER;
add(_textMaxLat, constraints);
constraints.gridwidth = GridBagConstraints.RELATIVE;
add(_labelMinLon, constraints);
constraints.gridwidth = GridBagConstraints.REMAINDER;
add(_textMinLon, constraints);
constraints.gridwidth = GridBagConstraints.RELATIVE;
add(_labelMaxLon, constraints);
constraints.gridwidth = GridBagConstraints.REMAINDER;
add(_textMaxLon, constraints);
add(_buttonSlippyMapChooser, constraints);
}
public void setCoordinates(double minLatitude, double minLongitude, double maxLatitude, double maxLongitude)
{
_textMaxLon.setText(String.valueOf(maxLongitude));
_textMaxLat.setText(String.valueOf(maxLatitude));
_textMinLon.setText(String.valueOf(minLongitude));
_textMinLat.setText(String.valueOf(minLatitude));
updateTileList(true);
}
/**
*
*/
private void updateTileList(boolean onlyLatLonChanged)
{
_tileList.setDownloadZoomLevels(getDownloadZoomLevel());
_tileList.setMinLat(getMinLat());
_tileList.setMinLon(getMinLon());
_tileList.setMaxLat(getMaxLat());
_tileList.setMaxLon(getMaxLon());
_tileList.calculateTileValuesXY();
updateNumberOfTiles();
if (smc != null && !onlyLatLonChanged)
{
smc.setVisible(false);
}
}
@Override
public void saveConfig(DownloadConfigurationSaverIf configurationSave)
{
if (_downloadConfig == null)
{
return;
}
_downloadConfig.setMinLat(getMinLat());
_downloadConfig.setMinLon(getMinLon());
_downloadConfig.setMaxLat(getMaxLat());
_downloadConfig.setMaxLon(getMaxLon());
configurationSave.saveDownloadConfig(_downloadConfig);
}
/**
* @return min latitude
*/
public double getMinLat()
{
String str = _textMinLat.getText().trim();
if (str == null || str.length() == 0)
{
return 0.0;
}
return Double.parseDouble(str);
}
/**
* @return min longitude
*/
public double getMinLon()
{
String str = _textMinLon.getText().trim();
if (str == null || str.length() == 0)
{
return 0.0;
}
return Double.parseDouble(str);
}
/**
* @return max latitude
*/
public double getMaxLat()
{
String str = _textMaxLat.getText().trim();
if (str == null || str.length() == 0)
{
return 0.0;
}
return Double.parseDouble(str);
}
/**
* @return max longitude
*/
public double getMaxLon()
{
String str = _textMaxLon.getText().trim();
if (str == null || str.length() == 0)
{
return 0.0;
}
return Double.parseDouble(str);
}
/**
* @return number of tiles
*/
@Override
public int getNumberOfTilesToDownload()
{
return _tileList.getTileCount();
}
class MyFocusListener
implements FocusListener
{
/**
* @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent)
*/
public void focusGained(FocusEvent focusevent)
{
}
/**
* @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent)
*/
public void focusLost(FocusEvent focusevent)
{
String componentName = focusevent.getComponent().getName();
System.out.println("focusLost: " + componentName);
if (componentName.equalsIgnoreCase(COMPONENT_MINLAT))
{
updateAll();
}
else if (componentName.equalsIgnoreCase(COMPONENT_MINLON))
{
updateAll();
}
else if (componentName.equalsIgnoreCase(COMPONENT_MAXLAT))
{
updateAll();
}
else if (componentName.equalsIgnoreCase(COMPONENT_MAXLON))
{
updateAll();
}
}
}
/**
* @see org.openstreetmap.fma.jtiledownloader.views.main.inputpanel.InputPanel#updateAll()
*/
@Override
public void updateAll()
{
if (changeListener != null)
{
changeListener.boundingBoxChanged();
}
updateTileList(false);
}
/**
* @see org.openstreetmap.fma.jtiledownloader.views.main.inputpanel.InputPanel#getTileList()
*/
@Override
public TileList getTileList()
{
return _tileList;
}
/**
* @see org.openstreetmap.fma.jtiledownloader.views.main.inputpanel.InputPanel#getInputName()
*/
@Override
public String getInputName()
{
return "Bounding Box (Lat/Lon)";
}
/**
* Setter for changeListener
* @param changeListener the changeListener to set
*/
public void setChangeListener(SlippyMapChooser changeListener)
{
this.changeListener = changeListener;
}
}
| false | true | private void initializePanel()
{
_textMinLat.setName(COMPONENT_MINLAT);
_textMinLat.addFocusListener(new MyFocusListener());
_textMinLon.setName(COMPONENT_MINLON);
_textMinLon.addFocusListener(new MyFocusListener());
_textMaxLat.setName(COMPONENT_MAXLAT);
_textMaxLat.addFocusListener(new MyFocusListener());
_textMaxLon.setName(COMPONENT_MAXLON);
_textMaxLon.addFocusListener(new MyFocusListener());
_buttonSlippyMapChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
boolean isOk = false;
if (AppConfiguration.getInstance().isSlippyMap_NoDownload())
{
JOptionPane.showMessageDialog(null, "SlippyMap will use \"" + AppConfiguration.getInstance().getOutputFolder() + "\" as local read-only-cache folder and will only display tiles which are already there (regardless of the selected tile-provider).");
isOk=true;
}
else if (!AppConfiguration.getInstance().isSlippyMap_SaveTiles())
{
JOptionPane.showMessageDialog(null, "SlippyMap will use \"" + AppConfiguration.getInstance().getOutputFolder() + "\" as local read-only-cache folder and will load missing tiles from tile provider \"" + _mainPanel.getSelectedTileProvider().getName() + "\" w/o saving them to the output-folder.");
isOk=true;
}
if (isOk || (AppConfiguration.getInstance().isSlippyMap_SaveTiles() && JOptionPane.showConfirmDialog(null, "SlippyMap will use \"" + AppConfiguration.getInstance().getOutputFolder() + "\" as local cache/download-folder and tileprovider \"" + _mainPanel.getSelectedTileProvider().getName() + "\".\nDo you want to continue?", "JTileDownloader SlippyMap", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
{
if (smc == null)
{
smc = new SlippyMapChooserWindow((BBoxLatLonPanel) ((Component) arg0.getSource()).getParent(), _mainPanel.getSelectedTileProvider(), AppConfiguration.getInstance().getOutputFolder());
}
smc.getSlippyMapChooser().setSaveTiles(AppConfiguration.getInstance().isSlippyMap_SaveTiles());
smc.getSlippyMapChooser().setNoDownload(AppConfiguration.getInstance().isSlippyMap_NoDownload());
smc.getSlippyMapChooser().setDirectory(AppConfiguration.getInstance().getOutputFolder());
smc.getSlippyMapChooser().setTileProvider(_mainPanel.getSelectedTileProvider());
smc.setVisible(true);
}
}
});
}
| private void initializePanel()
{
_textMinLat.setName(COMPONENT_MINLAT);
_textMinLat.addFocusListener(new MyFocusListener());
_textMinLon.setName(COMPONENT_MINLON);
_textMinLon.addFocusListener(new MyFocusListener());
_textMaxLat.setName(COMPONENT_MAXLAT);
_textMaxLat.addFocusListener(new MyFocusListener());
_textMaxLon.setName(COMPONENT_MAXLON);
_textMaxLon.addFocusListener(new MyFocusListener());
_buttonSlippyMapChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
boolean isOk = false;
if (AppConfiguration.getInstance().isSlippyMap_NoDownload())
{
JOptionPane.showMessageDialog(null, "SlippyMap will use \"" + _mainPanel.getOutputfolder() + "\" as local read-only-cache folder and will only display tiles which are already there (regardless of the selected tile-provider).");
isOk=true;
}
else if (!AppConfiguration.getInstance().isSlippyMap_SaveTiles())
{
JOptionPane.showMessageDialog(null, "SlippyMap will use \"" + _mainPanel.getOutputfolder() + "\" as local read-only-cache folder and will load missing tiles from tile provider \"" + _mainPanel.getSelectedTileProvider().getName() + "\" w/o saving them to the output-folder.");
isOk=true;
}
if (isOk || (AppConfiguration.getInstance().isSlippyMap_SaveTiles() && JOptionPane.showConfirmDialog(null, "SlippyMap will use \"" + _mainPanel.getOutputfolder() + "\" as local cache/download-folder and tileprovider \"" + _mainPanel.getSelectedTileProvider().getName() + "\".\nDo you want to continue?", "JTileDownloader SlippyMap", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
{
if (smc == null)
{
smc = new SlippyMapChooserWindow((BBoxLatLonPanel) ((Component) arg0.getSource()).getParent(), _mainPanel.getSelectedTileProvider(), _mainPanel.getOutputfolder());
}
smc.getSlippyMapChooser().setSaveTiles(AppConfiguration.getInstance().isSlippyMap_SaveTiles());
smc.getSlippyMapChooser().setNoDownload(AppConfiguration.getInstance().isSlippyMap_NoDownload());
smc.getSlippyMapChooser().setDirectory(_mainPanel.getOutputfolder());
smc.getSlippyMapChooser().setTileProvider(_mainPanel.getSelectedTileProvider());
smc.setVisible(true);
}
}
});
}
|
diff --git a/src/main/java/me/blha303/giveeverydamnachievement/Main.java b/src/main/java/me/blha303/giveeverydamnachievement/Main.java
index 5d847b2..7f29137 100644
--- a/src/main/java/me/blha303/giveeverydamnachievement/Main.java
+++ b/src/main/java/me/blha303/giveeverydamnachievement/Main.java
@@ -1,27 +1,32 @@
package me.blha303.giveeverydamnachievement;
import org.bukkit.Achievement;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
- public boolean onCommand(CommandSender sender, Command command,
- String label, String[] args) {
- Player p = null;
- try {
- p = getServer().getPlayer(args[0]);
- } catch (Exception e) {
- return false;
+ public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
+ {
+ Player p = null;
+ try
+ {
+ p = getServer().getPlayer(args[0]);
+ }
+ catch (Exception e)
+ {
+ return false;
+ }
+ if (p != null)
+ {
+ for (Achievement ach : Achievement.values())
+ {
+ p.awardAchievement(ach);
+ }
+ return true;
+ }
+ return false;
}
- if (p != null) {
- for (Achievement ach : Achievement.values()) {
- p.awardAchievement(ach);
- }
- return true;
- }
- return false;
- }
}
| false | true | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
Player p = null;
try {
p = getServer().getPlayer(args[0]);
} catch (Exception e) {
return false;
}
if (p != null) {
for (Achievement ach : Achievement.values()) {
p.awardAchievement(ach);
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
Player p = null;
try
{
p = getServer().getPlayer(args[0]);
}
catch (Exception e)
{
return false;
}
if (p != null)
{
for (Achievement ach : Achievement.values())
{
p.awardAchievement(ach);
}
return true;
}
return false;
}
|
diff --git a/core/src/main/java/org/mule/galaxy/impl/ScriptManagerImpl.java b/core/src/main/java/org/mule/galaxy/impl/ScriptManagerImpl.java
index 213679e3..89771929 100755
--- a/core/src/main/java/org/mule/galaxy/impl/ScriptManagerImpl.java
+++ b/core/src/main/java/org/mule/galaxy/impl/ScriptManagerImpl.java
@@ -1,96 +1,97 @@
package org.mule.galaxy.impl;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import java.io.IOException;
import java.util.Map;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.UnsupportedRepositoryOperationException;
import org.mule.galaxy.RegistryException;
import org.mule.galaxy.impl.jcr.JcrUtil;
import org.mule.galaxy.impl.jcr.onm.AbstractReflectionDao;
import org.mule.galaxy.script.Script;
import org.mule.galaxy.script.ScriptManager;
import org.mule.galaxy.security.AccessControlManager;
import org.mule.galaxy.security.AccessException;
import org.mule.galaxy.security.Permission;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springmodules.jcr.JcrCallback;
public class ScriptManagerImpl extends AbstractReflectionDao<Script>
implements ScriptManager, ApplicationContextAware {
private ApplicationContext applicationContext;
private AccessControlManager accessControlManager;
private Map<String, Object> scriptVariables;
public ScriptManagerImpl() throws Exception {
super(Script.class, "scripts", true);
}
@Override
protected void doInitializeInJcrTransaction(Session session) throws RepositoryException,
UnsupportedRepositoryOperationException {
super.doInitializeInJcrTransaction(session);
for (Script s : listAll()) {
if (s.isRunOnStartup()) {
try {
execute(s.getScript());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
public String execute(final String scriptText) throws AccessException, RegistryException {
accessControlManager.assertAccess(Permission.EXECUTE_ADMIN_SCRIPTS);
final Binding binding = new Binding();
binding.setProperty("applicationContext", applicationContext);
for (Map.Entry<String, Object> e : scriptVariables.entrySet()) {
binding.setProperty(e.getKey(), e.getValue());
}
try {
return (String)JcrUtil.doInTransaction(getSessionFactory(), new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
GroovyShell shell = new GroovyShell(Thread.currentThread().getContextClassLoader(), binding);
Object result = shell.evaluate(scriptText);
return result == null ? null : result.toString();
}
});
} catch (Exception e1) {
+ logger.error(e1);
throw new RegistryException(e1);
}
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void setAccessControlManager(AccessControlManager accessControlManager) {
this.accessControlManager = accessControlManager;
}
protected String generateNodeName(Script s) {
return s.getName();
}
public void setScriptVariables(Map<String, Object> scriptVariables) {
this.scriptVariables = scriptVariables;
}
}
| true | true | public String execute(final String scriptText) throws AccessException, RegistryException {
accessControlManager.assertAccess(Permission.EXECUTE_ADMIN_SCRIPTS);
final Binding binding = new Binding();
binding.setProperty("applicationContext", applicationContext);
for (Map.Entry<String, Object> e : scriptVariables.entrySet()) {
binding.setProperty(e.getKey(), e.getValue());
}
try {
return (String)JcrUtil.doInTransaction(getSessionFactory(), new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
GroovyShell shell = new GroovyShell(Thread.currentThread().getContextClassLoader(), binding);
Object result = shell.evaluate(scriptText);
return result == null ? null : result.toString();
}
});
} catch (Exception e1) {
throw new RegistryException(e1);
}
}
| public String execute(final String scriptText) throws AccessException, RegistryException {
accessControlManager.assertAccess(Permission.EXECUTE_ADMIN_SCRIPTS);
final Binding binding = new Binding();
binding.setProperty("applicationContext", applicationContext);
for (Map.Entry<String, Object> e : scriptVariables.entrySet()) {
binding.setProperty(e.getKey(), e.getValue());
}
try {
return (String)JcrUtil.doInTransaction(getSessionFactory(), new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
GroovyShell shell = new GroovyShell(Thread.currentThread().getContextClassLoader(), binding);
Object result = shell.evaluate(scriptText);
return result == null ? null : result.toString();
}
});
} catch (Exception e1) {
logger.error(e1);
throw new RegistryException(e1);
}
}
|
diff --git a/km/com/hifiremote/jp1/DeviceUpgrade.java b/km/com/hifiremote/jp1/DeviceUpgrade.java
index a3dc28b..79f9605 100644
--- a/km/com/hifiremote/jp1/DeviceUpgrade.java
+++ b/km/com/hifiremote/jp1/DeviceUpgrade.java
@@ -1,1536 +1,1560 @@
package com.hifiremote.jp1;
import java.util.*;
import java.io.*;
import java.text.*;
import javax.swing.*;
import java.awt.*;
public class DeviceUpgrade
{
public DeviceUpgrade()
{
devTypeAliasName = deviceTypeAliasNames[ 0 ];
initFunctions();
}
public void reset()
{
description = null;
setupCode = 0;
// remove all currently assigned functions
remote.clearButtonAssignments();
Remote[] remotes = RemoteManager.getRemoteManager().getRemotes();
if ( remote == null )
remote = remotes[ 0 ];
devTypeAliasName = deviceTypeAliasNames[ 0 ];
ProtocolManager pm = ProtocolManager.getProtocolManager();
Vector names = pm.getNames();
Protocol tentative = null;
for ( Enumeration e = names.elements(); e.hasMoreElements(); )
{
String protocolName = ( String )e.nextElement();
Protocol p = pm.findProtocolForRemote( remote, protocolName );
if ( p != null )
{
protocol = p;
break;
}
}
DeviceParameter[] devParms = protocol.getDeviceParameters();
for ( int i = 0; i < devParms.length; i++ )
devParms[ i ].setValue( null );
setProtocol( protocol );
notes = null;
file = null;
functions.clear();
initFunctions();
extFunctions.clear();
}
private void initFunctions()
{
String[] names = KeyMapMaster.getCustomNames();
if ( names == null )
names = defaultFunctionNames;
for ( int i = 0; i < names.length; i++ )
functions.add( new Function( names[ i ]));
}
public void setDescription( String text )
{
description = text;
}
public String getDescription()
{
return description;
}
public void setSetupCode( int setupCode )
{
this.setupCode = setupCode;
}
public int getSetupCode()
{
return setupCode;
}
public void setRemote( Remote newRemote )
{
Protocol p = protocol;
ProtocolManager pm = ProtocolManager.getProtocolManager();
Vector protocols = pm.getProtocolsForRemote( newRemote, false );
if ( !protocols.contains( p ))
{
System.err.println( "DeviceUpgrade.setRemote(), protocol " + p.getDiagnosticName() +
" is not built into remote " + newRemote.getName());
Protocol newp = pm.findProtocolForRemote( newRemote, p.getName() );
if ( newp != null )
{
System.err.println( "protocol " + newp.getDiagnosticName() + " will be used." );
if ( newp != p )
{
System.err.println( "\tChecking for matching dev. parms" );
DeviceParameter[] parms = p.getDeviceParameters();
DeviceParameter[] parms2 = newp.getDeviceParameters();
int[] map = new int[ parms.length ];
boolean parmsMatch = true;
for ( int i = 0; i < parms.length; i++ )
{
String name = parms[ i ].getName();
System.err.print( "\tchecking " + name );
boolean nameMatch = false;
for ( int j = 0; j < parms2.length; j++ )
{
if ( name.equals( parms2[ j ].getName()))
{
map[ i ] = j;
nameMatch = true;
System.err.print( " has a match!" );
break;
}
}
if ( !nameMatch )
{
Object v = parms[ i ].getValue();
Object d = parms[ i ].getDefaultValue();
if ( d != null )
d = (( DefaultValue )d ).value();
System.err.print( " no match!" );
if (( v == null ) ||
( v.equals( d )))
{
nameMatch = true;
map[ i ] = -1;
System.err.print( " But there's no value anyway! " );
}
}
System.err.println();
parmsMatch = nameMatch;
if ( !parmsMatch )
break;
}
if ( parmsMatch )
{
// copy parameters from p to p2!
System.err.println( "\tCopying dev. parms" );
for ( int i = 0; i < map.length; i++ )
{
if ( map[ i ] == -1 )
continue;
System.err.println( "\tfrom index " + i + " to index " + map[ i ]);
parms2[ map[ i ]].setValue( parms[ i ].getValue());
}
System.err.println();
System.err.println( "Setting new protocol" );
p.convertFunctions( functions, newp );
protocol = newp;
}
}
}
else
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The selected protocol " + p.getDiagnosticName() +
"\nis not compatible with the selected remote.\n" +
"This upgrade will NOT function correctly.\n" +
"Please choose a different protocol.",
"Error", JOptionPane.ERROR_MESSAGE );
}
if (( remote != null ) && ( remote != newRemote ))
{
Button[] buttons = remote.getUpgradeButtons();
Button[] newButtons = newRemote.getUpgradeButtons();
Vector unassigned = new Vector();
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
Function sf = b.getShiftedFunction();
Function xf = b.getXShiftedFunction();
if (( f != null ) || ( sf != null ) || ( xf != null ))
{
if ( f != null )
b.setFunction( null );
if ( sf != null )
b.setShiftedFunction( null );
if ( xf != null )
b.setXShiftedFunction( null );
Button newB = newRemote.findByStandardName( b );
if ( newB != null )
{
if ( f != null )
newB.setFunction( f );
if ( sf != null )
newB.setShiftedFunction( sf );
if ( xf != null )
newB.setXShiftedFunction( xf );
}
else // keep track of lost assignments
{
Vector temp = null;
if ( f != null )
{
temp = new Vector();
temp.add( f.getName());
temp.add( b.getName());
unassigned.add( temp );
}
if ( sf != null )
{
temp = new Vector();
temp.add( sf.getName());
temp.add( b.getShiftedName());
unassigned.add( temp );
}
if ( xf != null )
{
temp = new Vector();
temp.add( xf.getName());
temp.add( b.getXShiftedName());
unassigned.add( temp );
}
}
}
}
if ( !unassigned.isEmpty())
{
String message = "Some of the functions defined in the device upgrade " +
"were assigned to buttons that do not match buttons on the newly selected remote. " +
"The functions and the corresponding button names from the original remote are listed below." +
"\n\nUse the Button or Layout panel to assign those functions properly.";
JFrame frame = new JFrame( "Lost Function Assignments" );
Container container = frame.getContentPane();
JTextArea text = new JTextArea( message );
text.setEditable( false );
text.setLineWrap( true );
text.setWrapStyleWord( true );
text.setBackground( container.getBackground() );
text.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ));
container.add( text, BorderLayout.NORTH );
Vector titles = new Vector();
titles.add( "Function name" );
titles.add( "Button name" );
JTable table = new JTable( unassigned, titles );
Dimension d = table.getPreferredScrollableViewportSize();
d.height = d.height / 4;
table.setPreferredScrollableViewportSize( d );
container.add( new JScrollPane( table ), BorderLayout.CENTER );
frame.pack();
frame.setLocationRelativeTo( KeyMapMaster.getKeyMapMaster());
frame.show();
}
}
remote = newRemote;
}
public Remote getRemote()
{
return remote;
}
public void setDeviceTypeAliasName( String name )
{
if ( name != null )
{
if ( remote.getDeviceTypeByAliasName( name ) != null )
{
devTypeAliasName = name;
return;
}
System.err.println( "Unable to find device type with alias name " + name );
}
devTypeAliasName = deviceTypeAliasNames[ 0 ];
}
public String getDeviceTypeAliasName()
{
return devTypeAliasName;
}
public DeviceType getDeviceType()
{
return remote.getDeviceTypeByAliasName( devTypeAliasName );
}
public void setProtocol( Protocol protocol )
{
this.protocol = protocol;
parmValues = protocol.getDeviceParmValues();
}
public Protocol getProtocol()
{
return protocol;
}
public void setNotes( String notes )
{
this.notes = notes;
}
public String getNotes()
{
return notes;
}
public Vector getFunctions()
{
return functions;
}
public Function getFunction( String name )
{
Function rc = getFunction( name, functions );
if ( rc == null )
rc = getFunction( name, extFunctions );
return rc;
}
public Function getFunction( String name, Vector funcs )
{
Function rc = null;
for ( Enumeration e = funcs.elements(); e.hasMoreElements(); )
{
Function func = ( Function )e.nextElement();
String funcName = func.getName();
if (( funcName != null ) && funcName.equalsIgnoreCase( name ))
{
rc = func;
break;
}
}
return rc;
}
public Vector getExternalFunctions()
{
return extFunctions;
}
public Vector getKeyMoves()
{
return keymoves;
}
public void setFile( File file )
{
this.file = file;
}
public File getFile(){ return file; }
private int findDigitMapIndex()
{
Button[] buttons = remote.getUpgradeButtons();
int[] digitMaps = remote.getDigitMaps();
if (( digitMaps != null ) && ( protocol.getDefaultCmd().length() == 1 ))
{
for ( int i = 0; i < digitMaps.length; i++ )
{
int mapNum = digitMaps[ i ];
if ( mapNum == 999 )
continue;
int[] codes = DigitMaps.data[ mapNum ];
int rc = -1;
for ( int j = 0; ; j++ )
{
Function f = buttons[ j ].getFunction();
if (( f != null ) && !f.isExternal())
{
if (( f.getHex().getData()[ 0 ] & 0xFF ) == codes[ j ])
rc = i + 1;
else
break;
}
if ( j == 9 )
{
return rc;
}
}
}
}
return -1;
}
public String getUpgradeText( boolean includeNotes )
{
StringBuffer buff = new StringBuffer( 400 );
buff.append( "Upgrade code 0 = " );
DeviceType devType = remote.getDeviceTypeByAliasName( devTypeAliasName );
int[] id = protocol.getID( remote ).getData();
int temp = devType.getNumber() * 0x1000 +
( id[ 0 ] & 1 ) * 0x0800 +
setupCode - remote.getDeviceCodeOffset();
int[] deviceCode = new int[2];
deviceCode[ 0 ] = (temp >> 8 );
deviceCode[ 1 ] = temp;
buff.append( Hex.toString( deviceCode ));
buff.append( " (" );
buff.append( devTypeAliasName );
buff.append( '/' );
DecimalFormat df = new DecimalFormat( "0000" );
buff.append( df.format( setupCode ));
buff.append( ")" );
if ( includeNotes )
{
String descr = "";
if ( description != null )
descr = description.trim();
if ( descr.length() != 0 )
{
buff.append( ' ' );
buff.append( descr );
}
buff.append( " (RM " );
buff.append( KeyMapMaster.version );
buff.append( ')' );
}
buff.append( "\n " );
buff.append( Hex.asString( id[ 1 ]));
int digitMapIndex = -1;
if ( !remote.getOmitDigitMapByte())
{
buff.append( ' ' );
digitMapIndex = findDigitMapIndex();
if ( digitMapIndex == -1 )
buff.append( "00" );
else
{
buff.append( Hex.asString( digitMapIndex ));
}
}
ButtonMap map = devType.getButtonMap();
if ( map != null )
{
buff.append( ' ' );
buff.append( Hex.toString( map.toBitMap( digitMapIndex != -1 )));
}
buff.append( ' ' );
buff.append( protocol.getFixedData( parmValues ).toString());
if ( map != null )
{
int[] data = map.toCommandList( digitMapIndex != -1 );
if (( data != null ) && ( data.length != 0 ))
{
buff.append( "\n " );
buff.append( Hex.toString( data, 16 ));
}
}
Button[] buttons = remote.getUpgradeButtons();
boolean hasKeyMoves = false;
int startingButton = 0;
int i;
for ( i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
Function sf = b.getShiftedFunction();
if ( b.getShiftedButton() != null )
sf = null;
Function xf = b.getXShiftedFunction();
if ( b.getXShiftedButton() != null )
xf = null;
if ((( f != null ) && (( map == null ) || !map.isPresent( b ) || f.isExternal())) ||
(( sf != null ) && ( sf.getHex() != null )) || (( xf != null) && ( xf.getHex() != null )))
{
hasKeyMoves = true;
break;
}
}
if ( hasKeyMoves )
{
deviceCode[ 0 ] = ( deviceCode[ 0 ] & 0xF7 );
buff.append( "\nKeyMoves" );
boolean first = true;
for ( ; i < buttons.length; i++ )
{
Button button = buttons[ i ];
Function f = button.getFunction();
first = appendKeyMove( buff, button.getKeyMove( f, 0, deviceCode, devType, remote ),
f, includeNotes, first );
f = button.getShiftedFunction();
if ( button.getShiftedButton() != null )
f = null;
first = appendKeyMove( buff, button.getKeyMove( f, remote.getShiftMask(), deviceCode, devType, remote ),
f, includeNotes, first );
f = button.getXShiftedFunction();
if ( button.getXShiftedButton() != null )
f = null;
first = appendKeyMove( buff, button.getKeyMove( f, remote.getXShiftMask(), deviceCode, devType, remote ),
f, includeNotes, first );
}
}
buff.append( "\nEnd" );
return buff.toString();
}
private boolean appendKeyMove( StringBuffer buff, int[] keyMove,Function f, boolean includeNotes, boolean first )
{
if (( keyMove == null ) || ( keyMove.length == 0 ))
return first;
if ( includeNotes && !first )
buff.append( '\u00a6' );
buff.append( "\n " );
buff.append( Hex.toString( keyMove ));
if ( includeNotes )
{
buff.append( '\u00ab' );
buff.append( f.getName());
String notes = f.getNotes();
if (( notes != null ) && ( notes.length() != 0 ))
{
buff.append( ": " );
buff.append( notes );
}
buff.append( '\u00bb' );
}
return false;
}
public void store()
throws IOException
{
store( file );
}
public static String valueArrayToString( Value[] parms )
{
StringBuffer buff = new StringBuffer( 200 );
for ( int i = 0; i < parms.length; i++ )
{
if ( i > 0 )
buff.append( ' ' );
buff.append( parms[ i ].getUserValue());
}
return buff.toString();
}
public static Value[] stringToValueArray( String str )
{
StringTokenizer st = new StringTokenizer( str );
Value[] parms = new Value[ st.countTokens()];
for ( int i = 0; i < parms.length; i++ )
{
String token = st.nextToken();
Object val = null;
if ( !token.equals( "null" ))
{
if ( token.equals( "true" ))
val = new Integer( 1 );
else if ( token.equals( "false" ))
val = new Integer( 0 );
else
val = new Integer( token );
}
parms[ i ] = new Value( val, null );
}
return parms;
}
public void store( File file )
throws IOException
{
this.file = file;
PropertyWriter out =
new PropertyWriter( new PrintWriter( new FileWriter( file )));
if ( description != null )
out.print( "Description", description );
out.print( "Remote.name", remote.getName());
out.print( "Remote.signature", remote.getSignature());
out.print( "DeviceType", devTypeAliasName );
DeviceType devType = remote.getDeviceTypeByAliasName( devTypeAliasName );
out.print( "DeviceIndex", Integer.toHexString( devType.getNumber()));
out.print( "SetupCode", Integer.toString( setupCode ));
// protocol.setDeviceParms( parmValues );
protocol.store( out, parmValues );
if ( notes != null )
out.print( "Notes", notes );
int i = 0;
for ( Enumeration e = functions.elements(); e.hasMoreElements(); i++ )
{
Function func = ( Function )e.nextElement();
func.store( out, "Function." + i );
}
i = 0;
for ( Enumeration e = extFunctions.elements(); e.hasMoreElements(); i++ )
{
ExternalFunction func = ( ExternalFunction )e.nextElement();
func.store( out, "ExtFunction." + i );
}
Button[] buttons = remote.getUpgradeButtons();
String regex = "\\|";
String replace = "\\\\u007c";
for ( i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
String fstr;
if ( f == null )
fstr = "null";
else
fstr = f.getName().replaceAll( regex, replace );
Function sf = b.getShiftedFunction();
String sstr;
if ( sf == null )
sstr = "null";
else
sstr = sf.getName().replaceAll( regex, replace );
Function xf = b.getXShiftedFunction();
String xstr;
if ( xf == null )
xstr = null;
else
xstr = xf.getName().replaceAll( regex, replace );
if (( f != null ) || ( sf != null ) || ( xf != null ))
{
out.print( "Button." + Integer.toHexString( b.getKeyCode()),
fstr + '|' + sstr + '|' + xstr );
}
}
out.flush();
out.close();
}
public void load( File file )
throws Exception
{
load( file, true );
}
public void load( File file, boolean loadButtons )
throws Exception
{
if ( file.getName().toLowerCase().endsWith( ".rmdu" ))
this.file = file;
BufferedReader reader = new BufferedReader( new FileReader( file ));
load( reader, loadButtons );
}
public void load( BufferedReader reader )
throws Exception
{
load( reader, true );
}
public void load( BufferedReader reader, boolean loadButtons )
throws Exception
{
reader.mark( 160 );
String line = reader.readLine();
reader.reset();
if ( line.startsWith( "Name:" ))
{
importUpgrade( reader, loadButtons );
return;
}
Properties props = new Properties();
Property property = new Property();
PropertyReader pr = new PropertyReader( reader );
while (( property = pr.nextProperty( property )) != null )
{
props.put( property.name, property.value );
}
reader.close();
String str = props.getProperty( "Description" );
if ( str != null )
description = str;
str = props.getProperty( "Remote.name" );
if ( str == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The upgrade you are trying to import is not valid! It does not contain a value for Remote.name",
"Import Failure", JOptionPane.ERROR_MESSAGE );
return;
}
String sig = props.getProperty( "Remote.signature" );
remote = RemoteManager.getRemoteManager().findRemoteByName( str );
remote.load();
int index = -1;
str = props.getProperty( "DeviceIndex" );
if ( str != null )
index = Integer.parseInt( str, 16 );
setDeviceTypeAliasName( props.getProperty( "DeviceType" ) );
setupCode = Integer.parseInt( props.getProperty( "SetupCode" ));
Hex pid = new Hex( props.getProperty( "Protocol", "0200" ));
String name = props.getProperty( "Protocol.name", "" );
String variantName = props.getProperty( "Protocol.variantName", "" );
ProtocolManager pm = ProtocolManager.getProtocolManager();
if ( name.equals( "Manual Settings" ) ||
name.equals( "Manual" ) ||
name.equals( "PID " + pid.toString()))
{
protocol = new ManualProtocol( pid, props );
pm.add( protocol );
}
else
{
protocol = pm.findNearestProtocol( name, pid, variantName );
if ( protocol == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"No protocol found with name=\"" + name +
"\", ID=" + pid.toString() +
", and variantName=\"" + variantName + "\"",
"File Load Error", JOptionPane.ERROR_MESSAGE );
return;
}
}
str = props.getProperty( "ProtocolParms" );
System.err.println( "ProtocolParms='" + str + "'" );
if (( str != null ) && ( str.length() != 0 ))
{
protocol.setDeviceParms( stringToValueArray( str ));
parmValues = protocol.getDeviceParmValues();
}
protocol.setProperties( props );
notes = props.getProperty( "Notes" );
functions.clear();
int i = 0;
while ( true )
{
Function f = new Function();
f.load( props, "Function." + i );
if ( f.isEmpty())
{
break;
}
functions.add( f );
i++;
}
extFunctions.clear();
i = 0;
while ( true )
{
ExternalFunction f = new ExternalFunction();
f.load( props, "ExtFunction." + i, remote );
if ( f.isEmpty())
{
break;
}
extFunctions.add( f );
i++;
}
if ( loadButtons )
{
Button[] buttons = remote.getUpgradeButtons();
String regex = "\\\\u007c";
String replace = "|";
for ( i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
str = props.getProperty( "Button." + Integer.toHexString( b.getKeyCode()));
if ( str == null )
{
continue;
}
StringTokenizer st = new StringTokenizer( str, "|" );
str = st.nextToken();
Function func = null;
if ( !str.equals( "null" ))
{
func = getFunction( str.replaceAll( regex, replace ));
b.setFunction( func );
}
str = st.nextToken();
if ( !str.equals( "null" ))
{
func = getFunction( str.replaceAll( regex, replace ));
b.setShiftedFunction( func );
}
if ( st.hasMoreTokens())
{
str = st.nextToken();
if ( !str.equals( "null" ))
{
func = getFunction( str.replaceAll( regex, replace ));
b.setXShiftedFunction( func );
}
}
}
}
}
private String getNextField( StringTokenizer st, String delim )
{
String rc = null;
if ( st.hasMoreTokens())
{
rc = st.nextToken();
if ( rc.equals( delim ))
rc = null;
else
{
if ( rc.startsWith( "\"" ))
{
if ( rc.endsWith( "\"" ))
{
rc = rc.substring( 1, rc.length() - 1 ).replaceAll( "\"\"", "\"" );
}
else
{
StringBuffer buff = new StringBuffer( 200 );
buff.append( rc.substring( 1 ));
while ( true )
{
String token = st.nextToken(); // skip delim
buff.append( delim );
token = st.nextToken();
if ( token.endsWith( "\"" ))
{
buff.append( token.substring( 0, token.length() - 1 ));
break;
}
else
buff.append( token );
}
rc = buff.toString().replaceAll( "\"\"", "\"" );
}
}
if ( st.hasMoreTokens())
st.nextToken(); // skip delim
}
}
return rc;
}
public void importUpgrade( BufferedReader in )
throws Exception
{
importUpgrade( in, true );
}
public void importUpgrade( BufferedReader in, boolean loadButtons )
throws Exception
{
String line = in.readLine(); // line 1
String token = line.substring( 0, 5 );
if ( !token.equals( "Name:" ))
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The upgrade you are trying to import is not valid!",
"Import Failure", JOptionPane.ERROR_MESSAGE );
return;
}
String delim = line.substring( 5, 6 );
StringTokenizer st = new StringTokenizer( line, delim, true );
getNextField( st, delim );
description = getNextField( st, delim );
String protocolLine = in.readLine(); // line 3
String manualLine = in.readLine(); // line 4
line = in.readLine(); // line 5
st = new StringTokenizer( line, delim );
st.nextToken();
token = st.nextToken();
setupCode = Integer.parseInt( token );
token = st.nextToken();
String str = token.substring( 5 );
remote = RemoteManager.getRemoteManager().findRemoteByName( str );
Hex pid = null;
while ( true )
{
line = in.readLine();
if (( line != null ) && ( line.length() > 0 ) && ( line.charAt( 0 ) == '\"' ))
line = line.substring( 1 );
int equals = line.indexOf( '=' );
if (( equals != -1 ) && line.substring( 0, equals ).toLowerCase().startsWith( "upgrade code " ))
{
int[] id = new int[ 2 ];
int temp = Integer.parseInt( line.substring( equals + 2, equals + 4 ), 16 );
if (( temp & 8 ) != 0 )
id[ 0 ] = 1;
line = in.readLine();
temp = Integer.parseInt( line.substring( 0, 2 ), 16 );
id[ 1 ] = temp;
pid = new Hex( id );
break;
}
}
remote.load();
token = st.nextToken();
str = token.substring( 5 );
if ( remote.getDeviceTypeByAliasName( str ) == null )
{
String rc = null;
String msg = "Remote \"" + remote.getName() + "\" does not support the device type " +
str + ". Please select one of the supported device types below to use instead.\n";
while ( rc == null )
{
rc = ( String )JOptionPane.showInputDialog( KeyMapMaster.getKeyMapMaster(),
msg,
"Unsupported Device Type",
JOptionPane.ERROR_MESSAGE,
null,
remote.getDeviceTypeAliasNames(),
null );
}
str = rc;
}
setDeviceTypeAliasName( str );
String buttonStyle = st.nextToken();
st = new StringTokenizer( protocolLine, delim, true );
getNextField( st, delim ); // skip header
String protocolName = getNextField( st, delim ); // protocol name
ProtocolManager protocolManager = ProtocolManager.getProtocolManager();
if ( protocolName.equals( "Manual Settings" ))
{
System.err.println( "protocolName=" + protocolName );
System.err.println( "manualLine=" + manualLine );
StringTokenizer manual = new StringTokenizer( manualLine, delim, true );
System.err.println( "skipping " + getNextField( manual, delim )); // skip header
String pidStr = getNextField( manual, delim );
System.err.println( "pid=" + pidStr );
if ( pidStr != null )
{
int space = pidStr.indexOf( ' ' );
if ( space != -1 )
{
pid = new Hex( pidStr );
}
else
{
int pidInt = Integer.parseInt( pidStr, 16 );
int[] data = new int[ 2 ];
data[ 0 ] = ( pidInt & 0xFF00 ) >> 8;
data[ 1 ] = pidInt & 0xFF;
pid = new Hex( data );
}
}
int byte2 = Integer.parseInt( getNextField( manual, delim ).substring( 0, 1 ));
System.err.println( "byte2=" + byte2 );
String signalStyle = getNextField( manual, delim );
System.err.println( "SignalStyle=" + signalStyle );
String bitsStr = getNextField( manual, delim );
int devBits = Integer.parseInt( bitsStr.substring( 0, 1 ), 16);
int cmdBits = Integer.parseInt( bitsStr.substring( 1 ), 16 );
System.err.println( "devBits=" + devBits + " and cmdBits=" + cmdBits );
Vector values = new Vector();
str = getNextField( st, delim ); // Device 1
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 2
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 3
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Raw Fixed Data
if ( str == null )
str = "";
int[] rawHex = Hex.parseHex( str );
protocol = new ManualProtocol( protocolName, pid, byte2, signalStyle, devBits, values, rawHex, cmdBits );
protocolName = protocol.getName();
setParmValues( protocol.getDeviceParmValues());
protocolManager.add( protocol );
}
else
{
// protocol = protocolManager.findProtocolForRemote( remote, protocolName );
Protocol p = protocolManager.findNearestProtocol( protocolName, pid, null );
if ( p == null )
{
p = protocolManager.findProtocolByOldName( remote, protocolName, pid );
if ( p == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"No protocol found with name=\"" + protocolName +
"\" for remote \"" + remote.getName() + "\".",
"Import Failure", JOptionPane.ERROR_MESSAGE );
reset();
return;
}
}
protocol = p;
Value[] importParms = new Value[ 4 ];
for ( int i = 0; i < importParms.length; i++ )
{
token = getNextField( st, delim );
Object val = null;
if ( token == null )
val = null;
else
{
if ( token.equals( "true" ))
val = new Integer( 1 );
else if ( token.equals( "false" ))
val = new Integer( 0 );
else
val = token;
// val = new Integer( token );
}
importParms[ i ] = new Value( val );
}
protocol.importDeviceParms( importParms );
parmValues = protocol.getDeviceParmValues();
}
// compute cmdIndex
boolean useOBC = false;
boolean useEFC = false;
if ( buttonStyle.equals( "OBC" ))
useOBC = true;
else if ( buttonStyle.equals( "EFC" ))
useEFC = true;
int obcIndex = -1;
CmdParameter[] cmdParms = protocol.getCommandParameters();
for ( obcIndex = 0; obcIndex < cmdParms.length; obcIndex++ )
{
if ( cmdParms[ obcIndex ].getName().equals( "OBC" ))
break;
}
String match1 = "fFunctions" + delim;
String match2 = "Functions" + delim;
if ( useOBC )
{
match1 = match1 + "fOBC" + delim;
match2 = match2 + "OBC" + delim;
}
else
{
match1 = match1 + "fEFC" + delim;
match2 = match2 + "EFC" + delim;
}
while ( true )
{
line = in.readLine();
if ( line.startsWith( match1 ) || line.startsWith( match2 ))
break;
}
functions.clear();
DeviceCombiner combiner = null;
if ( protocol.getClass() == DeviceCombiner.class )
combiner = ( DeviceCombiner )protocol;
Vector unassigned = new Vector();
Vector usedFunctions = new Vector();
for ( int i = 0; i < 128; i++ )
{
line = in.readLine();
st = new StringTokenizer( line, delim, true );
token = getNextField( st, delim ); // get the name (field 1)
if (( token != null ) && ( token.length() == 5 ) &&
token.startsWith( "num " ) && Character.isDigit( token.charAt( 4 )))
token = token.substring( 4 );
System.err.println( "Looking for function " + token );
Function f = getFunction( token, usedFunctions );
if ( f == null )
{
System.err.println( "Had to create a new one!" );
if (( token != null ) && ( token.charAt( 0 ) == '=' ) && ( token.indexOf( '/' ) != -1 ))
f = new ExternalFunction();
else
f = new Function();
f.setName( token );
}
else
System.err.println( "Found it!" );
token = getNextField( st, delim ); // get the function code (field 2)
if ( token != null )
{
Hex hex = null;
if ( f.isExternal())
{
ExternalFunction ef = ( ExternalFunction )f;
String name = ef.getName();
int slash = name.indexOf( '/' );
String devName = name.substring( 1, slash );
- ef.setDeviceTypeAliasName( devName );
+ String match = null;
+ String[] names = remote.getDeviceTypeAliasNames();
+ for ( int j = 0; j < names.length; j++ )
+ {
+ if ( devName.equalsIgnoreCase( names[ j ]))
+ match = names[ j ];
+ }
+ if ( match == null )
+ {
+ String msg = "The Keymap Master device upgrade you are importing includes an\nexternal function that uses the unknown device type " +
+ devName + ".\n\nPlease select one of the supported device types below to use instead.";
+ while ( match == null )
+ {
+ match = ( String )JOptionPane.showInputDialog( KeyMapMaster.getKeyMapMaster(),
+ msg,
+ "Unsupported Device Type",
+ JOptionPane.ERROR_MESSAGE,
+ null,
+ names,
+ null );
+ }
+ }
+ ef.setDeviceTypeAliasName( match );
int space = name.indexOf( ' ', slash + 1 );
String codeString = null;
if ( space == -1 )
codeString = name.substring( slash + 1 );
else
codeString = name.substring( slash + 1, space );
ef.setSetupCode( Integer.parseInt( codeString ));
if (( token.indexOf( 'h' ) != -1 ) || ( token.indexOf( '$') != -1 ) || (token.indexOf( ' ' ) != -1 ))
{
hex = new Hex( token );
ef.setType( ExternalFunction.HexType );
}
else
{
hex = new Hex( 1 );
protocol.efc2hex( new EFC( token ), hex, 0 );
ef.setType( ExternalFunction.EFCType );
}
getNextField( st, delim ); // skip byte2 (field 3)
}
else
{
hex = protocol.getDefaultCmd();
protocol.importCommand( hex, token, useOBC, obcIndex, useEFC );
token = getNextField( st, delim ); // get byte2 (field 3)
if ( token != null )
protocol.importCommandParms( hex, token );
}
f.setHex( hex );
}
else
{
token = getNextField( st, delim ); // skip field 3
}
String actualName = getNextField( st, delim ); // get assigned button name (field 4)
System.err.println( "actualName='" + actualName + "'" );
if (( actualName != null ) && actualName.length() == 0 )
actualName = null;
String buttonName = null;
if ( actualName != null )
{
if ( i < genericButtonNames.length )
buttonName = genericButtonNames[ i ];
else
{
System.err.println( "No generic name available!" );
Button b = remote.getButton( actualName );
if ( b == null )
b = remote.getButton( actualName.replace( ' ', '_' ));
if ( b != null )
buttonName = b.getStandardName();
}
}
Button b = null;
if ( buttonName != null )
{
System.err.println( "Searching for button w/ name " + buttonName );
b = remote.findByStandardName( new Button( buttonName, null, ( byte )0, remote ));
System.err.println( "Found button " + b );
}
else
System.err.println( "No buttonName for actualName=" + actualName + " and i=" + i );
token = getNextField( st, delim ); // get normal function (field 5)
if (( buttonName != null ) && ( token != null ) &&
Character.isDigit( token.charAt( 0 )) &&
Character.isDigit( token.charAt( 1 )) &&
( token.charAt( 2 ) == ' ' ) &&
( token.charAt( 3 ) == '-' ) &&
( token.charAt( 4 ) == ' ' ))
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( name.charAt( 4 )))
name = name.substring( 4 );
Function func = null;
if (( f.getName() != null ) && f.getName().equalsIgnoreCase( name ))
func = f;
else
{
func = getFunction( name, functions );
if ( func == null )
+ func = getFunction( name, extFunctions );
+ if ( func == null )
func = getFunction( name, usedFunctions );
}
if ( func == null )
{
System.err.println( "Creating new function " + name );
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
if ( b != null )
usedFunctions.add( func );
}
else
System.err.println( "Found function " + name );
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( actualName );
unassigned.add( temp );
System.err.println( "Couldn't find button " + buttonName + " to assign function " + name );
}
else if ( loadButtons )
{
System.err.println( "Setting function " + name + " on button " + b );
b.setFunction( func );
}
}
token = getNextField( st, delim ); // get notes (field 6)
if ( token != null )
f.setNotes( token );
if ( !f.isEmpty())
{
if ( f.isExternal())
extFunctions.add( f );
else
functions.add( f );
}
String pidStr = getNextField( st, delim ); // field 7
String fixedDataStr = getNextField( st, delim ); // field 8
if (( combiner != null ) && ( pidStr != null ) && // ( fixedDataStr != null ) &&
!pidStr.equals( "Protocol ID" )) // && !fixedDataStr.equals( "Fixed Data" )
{
Hex fixedData = new Hex();
if ( fixedDataStr != null )
fixedData = new Hex( fixedDataStr );
Hex newPid = new Hex( pidStr );
Vector protocols = protocolManager.findByPID( newPid );
boolean foundMatch = false;
for ( Enumeration e = protocols.elements(); e.hasMoreElements(); )
{
Protocol p = ( Protocol )e.nextElement();
if ( !remote.supportsVariant( newPid, p.getVariantName()))
continue;
CombinerDevice dev = new CombinerDevice( p, fixedData );
Hex calculatedFixedData = dev.getFixedData();
if ( !calculatedFixedData.equals( fixedData ))
continue;
combiner.add( dev );
foundMatch = true;
break;
}
if ( !foundMatch )
{
ManualProtocol p = new ManualProtocol( newPid, new Properties());
p.setRawHex( fixedData );
combiner.add( new CombinerDevice( p, null, null ));
}
}
// skip to field 13
for ( int j = 8; j < 13; j++ )
token = getNextField( st, delim );
if ( token != null )
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( token.charAt( 4 )))
name = name.substring( 4 );
Function func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, extFunctions );
if ( func == null )
{
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
usedFunctions.add( func );
}
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( "shift-" + buttonName );
unassigned.add( temp );
}
else if ( loadButtons )
b.setShiftedFunction( func );
}
}
while (( line = in.readLine()) != null )
{
st = new StringTokenizer( line, delim );
token = getNextField( st, delim );
if ( token != null )
{
if ( token.equals( "Line Notes:" ) || token.equals( "Notes:" ))
{
StringBuffer buff = new StringBuffer();
boolean first = true;
String tempDelim = null;
while (( line = in.readLine()) != null )
{
if ( line.charAt( 0 ) == '"' )
tempDelim = "\"";
else
tempDelim = delim;
st = new StringTokenizer( line, tempDelim );
if ( st.hasMoreTokens())
{
token = st.nextToken();
if ( token.startsWith( "EOF Marker" ))
break;
if ( first )
first = false;
else
buff.append( "\n" );
buff.append( token.trim());
}
else
buff.append( "\n" );
}
notes = buff.toString().trim();
if ( protocol.getClass() == ManualProtocol.class )
protocol.importUpgradeCode( notes );
}
}
}
if ( !unassigned.isEmpty())
{
System.err.println( "Removing undefined functions from usedFunctions" );
for( ListIterator i = unassigned.listIterator(); i.hasNext(); )
{
Vector temp = ( Vector )i.next();
String funcName = ( String )temp.elementAt( 0 );
System.err.print( "Checking '" + funcName + "'" );
Function f = getFunction( funcName, usedFunctions );
if (( f == null ) || ( f.getHex() == null ) || ( f.getHex().length() == 0 ))
{
System.err.println( "Removing function " + f + ", which has name '" + funcName + "'" );
i.remove();
}
}
}
if ( !unassigned.isEmpty())
{
String message = "Some of the functions defined in the imported device upgrade " +
"were assigned to buttons that could not be matched by name. " +
"The functions and the corresponding button names are listed below." +
"\n\nPlease post this information in the \"JP1 - Software\" section of the " +
"JP1 Forums at www.hifi-remote.com" +
"\n\nUse the Button or Layout panel to assign those functions properly.";
JFrame frame = new JFrame( "Import Failure" );
Container container = frame.getContentPane();
JTextArea text = new JTextArea( message );
text.setEditable( false );
text.setLineWrap( true );
text.setWrapStyleWord( true );
text.setBackground( container.getBackground() );
text.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ));
container.add( text, BorderLayout.NORTH );
Vector titles = new Vector();
titles.add( "Function name" );
titles.add( "Button name" );
JTable table = new JTable( unassigned, titles );
Dimension d = table.getPreferredScrollableViewportSize();
d.height = d.height / 4;
table.setPreferredScrollableViewportSize( d );
container.add( new JScrollPane( table ), BorderLayout.CENTER );
frame.pack();
frame.setLocationRelativeTo( KeyMapMaster.getKeyMapMaster());
frame.show();
}
Button[] buttons = remote.getUpgradeButtons();
System.err.println( "Removing assigned functions with no hex!" );
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setFunction( null );
f = b.getShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setShiftedFunction( null );
f = b.getXShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setXShiftedFunction( null );
}
System.err.println( "Done!" );
}
public Value[] getParmValues()
{
return parmValues;
}
public void setParmValues( Value[] parmValues )
{
this.parmValues = parmValues;
}
public static final String[] getDeviceTypeAliasNames()
{
return deviceTypeAliasNames;
}
public void autoAssignFunctions()
{
autoAssignFunctions( functions );
autoAssignFunctions( extFunctions );
}
private void autoAssignFunctions( Vector funcs )
{
Button[] buttons = remote.getUpgradeButtons();
for ( Enumeration e = funcs.elements(); e.hasMoreElements(); )
{
Function func = ( Function )e.nextElement();
if ( func.getHex() != null )
{
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
if ( b.getFunction() == null )
{
if ( b.getName().equalsIgnoreCase( func.getName()) ||
b.getStandardName().equalsIgnoreCase( func.getName()))
{
b.setFunction( func );
break;
}
}
}
}
}
}
private String description = null;
private int setupCode = 0;
private Remote remote = null;
private String devTypeAliasName = null;
private Protocol protocol = null;
private Value[] parmValues = new Value[ 0 ];
private String notes = null;
private Vector functions = new Vector();
private Vector extFunctions = new Vector();
private Vector keymoves = new Vector();
private File file = null;
private static final String[] deviceTypeAliasNames =
{
"Cable", "TV", "VCR", "CD", "Tuner", "DVD", "SAT", "Tape", "Laserdisc",
"DAT", "Home Auto", "Misc Audio", "Phono", "Video Acc", "Amp", "PVR", "OEM Mode"
};
private static final String[] defaultFunctionNames =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"vol up", "vol down", "mute",
"channel up", "channel down",
"power", "enter", "tv/vcr",
"last (prev ch)", "menu", "program guide", "up arrow", "down arrow",
"left arrow", "right arrow", "select", "sleep", "pip on/off", "display",
"pip swap", "pip move", "play", "pause", "rewind", "fast fwd", "stop",
"record", "exit", "surround", "input toggle", "+100", "fav/scan",
"device button", "next track", "prev track", "shift-left", "shift-right",
"pip freeze", "slow", "eject", "slow+", "slow-", "X2", "center", "rear"
};
private final static String[] genericButtonNames =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"vol up", "vol down", "mute",
"channel up", "channel down",
"power", "enter", "tv/vcr", "prev ch", "menu", "guide",
"up arrow", "down arrow", "left arrow", "right arrow", "select",
"sleep", "pip on/off", "display", "pip swap", "pip move",
"play", "pause", "rewind", "fast fwd", "stop", "record",
"exit", "surround", "input", "+100", "fav/scan",
"device button", "next track", "prev track", "shift-left", "shift-right",
"pip freeze", "slow", "eject", "slow+", "slow-", "x2", "center", "rear",
"phantom1", "phantom2", "phantom3", "phantom4", "phantom5", "phantom6",
"phantom7", "phantom8", "phantom9", "phantom10",
"setup", "light", "theater",
"macro1", "macro2", "macro3", "macro4",
"learn1", "learn2", "learn3", "learn4" // ,
// "button85", "button86", "button87", "button88", "button89", "button90",
// "button91", "button92", "button93", "button94", "button95", "button96",
// "button97", "button98", "button99", "button100", "button101", "button102",
// "button103", "button104", "button105", "button106", "button107", "button108",
// "button109", "button110", "button112", "button113", "button114", "button115",
// "button116", "button117", "button118", "button119", "button120", "button121",
// "button122", "button123", "button124", "button125", "button126", "button127",
// "button128", "button129", "button130", "button131", "button132", "button133",
// "button134", "button135", "button136"
};
}
| false | true | public void importUpgrade( BufferedReader in, boolean loadButtons )
throws Exception
{
String line = in.readLine(); // line 1
String token = line.substring( 0, 5 );
if ( !token.equals( "Name:" ))
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The upgrade you are trying to import is not valid!",
"Import Failure", JOptionPane.ERROR_MESSAGE );
return;
}
String delim = line.substring( 5, 6 );
StringTokenizer st = new StringTokenizer( line, delim, true );
getNextField( st, delim );
description = getNextField( st, delim );
String protocolLine = in.readLine(); // line 3
String manualLine = in.readLine(); // line 4
line = in.readLine(); // line 5
st = new StringTokenizer( line, delim );
st.nextToken();
token = st.nextToken();
setupCode = Integer.parseInt( token );
token = st.nextToken();
String str = token.substring( 5 );
remote = RemoteManager.getRemoteManager().findRemoteByName( str );
Hex pid = null;
while ( true )
{
line = in.readLine();
if (( line != null ) && ( line.length() > 0 ) && ( line.charAt( 0 ) == '\"' ))
line = line.substring( 1 );
int equals = line.indexOf( '=' );
if (( equals != -1 ) && line.substring( 0, equals ).toLowerCase().startsWith( "upgrade code " ))
{
int[] id = new int[ 2 ];
int temp = Integer.parseInt( line.substring( equals + 2, equals + 4 ), 16 );
if (( temp & 8 ) != 0 )
id[ 0 ] = 1;
line = in.readLine();
temp = Integer.parseInt( line.substring( 0, 2 ), 16 );
id[ 1 ] = temp;
pid = new Hex( id );
break;
}
}
remote.load();
token = st.nextToken();
str = token.substring( 5 );
if ( remote.getDeviceTypeByAliasName( str ) == null )
{
String rc = null;
String msg = "Remote \"" + remote.getName() + "\" does not support the device type " +
str + ". Please select one of the supported device types below to use instead.\n";
while ( rc == null )
{
rc = ( String )JOptionPane.showInputDialog( KeyMapMaster.getKeyMapMaster(),
msg,
"Unsupported Device Type",
JOptionPane.ERROR_MESSAGE,
null,
remote.getDeviceTypeAliasNames(),
null );
}
str = rc;
}
setDeviceTypeAliasName( str );
String buttonStyle = st.nextToken();
st = new StringTokenizer( protocolLine, delim, true );
getNextField( st, delim ); // skip header
String protocolName = getNextField( st, delim ); // protocol name
ProtocolManager protocolManager = ProtocolManager.getProtocolManager();
if ( protocolName.equals( "Manual Settings" ))
{
System.err.println( "protocolName=" + protocolName );
System.err.println( "manualLine=" + manualLine );
StringTokenizer manual = new StringTokenizer( manualLine, delim, true );
System.err.println( "skipping " + getNextField( manual, delim )); // skip header
String pidStr = getNextField( manual, delim );
System.err.println( "pid=" + pidStr );
if ( pidStr != null )
{
int space = pidStr.indexOf( ' ' );
if ( space != -1 )
{
pid = new Hex( pidStr );
}
else
{
int pidInt = Integer.parseInt( pidStr, 16 );
int[] data = new int[ 2 ];
data[ 0 ] = ( pidInt & 0xFF00 ) >> 8;
data[ 1 ] = pidInt & 0xFF;
pid = new Hex( data );
}
}
int byte2 = Integer.parseInt( getNextField( manual, delim ).substring( 0, 1 ));
System.err.println( "byte2=" + byte2 );
String signalStyle = getNextField( manual, delim );
System.err.println( "SignalStyle=" + signalStyle );
String bitsStr = getNextField( manual, delim );
int devBits = Integer.parseInt( bitsStr.substring( 0, 1 ), 16);
int cmdBits = Integer.parseInt( bitsStr.substring( 1 ), 16 );
System.err.println( "devBits=" + devBits + " and cmdBits=" + cmdBits );
Vector values = new Vector();
str = getNextField( st, delim ); // Device 1
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 2
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 3
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Raw Fixed Data
if ( str == null )
str = "";
int[] rawHex = Hex.parseHex( str );
protocol = new ManualProtocol( protocolName, pid, byte2, signalStyle, devBits, values, rawHex, cmdBits );
protocolName = protocol.getName();
setParmValues( protocol.getDeviceParmValues());
protocolManager.add( protocol );
}
else
{
// protocol = protocolManager.findProtocolForRemote( remote, protocolName );
Protocol p = protocolManager.findNearestProtocol( protocolName, pid, null );
if ( p == null )
{
p = protocolManager.findProtocolByOldName( remote, protocolName, pid );
if ( p == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"No protocol found with name=\"" + protocolName +
"\" for remote \"" + remote.getName() + "\".",
"Import Failure", JOptionPane.ERROR_MESSAGE );
reset();
return;
}
}
protocol = p;
Value[] importParms = new Value[ 4 ];
for ( int i = 0; i < importParms.length; i++ )
{
token = getNextField( st, delim );
Object val = null;
if ( token == null )
val = null;
else
{
if ( token.equals( "true" ))
val = new Integer( 1 );
else if ( token.equals( "false" ))
val = new Integer( 0 );
else
val = token;
// val = new Integer( token );
}
importParms[ i ] = new Value( val );
}
protocol.importDeviceParms( importParms );
parmValues = protocol.getDeviceParmValues();
}
// compute cmdIndex
boolean useOBC = false;
boolean useEFC = false;
if ( buttonStyle.equals( "OBC" ))
useOBC = true;
else if ( buttonStyle.equals( "EFC" ))
useEFC = true;
int obcIndex = -1;
CmdParameter[] cmdParms = protocol.getCommandParameters();
for ( obcIndex = 0; obcIndex < cmdParms.length; obcIndex++ )
{
if ( cmdParms[ obcIndex ].getName().equals( "OBC" ))
break;
}
String match1 = "fFunctions" + delim;
String match2 = "Functions" + delim;
if ( useOBC )
{
match1 = match1 + "fOBC" + delim;
match2 = match2 + "OBC" + delim;
}
else
{
match1 = match1 + "fEFC" + delim;
match2 = match2 + "EFC" + delim;
}
while ( true )
{
line = in.readLine();
if ( line.startsWith( match1 ) || line.startsWith( match2 ))
break;
}
functions.clear();
DeviceCombiner combiner = null;
if ( protocol.getClass() == DeviceCombiner.class )
combiner = ( DeviceCombiner )protocol;
Vector unassigned = new Vector();
Vector usedFunctions = new Vector();
for ( int i = 0; i < 128; i++ )
{
line = in.readLine();
st = new StringTokenizer( line, delim, true );
token = getNextField( st, delim ); // get the name (field 1)
if (( token != null ) && ( token.length() == 5 ) &&
token.startsWith( "num " ) && Character.isDigit( token.charAt( 4 )))
token = token.substring( 4 );
System.err.println( "Looking for function " + token );
Function f = getFunction( token, usedFunctions );
if ( f == null )
{
System.err.println( "Had to create a new one!" );
if (( token != null ) && ( token.charAt( 0 ) == '=' ) && ( token.indexOf( '/' ) != -1 ))
f = new ExternalFunction();
else
f = new Function();
f.setName( token );
}
else
System.err.println( "Found it!" );
token = getNextField( st, delim ); // get the function code (field 2)
if ( token != null )
{
Hex hex = null;
if ( f.isExternal())
{
ExternalFunction ef = ( ExternalFunction )f;
String name = ef.getName();
int slash = name.indexOf( '/' );
String devName = name.substring( 1, slash );
ef.setDeviceTypeAliasName( devName );
int space = name.indexOf( ' ', slash + 1 );
String codeString = null;
if ( space == -1 )
codeString = name.substring( slash + 1 );
else
codeString = name.substring( slash + 1, space );
ef.setSetupCode( Integer.parseInt( codeString ));
if (( token.indexOf( 'h' ) != -1 ) || ( token.indexOf( '$') != -1 ) || (token.indexOf( ' ' ) != -1 ))
{
hex = new Hex( token );
ef.setType( ExternalFunction.HexType );
}
else
{
hex = new Hex( 1 );
protocol.efc2hex( new EFC( token ), hex, 0 );
ef.setType( ExternalFunction.EFCType );
}
getNextField( st, delim ); // skip byte2 (field 3)
}
else
{
hex = protocol.getDefaultCmd();
protocol.importCommand( hex, token, useOBC, obcIndex, useEFC );
token = getNextField( st, delim ); // get byte2 (field 3)
if ( token != null )
protocol.importCommandParms( hex, token );
}
f.setHex( hex );
}
else
{
token = getNextField( st, delim ); // skip field 3
}
String actualName = getNextField( st, delim ); // get assigned button name (field 4)
System.err.println( "actualName='" + actualName + "'" );
if (( actualName != null ) && actualName.length() == 0 )
actualName = null;
String buttonName = null;
if ( actualName != null )
{
if ( i < genericButtonNames.length )
buttonName = genericButtonNames[ i ];
else
{
System.err.println( "No generic name available!" );
Button b = remote.getButton( actualName );
if ( b == null )
b = remote.getButton( actualName.replace( ' ', '_' ));
if ( b != null )
buttonName = b.getStandardName();
}
}
Button b = null;
if ( buttonName != null )
{
System.err.println( "Searching for button w/ name " + buttonName );
b = remote.findByStandardName( new Button( buttonName, null, ( byte )0, remote ));
System.err.println( "Found button " + b );
}
else
System.err.println( "No buttonName for actualName=" + actualName + " and i=" + i );
token = getNextField( st, delim ); // get normal function (field 5)
if (( buttonName != null ) && ( token != null ) &&
Character.isDigit( token.charAt( 0 )) &&
Character.isDigit( token.charAt( 1 )) &&
( token.charAt( 2 ) == ' ' ) &&
( token.charAt( 3 ) == '-' ) &&
( token.charAt( 4 ) == ' ' ))
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( name.charAt( 4 )))
name = name.substring( 4 );
Function func = null;
if (( f.getName() != null ) && f.getName().equalsIgnoreCase( name ))
func = f;
else
{
func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, usedFunctions );
}
if ( func == null )
{
System.err.println( "Creating new function " + name );
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
if ( b != null )
usedFunctions.add( func );
}
else
System.err.println( "Found function " + name );
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( actualName );
unassigned.add( temp );
System.err.println( "Couldn't find button " + buttonName + " to assign function " + name );
}
else if ( loadButtons )
{
System.err.println( "Setting function " + name + " on button " + b );
b.setFunction( func );
}
}
token = getNextField( st, delim ); // get notes (field 6)
if ( token != null )
f.setNotes( token );
if ( !f.isEmpty())
{
if ( f.isExternal())
extFunctions.add( f );
else
functions.add( f );
}
String pidStr = getNextField( st, delim ); // field 7
String fixedDataStr = getNextField( st, delim ); // field 8
if (( combiner != null ) && ( pidStr != null ) && // ( fixedDataStr != null ) &&
!pidStr.equals( "Protocol ID" )) // && !fixedDataStr.equals( "Fixed Data" )
{
Hex fixedData = new Hex();
if ( fixedDataStr != null )
fixedData = new Hex( fixedDataStr );
Hex newPid = new Hex( pidStr );
Vector protocols = protocolManager.findByPID( newPid );
boolean foundMatch = false;
for ( Enumeration e = protocols.elements(); e.hasMoreElements(); )
{
Protocol p = ( Protocol )e.nextElement();
if ( !remote.supportsVariant( newPid, p.getVariantName()))
continue;
CombinerDevice dev = new CombinerDevice( p, fixedData );
Hex calculatedFixedData = dev.getFixedData();
if ( !calculatedFixedData.equals( fixedData ))
continue;
combiner.add( dev );
foundMatch = true;
break;
}
if ( !foundMatch )
{
ManualProtocol p = new ManualProtocol( newPid, new Properties());
p.setRawHex( fixedData );
combiner.add( new CombinerDevice( p, null, null ));
}
}
// skip to field 13
for ( int j = 8; j < 13; j++ )
token = getNextField( st, delim );
if ( token != null )
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( token.charAt( 4 )))
name = name.substring( 4 );
Function func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, extFunctions );
if ( func == null )
{
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
usedFunctions.add( func );
}
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( "shift-" + buttonName );
unassigned.add( temp );
}
else if ( loadButtons )
b.setShiftedFunction( func );
}
}
while (( line = in.readLine()) != null )
{
st = new StringTokenizer( line, delim );
token = getNextField( st, delim );
if ( token != null )
{
if ( token.equals( "Line Notes:" ) || token.equals( "Notes:" ))
{
StringBuffer buff = new StringBuffer();
boolean first = true;
String tempDelim = null;
while (( line = in.readLine()) != null )
{
if ( line.charAt( 0 ) == '"' )
tempDelim = "\"";
else
tempDelim = delim;
st = new StringTokenizer( line, tempDelim );
if ( st.hasMoreTokens())
{
token = st.nextToken();
if ( token.startsWith( "EOF Marker" ))
break;
if ( first )
first = false;
else
buff.append( "\n" );
buff.append( token.trim());
}
else
buff.append( "\n" );
}
notes = buff.toString().trim();
if ( protocol.getClass() == ManualProtocol.class )
protocol.importUpgradeCode( notes );
}
}
}
if ( !unassigned.isEmpty())
{
System.err.println( "Removing undefined functions from usedFunctions" );
for( ListIterator i = unassigned.listIterator(); i.hasNext(); )
{
Vector temp = ( Vector )i.next();
String funcName = ( String )temp.elementAt( 0 );
System.err.print( "Checking '" + funcName + "'" );
Function f = getFunction( funcName, usedFunctions );
if (( f == null ) || ( f.getHex() == null ) || ( f.getHex().length() == 0 ))
{
System.err.println( "Removing function " + f + ", which has name '" + funcName + "'" );
i.remove();
}
}
}
if ( !unassigned.isEmpty())
{
String message = "Some of the functions defined in the imported device upgrade " +
"were assigned to buttons that could not be matched by name. " +
"The functions and the corresponding button names are listed below." +
"\n\nPlease post this information in the \"JP1 - Software\" section of the " +
"JP1 Forums at www.hifi-remote.com" +
"\n\nUse the Button or Layout panel to assign those functions properly.";
JFrame frame = new JFrame( "Import Failure" );
Container container = frame.getContentPane();
JTextArea text = new JTextArea( message );
text.setEditable( false );
text.setLineWrap( true );
text.setWrapStyleWord( true );
text.setBackground( container.getBackground() );
text.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ));
container.add( text, BorderLayout.NORTH );
Vector titles = new Vector();
titles.add( "Function name" );
titles.add( "Button name" );
JTable table = new JTable( unassigned, titles );
Dimension d = table.getPreferredScrollableViewportSize();
d.height = d.height / 4;
table.setPreferredScrollableViewportSize( d );
container.add( new JScrollPane( table ), BorderLayout.CENTER );
frame.pack();
frame.setLocationRelativeTo( KeyMapMaster.getKeyMapMaster());
frame.show();
}
Button[] buttons = remote.getUpgradeButtons();
System.err.println( "Removing assigned functions with no hex!" );
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setFunction( null );
f = b.getShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setShiftedFunction( null );
f = b.getXShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setXShiftedFunction( null );
}
System.err.println( "Done!" );
}
| public void importUpgrade( BufferedReader in, boolean loadButtons )
throws Exception
{
String line = in.readLine(); // line 1
String token = line.substring( 0, 5 );
if ( !token.equals( "Name:" ))
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The upgrade you are trying to import is not valid!",
"Import Failure", JOptionPane.ERROR_MESSAGE );
return;
}
String delim = line.substring( 5, 6 );
StringTokenizer st = new StringTokenizer( line, delim, true );
getNextField( st, delim );
description = getNextField( st, delim );
String protocolLine = in.readLine(); // line 3
String manualLine = in.readLine(); // line 4
line = in.readLine(); // line 5
st = new StringTokenizer( line, delim );
st.nextToken();
token = st.nextToken();
setupCode = Integer.parseInt( token );
token = st.nextToken();
String str = token.substring( 5 );
remote = RemoteManager.getRemoteManager().findRemoteByName( str );
Hex pid = null;
while ( true )
{
line = in.readLine();
if (( line != null ) && ( line.length() > 0 ) && ( line.charAt( 0 ) == '\"' ))
line = line.substring( 1 );
int equals = line.indexOf( '=' );
if (( equals != -1 ) && line.substring( 0, equals ).toLowerCase().startsWith( "upgrade code " ))
{
int[] id = new int[ 2 ];
int temp = Integer.parseInt( line.substring( equals + 2, equals + 4 ), 16 );
if (( temp & 8 ) != 0 )
id[ 0 ] = 1;
line = in.readLine();
temp = Integer.parseInt( line.substring( 0, 2 ), 16 );
id[ 1 ] = temp;
pid = new Hex( id );
break;
}
}
remote.load();
token = st.nextToken();
str = token.substring( 5 );
if ( remote.getDeviceTypeByAliasName( str ) == null )
{
String rc = null;
String msg = "Remote \"" + remote.getName() + "\" does not support the device type " +
str + ". Please select one of the supported device types below to use instead.\n";
while ( rc == null )
{
rc = ( String )JOptionPane.showInputDialog( KeyMapMaster.getKeyMapMaster(),
msg,
"Unsupported Device Type",
JOptionPane.ERROR_MESSAGE,
null,
remote.getDeviceTypeAliasNames(),
null );
}
str = rc;
}
setDeviceTypeAliasName( str );
String buttonStyle = st.nextToken();
st = new StringTokenizer( protocolLine, delim, true );
getNextField( st, delim ); // skip header
String protocolName = getNextField( st, delim ); // protocol name
ProtocolManager protocolManager = ProtocolManager.getProtocolManager();
if ( protocolName.equals( "Manual Settings" ))
{
System.err.println( "protocolName=" + protocolName );
System.err.println( "manualLine=" + manualLine );
StringTokenizer manual = new StringTokenizer( manualLine, delim, true );
System.err.println( "skipping " + getNextField( manual, delim )); // skip header
String pidStr = getNextField( manual, delim );
System.err.println( "pid=" + pidStr );
if ( pidStr != null )
{
int space = pidStr.indexOf( ' ' );
if ( space != -1 )
{
pid = new Hex( pidStr );
}
else
{
int pidInt = Integer.parseInt( pidStr, 16 );
int[] data = new int[ 2 ];
data[ 0 ] = ( pidInt & 0xFF00 ) >> 8;
data[ 1 ] = pidInt & 0xFF;
pid = new Hex( data );
}
}
int byte2 = Integer.parseInt( getNextField( manual, delim ).substring( 0, 1 ));
System.err.println( "byte2=" + byte2 );
String signalStyle = getNextField( manual, delim );
System.err.println( "SignalStyle=" + signalStyle );
String bitsStr = getNextField( manual, delim );
int devBits = Integer.parseInt( bitsStr.substring( 0, 1 ), 16);
int cmdBits = Integer.parseInt( bitsStr.substring( 1 ), 16 );
System.err.println( "devBits=" + devBits + " and cmdBits=" + cmdBits );
Vector values = new Vector();
str = getNextField( st, delim ); // Device 1
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 2
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 3
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Raw Fixed Data
if ( str == null )
str = "";
int[] rawHex = Hex.parseHex( str );
protocol = new ManualProtocol( protocolName, pid, byte2, signalStyle, devBits, values, rawHex, cmdBits );
protocolName = protocol.getName();
setParmValues( protocol.getDeviceParmValues());
protocolManager.add( protocol );
}
else
{
// protocol = protocolManager.findProtocolForRemote( remote, protocolName );
Protocol p = protocolManager.findNearestProtocol( protocolName, pid, null );
if ( p == null )
{
p = protocolManager.findProtocolByOldName( remote, protocolName, pid );
if ( p == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"No protocol found with name=\"" + protocolName +
"\" for remote \"" + remote.getName() + "\".",
"Import Failure", JOptionPane.ERROR_MESSAGE );
reset();
return;
}
}
protocol = p;
Value[] importParms = new Value[ 4 ];
for ( int i = 0; i < importParms.length; i++ )
{
token = getNextField( st, delim );
Object val = null;
if ( token == null )
val = null;
else
{
if ( token.equals( "true" ))
val = new Integer( 1 );
else if ( token.equals( "false" ))
val = new Integer( 0 );
else
val = token;
// val = new Integer( token );
}
importParms[ i ] = new Value( val );
}
protocol.importDeviceParms( importParms );
parmValues = protocol.getDeviceParmValues();
}
// compute cmdIndex
boolean useOBC = false;
boolean useEFC = false;
if ( buttonStyle.equals( "OBC" ))
useOBC = true;
else if ( buttonStyle.equals( "EFC" ))
useEFC = true;
int obcIndex = -1;
CmdParameter[] cmdParms = protocol.getCommandParameters();
for ( obcIndex = 0; obcIndex < cmdParms.length; obcIndex++ )
{
if ( cmdParms[ obcIndex ].getName().equals( "OBC" ))
break;
}
String match1 = "fFunctions" + delim;
String match2 = "Functions" + delim;
if ( useOBC )
{
match1 = match1 + "fOBC" + delim;
match2 = match2 + "OBC" + delim;
}
else
{
match1 = match1 + "fEFC" + delim;
match2 = match2 + "EFC" + delim;
}
while ( true )
{
line = in.readLine();
if ( line.startsWith( match1 ) || line.startsWith( match2 ))
break;
}
functions.clear();
DeviceCombiner combiner = null;
if ( protocol.getClass() == DeviceCombiner.class )
combiner = ( DeviceCombiner )protocol;
Vector unassigned = new Vector();
Vector usedFunctions = new Vector();
for ( int i = 0; i < 128; i++ )
{
line = in.readLine();
st = new StringTokenizer( line, delim, true );
token = getNextField( st, delim ); // get the name (field 1)
if (( token != null ) && ( token.length() == 5 ) &&
token.startsWith( "num " ) && Character.isDigit( token.charAt( 4 )))
token = token.substring( 4 );
System.err.println( "Looking for function " + token );
Function f = getFunction( token, usedFunctions );
if ( f == null )
{
System.err.println( "Had to create a new one!" );
if (( token != null ) && ( token.charAt( 0 ) == '=' ) && ( token.indexOf( '/' ) != -1 ))
f = new ExternalFunction();
else
f = new Function();
f.setName( token );
}
else
System.err.println( "Found it!" );
token = getNextField( st, delim ); // get the function code (field 2)
if ( token != null )
{
Hex hex = null;
if ( f.isExternal())
{
ExternalFunction ef = ( ExternalFunction )f;
String name = ef.getName();
int slash = name.indexOf( '/' );
String devName = name.substring( 1, slash );
String match = null;
String[] names = remote.getDeviceTypeAliasNames();
for ( int j = 0; j < names.length; j++ )
{
if ( devName.equalsIgnoreCase( names[ j ]))
match = names[ j ];
}
if ( match == null )
{
String msg = "The Keymap Master device upgrade you are importing includes an\nexternal function that uses the unknown device type " +
devName + ".\n\nPlease select one of the supported device types below to use instead.";
while ( match == null )
{
match = ( String )JOptionPane.showInputDialog( KeyMapMaster.getKeyMapMaster(),
msg,
"Unsupported Device Type",
JOptionPane.ERROR_MESSAGE,
null,
names,
null );
}
}
ef.setDeviceTypeAliasName( match );
int space = name.indexOf( ' ', slash + 1 );
String codeString = null;
if ( space == -1 )
codeString = name.substring( slash + 1 );
else
codeString = name.substring( slash + 1, space );
ef.setSetupCode( Integer.parseInt( codeString ));
if (( token.indexOf( 'h' ) != -1 ) || ( token.indexOf( '$') != -1 ) || (token.indexOf( ' ' ) != -1 ))
{
hex = new Hex( token );
ef.setType( ExternalFunction.HexType );
}
else
{
hex = new Hex( 1 );
protocol.efc2hex( new EFC( token ), hex, 0 );
ef.setType( ExternalFunction.EFCType );
}
getNextField( st, delim ); // skip byte2 (field 3)
}
else
{
hex = protocol.getDefaultCmd();
protocol.importCommand( hex, token, useOBC, obcIndex, useEFC );
token = getNextField( st, delim ); // get byte2 (field 3)
if ( token != null )
protocol.importCommandParms( hex, token );
}
f.setHex( hex );
}
else
{
token = getNextField( st, delim ); // skip field 3
}
String actualName = getNextField( st, delim ); // get assigned button name (field 4)
System.err.println( "actualName='" + actualName + "'" );
if (( actualName != null ) && actualName.length() == 0 )
actualName = null;
String buttonName = null;
if ( actualName != null )
{
if ( i < genericButtonNames.length )
buttonName = genericButtonNames[ i ];
else
{
System.err.println( "No generic name available!" );
Button b = remote.getButton( actualName );
if ( b == null )
b = remote.getButton( actualName.replace( ' ', '_' ));
if ( b != null )
buttonName = b.getStandardName();
}
}
Button b = null;
if ( buttonName != null )
{
System.err.println( "Searching for button w/ name " + buttonName );
b = remote.findByStandardName( new Button( buttonName, null, ( byte )0, remote ));
System.err.println( "Found button " + b );
}
else
System.err.println( "No buttonName for actualName=" + actualName + " and i=" + i );
token = getNextField( st, delim ); // get normal function (field 5)
if (( buttonName != null ) && ( token != null ) &&
Character.isDigit( token.charAt( 0 )) &&
Character.isDigit( token.charAt( 1 )) &&
( token.charAt( 2 ) == ' ' ) &&
( token.charAt( 3 ) == '-' ) &&
( token.charAt( 4 ) == ' ' ))
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( name.charAt( 4 )))
name = name.substring( 4 );
Function func = null;
if (( f.getName() != null ) && f.getName().equalsIgnoreCase( name ))
func = f;
else
{
func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, extFunctions );
if ( func == null )
func = getFunction( name, usedFunctions );
}
if ( func == null )
{
System.err.println( "Creating new function " + name );
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
if ( b != null )
usedFunctions.add( func );
}
else
System.err.println( "Found function " + name );
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( actualName );
unassigned.add( temp );
System.err.println( "Couldn't find button " + buttonName + " to assign function " + name );
}
else if ( loadButtons )
{
System.err.println( "Setting function " + name + " on button " + b );
b.setFunction( func );
}
}
token = getNextField( st, delim ); // get notes (field 6)
if ( token != null )
f.setNotes( token );
if ( !f.isEmpty())
{
if ( f.isExternal())
extFunctions.add( f );
else
functions.add( f );
}
String pidStr = getNextField( st, delim ); // field 7
String fixedDataStr = getNextField( st, delim ); // field 8
if (( combiner != null ) && ( pidStr != null ) && // ( fixedDataStr != null ) &&
!pidStr.equals( "Protocol ID" )) // && !fixedDataStr.equals( "Fixed Data" )
{
Hex fixedData = new Hex();
if ( fixedDataStr != null )
fixedData = new Hex( fixedDataStr );
Hex newPid = new Hex( pidStr );
Vector protocols = protocolManager.findByPID( newPid );
boolean foundMatch = false;
for ( Enumeration e = protocols.elements(); e.hasMoreElements(); )
{
Protocol p = ( Protocol )e.nextElement();
if ( !remote.supportsVariant( newPid, p.getVariantName()))
continue;
CombinerDevice dev = new CombinerDevice( p, fixedData );
Hex calculatedFixedData = dev.getFixedData();
if ( !calculatedFixedData.equals( fixedData ))
continue;
combiner.add( dev );
foundMatch = true;
break;
}
if ( !foundMatch )
{
ManualProtocol p = new ManualProtocol( newPid, new Properties());
p.setRawHex( fixedData );
combiner.add( new CombinerDevice( p, null, null ));
}
}
// skip to field 13
for ( int j = 8; j < 13; j++ )
token = getNextField( st, delim );
if ( token != null )
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( token.charAt( 4 )))
name = name.substring( 4 );
Function func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, extFunctions );
if ( func == null )
{
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
usedFunctions.add( func );
}
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( "shift-" + buttonName );
unassigned.add( temp );
}
else if ( loadButtons )
b.setShiftedFunction( func );
}
}
while (( line = in.readLine()) != null )
{
st = new StringTokenizer( line, delim );
token = getNextField( st, delim );
if ( token != null )
{
if ( token.equals( "Line Notes:" ) || token.equals( "Notes:" ))
{
StringBuffer buff = new StringBuffer();
boolean first = true;
String tempDelim = null;
while (( line = in.readLine()) != null )
{
if ( line.charAt( 0 ) == '"' )
tempDelim = "\"";
else
tempDelim = delim;
st = new StringTokenizer( line, tempDelim );
if ( st.hasMoreTokens())
{
token = st.nextToken();
if ( token.startsWith( "EOF Marker" ))
break;
if ( first )
first = false;
else
buff.append( "\n" );
buff.append( token.trim());
}
else
buff.append( "\n" );
}
notes = buff.toString().trim();
if ( protocol.getClass() == ManualProtocol.class )
protocol.importUpgradeCode( notes );
}
}
}
if ( !unassigned.isEmpty())
{
System.err.println( "Removing undefined functions from usedFunctions" );
for( ListIterator i = unassigned.listIterator(); i.hasNext(); )
{
Vector temp = ( Vector )i.next();
String funcName = ( String )temp.elementAt( 0 );
System.err.print( "Checking '" + funcName + "'" );
Function f = getFunction( funcName, usedFunctions );
if (( f == null ) || ( f.getHex() == null ) || ( f.getHex().length() == 0 ))
{
System.err.println( "Removing function " + f + ", which has name '" + funcName + "'" );
i.remove();
}
}
}
if ( !unassigned.isEmpty())
{
String message = "Some of the functions defined in the imported device upgrade " +
"were assigned to buttons that could not be matched by name. " +
"The functions and the corresponding button names are listed below." +
"\n\nPlease post this information in the \"JP1 - Software\" section of the " +
"JP1 Forums at www.hifi-remote.com" +
"\n\nUse the Button or Layout panel to assign those functions properly.";
JFrame frame = new JFrame( "Import Failure" );
Container container = frame.getContentPane();
JTextArea text = new JTextArea( message );
text.setEditable( false );
text.setLineWrap( true );
text.setWrapStyleWord( true );
text.setBackground( container.getBackground() );
text.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ));
container.add( text, BorderLayout.NORTH );
Vector titles = new Vector();
titles.add( "Function name" );
titles.add( "Button name" );
JTable table = new JTable( unassigned, titles );
Dimension d = table.getPreferredScrollableViewportSize();
d.height = d.height / 4;
table.setPreferredScrollableViewportSize( d );
container.add( new JScrollPane( table ), BorderLayout.CENTER );
frame.pack();
frame.setLocationRelativeTo( KeyMapMaster.getKeyMapMaster());
frame.show();
}
Button[] buttons = remote.getUpgradeButtons();
System.err.println( "Removing assigned functions with no hex!" );
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setFunction( null );
f = b.getShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setShiftedFunction( null );
f = b.getXShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setXShiftedFunction( null );
}
System.err.println( "Done!" );
}
|
diff --git a/plugins/org.eclipse.jst.servlet.ui/servlet_ui/org/eclipse/jst/servlet/ui/internal/navigator/CompressedJavaProject.java b/plugins/org.eclipse.jst.servlet.ui/servlet_ui/org/eclipse/jst/servlet/ui/internal/navigator/CompressedJavaProject.java
index 2dc5d92bf..cd2f7d516 100644
--- a/plugins/org.eclipse.jst.servlet.ui/servlet_ui/org/eclipse/jst/servlet/ui/internal/navigator/CompressedJavaProject.java
+++ b/plugins/org.eclipse.jst.servlet.ui/servlet_ui/org/eclipse/jst/servlet/ui/internal/navigator/CompressedJavaProject.java
@@ -1,119 +1,119 @@
/***************************************************************************************************
* Copyright (c) 2003, 2004 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.jst.servlet.ui.internal.navigator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.ISharedImages;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jst.servlet.ui.internal.plugin.ServletUIPlugin;
import org.eclipse.jst.servlet.ui.internal.plugin.WEBUIMessages;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.graphics.Image;
public class CompressedJavaProject implements ICompressedNode, IAdaptable {
private IJavaProject project;
private CompressedJavaLibraries compressedLibraries;
private Image image;
public CompressedJavaProject(StructuredViewer viewer, IJavaProject project) {
this.project = project;
}
public Image getImage() {
if(image == null)
image = JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_PACKFRAG_ROOT);
return image;
}
public String getLabel() {
return determineLabel();
}
public boolean isFlatteningSourceFolder() {
return getNonExternalSourceFolders().size() == 1;
}
private String determineLabel() {
List nonextSourceFolders = getNonExternalSourceFolders();
IPackageFragmentRoot singleRoot = null;
if (nonextSourceFolders.size() == 1) {
singleRoot = (IPackageFragmentRoot) nonextSourceFolders.get(0);
}
return NLS.bind(WEBUIMessages.Compressed_JavaResources, ((singleRoot != null) ? ": " + singleRoot.getElementName() : "")); //$NON-NLS-1$ //$NON-NLS-2$
}
public IJavaProject getProject() {
return project;
}
public Object[] getChildren(ITreeContentProvider delegateContentProvider) {
List nonExternalSourceFolders = getNonExternalSourceFolders();
if (nonExternalSourceFolders.size() == 1) {
Object[] sourceFolderChildren = delegateContentProvider.getChildren(nonExternalSourceFolders.get(0));
nonExternalSourceFolders.clear();
nonExternalSourceFolders.addAll(Arrays.asList(sourceFolderChildren));
}
nonExternalSourceFolders.add(getCompressedJavaLibraries());
return nonExternalSourceFolders.toArray();
}
public List getNonExternalSourceFolders() {
List nonExternalSourceFolders = null;
IPackageFragmentRoot[] sourceFolders;
try {
sourceFolders = project.getPackageFragmentRoots();
nonExternalSourceFolders = new ArrayList(Arrays.asList(sourceFolders));
for (Iterator iter = nonExternalSourceFolders.iterator(); iter.hasNext();) {
IPackageFragmentRoot root = (IPackageFragmentRoot) iter.next();
- if (root.isExternal() || root.isArchive())
+ if (root.isExternal() || root.isArchive() || root.getKind()==IPackageFragmentRoot.K_BINARY)
iter.remove();
}
} catch (JavaModelException e) {
ServletUIPlugin.log(e);
}
return nonExternalSourceFolders != null ? nonExternalSourceFolders : Collections.EMPTY_LIST;
}
public CompressedJavaLibraries getCompressedJavaLibraries() {
if(compressedLibraries == null)
compressedLibraries = new CompressedJavaLibraries(this);
return compressedLibraries;
}
public Object getAdapter(Class adapter) {
return Platform.getAdapterManager().getAdapter(this, adapter);
}
public IJavaElement getJavaElement() {
List nonExternalSourceFolders = getNonExternalSourceFolders();
if (nonExternalSourceFolders.size() == 1) {
return (IJavaElement) nonExternalSourceFolders.get(0);
}
return getProject();
}
}
| true | true | public List getNonExternalSourceFolders() {
List nonExternalSourceFolders = null;
IPackageFragmentRoot[] sourceFolders;
try {
sourceFolders = project.getPackageFragmentRoots();
nonExternalSourceFolders = new ArrayList(Arrays.asList(sourceFolders));
for (Iterator iter = nonExternalSourceFolders.iterator(); iter.hasNext();) {
IPackageFragmentRoot root = (IPackageFragmentRoot) iter.next();
if (root.isExternal() || root.isArchive())
iter.remove();
}
} catch (JavaModelException e) {
ServletUIPlugin.log(e);
}
return nonExternalSourceFolders != null ? nonExternalSourceFolders : Collections.EMPTY_LIST;
}
| public List getNonExternalSourceFolders() {
List nonExternalSourceFolders = null;
IPackageFragmentRoot[] sourceFolders;
try {
sourceFolders = project.getPackageFragmentRoots();
nonExternalSourceFolders = new ArrayList(Arrays.asList(sourceFolders));
for (Iterator iter = nonExternalSourceFolders.iterator(); iter.hasNext();) {
IPackageFragmentRoot root = (IPackageFragmentRoot) iter.next();
if (root.isExternal() || root.isArchive() || root.getKind()==IPackageFragmentRoot.K_BINARY)
iter.remove();
}
} catch (JavaModelException e) {
ServletUIPlugin.log(e);
}
return nonExternalSourceFolders != null ? nonExternalSourceFolders : Collections.EMPTY_LIST;
}
|
diff --git a/Hanto/src/hanto/studentndemarinis/common/AbstractHantoRuleSet.java b/Hanto/src/hanto/studentndemarinis/common/AbstractHantoRuleSet.java
index b8245b8..6f18806 100644
--- a/Hanto/src/hanto/studentndemarinis/common/AbstractHantoRuleSet.java
+++ b/Hanto/src/hanto/studentndemarinis/common/AbstractHantoRuleSet.java
@@ -1,172 +1,172 @@
/**
* This file was developed for CS4233: Object-Oriented Analysis & Design.
* The course was taken at Worcester Polytechnic Institute.
*
* 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 hanto.studentndemarinis.common;
import hanto.common.HantoException;
import hanto.util.HantoPieceType;
import hanto.util.MoveResult;
/**
* Provides common rule implementation for
* a HantoRuleSet
* @author ndemarinis
* @version 4 February 2013
*
*/
public abstract class AbstractHantoRuleSet implements HantoRuleSet {
protected HantoGameState state;
/**
* Perform checks that must take place before a move.
* See HantoRuleSet for details
*/
@Override
public void doPreMoveChecks(HantoPieceType piece,
HexCoordinate from, HexCoordinate to) throws HantoException
{
verifyGameIsNotOver();
verifySourceAndDestinationCoords(from, to);
verifyMoveIsLegal(from, to);
}
/**
* Perform a move for real
* See HantoRuleSet for details.
*/
@Override
public void actuallyMakeMove(HantoPieceType type, HexCoordinate from, HexCoordinate to)
throws HantoException
{
// If this move involved placing a new piece, remove it from the player's hand
if(from == null) {
state.getPlayersHand(state.getCurrPlayer()).removeFromHand(type);
}
// Remove the old piece from the board (if we haven't failed yet)
if(from != null) {
state.getBoard().remove(from);
}
// Finally, add the new piece to the board.
state.getBoard().addPieceAt(new HantoPiece(state.getCurrPlayer(), type, to), to);
}
/**
* Perform any checks that must take place after a move
* @param to Destination coordinate
* @throws HantoException if any of these rules have been violated
*/
@Override
public void doPostMoveChecks(HexCoordinate to) throws HantoException {
verifyBoardIsContiguous();
}
/**
* Determine the result of a move based on the game's rules.
* Must be overridden by concrete realization.
*/
public abstract MoveResult evaluateMoveResult() throws HantoException;
/**
* Verify the game is not over
* @throws HantoException if the game is over
*/
protected void verifyGameIsNotOver() throws HantoException
{
if(state.isGameOver()) {
throw new HantoException("Illegal move: game has already ended!");
}
}
/**
* Verify the source and destination coordinates exist.
* If a source is provided, it must exist on the board;
* a destination coordinate must exist for a valid move.
* @param from Source coordinate
* @param to Destination coordinate
* @throws HantoException if either of these conditions have been violated
*/
protected void verifySourceAndDestinationCoords(HexCoordinate from, HexCoordinate to)
throws HantoException
{
// If provided, a source piece must exist on the board
if(from != null)
{
if(state.board.getPieceAt(from) == null) {
throw new HantoException("Illegal move: " +
"source piece does not exist on board!");
}
}
// The move must have a destination coordinate
if(to == null){
throw new HantoException("Illegal move: Destination coordinate must be provided!");
}
}
/**
* Verify a move is legal, meaning that the first piece must be at the origin,
* players can only move pieces of their own color, and that the destination
* coordinate must be empty
* @param from Source coordinate of move to verify
* @param to Destination coordinate of move to verify
* @throws HantoException if any of these conditions have been violated
*/
protected void verifyMoveIsLegal(HexCoordinate from, HexCoordinate to)
throws HantoException
{
// Verify the piece to be moved is owned by the current player
if(from != null)
{
if(state.board.getPieceAt(from).getColor() != state.currPlayer) {
throw new HantoException("Illegal move: your can only move pieces" +
"of your own color!");
}
}
// If this is the first move, we need a piece at the origin
if(state.numMoves == 0 &&
- to.getX() != 0 && to.getY() != 0) {
+ (to.getX() != 0 || to.getY() != 0)) {
throw new HantoException("Illegal move: First piece must be placed " +
"at origin!");
}
// If we find any pieces at the destination, it's not a legal move.
if(state.board.getPieceAt(to) != null){
throw new HantoException("Illegal move: can't place a piece " +
"on top of an existing piece!");
}
}
/**
* Verify all of the pieces on the board are in a
* single contiguous grouping.
* @throws HantoException if any pieces are separated from the group
*/
protected void verifyBoardIsContiguous() throws HantoException
{
// If we violated the adjacency rules
if(!state.board.isBoardContiguous()) {
throw new HantoException("Illegal move: pieces must retain a contiguous group!");
}
}
/**
* Set whether or not the game has ended based on the current move result
* @param res Result to determine game's ending state
*/
protected void determineIfGameHasEnded(MoveResult res)
{
state.setGameOver(res == MoveResult.DRAW ||
res == MoveResult.BLUE_WINS || res == MoveResult.RED_WINS);
}
}
| true | true | protected void verifyMoveIsLegal(HexCoordinate from, HexCoordinate to)
throws HantoException
{
// Verify the piece to be moved is owned by the current player
if(from != null)
{
if(state.board.getPieceAt(from).getColor() != state.currPlayer) {
throw new HantoException("Illegal move: your can only move pieces" +
"of your own color!");
}
}
// If this is the first move, we need a piece at the origin
if(state.numMoves == 0 &&
to.getX() != 0 && to.getY() != 0) {
throw new HantoException("Illegal move: First piece must be placed " +
"at origin!");
}
// If we find any pieces at the destination, it's not a legal move.
if(state.board.getPieceAt(to) != null){
throw new HantoException("Illegal move: can't place a piece " +
"on top of an existing piece!");
}
}
| protected void verifyMoveIsLegal(HexCoordinate from, HexCoordinate to)
throws HantoException
{
// Verify the piece to be moved is owned by the current player
if(from != null)
{
if(state.board.getPieceAt(from).getColor() != state.currPlayer) {
throw new HantoException("Illegal move: your can only move pieces" +
"of your own color!");
}
}
// If this is the first move, we need a piece at the origin
if(state.numMoves == 0 &&
(to.getX() != 0 || to.getY() != 0)) {
throw new HantoException("Illegal move: First piece must be placed " +
"at origin!");
}
// If we find any pieces at the destination, it's not a legal move.
if(state.board.getPieceAt(to) != null){
throw new HantoException("Illegal move: can't place a piece " +
"on top of an existing piece!");
}
}
|
diff --git a/src/net/sf/freecol/server/FreeColServer.java b/src/net/sf/freecol/server/FreeColServer.java
index d0c433c3b..904fd5657 100644
--- a/src/net/sf/freecol/server/FreeColServer.java
+++ b/src/net/sf/freecol/server/FreeColServer.java
@@ -1,1338 +1,1334 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.server;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.logging.Logger;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.sf.freecol.FreeCol;
import net.sf.freecol.common.FreeColException;
import net.sf.freecol.common.PseudoRandom;
import net.sf.freecol.common.Specification;
import net.sf.freecol.common.io.FreeColSavegameFile;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.HighScore;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.NationOptions;
import net.sf.freecol.common.model.NationOptions.NationState;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.Player.PlayerType;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.common.networking.Connection;
import net.sf.freecol.common.networking.Message;
import net.sf.freecol.common.networking.NoRouteToServerException;
import net.sf.freecol.common.util.XMLStream;
import net.sf.freecol.server.ai.AIInGameInputHandler;
import net.sf.freecol.server.ai.AIMain;
import net.sf.freecol.server.control.Controller;
import net.sf.freecol.server.control.InGameController;
import net.sf.freecol.server.control.InGameInputHandler;
import net.sf.freecol.server.control.PreGameController;
import net.sf.freecol.server.control.PreGameInputHandler;
import net.sf.freecol.server.control.ServerModelController;
import net.sf.freecol.server.control.UserConnectionHandler;
import net.sf.freecol.server.generator.IMapGenerator;
import net.sf.freecol.server.generator.MapGenerator;
import net.sf.freecol.server.model.ServerGame;
import net.sf.freecol.server.model.ServerModelObject;
import net.sf.freecol.server.model.ServerPlayer;
import net.sf.freecol.server.networking.DummyConnection;
import net.sf.freecol.server.networking.Server;
import org.w3c.dom.Element;
/**
* The main control class for the FreeCol server. This class both starts and
* keeps references to all of the server objects and the game model objects.
* <br>
* <br>
* If you would like to start a new server you just create a new object of this
* class.
*/
public final class FreeColServer {
private static final Logger logger = Logger.getLogger(FreeColServer.class.getName());
private static final int META_SERVER_UPDATE_INTERVAL = 60000;
private static final int NUMBER_OF_HIGH_SCORES = 10;
private static final String HIGH_SCORE_FILE = "HighScores.xml";
/**
* The save game format used for saving games.
*/
public static final int SAVEGAME_VERSION = 6;
/**
* The oldest save game format that can still be loaded.
*/
public static final int MINIMUM_SAVEGAME_VERSION = 1;
/** Constant for storing the state of the game. */
public static enum GameState {STARTING_GAME, IN_GAME, ENDING_GAME}
/** Stores the current state of the game. */
private GameState gameState = GameState.STARTING_GAME;
// Networking:
private Server server;
// Control:
private final UserConnectionHandler userConnectionHandler;
private final PreGameController preGameController;
private final PreGameInputHandler preGameInputHandler;
private final InGameInputHandler inGameInputHandler;
private final ServerModelController modelController;
private final InGameController inGameController;
private ServerGame game;
private AIMain aiMain;
private IMapGenerator mapGenerator;
private boolean singleplayer;
// The username of the player owning this server.
private String owner;
private boolean publicServer = false;
private final int port;
/** The name of this server. */
private String name;
/** The provider for random numbers */
private final ServerPseudoRandom _pseudoRandom = new ServerPseudoRandom();
/** Did the integrity check succeed */
private boolean integrity = false;
/**
* The high scores on this server.
*/
private List<HighScore> highScores = null;
public static final Comparator<HighScore> highScoreComparator = new Comparator<HighScore>() {
public int compare(HighScore score1, HighScore score2) {
return score2.getScore() - score1.getScore();
}
};
/**
* Starts a new server in a specified mode and with a specified port.
*
* @param publicServer This value should be set to <code>true</code> in
* order to appear on the meta server's listing.
*
* @param singleplayer Sets the game as singleplayer (if <i>true</i>) or
* multiplayer (if <i>false</i>).
*
* @param port The TCP port to use for the public socket. That is the port
* the clients will connect to.
*
* @param name The name of the server, or <code>null</code> if the default
* name should be used.
*
* @throws IOException if the public socket cannot be created (the exception
* will be logged by this class).
*
*/
public FreeColServer(boolean publicServer, boolean singleplayer, int port, String name)
throws IOException, NoRouteToServerException {
this(publicServer, singleplayer, port, name, NationOptions.getDefaults());
}
public FreeColServer(boolean publicServer, boolean singleplayer, int port, String name,
NationOptions nationOptions) throws IOException, NoRouteToServerException {
this.publicServer = publicServer;
this.singleplayer = singleplayer;
this.port = port;
this.name = name;
modelController = new ServerModelController(this);
game = new ServerGame(modelController);
game.setNationOptions(nationOptions);
mapGenerator = new MapGenerator();
userConnectionHandler = new UserConnectionHandler(this);
preGameController = new PreGameController(this);
preGameInputHandler = new PreGameInputHandler(this);
inGameInputHandler = new InGameInputHandler(this);
inGameController = new InGameController(this);
try {
server = new Server(this, port);
server.start();
} catch (IOException e) {
logger.warning("Exception while starting server: " + e);
throw e;
}
updateMetaServer(true);
startMetaServerUpdateThread();
}
/**
* Starts a new server in a specified mode and with a specified port and
* loads the game from the given file.
*
* @param savegame The file where the game data is located.
*
* @param publicServer This value should be set to <code>true</code> in
* order to appear on the meta server's listing.
*
* @param singleplayer Sets the game as singleplayer (if <i>true</i>) or
* multiplayer (if <i>false</i>).
* @param port The TCP port to use for the public socket. That is the port
* the clients will connect to.
*
* @param name The name of the server, or <code>null</code> if the default
* name should be used.
*
* @throws IOException if the public socket cannot be created (the exception
* will be logged by this class).
*
* @throws FreeColException if the savegame could not be loaded.
*/
public FreeColServer(final FreeColSavegameFile savegame, boolean publicServer,
boolean singleplayer, int port, String name)
throws IOException, FreeColException, NoRouteToServerException {
this.publicServer = publicServer;
this.singleplayer = singleplayer;
this.port = port;
this.name = name;
//this.nationOptions = nationOptions;
mapGenerator = new MapGenerator();
modelController = new ServerModelController(this);
userConnectionHandler = new UserConnectionHandler(this);
preGameController = new PreGameController(this);
preGameInputHandler = new PreGameInputHandler(this);
inGameInputHandler = new InGameInputHandler(this);
inGameController = new InGameController(this);
try {
server = new Server(this, port);
server.start();
} catch (IOException e) {
logger.warning("Exception while starting server: " + e);
throw e;
}
try {
owner = loadGame(savegame);
} catch (FreeColException e) {
server.shutdown();
throw e;
} catch (Exception e) {
server.shutdown();
FreeColException fe = new FreeColException("couldNotLoadGame");
fe.initCause(e);
throw fe;
}
// Apply the difficulty level
Specification.getSpecification().applyDifficultyLevel(game.getGameOptions()
.getInteger(GameOptions.DIFFICULTY));
updateMetaServer(true);
startMetaServerUpdateThread();
}
/**
* Starts the metaserver update thread if <code>publicServer == true</code>.
*
* This update is really a "Hi! I am still here!"-message, since an
* additional update should be sent when a new player is added to/removed
* from this server etc.
*/
public void startMetaServerUpdateThread() {
if (!publicServer) {
return;
}
Timer t = new Timer(true);
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
try {
updateMetaServer();
} catch (NoRouteToServerException e) {}
}
}, META_SERVER_UPDATE_INTERVAL, META_SERVER_UPDATE_INTERVAL);
}
/**
* Enters revenge mode against those evil AIs.
*
* @param username The player to enter revenge mode.
*/
public void enterRevengeMode(String username) {
if (!singleplayer) {
throw new IllegalStateException("Cannot enter revenge mode when not singleplayer.");
}
final ServerPlayer p = (ServerPlayer) getGame().getPlayerByName(username);
synchronized (p) {
List<UnitType> undeads = FreeCol.getSpecification().getUnitTypesWithAbility("model.ability.undead");
ArrayList<UnitType> navalUnits = new ArrayList<UnitType>();
ArrayList<UnitType> landUnits = new ArrayList<UnitType>();
for (UnitType undead : undeads) {
if (undead.hasAbility("model.ability.navalUnit")) {
navalUnits.add(undead);
} else if (undead.getId().equals("model.unit.revenger")) { // TODO: softcode this
landUnits.add(undead);
}
}
if (navalUnits.size() > 0) {
UnitType navalType = navalUnits.get(getPseudoRandom().nextInt(navalUnits.size()));
Unit theFlyingDutchman = new Unit(game, p.getEntryLocation(), p, navalType, UnitState.ACTIVE);
if (landUnits.size() > 0) {
UnitType landType = landUnits.get(getPseudoRandom().nextInt(landUnits.size()));
new Unit(game, theFlyingDutchman, p, landType, UnitState.SENTRY);
}
p.setDead(false);
p.setPlayerType(PlayerType.UNDEAD);
p.setColor(Color.BLACK);
Element updateElement = Message.createNewRootElement("update");
updateElement.appendChild(((FreeColGameObject) p.getEntryLocation()).toXMLElement(p, updateElement
.getOwnerDocument()));
updateElement.appendChild(p.toXMLElement(p, updateElement.getOwnerDocument()));
try {
p.getConnection().sendAndWait(updateElement);
} catch (IOException e) {
logger.warning("Could not send update");
}
}
}
}
/**
* Gets the <code>MapGenerator</code> this <code>FreeColServer</code> is
* using when creating random maps.
*
* @return The <code>MapGenerator</code>.
*/
public IMapGenerator getMapGenerator() {
return mapGenerator;
}
/**
* Sets the <code>MapGenerator</code> this <code>FreeColServer</code> is
* using when creating random maps.
*
* @param mapGenerator The <code>MapGenerator</code>.
*/
public void setMapGenerator(IMapGenerator mapGenerator) {
this.mapGenerator = mapGenerator;
}
/**
* Sends information about this server to the meta-server. The information
* is only sent if <code>public == true</code>.
*/
public void updateMetaServer() throws NoRouteToServerException {
updateMetaServer(false);
}
/**
* Returns the name of this server.
*
* @return The name.
*/
public String getName() {
return name;
}
/**
* Sets the name of this server.
*
* @param name The name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Sends information about this server to the meta-server. The information
* is only sent if <code>public == true</code>.
*
* @param firstTime Should be set to <i>true></i> when calling this method
* for the first time.
* @throws NoRouteToServerException if the meta-server cannot connect to
* this server.
*/
public void updateMetaServer(boolean firstTime) throws NoRouteToServerException {
if (!publicServer) {
return;
}
Connection mc;
try {
mc = new Connection(FreeCol.META_SERVER_ADDRESS, FreeCol.META_SERVER_PORT, null, FreeCol.SERVER_THREAD);
} catch (IOException e) {
logger.warning("Could not connect to meta-server.");
return;
}
try {
Element element;
if (firstTime) {
element = Message.createNewRootElement("register");
} else {
element = Message.createNewRootElement("update");
}
// TODO: Add possibility of choosing a name:
if (name != null) {
element.setAttribute("name", name);
} else {
element.setAttribute("name", mc.getSocket().getLocalAddress().getHostAddress() + ":"
+ Integer.toString(port));
}
element.setAttribute("port", Integer.toString(port));
element.setAttribute("slotsAvailable", Integer.toString(getSlotsAvailable()));
element.setAttribute("currentlyPlaying", Integer.toString(getNumberOfLivingHumanPlayers()));
element.setAttribute("isGameStarted", Boolean.toString(gameState != GameState.STARTING_GAME));
element.setAttribute("version", FreeCol.getVersion());
element.setAttribute("gameState", Integer.toString(getGameState().ordinal()));
Element reply = mc.ask(element);
if (reply != null && reply.getTagName().equals("noRouteToServer")) {
throw new NoRouteToServerException();
}
} catch (IOException e) {
logger.warning("Network error while communicating with the meta-server.");
return;
} finally {
try {
// mc.reallyClose();
mc.close();
} catch (IOException e) {
logger.warning("Could not close connection to meta-server.");
return;
}
}
}
/**
* Removes this server from the metaserver's list. The information is only
* sent if <code>public == true</code>.
*/
public void removeFromMetaServer() {
if (!publicServer) {
return;
}
Connection mc;
try {
mc = new Connection(FreeCol.META_SERVER_ADDRESS, FreeCol.META_SERVER_PORT, null, FreeCol.SERVER_THREAD);
} catch (IOException e) {
logger.warning("Could not connect to meta-server.");
return;
}
try {
Element element = Message.createNewRootElement("remove");
element.setAttribute("port", Integer.toString(port));
mc.send(element);
} catch (IOException e) {
logger.warning("Network error while communicating with the meta-server.");
return;
} finally {
try {
// mc.reallyClose();
mc.close();
} catch (IOException e) {
logger.warning("Could not close connection to meta-server.");
return;
}
}
}
/**
* Gets the number of player that may connect.
*
* @return The number of available slots for human players. This number also
* includes european players currently controlled by the AI.
*/
public int getSlotsAvailable() {
List<Player> players = game.getPlayers();
int n = 0;
for (int i = 0; i < players.size(); i++) {
ServerPlayer p = (ServerPlayer) players.get(i);
if (!p.isEuropean() || p.isREF()) {
continue;
}
if (!(p.isDead() || p.isConnected() && !p.isAI())) {
n++;
}
}
return n;
}
/**
* Gets the number of human players in this game that is still playing.
*
* @return The number.
*/
public int getNumberOfLivingHumanPlayers() {
List<Player> players = game.getPlayers();
int n = 0;
for (int i = 0; i < players.size(); i++) {
if (!((ServerPlayer) players.get(i)).isAI() && !((ServerPlayer) players.get(i)).isDead()
&& ((ServerPlayer) players.get(i)).isConnected()) {
n++;
}
}
return n;
}
/**
* Gets the owner of the <code>Game</code>.
*
* @return The owner of the game. THis is the player that has loaded the
* game (if any).
* @see #loadGame
*/
public String getOwner() {
return owner;
}
/**
* Saves a game.
*
* @param file The file where the data will be written.
* @param username The username of the player saving the game.
* @throws IOException If a problem was encountered while trying to open,
* write or close the file.
*/
public void saveGame(File file, String username) throws IOException {
final Game game = getGame();
XMLOutputFactory xof = XMLOutputFactory.newInstance();
JarOutputStream fos = null;
try {
XMLStreamWriter xsw;
fos = new JarOutputStream(new FileOutputStream(file));
fos.putNextEntry(new JarEntry(file.getName().substring(0, file.getName().lastIndexOf('.')) + "/" + FreeColSavegameFile.SAVEGAME_FILE));
xsw = xof.createXMLStreamWriter(fos, "UTF-8");
xsw.writeStartDocument("UTF-8", "1.0");
xsw.writeComment("Game version: "+FreeCol.getRevision());
xsw.writeStartElement("savedGame");
// Add the attributes:
xsw.writeAttribute("owner", username);
xsw.writeAttribute("publicServer", Boolean.toString(publicServer));
xsw.writeAttribute("singleplayer", Boolean.toString(singleplayer));
xsw.writeAttribute("version", Integer.toString(SAVEGAME_VERSION));
xsw.writeAttribute("randomState", _pseudoRandom.getState());
// Add server side model information:
xsw.writeStartElement("serverObjects");
Iterator<FreeColGameObject> fcgoIterator = game.getFreeColGameObjectIterator();
while (fcgoIterator.hasNext()) {
FreeColGameObject fcgo = fcgoIterator.next();
if (fcgo instanceof ServerModelObject) {
((ServerModelObject) fcgo).toServerAdditionElement(xsw);
}
}
xsw.writeEndElement();
// Add the game:
game.toSavedXML(xsw);
// Add the AIObjects:
if (aiMain != null) {
aiMain.toXML(xsw);
}
xsw.writeEndElement();
xsw.writeEndDocument();
xsw.flush();
xsw.close();
} catch (XMLStreamException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException("XMLStreamException.");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException(e.toString());
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
// do nothing
}
}
}
/**
* Creates a <code>XMLStream</code> for reading the given file.
* Compression is automatically detected.
*
* @param fis The file to be read.
* @return The <code>XMLStreamr</code>.
* @exception IOException if thrown while loading the game or if a
* <code>XMLStreamException</code> have been thrown by the
* parser.
*/
public static XMLStream createXMLStreamReader(FreeColSavegameFile fis) throws IOException {
return new XMLStream(fis.getSavegameInputStream());
}
/**
* Loads a game.
*
* @param fis The file where the game data is located.
* @return The username of the player saving the game.
* @throws IOException If a problem was encountered while trying to open,
* read or close the file.
* @exception IOException if thrown while loading the game or if a
* <code>XMLStreamException</code> have been thrown by the
* parser.
* @exception FreeColException if the savegame contains incompatible data.
*/
public String loadGame(final FreeColSavegameFile fis) throws IOException, FreeColException {
boolean doNotLoadAI = false;
XMLStream xs = null;
try {
xs = createXMLStreamReader(fis);
final XMLStreamReader xsr = xs.getXMLStreamReader();
xsr.nextTag();
final String version = xsr.getAttributeValue(null, "version");
int savegameVersion = 0;
try {
- // TODO: remove this compatibility code BEFORE releasing 0.9
- if (version.equals("0.1.4")) {
- savegameVersion = 1;
- } else {
- savegameVersion = Integer.parseInt(version);
- }
+ savegameVersion = Integer.parseInt(version);
} catch(Exception e) {
throw new FreeColException("incompatibleVersions");
}
if (savegameVersion < MINIMUM_SAVEGAME_VERSION) {
throw new FreeColException("incompatibleVersions");
}
String randomState = xsr.getAttributeValue(null, "randomState");
if (randomState != null && randomState.length() > 0) {
try {
_pseudoRandom.restoreState(randomState);
} catch (IOException e) {
logger.warning("Failed to restore random state, ignoring!");
}
}
final String owner = xsr.getAttributeValue(null, "owner");
ArrayList<Object> serverObjects = null;
aiMain = null;
while (xsr.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (xsr.getLocalName().equals("serverObjects")) {
// Reads the ServerAdditionObjects:
serverObjects = new ArrayList<Object>();
while (xsr.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (xsr.getLocalName().equals(ServerPlayer.getServerAdditionXMLElementTagName())) {
serverObjects.add(new ServerPlayer(xsr));
} else {
throw new XMLStreamException("Unknown tag: " + xsr.getLocalName());
}
}
} else if (xsr.getLocalName().equals(Game.getXMLElementTagName())) {
// Read the game model:
game = new ServerGame(null, getModelController(), xsr, serverObjects
.toArray(new FreeColGameObject[0]));
game.setCurrentPlayer(null);
gameState = GameState.IN_GAME;
integrity = game.checkIntegrity();
} else if (xsr.getLocalName().equals(AIMain.getXMLElementTagName())) {
if (doNotLoadAI) {
aiMain = new AIMain(this);
game.setFreeColGameObjectListener(aiMain);
break;
}
// Read the AIObjects:
aiMain = new AIMain(this, xsr);
if (!aiMain.checkIntegrity()) {
aiMain = new AIMain(this);
logger.info("Replacing AIMain.");
}
game.setFreeColGameObjectListener(aiMain);
} else if (xsr.getLocalName().equals("marketdata")) {
logger.info("Ignoring market data for compatibility.");
} else {
throw new XMLStreamException("Unknown tag: " + xsr.getLocalName());
}
}
+ Collections.sort(game.getPlayers(), Player.playerComparator);
if (aiMain == null) {
aiMain = new AIMain(this);
game.setFreeColGameObjectListener(aiMain);
}
// Connect the AI-players:
Iterator<Player> playerIterator = game.getPlayerIterator();
while (playerIterator.hasNext()) {
ServerPlayer player = (ServerPlayer) playerIterator.next();
if (player.isAI()) {
DummyConnection theConnection = new DummyConnection(
"Server-Server-" + player.getName(),
getInGameInputHandler());
DummyConnection aiConnection = new DummyConnection(
"Server-AI-" + player.getName(),
new AIInGameInputHandler(this, player, aiMain));
aiConnection.setOutgoingMessageHandler(theConnection);
theConnection.setOutgoingMessageHandler(aiConnection);
getServer().addDummyConnection(theConnection);
player.setConnection(theConnection);
player.setConnected(true);
}
}
xs.close();
// Later, we might want to modify loaded savegames:
return owner;
} catch (XMLStreamException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException("XMLStreamException.");
} catch (FreeColException fe) {
StringWriter sw = new StringWriter();
fe.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw fe;
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException(e.toString());
} finally {
xs.close();
}
}
/**
* Sets the mode of the game: singleplayer/multiplayer.
*
* @param singleplayer Sets the game as singleplayer (if <i>true</i>) or
* multiplayer (if <i>false</i>).
*/
public void setSingleplayer(boolean singleplayer) {
this.singleplayer = singleplayer;
}
/**
* Checks if the user is playing in singleplayer mode.
*
* @return <i>true</i> if the user is playing in singleplayer mode,
* <i>false</i> otherwise.
*/
public boolean isSingleplayer() {
return singleplayer;
}
/**
* Makes the entire map visible for all players. Used only when debugging
* (will be removed).
*/
public void revealMapForAllPlayers() {
Iterator<Player> playerIterator = getGame().getPlayerIterator();
while (playerIterator.hasNext()) {
ServerPlayer player = (ServerPlayer) playerIterator.next();
player.revealMap();
}
playerIterator = getGame().getPlayerIterator();
while (playerIterator.hasNext()) {
ServerPlayer player = (ServerPlayer) playerIterator.next();
Element reconnect = Message.createNewRootElement("reconnect");
try {
player.getConnection().send(reconnect);
} catch (IOException ex) {
logger.warning("Could not send reconnect message!");
}
}
}
/**
* Gets a <code>Player</code> specified by a connection.
*
* @param connection The connection to use while searching for a
* <code>ServerPlayer</code>.
* @return The player.
*/
public ServerPlayer getPlayer(Connection connection) {
Iterator<Player> playerIterator = getGame().getPlayerIterator();
while (playerIterator.hasNext()) {
ServerPlayer player = (ServerPlayer) playerIterator.next();
if (player.getConnection() == connection) {
return player;
}
}
return null;
}
/**
* Gets the <code>UserConnectionHandler</code>.
*
* @return The <code>UserConnectionHandler</code> that is beeing used when
* new client connect.
*/
public UserConnectionHandler getUserConnectionHandler() {
return userConnectionHandler;
}
/**
* Gets the <code>Controller</code>.
*
* @return The <code>Controller</code>.
*/
public Controller getController() {
if (getGameState() == GameState.IN_GAME) {
return inGameController;
} else {
return preGameController;
}
}
/**
* Gets the <code>PreGameInputHandler</code>.
*
* @return The <code>PreGameInputHandler</code>.
*/
public PreGameInputHandler getPreGameInputHandler() {
return preGameInputHandler;
}
/**
* Gets the <code>InGameInputHandler</code>.
*
* @return The <code>InGameInputHandler</code>.
*/
public InGameInputHandler getInGameInputHandler() {
return inGameInputHandler;
}
/**
* Gets the controller being used while the game is running.
*
* @return The controller from making a new turn etc.
*/
public InGameController getInGameController() {
return inGameController;
}
/**
* Gets the <code>ModelController</code>.
*
* @return The controller used for generating random numbers and creating
* new {@link FreeColGameObject}s.
*/
public ServerModelController getModelController() {
return modelController;
}
/**
* Gets the <code>Game</code> that is being played.
*
* @return The <code>Game</code> which is the main class of the game-model
* being used in this game.
*/
public ServerGame getGame() {
return game;
}
/**
* Sets the main AI-object.
*
* @param aiMain The main AI-object which is responsible for controlling,
* updating and saving the AI objects.
*/
public void setAIMain(AIMain aiMain) {
this.aiMain = aiMain;
}
/**
* Gets the main AI-object.
*
* @return The main AI-object which is responsible for controlling, updating
* and saving the AI objects.
*/
public AIMain getAIMain() {
return aiMain;
}
/**
* Gets the current state of the game.
*
* @return One of: {@link #STARTING_GAME}, {@link #IN_GAME} and
* {@link #ENDING_GAME}.
*/
public GameState getGameState() {
return gameState;
}
/**
* Sets the current state of the game.
*
* @param state The new state to be set. One of: {@link #STARTING_GAME},
* {@link #IN_GAME} and {@link #ENDING_GAME}.
*/
public void setGameState(GameState state) {
gameState = state;
}
/**
* Gets the network server responsible of handling the connections.
*
* @return The network server.
*/
public Server getServer() {
return server;
}
/**
* Gets the integrity check result.
*
* @return The integrity check result.
*/
public boolean getIntegrity() {
return integrity;
}
/**
* Get the common pseudo random number generator for the server.
*
* @return random number generator.
*/
public PseudoRandom getPseudoRandom() {
return _pseudoRandom;
}
/**
* Get multiple random numbers.
*
* @param n The size of the returned array.
* @return array with random numbers.
*/
public int[] getRandomNumbers(int n) {
return _pseudoRandom.getRandomNumbers(n);
}
/**
* This class provides pseudo-random numbers. It is used on the server side.
*
* TODO (if others agree): refactor Game into an interface and client-side
* and server-side implementations, move this to the server-side class.
*/
private static class ServerPseudoRandom implements PseudoRandom {
private static final String HEX_DIGITS = "0123456789ABCDEF";
private Random _random;
/**
* Create a new random number generator with a random seed.
* <p>
* The initial seed is calculated using {@link SecureRandom}, which is
* slower but better than the normal {@link Random} class. Note,
* however, that {@link SecureRandom} cannot be used for all numbers, as
* it will return different numbers given the same seed! That breaks the
* contract established by {@link PseudoRandom}.
*/
public ServerPseudoRandom() {
_random = new Random(new SecureRandom().nextLong());
}
/**
* Get the next integer between 0 and n.
*
* @param n The upper bound (exclusive).
* @return random number between 0 and n.
*/
public synchronized int nextInt(int n) {
return _random.nextInt(n);
}
/**
* Get multiple random numbers. This can be used on the client side in
* order to reduce the number of round-trips to the server side.
*
* @param size The size of the returned array.
* @return array with random numbers.
*/
public synchronized int[] getRandomNumbers(int size) {
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
numbers[i] = _random.nextInt();
}
return numbers;
}
/**
* Get the internal state of the random provider as a string.
* <p>
* It would have been more convenient to simply return the current seed,
* but unfortunately it is private.
*
* @return state.
*/
public synchronized String getState() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(_random);
oos.flush();
} catch (IOException e) {
throw new IllegalStateException("IO exception in memory!?!", e);
}
byte[] bytes = bos.toByteArray();
StringBuffer sb = new StringBuffer(bytes.length * 2);
for (byte b : bytes) {
sb.append(HEX_DIGITS.charAt((b >> 4) & 0x0F));
sb.append(HEX_DIGITS.charAt(b & 0x0F));
}
return sb.toString();
}
/**
* Restore a previously saved state.
*
* @param state The saved state (@see #getState()).
* @throws IOException if unable to restore state.
*/
public synchronized void restoreState(String state) throws IOException {
byte[] bytes = new byte[state.length() / 2];
int pos = 0;
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) HEX_DIGITS.indexOf(state.charAt(pos++));
bytes[i] <<= 4;
bytes[i] |= (byte) HEX_DIGITS.indexOf(state.charAt(pos++));
}
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
try {
_random = (Random) ois.readObject();
} catch (ClassNotFoundException e) {
throw new IOException("Failed to restore random!");
}
}
}
/**
* Get a unit by ID, validating the ID as much as possible. Designed for
* message unpacking where the ID should not be trusted.
*
* @param unitId The ID of the unit to be found.
* @param serverPlayer The <code>ServerPlayer</code> to whom the unit must belong.
*
* @return The unit corresponding to the unitId argument.
* @throws IllegalStateException on failure to validate the unitId
* in any way.
* In the worst case this may be indicative of a malign client.
*/
public Unit getUnitSafely(String unitId, ServerPlayer serverPlayer)
throws IllegalStateException {
Game game = serverPlayer.getGame();
FreeColGameObject obj;
Unit unit;
if (unitId == null || unitId.length() == 0) {
throw new IllegalStateException("ID must not be empty.");
}
obj = game.getFreeColGameObjectSafely(unitId);
if (!(obj instanceof Unit)) {
throw new IllegalStateException("Not a unit ID: " + unitId);
}
unit = (Unit) obj;
if (unit.getOwner() != serverPlayer) {
throw new IllegalStateException("Not the owner of unit: " + unitId);
}
return unit;
}
/**
* Get a settlement by ID, validating the ID as much as possible.
* Designed for message unpacking where the ID should not be trusted.
*
* @param settlementId The ID of the <code>Settlement</code> to be found.
* @param unit A <code>Unit</code> which must be adjacent
* to the <code>Settlement</code>.
*
* @return The settlement corresponding to the settlementId argument.
* @throws IllegalStateException on failure to validate the settlementId
* in any way.
* In the worst case this may be indicative of a malign client.
*/
public Settlement getAdjacentSettlementSafely(String settlementId, Unit unit)
throws IllegalStateException {
Game game = unit.getOwner().getGame();
Settlement settlement;
if (settlementId == null || settlementId.length() == 0) {
throw new IllegalStateException("ID must not be empty.");
} else if (!(game.getFreeColGameObject(settlementId) instanceof Settlement)) {
throw new IllegalStateException("Not a settlement ID: " + settlementId);
}
settlement = (Settlement) game.getFreeColGameObject(settlementId);
if (settlement.getTile() == null) {
throw new IllegalStateException("Settlement is not on the map: "
+ settlementId);
}
if (unit.getTile() == null) {
throw new IllegalStateException("Unit is not on the map: "
+ unit.getId());
}
if (unit.getTile().getDistanceTo(settlement.getTile()) > 1) {
throw new IllegalStateException("Unit " + unit.getId()
+ " is not adjacent to settlement: " + settlementId);
}
if (unit.getOwner() == settlement.getOwner()) {
throw new IllegalStateException("Unit: " + unit.getId()
+ " and settlement: " + settlementId
+ " are both owned by player: "
+ unit.getOwner().getId());
}
return settlement;
}
/**
* Get an adjacent Indian settlement by ID, validating as much as possible,
* including checking whether the nation involved has been contacted.
* Designed for message unpacking where the ID should not be trusted.
*
* @param settlementId The ID of the <code>Settlement</code> to be found.
* @param unit A <code>Unit</code> which must be adjacent
* to the <code>Settlement</code>.
*
* @return The settlement corresponding to the settlementId argument.
* @throws IllegalStateException on failure to validate the settlementId
* in any way.
* In the worst case this may be indicative of a malign client.
*/
public IndianSettlement getAdjacentIndianSettlementSafely(String settlementId, Unit unit)
throws IllegalStateException {
Settlement settlement = getAdjacentSettlementSafely(settlementId, unit);
if (!(settlement instanceof IndianSettlement)) {
throw new IllegalStateException("Not an indianSettlement: " + settlementId);
}
if (!unit.getOwner().hasContacted(settlement.getOwner())) {
throw new IllegalStateException("Player has not established contact with the " + settlement.getOwner().getNationAsString());
}
return (IndianSettlement) settlement;
}
/**
* Adds a new AIPlayer to the Game.
*
* @param nation a <code>Nation</code> value
* @return a <code>ServerPlayer</code> value
*/
public ServerPlayer addAIPlayer(Nation nation) {
String name = nation.getRulerName();
DummyConnection theConnection =
new DummyConnection("Server connection - " + name, getInGameInputHandler());
ServerPlayer aiPlayer =
new ServerPlayer(getGame(), name, false, true, null, theConnection, nation);
DummyConnection aiConnection =
new DummyConnection("AI connection - " + name,
new AIInGameInputHandler(this, aiPlayer, getAIMain()));
aiConnection.setOutgoingMessageHandler(theConnection);
theConnection.setOutgoingMessageHandler(aiConnection);
getServer().addDummyConnection(theConnection);
getGame().addPlayer(aiPlayer);
// Send message to all players except to the new player:
Element addNewPlayer = Message.createNewRootElement("addPlayer");
addNewPlayer.appendChild(aiPlayer.toXMLElement(null, addNewPlayer.getOwnerDocument()));
getServer().sendToAll(addNewPlayer, theConnection);
return aiPlayer;
}
/**
* Get the <code>HighScores</code> value.
*
* @return a <code>List<HighScore></code> value
*/
public List<HighScore> getHighScores() {
if (highScores == null) {
try {
loadHighScores();
} catch (Exception e) {
logger.warning(e.toString());
highScores = new ArrayList<HighScore>();
}
}
return highScores;
}
/**
* Adds a new high score for player and returns <code>true</code>
* if possible.
*
* @param player a <code>Player</code> value
* @param nationName a <code>String</code> value
* @return a <code>boolean</code> value
*/
public boolean newHighScore(Player player) {
getHighScores();
if (!highScores.isEmpty() && player.getScore() <= highScores.get(highScores.size() - 1).getScore()) {
return false;
} else {
highScores.add(new HighScore(player, new Date()));
Collections.sort(highScores, highScoreComparator);
if (highScores.size() == NUMBER_OF_HIGH_SCORES) {
highScores.remove(NUMBER_OF_HIGH_SCORES - 1);
}
return true;
}
}
/**
* Saves high scores.
*
* @throws IOException If a problem was encountered while trying to open,
* write or close the file.
*/
public void saveHighScores() throws IOException {
if (highScores == null || highScores.isEmpty()) {
return;
}
Collections.sort(highScores, highScoreComparator);
XMLOutputFactory xof = XMLOutputFactory.newInstance();
FileOutputStream fos = null;
try {
XMLStreamWriter xsw;
fos = new FileOutputStream(new File(FreeCol.getDataDirectory(), HIGH_SCORE_FILE));
xsw = xof.createXMLStreamWriter(fos, "UTF-8");
xsw.writeStartDocument("UTF-8", "1.0");
xsw.writeStartElement("highScores");
int count = 0;
for (HighScore score : highScores) {
score.toXML(xsw);
count++;
if (count == NUMBER_OF_HIGH_SCORES) {
break;
}
}
xsw.writeEndElement();
xsw.writeEndDocument();
xsw.flush();
xsw.close();
} catch (XMLStreamException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException("XMLStreamException.");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException(e.toString());
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
// do nothing
}
}
}
/**
* Loads high scores.
*
* @throws IOException If a problem was encountered while trying to open,
* read or close the file.
* @exception IOException if thrown while loading the game or if a
* <code>XMLStreamException</code> have been thrown by the
* parser.
* @exception FreeColException if the savegame contains incompatible data.
*/
public void loadHighScores() throws IOException, FreeColException {
highScores = new ArrayList<HighScore>();
XMLInputFactory xif = XMLInputFactory.newInstance();
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(FreeCol.getDataDirectory(), HIGH_SCORE_FILE));
XMLStreamReader xsr = xif.createXMLStreamReader(fis, "UTF-8");
xsr.nextTag();
while (xsr.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (xsr.getLocalName().equals("highScore")) {
highScores.add(new HighScore(xsr));
}
}
xsr.close();
Collections.sort(highScores, highScoreComparator);
} catch (XMLStreamException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException("XMLStreamException.");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException(e.toString());
} finally {
if (fis != null) {
fis.close();
}
}
}
}
| false | true | public String loadGame(final FreeColSavegameFile fis) throws IOException, FreeColException {
boolean doNotLoadAI = false;
XMLStream xs = null;
try {
xs = createXMLStreamReader(fis);
final XMLStreamReader xsr = xs.getXMLStreamReader();
xsr.nextTag();
final String version = xsr.getAttributeValue(null, "version");
int savegameVersion = 0;
try {
// TODO: remove this compatibility code BEFORE releasing 0.9
if (version.equals("0.1.4")) {
savegameVersion = 1;
} else {
savegameVersion = Integer.parseInt(version);
}
} catch(Exception e) {
throw new FreeColException("incompatibleVersions");
}
if (savegameVersion < MINIMUM_SAVEGAME_VERSION) {
throw new FreeColException("incompatibleVersions");
}
String randomState = xsr.getAttributeValue(null, "randomState");
if (randomState != null && randomState.length() > 0) {
try {
_pseudoRandom.restoreState(randomState);
} catch (IOException e) {
logger.warning("Failed to restore random state, ignoring!");
}
}
final String owner = xsr.getAttributeValue(null, "owner");
ArrayList<Object> serverObjects = null;
aiMain = null;
while (xsr.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (xsr.getLocalName().equals("serverObjects")) {
// Reads the ServerAdditionObjects:
serverObjects = new ArrayList<Object>();
while (xsr.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (xsr.getLocalName().equals(ServerPlayer.getServerAdditionXMLElementTagName())) {
serverObjects.add(new ServerPlayer(xsr));
} else {
throw new XMLStreamException("Unknown tag: " + xsr.getLocalName());
}
}
} else if (xsr.getLocalName().equals(Game.getXMLElementTagName())) {
// Read the game model:
game = new ServerGame(null, getModelController(), xsr, serverObjects
.toArray(new FreeColGameObject[0]));
game.setCurrentPlayer(null);
gameState = GameState.IN_GAME;
integrity = game.checkIntegrity();
} else if (xsr.getLocalName().equals(AIMain.getXMLElementTagName())) {
if (doNotLoadAI) {
aiMain = new AIMain(this);
game.setFreeColGameObjectListener(aiMain);
break;
}
// Read the AIObjects:
aiMain = new AIMain(this, xsr);
if (!aiMain.checkIntegrity()) {
aiMain = new AIMain(this);
logger.info("Replacing AIMain.");
}
game.setFreeColGameObjectListener(aiMain);
} else if (xsr.getLocalName().equals("marketdata")) {
logger.info("Ignoring market data for compatibility.");
} else {
throw new XMLStreamException("Unknown tag: " + xsr.getLocalName());
}
}
if (aiMain == null) {
aiMain = new AIMain(this);
game.setFreeColGameObjectListener(aiMain);
}
// Connect the AI-players:
Iterator<Player> playerIterator = game.getPlayerIterator();
while (playerIterator.hasNext()) {
ServerPlayer player = (ServerPlayer) playerIterator.next();
if (player.isAI()) {
DummyConnection theConnection = new DummyConnection(
"Server-Server-" + player.getName(),
getInGameInputHandler());
DummyConnection aiConnection = new DummyConnection(
"Server-AI-" + player.getName(),
new AIInGameInputHandler(this, player, aiMain));
aiConnection.setOutgoingMessageHandler(theConnection);
theConnection.setOutgoingMessageHandler(aiConnection);
getServer().addDummyConnection(theConnection);
player.setConnection(theConnection);
player.setConnected(true);
}
}
xs.close();
// Later, we might want to modify loaded savegames:
return owner;
} catch (XMLStreamException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException("XMLStreamException.");
} catch (FreeColException fe) {
StringWriter sw = new StringWriter();
fe.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw fe;
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException(e.toString());
} finally {
xs.close();
}
}
| public String loadGame(final FreeColSavegameFile fis) throws IOException, FreeColException {
boolean doNotLoadAI = false;
XMLStream xs = null;
try {
xs = createXMLStreamReader(fis);
final XMLStreamReader xsr = xs.getXMLStreamReader();
xsr.nextTag();
final String version = xsr.getAttributeValue(null, "version");
int savegameVersion = 0;
try {
savegameVersion = Integer.parseInt(version);
} catch(Exception e) {
throw new FreeColException("incompatibleVersions");
}
if (savegameVersion < MINIMUM_SAVEGAME_VERSION) {
throw new FreeColException("incompatibleVersions");
}
String randomState = xsr.getAttributeValue(null, "randomState");
if (randomState != null && randomState.length() > 0) {
try {
_pseudoRandom.restoreState(randomState);
} catch (IOException e) {
logger.warning("Failed to restore random state, ignoring!");
}
}
final String owner = xsr.getAttributeValue(null, "owner");
ArrayList<Object> serverObjects = null;
aiMain = null;
while (xsr.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (xsr.getLocalName().equals("serverObjects")) {
// Reads the ServerAdditionObjects:
serverObjects = new ArrayList<Object>();
while (xsr.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (xsr.getLocalName().equals(ServerPlayer.getServerAdditionXMLElementTagName())) {
serverObjects.add(new ServerPlayer(xsr));
} else {
throw new XMLStreamException("Unknown tag: " + xsr.getLocalName());
}
}
} else if (xsr.getLocalName().equals(Game.getXMLElementTagName())) {
// Read the game model:
game = new ServerGame(null, getModelController(), xsr, serverObjects
.toArray(new FreeColGameObject[0]));
game.setCurrentPlayer(null);
gameState = GameState.IN_GAME;
integrity = game.checkIntegrity();
} else if (xsr.getLocalName().equals(AIMain.getXMLElementTagName())) {
if (doNotLoadAI) {
aiMain = new AIMain(this);
game.setFreeColGameObjectListener(aiMain);
break;
}
// Read the AIObjects:
aiMain = new AIMain(this, xsr);
if (!aiMain.checkIntegrity()) {
aiMain = new AIMain(this);
logger.info("Replacing AIMain.");
}
game.setFreeColGameObjectListener(aiMain);
} else if (xsr.getLocalName().equals("marketdata")) {
logger.info("Ignoring market data for compatibility.");
} else {
throw new XMLStreamException("Unknown tag: " + xsr.getLocalName());
}
}
Collections.sort(game.getPlayers(), Player.playerComparator);
if (aiMain == null) {
aiMain = new AIMain(this);
game.setFreeColGameObjectListener(aiMain);
}
// Connect the AI-players:
Iterator<Player> playerIterator = game.getPlayerIterator();
while (playerIterator.hasNext()) {
ServerPlayer player = (ServerPlayer) playerIterator.next();
if (player.isAI()) {
DummyConnection theConnection = new DummyConnection(
"Server-Server-" + player.getName(),
getInGameInputHandler());
DummyConnection aiConnection = new DummyConnection(
"Server-AI-" + player.getName(),
new AIInGameInputHandler(this, player, aiMain));
aiConnection.setOutgoingMessageHandler(theConnection);
theConnection.setOutgoingMessageHandler(aiConnection);
getServer().addDummyConnection(theConnection);
player.setConnection(theConnection);
player.setConnected(true);
}
}
xs.close();
// Later, we might want to modify loaded savegames:
return owner;
} catch (XMLStreamException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException("XMLStreamException.");
} catch (FreeColException fe) {
StringWriter sw = new StringWriter();
fe.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw fe;
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
throw new IOException(e.toString());
} finally {
xs.close();
}
}
|
diff --git a/bndtools.core/src/bndtools/wizards/bndfile/EnableSubBundlesDialog.java b/bndtools.core/src/bndtools/wizards/bndfile/EnableSubBundlesDialog.java
index 047bac5f..0286dca4 100644
--- a/bndtools.core/src/bndtools/wizards/bndfile/EnableSubBundlesDialog.java
+++ b/bndtools.core/src/bndtools/wizards/bndfile/EnableSubBundlesDialog.java
@@ -1,168 +1,172 @@
package bndtools.wizards.bndfile;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Collections;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.PlatformUI;
import bndtools.Plugin;
public class EnableSubBundlesDialog extends TitleAreaDialog {
private boolean enableSubBundles = true;
private final Collection<String> allProperties;
private final Collection<String> selectedProperties;
private Table propsTable;
private CheckboxTableViewer viewer;
private Button btnCheckAll;
private Button btnUncheckAll;
private Link link;
private Button btnEnableSubbundles;
private Label lblHeaderCount;
/**
* Create the dialog.
*
* @param parentShell
*/
public EnableSubBundlesDialog(Shell parentShell, Collection<String> allProperties, Collection<String> selectedProperties) {
super(parentShell);
setShellStyle(SWT.CLOSE | SWT.MAX | SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL | SWT.RESIZE | getDefaultOrientation());
this.allProperties = allProperties;
this.selectedProperties = selectedProperties;
setHelpAvailable(true);
setDialogHelpAvailable(true);
}
/**
* Create contents of the dialog.
*
* @param parent
*/
@Override
protected Control createDialogArea(Composite parent) {
setMessage(Messages.EmptyBndFileWizard_questionSubBundlesNotEnabled);
setTitle("Sub-bundles not enabled");
Composite area = (Composite) super.createDialogArea(parent);
Composite container = new Composite(area, SWT.NONE);
- container.setLayout(new GridLayout(2, false));
+ GridLayout layout = new GridLayout(2, false);
+ layout.marginTop = 20;
+ layout.marginWidth = 10;
+ layout.verticalSpacing = 10;
+ container.setLayout(layout);
container.setLayoutData(new GridData(GridData.FILL_BOTH));
btnEnableSubbundles = new Button(container, SWT.CHECK);
btnEnableSubbundles.setText(Messages.EnableSubBundlesDialog_btnEnableSubbundles_text_3);
btnEnableSubbundles.setSelection(enableSubBundles);
new Label(container, SWT.NONE);
link = new Link(container, SWT.NONE);
link.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
link.setText(Messages.EnableSubBundlesDialog_link_text);
link.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getShell().notifyListeners(SWT.Help, new Event());
}
});
propsTable = new Table(container, SWT.BORDER | SWT.CHECK | SWT.FULL_SELECTION);
GridData gd_propsTable = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2);
gd_propsTable.heightHint = 100;
gd_propsTable.widthHint = 175;
propsTable.setLayoutData(gd_propsTable);
viewer = new CheckboxTableViewer(propsTable);
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setInput(allProperties);
viewer.setCheckedElements(selectedProperties.toArray());
btnCheckAll = new Button(container, SWT.NONE);
btnCheckAll.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
btnCheckAll.setText(Messages.EnableSubBundlesDialog_btnCheckAll_text);
btnUncheckAll = new Button(container, SWT.NONE);
btnUncheckAll.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
btnUncheckAll.setText(Messages.EnableSubBundlesDialog_btnUncheckAll_text);
lblHeaderCount = new Label(container, SWT.NONE);
lblHeaderCount.setText(MessageFormat.format("", allProperties.size()));
new Label(container, SWT.NONE); // Spacer
btnEnableSubbundles.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
enableSubBundles = btnEnableSubbundles.getSelection();
updateEnablement();
}
});
viewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
String property = (String) event.getElement();
if (event.getChecked())
selectedProperties.add(property);
else
selectedProperties.remove(property);
}
});
btnCheckAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selectedProperties.clear();
selectedProperties.addAll(allProperties);
viewer.setCheckedElements(selectedProperties.toArray());
}
});
btnUncheckAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selectedProperties.clear();
viewer.setCheckedElements(selectedProperties.toArray());
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(getShell(), Plugin.PLUGIN_ID + ".enableSubBundles");
return area;
}
void updateEnablement() {
btnCheckAll.setEnabled(enableSubBundles);
btnUncheckAll.setEnabled(enableSubBundles);
propsTable.setEnabled(enableSubBundles);
}
@Override
protected Point getInitialSize() {
return new Point(475, 330);
}
public boolean isEnableSubBundles() {
return enableSubBundles;
}
public Collection<String> getSelectedProperties() {
return Collections.unmodifiableCollection(selectedProperties);
}
}
| true | true | protected Control createDialogArea(Composite parent) {
setMessage(Messages.EmptyBndFileWizard_questionSubBundlesNotEnabled);
setTitle("Sub-bundles not enabled");
Composite area = (Composite) super.createDialogArea(parent);
Composite container = new Composite(area, SWT.NONE);
container.setLayout(new GridLayout(2, false));
container.setLayoutData(new GridData(GridData.FILL_BOTH));
btnEnableSubbundles = new Button(container, SWT.CHECK);
btnEnableSubbundles.setText(Messages.EnableSubBundlesDialog_btnEnableSubbundles_text_3);
btnEnableSubbundles.setSelection(enableSubBundles);
new Label(container, SWT.NONE);
link = new Link(container, SWT.NONE);
link.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
link.setText(Messages.EnableSubBundlesDialog_link_text);
link.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getShell().notifyListeners(SWT.Help, new Event());
}
});
propsTable = new Table(container, SWT.BORDER | SWT.CHECK | SWT.FULL_SELECTION);
GridData gd_propsTable = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2);
gd_propsTable.heightHint = 100;
gd_propsTable.widthHint = 175;
propsTable.setLayoutData(gd_propsTable);
viewer = new CheckboxTableViewer(propsTable);
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setInput(allProperties);
viewer.setCheckedElements(selectedProperties.toArray());
btnCheckAll = new Button(container, SWT.NONE);
btnCheckAll.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
btnCheckAll.setText(Messages.EnableSubBundlesDialog_btnCheckAll_text);
btnUncheckAll = new Button(container, SWT.NONE);
btnUncheckAll.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
btnUncheckAll.setText(Messages.EnableSubBundlesDialog_btnUncheckAll_text);
lblHeaderCount = new Label(container, SWT.NONE);
lblHeaderCount.setText(MessageFormat.format("", allProperties.size()));
new Label(container, SWT.NONE); // Spacer
btnEnableSubbundles.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
enableSubBundles = btnEnableSubbundles.getSelection();
updateEnablement();
}
});
viewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
String property = (String) event.getElement();
if (event.getChecked())
selectedProperties.add(property);
else
selectedProperties.remove(property);
}
});
btnCheckAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selectedProperties.clear();
selectedProperties.addAll(allProperties);
viewer.setCheckedElements(selectedProperties.toArray());
}
});
btnUncheckAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selectedProperties.clear();
viewer.setCheckedElements(selectedProperties.toArray());
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(getShell(), Plugin.PLUGIN_ID + ".enableSubBundles");
return area;
}
| protected Control createDialogArea(Composite parent) {
setMessage(Messages.EmptyBndFileWizard_questionSubBundlesNotEnabled);
setTitle("Sub-bundles not enabled");
Composite area = (Composite) super.createDialogArea(parent);
Composite container = new Composite(area, SWT.NONE);
GridLayout layout = new GridLayout(2, false);
layout.marginTop = 20;
layout.marginWidth = 10;
layout.verticalSpacing = 10;
container.setLayout(layout);
container.setLayoutData(new GridData(GridData.FILL_BOTH));
btnEnableSubbundles = new Button(container, SWT.CHECK);
btnEnableSubbundles.setText(Messages.EnableSubBundlesDialog_btnEnableSubbundles_text_3);
btnEnableSubbundles.setSelection(enableSubBundles);
new Label(container, SWT.NONE);
link = new Link(container, SWT.NONE);
link.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
link.setText(Messages.EnableSubBundlesDialog_link_text);
link.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getShell().notifyListeners(SWT.Help, new Event());
}
});
propsTable = new Table(container, SWT.BORDER | SWT.CHECK | SWT.FULL_SELECTION);
GridData gd_propsTable = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2);
gd_propsTable.heightHint = 100;
gd_propsTable.widthHint = 175;
propsTable.setLayoutData(gd_propsTable);
viewer = new CheckboxTableViewer(propsTable);
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setInput(allProperties);
viewer.setCheckedElements(selectedProperties.toArray());
btnCheckAll = new Button(container, SWT.NONE);
btnCheckAll.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
btnCheckAll.setText(Messages.EnableSubBundlesDialog_btnCheckAll_text);
btnUncheckAll = new Button(container, SWT.NONE);
btnUncheckAll.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
btnUncheckAll.setText(Messages.EnableSubBundlesDialog_btnUncheckAll_text);
lblHeaderCount = new Label(container, SWT.NONE);
lblHeaderCount.setText(MessageFormat.format("", allProperties.size()));
new Label(container, SWT.NONE); // Spacer
btnEnableSubbundles.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
enableSubBundles = btnEnableSubbundles.getSelection();
updateEnablement();
}
});
viewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
String property = (String) event.getElement();
if (event.getChecked())
selectedProperties.add(property);
else
selectedProperties.remove(property);
}
});
btnCheckAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selectedProperties.clear();
selectedProperties.addAll(allProperties);
viewer.setCheckedElements(selectedProperties.toArray());
}
});
btnUncheckAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selectedProperties.clear();
viewer.setCheckedElements(selectedProperties.toArray());
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(getShell(), Plugin.PLUGIN_ID + ".enableSubBundles");
return area;
}
|
diff --git a/src/main/java/com/yahoo/pasc/paxos/messages/serialization/ManualDecoder.java b/src/main/java/com/yahoo/pasc/paxos/messages/serialization/ManualDecoder.java
index ae864c3..07eff66 100644
--- a/src/main/java/com/yahoo/pasc/paxos/messages/serialization/ManualDecoder.java
+++ b/src/main/java/com/yahoo/pasc/paxos/messages/serialization/ManualDecoder.java
@@ -1,275 +1,278 @@
/**
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
*
* 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. See accompanying LICENSE file.
*/
package com.yahoo.pasc.paxos.messages.serialization;
import java.util.zip.Checksum;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yahoo.pasc.PascRuntime;
import com.yahoo.pasc.paxos.messages.Accept;
import com.yahoo.pasc.paxos.messages.Accepted;
import com.yahoo.pasc.paxos.messages.AsyncMessage;
import com.yahoo.pasc.paxos.messages.Bye;
import com.yahoo.pasc.paxos.messages.ControlMessage;
import com.yahoo.pasc.paxos.messages.Digest;
import com.yahoo.pasc.paxos.messages.Hello;
import com.yahoo.pasc.paxos.messages.InlineRequest;
import com.yahoo.pasc.paxos.messages.InvalidMessage;
import com.yahoo.pasc.paxos.messages.MessageType;
import com.yahoo.pasc.paxos.messages.PaxosMessage;
import com.yahoo.pasc.paxos.messages.Prepare;
import com.yahoo.pasc.paxos.messages.Prepared;
import com.yahoo.pasc.paxos.messages.Reply;
import com.yahoo.pasc.paxos.messages.Request;
import com.yahoo.pasc.paxos.messages.ServerHello;
import com.yahoo.pasc.paxos.state.ClientTimestamp;
import com.yahoo.pasc.paxos.state.DigestidDigest;
import com.yahoo.pasc.paxos.state.InstanceRecord;
public class ManualDecoder extends FrameDecoder {
private static final Logger LOG = LoggerFactory.getLogger(ManualDecoder.class);
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {
Object result = decode2(ctx, channel, buf);
if (result != null) {
PaxosMessage message = (PaxosMessage) result;
message.setCloned(PascRuntime.clone(message));
}
if (LOG.isTraceEnabled()) {
LOG.trace("Received msg: {}", result);
}
return result;
}
protected Object decode2(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {
if (buf.readableBytes() < 4)
return null;
buf.markReaderIndex();
int length = buf.readInt();
length -= 4; // length has already been read
if (buf.readableBytes() < length) {
buf.resetReaderIndex();
return null;
}
long crc = buf.readLong();
length -= 8; // crc has been read
if (length == 0) {
LOG.warn("Length is 0.");
}
byte[] bytearray = new byte[length];
buf.markReaderIndex();
buf.readBytes(bytearray, 0, length);
Checksum crc32 = CRC32Pool.getCRC32();
crc32.reset();
crc32.update(bytearray, 0, bytearray.length);
long result = crc32.getValue();
if (LOG.isTraceEnabled()) {
LOG.trace("Decoding message with bytes {} computed CRC {} received CRC {}", new Object[] { bytearray,
result, crc });
}
if (result != crc) {
- byte b = buf.readByte();
- MessageType type = MessageType.values()[b];
+ MessageType type = null;
+ if (length > 0) {
+ byte b = bytearray[0];
+ type = MessageType.values()[b];
+ }
LOG.error("Invalid CRC for {}. Expected {} Actual {}", new Object[] { type, crc, result });
return new InvalidMessage();
}
// If CRC matches reset reader index
buf.resetReaderIndex();
CRC32Pool.pushCRC32(crc32);
byte b = buf.readByte();
int len;
MessageType type = MessageType.values()[b];
switch (type) {
case REQUEST:
case INLINEREQ: {
Request s = type.equals(MessageType.REQUEST) ? new Request() : new InlineRequest();
s.setCRC(crc);
s.setClientId(buf.readInt());
s.setTimestamp(buf.readLong());
len = buf.readInt();
byte[] request = new byte[len];
buf.readBytes(request);
s.setRequest(request);
return s;
}
case ACCEPT: {
int senderId = buf.readInt();
int ballot = buf.readInt();
long iid = buf.readLong();
len = buf.readInt();
ClientTimestamp[] values = new ClientTimestamp[len];
for (int i = 0; i < len; ++i) {
ClientTimestamp value = new ClientTimestamp();
value.setClientId(buf.readInt());
value.setTimestamp(buf.readLong());
values[i] = value;
}
byte[][] requests = null;
int requestsSize = buf.readInt();
if (requestsSize != -1) {
requests = new byte[requestsSize][];
for (int i = 0; i < requestsSize; ++i) {
int reqSize = buf.readInt();
if (reqSize == -1)
continue;
byte[] request = new byte[reqSize];
buf.readBytes(request);
requests[i] = request;
}
}
Accept a = new Accept(senderId, iid, ballot, values, len);
a.setRequests(requests);
a.setCRC(crc);
return a;
}
case ACCEPTED: {
int senderId = buf.readInt();
int ballot = buf.readInt();
long iid = buf.readLong();
Accepted ad = new Accepted(senderId, ballot, iid);
ad.setCRC(crc);
return ad;
}
case REPLY: {
Reply r = new Reply();
r.setCRC(crc);
r.setServerId(buf.readInt());
r.setClientId(buf.readInt());
r.setTimestamp(buf.readLong());
len = buf.readInt();
byte[] v = new byte[len];
buf.readBytes(v);
r.setValue(v);
return r;
}
case DIGEST: {
Digest d = new Digest();
d.setCRC(crc);
d.setSenderId(buf.readInt());
d.setDigestId(buf.readLong());
d.setDigest(buf.readLong());
return d;
}
case HELLO: {
Hello h = new Hello(buf.readInt());
h.setCRC(crc);
return h;
}
case SERVERHELLO: {
ServerHello h = new ServerHello(buf.readInt(), buf.readInt());
h.setCRC(crc);
return h;
}
case BYE: {
Bye h = new Bye(buf.readInt(), buf.readInt());
h.setCRC(crc);
return h;
}
case PREPARE: {
int senderId = buf.readInt();
int ballot = buf.readInt();
long maxExecutedIid = buf.readLong();
Prepare p = new Prepare(senderId, ballot, maxExecutedIid);
p.setCRC(crc);
return p;
}
case PREPARED: {
int senderId = buf.readInt();
int receiver = buf.readInt();
int replyBallot = buf.readInt();
int acceptedSize = buf.readInt();
InstanceRecord[] acceptedReqs = new InstanceRecord[acceptedSize];
for (int i = 0; i < acceptedSize; i++) {
long iid = buf.readLong();
int ballot = buf.readInt();
int arraySize = buf.readInt();
ClientTimestamp[] ct = new ClientTimestamp[arraySize];
for (int j = 0; j < arraySize; j++) {
int clientId = buf.readInt();
long timestamp = buf.readLong();
ct[j] = new ClientTimestamp(clientId, timestamp);
}
acceptedReqs[i] = new InstanceRecord(iid, ballot, ct, arraySize);
}
int learnedSize = buf.readInt();
Accept[] learnedReqs = new Accept[learnedSize];
for (int i = 0; i < learnedSize; i++) {
learnedReqs[i] = (Accept) decode2(ctx, channel, buf);
}
int digestId = buf.readInt();
long digest = buf.readLong();
DigestidDigest checkpointDigest = new DigestidDigest(digestId, digest);
long maxForgotten = buf.readLong();
Prepared pd = new Prepared(senderId, receiver, replyBallot, acceptedSize, acceptedReqs, learnedSize,
learnedReqs, checkpointDigest, maxForgotten);
pd.setCRC(crc);
return pd;
}
case ASYNC_MESSAGE: {
int clientId = buf.readInt();
int serverId = buf.readInt();
long ts = buf.readLong();
len = buf.readInt();
byte[] message = new byte[len];
buf.readBytes(message);
AsyncMessage am = new AsyncMessage(clientId, serverId, ts, message);
am.setCRC(crc);
return am;
}
case CONTROL: {
int clientId = buf.readInt();
len = buf.readInt();
byte[] message = new byte[len];
buf.readBytes(message);
ControlMessage cm = new ControlMessage(clientId, message);
cm.setCRC(crc);
return cm;
}
default: {
LOG.error("Unknown message type");
return new InvalidMessage();
}
}
}
}
| true | true | protected Object decode2(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {
if (buf.readableBytes() < 4)
return null;
buf.markReaderIndex();
int length = buf.readInt();
length -= 4; // length has already been read
if (buf.readableBytes() < length) {
buf.resetReaderIndex();
return null;
}
long crc = buf.readLong();
length -= 8; // crc has been read
if (length == 0) {
LOG.warn("Length is 0.");
}
byte[] bytearray = new byte[length];
buf.markReaderIndex();
buf.readBytes(bytearray, 0, length);
Checksum crc32 = CRC32Pool.getCRC32();
crc32.reset();
crc32.update(bytearray, 0, bytearray.length);
long result = crc32.getValue();
if (LOG.isTraceEnabled()) {
LOG.trace("Decoding message with bytes {} computed CRC {} received CRC {}", new Object[] { bytearray,
result, crc });
}
if (result != crc) {
byte b = buf.readByte();
MessageType type = MessageType.values()[b];
LOG.error("Invalid CRC for {}. Expected {} Actual {}", new Object[] { type, crc, result });
return new InvalidMessage();
}
// If CRC matches reset reader index
buf.resetReaderIndex();
CRC32Pool.pushCRC32(crc32);
byte b = buf.readByte();
int len;
MessageType type = MessageType.values()[b];
switch (type) {
case REQUEST:
case INLINEREQ: {
Request s = type.equals(MessageType.REQUEST) ? new Request() : new InlineRequest();
s.setCRC(crc);
s.setClientId(buf.readInt());
s.setTimestamp(buf.readLong());
len = buf.readInt();
byte[] request = new byte[len];
buf.readBytes(request);
s.setRequest(request);
return s;
}
case ACCEPT: {
int senderId = buf.readInt();
int ballot = buf.readInt();
long iid = buf.readLong();
len = buf.readInt();
ClientTimestamp[] values = new ClientTimestamp[len];
for (int i = 0; i < len; ++i) {
ClientTimestamp value = new ClientTimestamp();
value.setClientId(buf.readInt());
value.setTimestamp(buf.readLong());
values[i] = value;
}
byte[][] requests = null;
int requestsSize = buf.readInt();
if (requestsSize != -1) {
requests = new byte[requestsSize][];
for (int i = 0; i < requestsSize; ++i) {
int reqSize = buf.readInt();
if (reqSize == -1)
continue;
byte[] request = new byte[reqSize];
buf.readBytes(request);
requests[i] = request;
}
}
Accept a = new Accept(senderId, iid, ballot, values, len);
a.setRequests(requests);
a.setCRC(crc);
return a;
}
case ACCEPTED: {
int senderId = buf.readInt();
int ballot = buf.readInt();
long iid = buf.readLong();
Accepted ad = new Accepted(senderId, ballot, iid);
ad.setCRC(crc);
return ad;
}
case REPLY: {
Reply r = new Reply();
r.setCRC(crc);
r.setServerId(buf.readInt());
r.setClientId(buf.readInt());
r.setTimestamp(buf.readLong());
len = buf.readInt();
byte[] v = new byte[len];
buf.readBytes(v);
r.setValue(v);
return r;
}
case DIGEST: {
Digest d = new Digest();
d.setCRC(crc);
d.setSenderId(buf.readInt());
d.setDigestId(buf.readLong());
d.setDigest(buf.readLong());
return d;
}
case HELLO: {
Hello h = new Hello(buf.readInt());
h.setCRC(crc);
return h;
}
case SERVERHELLO: {
ServerHello h = new ServerHello(buf.readInt(), buf.readInt());
h.setCRC(crc);
return h;
}
case BYE: {
Bye h = new Bye(buf.readInt(), buf.readInt());
h.setCRC(crc);
return h;
}
case PREPARE: {
int senderId = buf.readInt();
int ballot = buf.readInt();
long maxExecutedIid = buf.readLong();
Prepare p = new Prepare(senderId, ballot, maxExecutedIid);
p.setCRC(crc);
return p;
}
case PREPARED: {
int senderId = buf.readInt();
int receiver = buf.readInt();
int replyBallot = buf.readInt();
int acceptedSize = buf.readInt();
InstanceRecord[] acceptedReqs = new InstanceRecord[acceptedSize];
for (int i = 0; i < acceptedSize; i++) {
long iid = buf.readLong();
int ballot = buf.readInt();
int arraySize = buf.readInt();
ClientTimestamp[] ct = new ClientTimestamp[arraySize];
for (int j = 0; j < arraySize; j++) {
int clientId = buf.readInt();
long timestamp = buf.readLong();
ct[j] = new ClientTimestamp(clientId, timestamp);
}
acceptedReqs[i] = new InstanceRecord(iid, ballot, ct, arraySize);
}
int learnedSize = buf.readInt();
Accept[] learnedReqs = new Accept[learnedSize];
for (int i = 0; i < learnedSize; i++) {
learnedReqs[i] = (Accept) decode2(ctx, channel, buf);
}
int digestId = buf.readInt();
long digest = buf.readLong();
DigestidDigest checkpointDigest = new DigestidDigest(digestId, digest);
long maxForgotten = buf.readLong();
Prepared pd = new Prepared(senderId, receiver, replyBallot, acceptedSize, acceptedReqs, learnedSize,
learnedReqs, checkpointDigest, maxForgotten);
pd.setCRC(crc);
return pd;
}
case ASYNC_MESSAGE: {
int clientId = buf.readInt();
int serverId = buf.readInt();
long ts = buf.readLong();
len = buf.readInt();
byte[] message = new byte[len];
buf.readBytes(message);
AsyncMessage am = new AsyncMessage(clientId, serverId, ts, message);
am.setCRC(crc);
return am;
}
case CONTROL: {
int clientId = buf.readInt();
len = buf.readInt();
byte[] message = new byte[len];
buf.readBytes(message);
ControlMessage cm = new ControlMessage(clientId, message);
cm.setCRC(crc);
return cm;
}
default: {
LOG.error("Unknown message type");
return new InvalidMessage();
}
}
}
| protected Object decode2(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {
if (buf.readableBytes() < 4)
return null;
buf.markReaderIndex();
int length = buf.readInt();
length -= 4; // length has already been read
if (buf.readableBytes() < length) {
buf.resetReaderIndex();
return null;
}
long crc = buf.readLong();
length -= 8; // crc has been read
if (length == 0) {
LOG.warn("Length is 0.");
}
byte[] bytearray = new byte[length];
buf.markReaderIndex();
buf.readBytes(bytearray, 0, length);
Checksum crc32 = CRC32Pool.getCRC32();
crc32.reset();
crc32.update(bytearray, 0, bytearray.length);
long result = crc32.getValue();
if (LOG.isTraceEnabled()) {
LOG.trace("Decoding message with bytes {} computed CRC {} received CRC {}", new Object[] { bytearray,
result, crc });
}
if (result != crc) {
MessageType type = null;
if (length > 0) {
byte b = bytearray[0];
type = MessageType.values()[b];
}
LOG.error("Invalid CRC for {}. Expected {} Actual {}", new Object[] { type, crc, result });
return new InvalidMessage();
}
// If CRC matches reset reader index
buf.resetReaderIndex();
CRC32Pool.pushCRC32(crc32);
byte b = buf.readByte();
int len;
MessageType type = MessageType.values()[b];
switch (type) {
case REQUEST:
case INLINEREQ: {
Request s = type.equals(MessageType.REQUEST) ? new Request() : new InlineRequest();
s.setCRC(crc);
s.setClientId(buf.readInt());
s.setTimestamp(buf.readLong());
len = buf.readInt();
byte[] request = new byte[len];
buf.readBytes(request);
s.setRequest(request);
return s;
}
case ACCEPT: {
int senderId = buf.readInt();
int ballot = buf.readInt();
long iid = buf.readLong();
len = buf.readInt();
ClientTimestamp[] values = new ClientTimestamp[len];
for (int i = 0; i < len; ++i) {
ClientTimestamp value = new ClientTimestamp();
value.setClientId(buf.readInt());
value.setTimestamp(buf.readLong());
values[i] = value;
}
byte[][] requests = null;
int requestsSize = buf.readInt();
if (requestsSize != -1) {
requests = new byte[requestsSize][];
for (int i = 0; i < requestsSize; ++i) {
int reqSize = buf.readInt();
if (reqSize == -1)
continue;
byte[] request = new byte[reqSize];
buf.readBytes(request);
requests[i] = request;
}
}
Accept a = new Accept(senderId, iid, ballot, values, len);
a.setRequests(requests);
a.setCRC(crc);
return a;
}
case ACCEPTED: {
int senderId = buf.readInt();
int ballot = buf.readInt();
long iid = buf.readLong();
Accepted ad = new Accepted(senderId, ballot, iid);
ad.setCRC(crc);
return ad;
}
case REPLY: {
Reply r = new Reply();
r.setCRC(crc);
r.setServerId(buf.readInt());
r.setClientId(buf.readInt());
r.setTimestamp(buf.readLong());
len = buf.readInt();
byte[] v = new byte[len];
buf.readBytes(v);
r.setValue(v);
return r;
}
case DIGEST: {
Digest d = new Digest();
d.setCRC(crc);
d.setSenderId(buf.readInt());
d.setDigestId(buf.readLong());
d.setDigest(buf.readLong());
return d;
}
case HELLO: {
Hello h = new Hello(buf.readInt());
h.setCRC(crc);
return h;
}
case SERVERHELLO: {
ServerHello h = new ServerHello(buf.readInt(), buf.readInt());
h.setCRC(crc);
return h;
}
case BYE: {
Bye h = new Bye(buf.readInt(), buf.readInt());
h.setCRC(crc);
return h;
}
case PREPARE: {
int senderId = buf.readInt();
int ballot = buf.readInt();
long maxExecutedIid = buf.readLong();
Prepare p = new Prepare(senderId, ballot, maxExecutedIid);
p.setCRC(crc);
return p;
}
case PREPARED: {
int senderId = buf.readInt();
int receiver = buf.readInt();
int replyBallot = buf.readInt();
int acceptedSize = buf.readInt();
InstanceRecord[] acceptedReqs = new InstanceRecord[acceptedSize];
for (int i = 0; i < acceptedSize; i++) {
long iid = buf.readLong();
int ballot = buf.readInt();
int arraySize = buf.readInt();
ClientTimestamp[] ct = new ClientTimestamp[arraySize];
for (int j = 0; j < arraySize; j++) {
int clientId = buf.readInt();
long timestamp = buf.readLong();
ct[j] = new ClientTimestamp(clientId, timestamp);
}
acceptedReqs[i] = new InstanceRecord(iid, ballot, ct, arraySize);
}
int learnedSize = buf.readInt();
Accept[] learnedReqs = new Accept[learnedSize];
for (int i = 0; i < learnedSize; i++) {
learnedReqs[i] = (Accept) decode2(ctx, channel, buf);
}
int digestId = buf.readInt();
long digest = buf.readLong();
DigestidDigest checkpointDigest = new DigestidDigest(digestId, digest);
long maxForgotten = buf.readLong();
Prepared pd = new Prepared(senderId, receiver, replyBallot, acceptedSize, acceptedReqs, learnedSize,
learnedReqs, checkpointDigest, maxForgotten);
pd.setCRC(crc);
return pd;
}
case ASYNC_MESSAGE: {
int clientId = buf.readInt();
int serverId = buf.readInt();
long ts = buf.readLong();
len = buf.readInt();
byte[] message = new byte[len];
buf.readBytes(message);
AsyncMessage am = new AsyncMessage(clientId, serverId, ts, message);
am.setCRC(crc);
return am;
}
case CONTROL: {
int clientId = buf.readInt();
len = buf.readInt();
byte[] message = new byte[len];
buf.readBytes(message);
ControlMessage cm = new ControlMessage(clientId, message);
cm.setCRC(crc);
return cm;
}
default: {
LOG.error("Unknown message type");
return new InvalidMessage();
}
}
}
|
diff --git a/eomplsPSS/src/main/java/net/es/oscars/pss/eompls/junos/MXConfigGen.java b/eomplsPSS/src/main/java/net/es/oscars/pss/eompls/junos/MXConfigGen.java
index 37a4134..3178fdb 100644
--- a/eomplsPSS/src/main/java/net/es/oscars/pss/eompls/junos/MXConfigGen.java
+++ b/eomplsPSS/src/main/java/net/es/oscars/pss/eompls/junos/MXConfigGen.java
@@ -1,614 +1,614 @@
package net.es.oscars.pss.eompls.junos;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.log4j.Logger;
import org.ogf.schema.network.topology.ctrlplane.CtrlPlaneHopContent;
import org.ogf.schema.network.topology.ctrlplane.CtrlPlaneLinkContent;
import net.es.oscars.api.soap.gen.v06.PathInfo;
import net.es.oscars.api.soap.gen.v06.ResDetails;
import net.es.oscars.api.soap.gen.v06.ReservedConstraintType;
import net.es.oscars.pss.api.DeviceConfigGenerator;
import net.es.oscars.pss.beans.PSSAction;
import net.es.oscars.pss.beans.PSSException;
import net.es.oscars.pss.beans.config.GenericConfig;
import net.es.oscars.pss.eompls.api.EoMPLSDeviceAddressResolver;
import net.es.oscars.pss.eompls.api.EoMPLSIfceAddressResolver;
import net.es.oscars.pss.eompls.beans.LSP;
import net.es.oscars.pss.eompls.util.EoMPLSClassFactory;
import net.es.oscars.pss.eompls.util.EoMPLSUtils;
import net.es.oscars.pss.util.URNParser;
import net.es.oscars.pss.util.URNParserResult;
import net.es.oscars.utils.soap.OSCARSServiceException;
import net.es.oscars.utils.topology.PathTools;
public class MXConfigGen implements DeviceConfigGenerator {
private Logger log = Logger.getLogger(MXConfigGen.class);
public String getConfig(PSSAction action, String deviceId) throws PSSException {
switch (action.getActionType()) {
case SETUP :
return this.getSetup(action, deviceId);
case TEARDOWN:
return this.getTeardown(action, deviceId);
case STATUS:
return this.getStatus(action, deviceId);
case MODIFY:
throw new PSSException("Modify not supported");
}
throw new PSSException("Invalid action type");
}
private String getStatus(PSSAction action, String deviceId) throws PSSException {
ResDetails res = action.getRequest().getSetupReq().getReservation();
String srcDeviceId = EoMPLSUtils.getDeviceId(res, false);
String dstDeviceId = EoMPLSUtils.getDeviceId(res, true);
boolean sameDevice = srcDeviceId.equals(dstDeviceId);
if (sameDevice) {
return "";
} else {
return this.getLSPStatus(action, deviceId);
}
}
private String getSetup(PSSAction action, String deviceId) throws PSSException {
log.debug("getSetup start");
ResDetails res = action.getRequest().getSetupReq().getReservation();
String srcDeviceId = EoMPLSUtils.getDeviceId(res, false);
String dstDeviceId = EoMPLSUtils.getDeviceId(res, true);
boolean sameDevice = srcDeviceId.equals(dstDeviceId);
if (sameDevice) {
return this.getSwitchingSetup(res, deviceId);
} else {
return this.getLSPSetup(res, deviceId);
}
}
private String getTeardown(PSSAction action, String deviceId) throws PSSException {
log.debug("getTeardown start");
ResDetails res = action.getRequest().getTeardownReq().getReservation();
String srcDeviceId = EoMPLSUtils.getDeviceId(res, false);
String dstDeviceId = EoMPLSUtils.getDeviceId(res, true);
boolean sameDevice = srcDeviceId.equals(dstDeviceId);
if (sameDevice) {
return this.getSwitchingTeardown(res, deviceId);
} else {
return this.getLSPTeardown(res, deviceId);
}
}
@SuppressWarnings("rawtypes")
private String getLSPStatus(PSSAction action, String deviceId) throws PSSException {
String templateFile = "junos-mx-lsp-status.txt";
Map root = new HashMap();
String config = EoMPLSUtils.generateConfig(root, templateFile);
return config;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private String getLSPSetup(ResDetails res, String deviceId) throws PSSException {
log.debug("getLSPSetup start");
String templateFile = "junos-mx-lsp-setup.txt";
String srcDeviceId = EoMPLSUtils.getDeviceId(res, false);
String ifceName;
String srcIfceName;
String ifceDescription;
String ifceVlan;
String srcIfceVlan;
String egressVlan;
String policyName;
String policyTerm;
String communityName;
String communityMembers;
Long lspBandwidth;
String pathName;
String lspName;
String l2circuitVCID;
String l2circuitEgress;
String l2circuitDescription;
String policerName;
Long policerBurstSizeLimit;
Long policerBandwidthLimit;
String statsFilterName;
String statsFilterTerm;
String statsFilterCount;
String policingFilterName;
String policingFilterTerm;
String policingFilterCount;
EoMPLSClassFactory ecf = EoMPLSClassFactory.getInstance();
/* *********************** */
/* BEGIN POPULATING VALUES */
/* *********************** */
ReservedConstraintType rc = res.getReservedConstraint();
Integer bw = rc.getBandwidth();
PathInfo pi = rc.getPathInfo();
List<CtrlPlaneHopContent> localHops;
try {
localHops = PathTools.getLocalHops(pi.getPath(), PathTools.getLocalDomainId());
} catch (OSCARSServiceException e) {
throw new PSSException(e);
}
CtrlPlaneLinkContent ingressLink = localHops.get(0).getLink();
CtrlPlaneLinkContent egressLink = localHops.get(localHops.size()-1).getLink();
String srcLinkId = ingressLink.getId();
URNParserResult srcRes = URNParser.parseTopoIdent(srcLinkId);
String dstLinkId = egressLink.getId();
URNParserResult dstRes = URNParser.parseTopoIdent(dstLinkId);
EoMPLSIfceAddressResolver iar = ecf.getEomplsIfceAddressResolver();
EoMPLSDeviceAddressResolver dar = ecf.getEomplsDeviceAddressResolver();
SDNNameGenerator ng = SDNNameGenerator.getInstance();
String gri = res.getGlobalReservationId();
// bandwidth in Mbps
lspBandwidth = 1000000L*bw;
policerBandwidthLimit = lspBandwidth;
policerBurstSizeLimit = lspBandwidth / 10;
String lspTargetDeviceId;
boolean reverse = false;
log.debug("source edge device id is: "+srcDeviceId+", config to generate is for "+deviceId);
if (srcDeviceId.equals(deviceId)) {
// forward direction
log.debug("forward");
ifceName = srcRes.getPortId();
srcIfceName = ifceName;
ifceVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
srcIfceVlan = ifceVlan;
egressVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
lspTargetDeviceId = dstRes.getNodeId();
} else {
// reverse direction
log.debug("reverse");
ifceName = dstRes.getPortId();
srcIfceName = srcRes.getPortId();
ifceVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
srcIfceVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
- egressVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
+ egressVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
lspTargetDeviceId = srcRes.getNodeId();
reverse = true;
}
LSP lspBean = new LSP(deviceId, pi, dar, iar, reverse);
ifceDescription = ng.getInterfaceDescription(gri, lspBandwidth);
policingFilterName = ng.getFilterName(gri, "policing");
policingFilterTerm = policingFilterName;
policingFilterCount = policingFilterName;
statsFilterName = ng.getFilterName(gri, "stats");
statsFilterTerm = statsFilterName;
statsFilterCount = statsFilterName;
communityName = ng.getCommunityName(gri);
policyName = ng.getPolicyName(gri);
policyTerm = policyName;
policerName = ng.getPolicerName(gri);
pathName = ng.getPathName(gri);
lspName = ng.getLSPName(gri);
l2circuitDescription = ng.getL2CircuitDescription(gri);
l2circuitEgress = dar.getDeviceAddress(lspTargetDeviceId);
l2circuitVCID = EoMPLSUtils.genJunosVCId(srcIfceName, srcIfceVlan);
// community is 30000 - 65500
String oscarsCommunity;
Random rand = new Random();
Integer randInt = 30000 + rand.nextInt(35500);
if (ng.getOscarsCommunity(gri) > 65535) {
oscarsCommunity = ng.getOscarsCommunity(gri)+"L";
} else {
oscarsCommunity = ng.getOscarsCommunity(gri).toString();
}
communityMembers = "65000:"+oscarsCommunity+":"+randInt;
// create and populate the model
// this needs to match with the template
Map root = new HashMap();
Map lsp = new HashMap();
Map path = new HashMap();
Map ifce = new HashMap();
Map filters = new HashMap();
Map stats = new HashMap();
Map policing = new HashMap();
Map community = new HashMap();
Map policy = new HashMap();
Map l2circuit = new HashMap();
Map policer = new HashMap();
root.put("lsp", lsp);
root.put("path", path);
root.put("ifce", ifce);
root.put("filters", filters);
root.put("policy", policy);
root.put("policer", policer);
root.put("l2circuit", l2circuit);
root.put("community", community);
root.put("egressvlan", egressVlan);
filters.put("stats", stats);
filters.put("policing", policing);
stats.put("name", statsFilterName);
stats.put("term", statsFilterTerm);
stats.put("count", statsFilterCount);
policing.put("name", policingFilterName);
policing.put("term", policingFilterTerm);
policing.put("count", policingFilterCount);
ifce.put("name", ifceName);
ifce.put("vlan", ifceVlan);
ifce.put("description", ifceDescription);
lsp.put("name", lspName);
lsp.put("from", lspBean.getFrom());
lsp.put("to", lspBean.getTo());
lsp.put("bandwidth", lspBandwidth);
path.put("hops", lspBean.getPathAddresses());
path.put("name", pathName);
l2circuit.put("egress", l2circuitEgress);
l2circuit.put("vcid", l2circuitVCID);
l2circuit.put("description", l2circuitDescription);
policer.put("name", policerName);
policer.put("burst_size_limit", policerBurstSizeLimit);
policer.put("bandwidth_limit", policerBandwidthLimit);
community.put("name", communityName);
community.put("members", communityMembers);
policy.put("name", policyName);
policy.put("term", policyTerm);
log.debug("getLSPSetup ready");
String config = EoMPLSUtils.generateConfig(root, templateFile);
log.debug("getLSPSetup done");
return config;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private String getLSPTeardown(ResDetails res, String deviceId) throws PSSException {
String templateFile = "junos-mx-lsp-teardown.txt";
String srcDeviceId = EoMPLSUtils.getDeviceId(res, false);
String ifceName;
String ifceVlan;
String policyName;
String communityName;
String pathName;
String lspName;
String l2circuitEgress;
String policerName;
String statsFilterName;
String policingFilterName;
EoMPLSClassFactory ecf = EoMPLSClassFactory.getInstance();
ReservedConstraintType rc = res.getReservedConstraint();
PathInfo pi = rc.getPathInfo();
List<CtrlPlaneHopContent> localHops;
try {
localHops = PathTools.getLocalHops(pi.getPath(), PathTools.getLocalDomainId());
} catch (OSCARSServiceException e) {
throw new PSSException(e);
}
CtrlPlaneLinkContent ingressLink = localHops.get(0).getLink();
CtrlPlaneLinkContent egressLink = localHops.get(localHops.size()-1).getLink();
String srcLinkId = ingressLink.getId();
URNParserResult srcRes = URNParser.parseTopoIdent(srcLinkId);
String dstLinkId = egressLink.getId();
URNParserResult dstRes = URNParser.parseTopoIdent(dstLinkId);
EoMPLSDeviceAddressResolver dar = ecf.getEomplsDeviceAddressResolver();
SDNNameGenerator ng = SDNNameGenerator.getInstance();
String gri = res.getGlobalReservationId();
/* *********************** */
/* BEGIN POPULATING VALUES */
/* *********************** */
String lspTargetDeviceId;
log.debug("source edge device id is: "+srcDeviceId+", config to generate is for "+deviceId);
if (srcDeviceId.equals(deviceId)) {
// forward direction
log.debug("forward");
ifceName = srcRes.getPortId();
ifceVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
lspTargetDeviceId = dstRes.getNodeId();
} else {
// reverse direction
log.debug("reverse");
ifceName = dstRes.getPortId();
ifceVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
lspTargetDeviceId = srcRes.getNodeId();
}
policingFilterName = ng.getFilterName(gri, "policing");
statsFilterName = ng.getFilterName(gri, "stats");
communityName = ng.getCommunityName(gri);
policyName = ng.getPolicyName(gri);
policerName = ng.getPolicerName(gri);
pathName = ng.getPathName(gri);
lspName = ng.getLSPName(gri);
l2circuitEgress = dar.getDeviceAddress(lspTargetDeviceId);
// create and populate the model
// this needs to match with the template
Map root = new HashMap();
Map lsp = new HashMap();
Map path = new HashMap();
Map ifce = new HashMap();
Map filters = new HashMap();
Map stats = new HashMap();
Map policing = new HashMap();
Map community = new HashMap();
Map policy = new HashMap();
Map l2circuit = new HashMap();
Map policer = new HashMap();
root.put("lsp", lsp);
root.put("path", path);
root.put("ifce", ifce);
root.put("filters", filters);
root.put("policy", policy);
root.put("policer", policer);
root.put("l2circuit", l2circuit);
root.put("community", community);
filters.put("stats", stats);
filters.put("policing", policing);
ifce.put("name", ifceName);
ifce.put("vlan", ifceVlan);
stats.put("name", statsFilterName);
policing.put("name", policingFilterName);
lsp.put("name", lspName);
path.put("name", pathName);
l2circuit.put("egress", l2circuitEgress);
policer.put("name", policerName);
community.put("name", communityName);
policy.put("name", policyName);
log.debug("getLSPTeardown ready");
String config = EoMPLSUtils.generateConfig(root, templateFile);
log.debug("getLSPTeardown done");
return config;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private String getSwitchingSetup(ResDetails res, String deviceId) throws PSSException {
String templateFile = "junos-mx-sw-setup.txt";
String ifceAName, ifceZName;
String ifceAVlan, ifceZVlan;
String ifceADesc, ifceZDesc;
String filterName, filterTerm, filterCount;
String iswitchName;
String policerName;
Long policerBurstSizeLimit;
Long policerBandwidthLimit;
/* *********************** */
/* BEGIN POPULATING VALUES */
/* *********************** */
ReservedConstraintType rc = res.getReservedConstraint();
Integer bw = rc.getBandwidth();
PathInfo pi = rc.getPathInfo();
CtrlPlaneLinkContent ingressLink = pi.getPath().getHop().get(0).getLink();
CtrlPlaneLinkContent egressLink = pi.getPath().getHop().get(pi.getPath().getHop().size()-1).getLink();
String srcLinkId = ingressLink.getId();
URNParserResult srcRes = URNParser.parseTopoIdent(srcLinkId);
String dstLinkId = egressLink.getId();
URNParserResult dstRes = URNParser.parseTopoIdent(dstLinkId);
SDNNameGenerator ng = SDNNameGenerator.getInstance();
String gri = res.getGlobalReservationId();
Long bandwidth = 1000000L*bw;
policerBandwidthLimit = bandwidth;
policerBurstSizeLimit = bandwidth / 10;
ifceAName = srcRes.getPortId();
ifceZName = dstRes.getPortId();
ifceAVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
ifceZVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
policerName = ng.getPolicerName(gri);
ifceADesc = ng.getInterfaceDescription(gri, bandwidth);
ifceZDesc = ng.getInterfaceDescription(gri, bandwidth);
iswitchName = ng.getIswitchTerm(gri);
filterName = ng.getFilterName(gri, "policing");
filterTerm = filterName;
filterCount = filterName;
// create and populate the model
// this needs to match with the template
Map root = new HashMap();
Map ifce_a = new HashMap();
Map ifce_z = new HashMap();
Map filter = new HashMap();
Map iswitch = new HashMap();
Map policer = new HashMap();
root.put("ifce_a", ifce_a);
root.put("ifce_z", ifce_z);
root.put("filter", filter);
root.put("iswitch", iswitch);
root.put("policer", policer);
ifce_a.put("name", ifceAName);
ifce_a.put("vlan", ifceAVlan);
ifce_a.put("description", ifceADesc);
ifce_z.put("name", ifceZName);
ifce_z.put("vlan", ifceZVlan);
ifce_z.put("description", ifceZDesc);
filter.put("name", filterName);
filter.put("term", filterTerm);
filter.put("count", filterCount);
iswitch.put("name", iswitchName);
policer.put("name", policerName);
policer.put("burst_size_limit", policerBurstSizeLimit);
policer.put("bandwidth_limit", policerBandwidthLimit);
log.debug("getSwitchingSetup ready");
String config = EoMPLSUtils.generateConfig(root, templateFile);
log.debug("getSwitchingSetup done");
return config;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private String getSwitchingTeardown(ResDetails res, String deviceId) throws PSSException {
String templateFile = "junos-mx-sw-teardown.txt";
String ifceAName, ifceZName;
String ifceAVlan, ifceZVlan;
String filterName;
String iswitchName;
String policerName;
/* *********************** */
/* BEGIN POPULATING VALUES */
/* *********************** */
ReservedConstraintType rc = res.getReservedConstraint();
PathInfo pi = rc.getPathInfo();
CtrlPlaneLinkContent ingressLink = pi.getPath().getHop().get(0).getLink();
CtrlPlaneLinkContent egressLink = pi.getPath().getHop().get(pi.getPath().getHop().size()-1).getLink();
String srcLinkId = ingressLink.getId();
URNParserResult srcRes = URNParser.parseTopoIdent(srcLinkId);
String dstLinkId = egressLink.getId();
URNParserResult dstRes = URNParser.parseTopoIdent(dstLinkId);
SDNNameGenerator ng = SDNNameGenerator.getInstance();
String gri = res.getGlobalReservationId();
ifceAName = srcRes.getPortId();
ifceZName = dstRes.getPortId();
ifceAVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
ifceZVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
policerName = ng.getPolicerName(gri);
iswitchName = ng.getIswitchTerm(gri);
filterName = ng.getFilterName(gri, "policing");
// create and populate the model
// this needs to match with the template
Map root = new HashMap();
Map ifce_a = new HashMap();
Map ifce_z = new HashMap();
Map filter = new HashMap();
Map iswitch = new HashMap();
Map policer = new HashMap();
root.put("ifce_a", ifce_a);
root.put("ifce_z", ifce_z);
root.put("filter", filter);
root.put("iswitch", iswitch);
root.put("policer", policer);
ifce_a.put("name", ifceAName);
ifce_a.put("vlan", ifceAVlan);
ifce_z.put("name", ifceZName);
ifce_z.put("vlan", ifceZVlan);
filter.put("name", filterName);
iswitch.put("name", iswitchName);
policer.put("name", policerName);
log.debug("getSwitchingTeardown ready");
String config = EoMPLSUtils.generateConfig(root, templateFile);
log.debug("getSwitchingTeardown done");
return config;
}
public void setConfig(GenericConfig config) throws PSSException {
// TODO Auto-generated method stub
}
}
| true | true | private String getLSPSetup(ResDetails res, String deviceId) throws PSSException {
log.debug("getLSPSetup start");
String templateFile = "junos-mx-lsp-setup.txt";
String srcDeviceId = EoMPLSUtils.getDeviceId(res, false);
String ifceName;
String srcIfceName;
String ifceDescription;
String ifceVlan;
String srcIfceVlan;
String egressVlan;
String policyName;
String policyTerm;
String communityName;
String communityMembers;
Long lspBandwidth;
String pathName;
String lspName;
String l2circuitVCID;
String l2circuitEgress;
String l2circuitDescription;
String policerName;
Long policerBurstSizeLimit;
Long policerBandwidthLimit;
String statsFilterName;
String statsFilterTerm;
String statsFilterCount;
String policingFilterName;
String policingFilterTerm;
String policingFilterCount;
EoMPLSClassFactory ecf = EoMPLSClassFactory.getInstance();
/* *********************** */
/* BEGIN POPULATING VALUES */
/* *********************** */
ReservedConstraintType rc = res.getReservedConstraint();
Integer bw = rc.getBandwidth();
PathInfo pi = rc.getPathInfo();
List<CtrlPlaneHopContent> localHops;
try {
localHops = PathTools.getLocalHops(pi.getPath(), PathTools.getLocalDomainId());
} catch (OSCARSServiceException e) {
throw new PSSException(e);
}
CtrlPlaneLinkContent ingressLink = localHops.get(0).getLink();
CtrlPlaneLinkContent egressLink = localHops.get(localHops.size()-1).getLink();
String srcLinkId = ingressLink.getId();
URNParserResult srcRes = URNParser.parseTopoIdent(srcLinkId);
String dstLinkId = egressLink.getId();
URNParserResult dstRes = URNParser.parseTopoIdent(dstLinkId);
EoMPLSIfceAddressResolver iar = ecf.getEomplsIfceAddressResolver();
EoMPLSDeviceAddressResolver dar = ecf.getEomplsDeviceAddressResolver();
SDNNameGenerator ng = SDNNameGenerator.getInstance();
String gri = res.getGlobalReservationId();
// bandwidth in Mbps
lspBandwidth = 1000000L*bw;
policerBandwidthLimit = lspBandwidth;
policerBurstSizeLimit = lspBandwidth / 10;
String lspTargetDeviceId;
boolean reverse = false;
log.debug("source edge device id is: "+srcDeviceId+", config to generate is for "+deviceId);
if (srcDeviceId.equals(deviceId)) {
// forward direction
log.debug("forward");
ifceName = srcRes.getPortId();
srcIfceName = ifceName;
ifceVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
srcIfceVlan = ifceVlan;
egressVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
lspTargetDeviceId = dstRes.getNodeId();
} else {
// reverse direction
log.debug("reverse");
ifceName = dstRes.getPortId();
srcIfceName = srcRes.getPortId();
ifceVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
srcIfceVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
egressVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
lspTargetDeviceId = srcRes.getNodeId();
reverse = true;
}
LSP lspBean = new LSP(deviceId, pi, dar, iar, reverse);
ifceDescription = ng.getInterfaceDescription(gri, lspBandwidth);
policingFilterName = ng.getFilterName(gri, "policing");
policingFilterTerm = policingFilterName;
policingFilterCount = policingFilterName;
statsFilterName = ng.getFilterName(gri, "stats");
statsFilterTerm = statsFilterName;
statsFilterCount = statsFilterName;
communityName = ng.getCommunityName(gri);
policyName = ng.getPolicyName(gri);
policyTerm = policyName;
policerName = ng.getPolicerName(gri);
pathName = ng.getPathName(gri);
lspName = ng.getLSPName(gri);
l2circuitDescription = ng.getL2CircuitDescription(gri);
l2circuitEgress = dar.getDeviceAddress(lspTargetDeviceId);
l2circuitVCID = EoMPLSUtils.genJunosVCId(srcIfceName, srcIfceVlan);
// community is 30000 - 65500
String oscarsCommunity;
Random rand = new Random();
Integer randInt = 30000 + rand.nextInt(35500);
if (ng.getOscarsCommunity(gri) > 65535) {
oscarsCommunity = ng.getOscarsCommunity(gri)+"L";
} else {
oscarsCommunity = ng.getOscarsCommunity(gri).toString();
}
communityMembers = "65000:"+oscarsCommunity+":"+randInt;
// create and populate the model
// this needs to match with the template
Map root = new HashMap();
Map lsp = new HashMap();
Map path = new HashMap();
Map ifce = new HashMap();
Map filters = new HashMap();
Map stats = new HashMap();
Map policing = new HashMap();
Map community = new HashMap();
Map policy = new HashMap();
Map l2circuit = new HashMap();
Map policer = new HashMap();
root.put("lsp", lsp);
root.put("path", path);
root.put("ifce", ifce);
root.put("filters", filters);
root.put("policy", policy);
root.put("policer", policer);
root.put("l2circuit", l2circuit);
root.put("community", community);
root.put("egressvlan", egressVlan);
filters.put("stats", stats);
filters.put("policing", policing);
stats.put("name", statsFilterName);
stats.put("term", statsFilterTerm);
stats.put("count", statsFilterCount);
policing.put("name", policingFilterName);
policing.put("term", policingFilterTerm);
policing.put("count", policingFilterCount);
ifce.put("name", ifceName);
ifce.put("vlan", ifceVlan);
ifce.put("description", ifceDescription);
lsp.put("name", lspName);
lsp.put("from", lspBean.getFrom());
lsp.put("to", lspBean.getTo());
lsp.put("bandwidth", lspBandwidth);
path.put("hops", lspBean.getPathAddresses());
path.put("name", pathName);
l2circuit.put("egress", l2circuitEgress);
l2circuit.put("vcid", l2circuitVCID);
l2circuit.put("description", l2circuitDescription);
policer.put("name", policerName);
policer.put("burst_size_limit", policerBurstSizeLimit);
policer.put("bandwidth_limit", policerBandwidthLimit);
community.put("name", communityName);
community.put("members", communityMembers);
policy.put("name", policyName);
policy.put("term", policyTerm);
log.debug("getLSPSetup ready");
String config = EoMPLSUtils.generateConfig(root, templateFile);
log.debug("getLSPSetup done");
return config;
}
| private String getLSPSetup(ResDetails res, String deviceId) throws PSSException {
log.debug("getLSPSetup start");
String templateFile = "junos-mx-lsp-setup.txt";
String srcDeviceId = EoMPLSUtils.getDeviceId(res, false);
String ifceName;
String srcIfceName;
String ifceDescription;
String ifceVlan;
String srcIfceVlan;
String egressVlan;
String policyName;
String policyTerm;
String communityName;
String communityMembers;
Long lspBandwidth;
String pathName;
String lspName;
String l2circuitVCID;
String l2circuitEgress;
String l2circuitDescription;
String policerName;
Long policerBurstSizeLimit;
Long policerBandwidthLimit;
String statsFilterName;
String statsFilterTerm;
String statsFilterCount;
String policingFilterName;
String policingFilterTerm;
String policingFilterCount;
EoMPLSClassFactory ecf = EoMPLSClassFactory.getInstance();
/* *********************** */
/* BEGIN POPULATING VALUES */
/* *********************** */
ReservedConstraintType rc = res.getReservedConstraint();
Integer bw = rc.getBandwidth();
PathInfo pi = rc.getPathInfo();
List<CtrlPlaneHopContent> localHops;
try {
localHops = PathTools.getLocalHops(pi.getPath(), PathTools.getLocalDomainId());
} catch (OSCARSServiceException e) {
throw new PSSException(e);
}
CtrlPlaneLinkContent ingressLink = localHops.get(0).getLink();
CtrlPlaneLinkContent egressLink = localHops.get(localHops.size()-1).getLink();
String srcLinkId = ingressLink.getId();
URNParserResult srcRes = URNParser.parseTopoIdent(srcLinkId);
String dstLinkId = egressLink.getId();
URNParserResult dstRes = URNParser.parseTopoIdent(dstLinkId);
EoMPLSIfceAddressResolver iar = ecf.getEomplsIfceAddressResolver();
EoMPLSDeviceAddressResolver dar = ecf.getEomplsDeviceAddressResolver();
SDNNameGenerator ng = SDNNameGenerator.getInstance();
String gri = res.getGlobalReservationId();
// bandwidth in Mbps
lspBandwidth = 1000000L*bw;
policerBandwidthLimit = lspBandwidth;
policerBurstSizeLimit = lspBandwidth / 10;
String lspTargetDeviceId;
boolean reverse = false;
log.debug("source edge device id is: "+srcDeviceId+", config to generate is for "+deviceId);
if (srcDeviceId.equals(deviceId)) {
// forward direction
log.debug("forward");
ifceName = srcRes.getPortId();
srcIfceName = ifceName;
ifceVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
srcIfceVlan = ifceVlan;
egressVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
lspTargetDeviceId = dstRes.getNodeId();
} else {
// reverse direction
log.debug("reverse");
ifceName = dstRes.getPortId();
srcIfceName = srcRes.getPortId();
ifceVlan = egressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
srcIfceVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
egressVlan = ingressLink.getSwitchingCapabilityDescriptors().getSwitchingCapabilitySpecificInfo().getSuggestedVLANRange();
lspTargetDeviceId = srcRes.getNodeId();
reverse = true;
}
LSP lspBean = new LSP(deviceId, pi, dar, iar, reverse);
ifceDescription = ng.getInterfaceDescription(gri, lspBandwidth);
policingFilterName = ng.getFilterName(gri, "policing");
policingFilterTerm = policingFilterName;
policingFilterCount = policingFilterName;
statsFilterName = ng.getFilterName(gri, "stats");
statsFilterTerm = statsFilterName;
statsFilterCount = statsFilterName;
communityName = ng.getCommunityName(gri);
policyName = ng.getPolicyName(gri);
policyTerm = policyName;
policerName = ng.getPolicerName(gri);
pathName = ng.getPathName(gri);
lspName = ng.getLSPName(gri);
l2circuitDescription = ng.getL2CircuitDescription(gri);
l2circuitEgress = dar.getDeviceAddress(lspTargetDeviceId);
l2circuitVCID = EoMPLSUtils.genJunosVCId(srcIfceName, srcIfceVlan);
// community is 30000 - 65500
String oscarsCommunity;
Random rand = new Random();
Integer randInt = 30000 + rand.nextInt(35500);
if (ng.getOscarsCommunity(gri) > 65535) {
oscarsCommunity = ng.getOscarsCommunity(gri)+"L";
} else {
oscarsCommunity = ng.getOscarsCommunity(gri).toString();
}
communityMembers = "65000:"+oscarsCommunity+":"+randInt;
// create and populate the model
// this needs to match with the template
Map root = new HashMap();
Map lsp = new HashMap();
Map path = new HashMap();
Map ifce = new HashMap();
Map filters = new HashMap();
Map stats = new HashMap();
Map policing = new HashMap();
Map community = new HashMap();
Map policy = new HashMap();
Map l2circuit = new HashMap();
Map policer = new HashMap();
root.put("lsp", lsp);
root.put("path", path);
root.put("ifce", ifce);
root.put("filters", filters);
root.put("policy", policy);
root.put("policer", policer);
root.put("l2circuit", l2circuit);
root.put("community", community);
root.put("egressvlan", egressVlan);
filters.put("stats", stats);
filters.put("policing", policing);
stats.put("name", statsFilterName);
stats.put("term", statsFilterTerm);
stats.put("count", statsFilterCount);
policing.put("name", policingFilterName);
policing.put("term", policingFilterTerm);
policing.put("count", policingFilterCount);
ifce.put("name", ifceName);
ifce.put("vlan", ifceVlan);
ifce.put("description", ifceDescription);
lsp.put("name", lspName);
lsp.put("from", lspBean.getFrom());
lsp.put("to", lspBean.getTo());
lsp.put("bandwidth", lspBandwidth);
path.put("hops", lspBean.getPathAddresses());
path.put("name", pathName);
l2circuit.put("egress", l2circuitEgress);
l2circuit.put("vcid", l2circuitVCID);
l2circuit.put("description", l2circuitDescription);
policer.put("name", policerName);
policer.put("burst_size_limit", policerBurstSizeLimit);
policer.put("bandwidth_limit", policerBandwidthLimit);
community.put("name", communityName);
community.put("members", communityMembers);
policy.put("name", policyName);
policy.put("term", policyTerm);
log.debug("getLSPSetup ready");
String config = EoMPLSUtils.generateConfig(root, templateFile);
log.debug("getLSPSetup done");
return config;
}
|
diff --git a/src/org/eclipse/cdt/core/resources/ACBuilder.java b/src/org/eclipse/cdt/core/resources/ACBuilder.java
index 62add0f68..458310208 100644
--- a/src/org/eclipse/cdt/core/resources/ACBuilder.java
+++ b/src/org/eclipse/cdt/core/resources/ACBuilder.java
@@ -1,74 +1,75 @@
package org.eclipse.cdt.core.resources;
/*
* (c) Copyright QNX Software Systems Ltd. 2002.
* All Rights Reserved.
*/
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.IMarkerGenerator;
import org.eclipse.cdt.core.model.ICModelMarker;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
public abstract class ACBuilder extends IncrementalProjectBuilder implements IMarkerGenerator {
/**
* Constructor for ACBuilder
*/
public ACBuilder() {
super();
}
/*
* callback from Output Parser
*/
public void addMarker(IResource file, int lineNumber, String errorDesc, int severity, String errorVar) {
try {
IMarker[] cur = file.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_ONE);
/*
* Try to find matching markers and don't put in duplicates
*/
if ((cur != null) && (cur.length > 0)) {
for (int i = 0; i < cur.length; i++) {
- if ((((Integer) cur[i].getAttribute(IMarker.LOCATION)).intValue() == lineNumber)
- && (((Integer) cur[i].getAttribute(IMarker.SEVERITY)).intValue() == severity)
- && (((String) cur[i].getAttribute(IMarker.MESSAGE)).equals(errorDesc))) {
+ int line = ((Integer) cur[i].getAttribute(IMarker.LOCATION)).intValue();
+ int sev = ((Integer) cur[i].getAttribute(IMarker.SEVERITY)).intValue();
+ String mesg = (String) cur[i].getAttribute(IMarker.MESSAGE);
+ if (line == lineNumber && sev == mapMarkerSeverity(severity) && mesg.equals(errorDesc)) {
return;
}
}
}
IMarker marker = file.createMarker(ICModelMarker.C_MODEL_PROBLEM_MARKER);
marker.setAttribute(IMarker.LOCATION, lineNumber);
marker.setAttribute(IMarker.MESSAGE, errorDesc);
marker.setAttribute(IMarker.SEVERITY, mapMarkerSeverity(severity));
marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
marker.setAttribute(IMarker.CHAR_START, -1);
marker.setAttribute(IMarker.CHAR_END, -1);
if (errorVar != null) {
marker.setAttribute(ICModelMarker.C_MODEL_MARKER_VARIABLE, errorVar);
}
}
catch (CoreException e) {
CCorePlugin.log(e.getStatus());
}
}
int mapMarkerSeverity(int severity) {
switch (severity) {
case SEVERITY_ERROR_BUILD :
case SEVERITY_ERROR_RESOURCE :
return IMarker.SEVERITY_ERROR;
case SEVERITY_INFO :
return IMarker.SEVERITY_INFO;
case SEVERITY_WARNING :
return IMarker.SEVERITY_WARNING;
}
return IMarker.SEVERITY_ERROR;
}
}
| true | true | public void addMarker(IResource file, int lineNumber, String errorDesc, int severity, String errorVar) {
try {
IMarker[] cur = file.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_ONE);
/*
* Try to find matching markers and don't put in duplicates
*/
if ((cur != null) && (cur.length > 0)) {
for (int i = 0; i < cur.length; i++) {
if ((((Integer) cur[i].getAttribute(IMarker.LOCATION)).intValue() == lineNumber)
&& (((Integer) cur[i].getAttribute(IMarker.SEVERITY)).intValue() == severity)
&& (((String) cur[i].getAttribute(IMarker.MESSAGE)).equals(errorDesc))) {
return;
}
}
}
IMarker marker = file.createMarker(ICModelMarker.C_MODEL_PROBLEM_MARKER);
marker.setAttribute(IMarker.LOCATION, lineNumber);
marker.setAttribute(IMarker.MESSAGE, errorDesc);
marker.setAttribute(IMarker.SEVERITY, mapMarkerSeverity(severity));
marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
marker.setAttribute(IMarker.CHAR_START, -1);
marker.setAttribute(IMarker.CHAR_END, -1);
if (errorVar != null) {
marker.setAttribute(ICModelMarker.C_MODEL_MARKER_VARIABLE, errorVar);
}
}
catch (CoreException e) {
CCorePlugin.log(e.getStatus());
}
}
| public void addMarker(IResource file, int lineNumber, String errorDesc, int severity, String errorVar) {
try {
IMarker[] cur = file.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_ONE);
/*
* Try to find matching markers and don't put in duplicates
*/
if ((cur != null) && (cur.length > 0)) {
for (int i = 0; i < cur.length; i++) {
int line = ((Integer) cur[i].getAttribute(IMarker.LOCATION)).intValue();
int sev = ((Integer) cur[i].getAttribute(IMarker.SEVERITY)).intValue();
String mesg = (String) cur[i].getAttribute(IMarker.MESSAGE);
if (line == lineNumber && sev == mapMarkerSeverity(severity) && mesg.equals(errorDesc)) {
return;
}
}
}
IMarker marker = file.createMarker(ICModelMarker.C_MODEL_PROBLEM_MARKER);
marker.setAttribute(IMarker.LOCATION, lineNumber);
marker.setAttribute(IMarker.MESSAGE, errorDesc);
marker.setAttribute(IMarker.SEVERITY, mapMarkerSeverity(severity));
marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
marker.setAttribute(IMarker.CHAR_START, -1);
marker.setAttribute(IMarker.CHAR_END, -1);
if (errorVar != null) {
marker.setAttribute(ICModelMarker.C_MODEL_MARKER_VARIABLE, errorVar);
}
}
catch (CoreException e) {
CCorePlugin.log(e.getStatus());
}
}
|
diff --git a/email2/src/com/android/email/provider/AttachmentProvider.java b/email2/src/com/android/email/provider/AttachmentProvider.java
index e0133156c..71955851e 100644
--- a/email2/src/com/android/email/provider/AttachmentProvider.java
+++ b/email2/src/com/android/email/provider/AttachmentProvider.java
@@ -1,334 +1,334 @@
/*
* 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.email.provider;
import com.android.emailcommon.Logging;
import com.android.emailcommon.internet.MimeUtility;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.Attachment;
import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
import com.android.emailcommon.utility.AttachmentUtilities;
import com.android.emailcommon.utility.AttachmentUtilities.Columns;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Binder;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/*
* A simple ContentProvider that allows file access to Email's attachments.
*
* The URI scheme is as follows. For raw file access:
* content://com.android.email.attachmentprovider/acct#/attach#/RAW
*
* And for access to thumbnails:
* content://com.android.email.attachmentprovider/acct#/attach#/THUMBNAIL/width#/height#
*
* The on-disk (storage) schema is as follows.
*
* Attachments are stored at: <database-path>/account#.db_att/item#
* Thumbnails are stored at: <cache-path>/thmb_account#_item#
*
* Using the standard application context, account #10 and attachment # 20, this would be:
* /data/data/com.android.email/databases/10.db_att/20
* /data/data/com.android.email/cache/thmb_10_20
*/
public class AttachmentProvider extends ContentProvider {
private static final String[] MIME_TYPE_PROJECTION = new String[] {
AttachmentColumns.MIME_TYPE, AttachmentColumns.FILENAME };
private static final int MIME_TYPE_COLUMN_MIME_TYPE = 0;
private static final int MIME_TYPE_COLUMN_FILENAME = 1;
private static final String[] PROJECTION_QUERY = new String[] { AttachmentColumns.FILENAME,
AttachmentColumns.SIZE, AttachmentColumns.CONTENT_URI };
@Override
public boolean onCreate() {
/*
* We use the cache dir as a temporary directory (since Android doesn't give us one) so
* on startup we'll clean up any .tmp files from the last run.
*/
File[] files = getContext().getCacheDir().listFiles();
for (File file : files) {
String filename = file.getName();
if (filename.endsWith(".tmp") || filename.startsWith("thmb_")) {
file.delete();
}
}
return true;
}
/**
* Returns the mime type for a given attachment. There are three possible results:
* - If thumbnail Uri, always returns "image/png" (even if there's no attachment)
* - If the attachment does not exist, returns null
* - Returns the mime type of the attachment
*/
@Override
public String getType(Uri uri) {
long callingId = Binder.clearCallingIdentity();
try {
List<String> segments = uri.getPathSegments();
String id = segments.get(1);
String format = segments.get(2);
if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) {
return "image/png";
} else {
uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id));
Cursor c = getContext().getContentResolver().query(uri, MIME_TYPE_PROJECTION, null,
null, null);
try {
if (c.moveToFirst()) {
String mimeType = c.getString(MIME_TYPE_COLUMN_MIME_TYPE);
String fileName = c.getString(MIME_TYPE_COLUMN_FILENAME);
mimeType = AttachmentUtilities.inferMimeType(fileName, mimeType);
return mimeType;
}
} finally {
c.close();
}
return null;
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
/**
* Open an attachment file. There are two "formats" - "raw", which returns an actual file,
* and "thumbnail", which attempts to generate a thumbnail image.
*
* Thumbnails are cached for easy space recovery and cleanup.
*
* TODO: The thumbnail format returns null for its failure cases, instead of throwing
* FileNotFoundException, and should be fixed for consistency.
*
* @throws FileNotFoundException
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// If this is a write, the caller must have the EmailProvider permission, which is
// based on signature only
if (mode.equals("w")) {
Context context = getContext();
- if (context.checkCallingPermission(EmailContent.PROVIDER_PERMISSION)
+ if (context.checkCallingOrSelfPermission(EmailContent.PROVIDER_PERMISSION)
!= PackageManager.PERMISSION_GRANTED) {
throw new FileNotFoundException();
}
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
File saveIn =
AttachmentUtilities.getAttachmentDirectory(context, Long.parseLong(accountId));
if (!saveIn.exists()) {
saveIn.mkdirs();
}
File newFile = new File(saveIn, id);
return ParcelFileDescriptor.open(
newFile, ParcelFileDescriptor.MODE_READ_WRITE |
ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE);
}
long callingId = Binder.clearCallingIdentity();
try {
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
String format = segments.get(2);
if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) {
int width = Integer.parseInt(segments.get(3));
int height = Integer.parseInt(segments.get(4));
String filename = "thmb_" + accountId + "_" + id;
File dir = getContext().getCacheDir();
File file = new File(dir, filename);
if (!file.exists()) {
Uri attachmentUri = AttachmentUtilities.
getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id));
Cursor c = query(attachmentUri,
new String[] { Columns.DATA }, null, null, null);
if (c != null) {
try {
if (c.moveToFirst()) {
attachmentUri = Uri.parse(c.getString(0));
} else {
return null;
}
} finally {
c.close();
}
}
String type = getContext().getContentResolver().getType(attachmentUri);
try {
InputStream in =
getContext().getContentResolver().openInputStream(attachmentUri);
Bitmap thumbnail = createThumbnail(type, in);
if (thumbnail == null) {
return null;
}
thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true);
FileOutputStream out = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
in.close();
} catch (IOException ioe) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
ioe.getMessage());
return null;
} catch (OutOfMemoryError oome) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
oome.getMessage());
return null;
}
}
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
else {
return ParcelFileDescriptor.open(
new File(getContext().getDatabasePath(accountId + ".db_att"), id),
ParcelFileDescriptor.MODE_READ_ONLY);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
@Override
public int delete(Uri uri, String arg1, String[] arg2) {
return 0;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
/**
* Returns a cursor based on the data in the attachments table, or null if the attachment
* is not recorded in the table.
*
* Supports REST Uri only, for a single row - selection, selection args, and sortOrder are
* ignored (non-null values should probably throw an exception....)
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
long callingId = Binder.clearCallingIdentity();
try {
if (projection == null) {
projection =
new String[] {
Columns._ID,
Columns.DATA,
};
}
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
String format = segments.get(2);
String name = null;
int size = -1;
String contentUri = null;
uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id));
Cursor c = getContext().getContentResolver().query(uri, PROJECTION_QUERY,
null, null, null);
try {
if (c.moveToFirst()) {
name = c.getString(0);
size = c.getInt(1);
contentUri = c.getString(2);
} else {
return null;
}
} finally {
c.close();
}
MatrixCursor ret = new MatrixCursor(projection);
Object[] values = new Object[projection.length];
for (int i = 0, count = projection.length; i < count; i++) {
String column = projection[i];
if (Columns._ID.equals(column)) {
values[i] = id;
}
else if (Columns.DATA.equals(column)) {
values[i] = contentUri;
}
else if (Columns.DISPLAY_NAME.equals(column)) {
values[i] = name;
}
else if (Columns.SIZE.equals(column)) {
values[i] = size;
}
}
ret.addRow(values);
return ret;
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
private Bitmap createThumbnail(String type, InputStream data) {
if(MimeUtility.mimeTypeMatches(type, "image/*")) {
return createImageThumbnail(data);
}
return null;
}
private Bitmap createImageThumbnail(InputStream data) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(data);
return bitmap;
} catch (OutOfMemoryError oome) {
Log.d(Logging.LOG_TAG, "createImageThumbnail failed with " + oome.getMessage());
return null;
} catch (Exception e) {
Log.d(Logging.LOG_TAG, "createImageThumbnail failed with " + e.getMessage());
return null;
}
}
/**
* Need this to suppress warning in unit tests.
*/
@Override
public void shutdown() {
// Don't call super.shutdown(), which emits a warning...
}
}
| true | true | public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// If this is a write, the caller must have the EmailProvider permission, which is
// based on signature only
if (mode.equals("w")) {
Context context = getContext();
if (context.checkCallingPermission(EmailContent.PROVIDER_PERMISSION)
!= PackageManager.PERMISSION_GRANTED) {
throw new FileNotFoundException();
}
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
File saveIn =
AttachmentUtilities.getAttachmentDirectory(context, Long.parseLong(accountId));
if (!saveIn.exists()) {
saveIn.mkdirs();
}
File newFile = new File(saveIn, id);
return ParcelFileDescriptor.open(
newFile, ParcelFileDescriptor.MODE_READ_WRITE |
ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE);
}
long callingId = Binder.clearCallingIdentity();
try {
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
String format = segments.get(2);
if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) {
int width = Integer.parseInt(segments.get(3));
int height = Integer.parseInt(segments.get(4));
String filename = "thmb_" + accountId + "_" + id;
File dir = getContext().getCacheDir();
File file = new File(dir, filename);
if (!file.exists()) {
Uri attachmentUri = AttachmentUtilities.
getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id));
Cursor c = query(attachmentUri,
new String[] { Columns.DATA }, null, null, null);
if (c != null) {
try {
if (c.moveToFirst()) {
attachmentUri = Uri.parse(c.getString(0));
} else {
return null;
}
} finally {
c.close();
}
}
String type = getContext().getContentResolver().getType(attachmentUri);
try {
InputStream in =
getContext().getContentResolver().openInputStream(attachmentUri);
Bitmap thumbnail = createThumbnail(type, in);
if (thumbnail == null) {
return null;
}
thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true);
FileOutputStream out = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
in.close();
} catch (IOException ioe) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
ioe.getMessage());
return null;
} catch (OutOfMemoryError oome) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
oome.getMessage());
return null;
}
}
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
else {
return ParcelFileDescriptor.open(
new File(getContext().getDatabasePath(accountId + ".db_att"), id),
ParcelFileDescriptor.MODE_READ_ONLY);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
| public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// If this is a write, the caller must have the EmailProvider permission, which is
// based on signature only
if (mode.equals("w")) {
Context context = getContext();
if (context.checkCallingOrSelfPermission(EmailContent.PROVIDER_PERMISSION)
!= PackageManager.PERMISSION_GRANTED) {
throw new FileNotFoundException();
}
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
File saveIn =
AttachmentUtilities.getAttachmentDirectory(context, Long.parseLong(accountId));
if (!saveIn.exists()) {
saveIn.mkdirs();
}
File newFile = new File(saveIn, id);
return ParcelFileDescriptor.open(
newFile, ParcelFileDescriptor.MODE_READ_WRITE |
ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE);
}
long callingId = Binder.clearCallingIdentity();
try {
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
String format = segments.get(2);
if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) {
int width = Integer.parseInt(segments.get(3));
int height = Integer.parseInt(segments.get(4));
String filename = "thmb_" + accountId + "_" + id;
File dir = getContext().getCacheDir();
File file = new File(dir, filename);
if (!file.exists()) {
Uri attachmentUri = AttachmentUtilities.
getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id));
Cursor c = query(attachmentUri,
new String[] { Columns.DATA }, null, null, null);
if (c != null) {
try {
if (c.moveToFirst()) {
attachmentUri = Uri.parse(c.getString(0));
} else {
return null;
}
} finally {
c.close();
}
}
String type = getContext().getContentResolver().getType(attachmentUri);
try {
InputStream in =
getContext().getContentResolver().openInputStream(attachmentUri);
Bitmap thumbnail = createThumbnail(type, in);
if (thumbnail == null) {
return null;
}
thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true);
FileOutputStream out = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
in.close();
} catch (IOException ioe) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
ioe.getMessage());
return null;
} catch (OutOfMemoryError oome) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
oome.getMessage());
return null;
}
}
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
else {
return ParcelFileDescriptor.open(
new File(getContext().getDatabasePath(accountId + ".db_att"), id),
ParcelFileDescriptor.MODE_READ_ONLY);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
|
diff --git a/src/java/com/android/internal/telephony/gsm/GsmConnection.java b/src/java/com/android/internal/telephony/gsm/GsmConnection.java
index 875b680..59aa12a 100644
--- a/src/java/com/android/internal/telephony/gsm/GsmConnection.java
+++ b/src/java/com/android/internal/telephony/gsm/GsmConnection.java
@@ -1,767 +1,768 @@
/*
* Copyright (C) 2006 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.internal.telephony.gsm;
import android.content.Context;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.Registrant;
import android.os.SystemClock;
import android.util.Log;
import android.telephony.PhoneNumberUtils;
import android.telephony.ServiceState;
import android.text.TextUtils;
import com.android.internal.telephony.*;
import com.android.internal.telephony.IccCardApplicationStatus.AppState;
import com.android.internal.telephony.uicc.UiccController;
/**
* {@hide}
*/
public class GsmConnection extends Connection {
static final String LOG_TAG = "GSM";
//***** Instance Variables
GsmCallTracker owner;
GsmCall parent;
String address; // MAY BE NULL!!!
String dialString; // outgoing calls only
String postDialString; // outgoing calls only
boolean isIncoming;
boolean disconnected;
int index; // index in GsmCallTracker.connections[], -1 if unassigned
// The GSM index is 1 + this
/*
* These time/timespan values are based on System.currentTimeMillis(),
* i.e., "wall clock" time.
*/
long createTime;
long connectTime;
long disconnectTime;
/*
* These time/timespan values are based on SystemClock.elapsedRealTime(),
* i.e., time since boot. They are appropriate for comparison and
* calculating deltas.
*/
long connectTimeReal;
long duration;
long holdingStartTime; // The time when the Connection last transitioned
// into HOLDING
int nextPostDialChar; // index into postDialString
DisconnectCause cause = DisconnectCause.NOT_DISCONNECTED;
PostDialState postDialState = PostDialState.NOT_STARTED;
int numberPresentation = PhoneConstants.PRESENTATION_ALLOWED;
UUSInfo uusInfo;
Handler h;
private PowerManager.WakeLock mPartialWakeLock;
//***** Event Constants
static final int EVENT_DTMF_DONE = 1;
static final int EVENT_PAUSE_DONE = 2;
static final int EVENT_NEXT_POST_DIAL = 3;
static final int EVENT_WAKE_LOCK_TIMEOUT = 4;
//***** Constants
static final int PAUSE_DELAY_FIRST_MILLIS = 100;
static final int PAUSE_DELAY_MILLIS = 3 * 1000;
static final int WAKE_LOCK_TIMEOUT_MILLIS = 60*1000;
//***** Inner Classes
class MyHandler extends Handler {
MyHandler(Looper l) {super(l);}
public void
handleMessage(Message msg) {
switch (msg.what) {
case EVENT_NEXT_POST_DIAL:
case EVENT_DTMF_DONE:
case EVENT_PAUSE_DONE:
processNextPostDialChar();
break;
case EVENT_WAKE_LOCK_TIMEOUT:
releaseWakeLock();
break;
}
}
}
//***** Constructors
/** This is probably an MT call that we first saw in a CLCC response */
/*package*/
GsmConnection (Context context, DriverCall dc, GsmCallTracker ct, int index) {
createWakeLock(context);
acquireWakeLock();
owner = ct;
h = new MyHandler(owner.getLooper());
address = dc.number;
isIncoming = dc.isMT;
createTime = System.currentTimeMillis();
cnapName = dc.name;
cnapNamePresentation = dc.namePresentation;
numberPresentation = dc.numberPresentation;
uusInfo = dc.uusInfo;
this.index = index;
parent = parentFromDCState (dc.state);
parent.attach(this, dc);
}
/** This is an MO call, created when dialing */
/*package*/
GsmConnection (Context context, String dialString, GsmCallTracker ct, GsmCall parent) {
createWakeLock(context);
acquireWakeLock();
owner = ct;
h = new MyHandler(owner.getLooper());
this.dialString = dialString;
this.address = PhoneNumberUtils.extractNetworkPortionAlt(dialString);
this.postDialString = PhoneNumberUtils.extractPostDialPortion(dialString);
index = -1;
isIncoming = false;
cnapName = null;
cnapNamePresentation = PhoneConstants.PRESENTATION_ALLOWED;
numberPresentation = PhoneConstants.PRESENTATION_ALLOWED;
createTime = System.currentTimeMillis();
this.parent = parent;
parent.attachFake(this, GsmCall.State.DIALING);
}
public void dispose() {
}
static boolean
equalsHandlesNulls (Object a, Object b) {
return (a == null) ? (b == null) : a.equals (b);
}
/*package*/ boolean
compareTo(DriverCall c) {
// On mobile originated (MO) calls, the phone number may have changed
// due to a SIM Toolkit call control modification.
//
// We assume we know when MO calls are created (since we created them)
// and therefore don't need to compare the phone number anyway.
if (! (isIncoming || c.isMT)) return true;
// ... but we can compare phone numbers on MT calls, and we have
// no control over when they begin, so we might as well
String cAddress = PhoneNumberUtils.stringFromStringAndTOA(c.number, c.TOA);
return isIncoming == c.isMT && equalsHandlesNulls(address, cAddress);
}
public String getAddress() {
return address;
}
public GsmCall getCall() {
return parent;
}
public long getCreateTime() {
return createTime;
}
public long getConnectTime() {
return connectTime;
}
public long getDisconnectTime() {
return disconnectTime;
}
public long getDurationMillis() {
if (connectTimeReal == 0) {
return 0;
} else if (duration == 0) {
return SystemClock.elapsedRealtime() - connectTimeReal;
} else {
return duration;
}
}
public long getHoldDurationMillis() {
if (getState() != GsmCall.State.HOLDING) {
// If not holding, return 0
return 0;
} else {
return SystemClock.elapsedRealtime() - holdingStartTime;
}
}
public DisconnectCause getDisconnectCause() {
return cause;
}
public boolean isIncoming() {
return isIncoming;
}
public GsmCall.State getState() {
if (disconnected) {
return GsmCall.State.DISCONNECTED;
} else {
return super.getState();
}
}
public void hangup() throws CallStateException {
if (!disconnected) {
owner.hangup(this);
} else {
throw new CallStateException ("disconnected");
}
}
public void separate() throws CallStateException {
if (!disconnected) {
owner.separate(this);
} else {
throw new CallStateException ("disconnected");
}
}
public PostDialState getPostDialState() {
return postDialState;
}
public void proceedAfterWaitChar() {
if (postDialState != PostDialState.WAIT) {
Log.w(LOG_TAG, "GsmConnection.proceedAfterWaitChar(): Expected "
+ "getPostDialState() to be WAIT but was " + postDialState);
return;
}
setPostDialState(PostDialState.STARTED);
processNextPostDialChar();
}
public void proceedAfterWildChar(String str) {
if (postDialState != PostDialState.WILD) {
Log.w(LOG_TAG, "GsmConnection.proceedAfterWaitChar(): Expected "
+ "getPostDialState() to be WILD but was " + postDialState);
return;
}
setPostDialState(PostDialState.STARTED);
if (false) {
boolean playedTone = false;
int len = (str != null ? str.length() : 0);
for (int i=0; i<len; i++) {
char c = str.charAt(i);
Message msg = null;
if (i == len-1) {
msg = h.obtainMessage(EVENT_DTMF_DONE);
}
if (PhoneNumberUtils.is12Key(c)) {
owner.cm.sendDtmf(c, msg);
playedTone = true;
}
}
if (!playedTone) {
processNextPostDialChar();
}
} else {
// make a new postDialString, with the wild char replacement string
// at the beginning, followed by the remaining postDialString.
StringBuilder buf = new StringBuilder(str);
buf.append(postDialString.substring(nextPostDialChar));
postDialString = buf.toString();
nextPostDialChar = 0;
if (Phone.DEBUG_PHONE) {
log("proceedAfterWildChar: new postDialString is " +
postDialString);
}
processNextPostDialChar();
}
}
public void cancelPostDial() {
setPostDialState(PostDialState.CANCELLED);
}
/**
* Called when this Connection is being hung up locally (eg, user pressed "end")
* Note that at this point, the hangup request has been dispatched to the radio
* but no response has yet been received so update() has not yet been called
*/
void
onHangupLocal() {
cause = DisconnectCause.LOCAL;
}
DisconnectCause
disconnectCauseFromCode(int causeCode) {
/**
* See 22.001 Annex F.4 for mapping of cause codes
* to local tones
*/
switch (causeCode) {
case CallFailCause.USER_BUSY:
return DisconnectCause.BUSY;
case CallFailCause.NO_CIRCUIT_AVAIL:
case CallFailCause.TEMPORARY_FAILURE:
case CallFailCause.SWITCHING_CONGESTION:
case CallFailCause.CHANNEL_NOT_AVAIL:
case CallFailCause.QOS_NOT_AVAIL:
case CallFailCause.BEARER_NOT_AVAIL:
return DisconnectCause.CONGESTION;
case CallFailCause.ACM_LIMIT_EXCEEDED:
return DisconnectCause.LIMIT_EXCEEDED;
case CallFailCause.CALL_BARRED:
return DisconnectCause.CALL_BARRED;
case CallFailCause.FDN_BLOCKED:
return DisconnectCause.FDN_BLOCKED;
case CallFailCause.UNOBTAINABLE_NUMBER:
return DisconnectCause.UNOBTAINABLE_NUMBER;
case CallFailCause.ERROR_UNSPECIFIED:
case CallFailCause.NORMAL_CLEARING:
default:
GSMPhone phone = owner.phone;
int serviceState = phone.getServiceState().getState();
- AppState uiccAppState = UiccController
+ UiccCardApplication cardApp = UiccController
.getInstance()
- .getUiccCardApplication(UiccController.APP_FAM_3GPP)
- .getState();
+ .getUiccCardApplication(UiccController.APP_FAM_3GPP);
+ AppState uiccAppState = (cardApp != null) ? cardApp.getState() :
+ AppState.APPSTATE_UNKNOWN;
if (serviceState == ServiceState.STATE_POWER_OFF) {
return DisconnectCause.POWER_OFF;
} else if (serviceState == ServiceState.STATE_OUT_OF_SERVICE
|| serviceState == ServiceState.STATE_EMERGENCY_ONLY ) {
return DisconnectCause.OUT_OF_SERVICE;
} else if (uiccAppState != AppState.APPSTATE_READY) {
return DisconnectCause.ICC_ERROR;
} else if (causeCode == CallFailCause.ERROR_UNSPECIFIED) {
if (phone.mSST.mRestrictedState.isCsRestricted()) {
return DisconnectCause.CS_RESTRICTED;
} else if (phone.mSST.mRestrictedState.isCsEmergencyRestricted()) {
return DisconnectCause.CS_RESTRICTED_EMERGENCY;
} else if (phone.mSST.mRestrictedState.isCsNormalRestricted()) {
return DisconnectCause.CS_RESTRICTED_NORMAL;
} else {
return DisconnectCause.ERROR_UNSPECIFIED;
}
} else if (causeCode == CallFailCause.NORMAL_CLEARING) {
return DisconnectCause.NORMAL;
} else {
// If nothing else matches, report unknown call drop reason
// to app, not NORMAL call end.
return DisconnectCause.ERROR_UNSPECIFIED;
}
}
}
/*package*/ void
onRemoteDisconnect(int causeCode) {
onDisconnect(disconnectCauseFromCode(causeCode));
}
/** Called when the radio indicates the connection has been disconnected */
/*package*/ void
onDisconnect(DisconnectCause cause) {
this.cause = cause;
if (!disconnected) {
index = -1;
disconnectTime = System.currentTimeMillis();
duration = SystemClock.elapsedRealtime() - connectTimeReal;
disconnected = true;
if (false) Log.d(LOG_TAG,
"[GSMConn] onDisconnect: cause=" + cause);
owner.phone.notifyDisconnect(this);
if (parent != null) {
parent.connectionDisconnected(this);
}
}
releaseWakeLock();
}
// Returns true if state has changed, false if nothing changed
/*package*/ boolean
update (DriverCall dc) {
GsmCall newParent;
boolean changed = false;
boolean wasConnectingInOrOut = isConnectingInOrOut();
boolean wasHolding = (getState() == GsmCall.State.HOLDING);
newParent = parentFromDCState(dc.state);
if (!equalsHandlesNulls(address, dc.number)) {
if (Phone.DEBUG_PHONE) log("update: phone # changed!");
address = dc.number;
changed = true;
}
// A null cnapName should be the same as ""
if (TextUtils.isEmpty(dc.name)) {
if (!TextUtils.isEmpty(cnapName)) {
changed = true;
cnapName = "";
}
} else if (!dc.name.equals(cnapName)) {
changed = true;
cnapName = dc.name;
}
if (Phone.DEBUG_PHONE) log("--dssds----"+cnapName);
cnapNamePresentation = dc.namePresentation;
numberPresentation = dc.numberPresentation;
if (newParent != parent) {
if (parent != null) {
parent.detach(this);
}
newParent.attach(this, dc);
parent = newParent;
changed = true;
} else {
boolean parentStateChange;
parentStateChange = parent.update (this, dc);
changed = changed || parentStateChange;
}
/** Some state-transition events */
if (Phone.DEBUG_PHONE) log(
"update: parent=" + parent +
", hasNewParent=" + (newParent != parent) +
", wasConnectingInOrOut=" + wasConnectingInOrOut +
", wasHolding=" + wasHolding +
", isConnectingInOrOut=" + isConnectingInOrOut() +
", changed=" + changed);
if (wasConnectingInOrOut && !isConnectingInOrOut()) {
onConnectedInOrOut();
}
if (changed && !wasHolding && (getState() == GsmCall.State.HOLDING)) {
// We've transitioned into HOLDING
onStartedHolding();
}
return changed;
}
/**
* Called when this Connection is in the foregroundCall
* when a dial is initiated.
* We know we're ACTIVE, and we know we're going to end up
* HOLDING in the backgroundCall
*/
void
fakeHoldBeforeDial() {
if (parent != null) {
parent.detach(this);
}
parent = owner.backgroundCall;
parent.attachFake(this, GsmCall.State.HOLDING);
onStartedHolding();
}
/*package*/ int
getGSMIndex() throws CallStateException {
if (index >= 0) {
return index + 1;
} else {
throw new CallStateException ("GSM index not yet assigned");
}
}
/**
* An incoming or outgoing call has connected
*/
void
onConnectedInOrOut() {
connectTime = System.currentTimeMillis();
connectTimeReal = SystemClock.elapsedRealtime();
duration = 0;
// bug #678474: incoming call interpreted as missed call, even though
// it sounds like the user has picked up the call.
if (Phone.DEBUG_PHONE) {
log("onConnectedInOrOut: connectTime=" + connectTime);
}
if (!isIncoming) {
// outgoing calls only
processNextPostDialChar();
}
releaseWakeLock();
}
private void
onStartedHolding() {
holdingStartTime = SystemClock.elapsedRealtime();
}
/**
* Performs the appropriate action for a post-dial char, but does not
* notify application. returns false if the character is invalid and
* should be ignored
*/
private boolean
processPostDialChar(char c) {
if (PhoneNumberUtils.is12Key(c)) {
owner.cm.sendDtmf(c, h.obtainMessage(EVENT_DTMF_DONE));
} else if (c == PhoneNumberUtils.PAUSE) {
// From TS 22.101:
// "The first occurrence of the "DTMF Control Digits Separator"
// shall be used by the ME to distinguish between the addressing
// digits (i.e. the phone number) and the DTMF digits...."
if (nextPostDialChar == 1) {
// The first occurrence.
// We don't need to pause here, but wait for just a bit anyway
h.sendMessageDelayed(h.obtainMessage(EVENT_PAUSE_DONE),
PAUSE_DELAY_FIRST_MILLIS);
} else {
// It continues...
// "Upon subsequent occurrences of the separator, the UE shall
// pause again for 3 seconds (\u00B1 20 %) before sending any
// further DTMF digits."
h.sendMessageDelayed(h.obtainMessage(EVENT_PAUSE_DONE),
PAUSE_DELAY_MILLIS);
}
} else if (c == PhoneNumberUtils.WAIT) {
setPostDialState(PostDialState.WAIT);
} else if (c == PhoneNumberUtils.WILD) {
setPostDialState(PostDialState.WILD);
} else {
return false;
}
return true;
}
public String
getRemainingPostDialString() {
if (postDialState == PostDialState.CANCELLED
|| postDialState == PostDialState.COMPLETE
|| postDialString == null
|| postDialString.length() <= nextPostDialChar
) {
return "";
}
return postDialString.substring(nextPostDialChar);
}
@Override
protected void finalize()
{
/**
* It is understood that This finializer is not guaranteed
* to be called and the release lock call is here just in
* case there is some path that doesn't call onDisconnect
* and or onConnectedInOrOut.
*/
if (mPartialWakeLock.isHeld()) {
Log.e(LOG_TAG, "[GSMConn] UNEXPECTED; mPartialWakeLock is held when finalizing.");
}
releaseWakeLock();
}
private void
processNextPostDialChar() {
char c = 0;
Registrant postDialHandler;
if (postDialState == PostDialState.CANCELLED) {
//Log.v("GSM", "##### processNextPostDialChar: postDialState == CANCELLED, bail");
return;
}
if (postDialString == null ||
postDialString.length() <= nextPostDialChar) {
setPostDialState(PostDialState.COMPLETE);
// notifyMessage.arg1 is 0 on complete
c = 0;
} else {
boolean isValid;
setPostDialState(PostDialState.STARTED);
c = postDialString.charAt(nextPostDialChar++);
isValid = processPostDialChar(c);
if (!isValid) {
// Will call processNextPostDialChar
h.obtainMessage(EVENT_NEXT_POST_DIAL).sendToTarget();
// Don't notify application
Log.e("GSM", "processNextPostDialChar: c=" + c + " isn't valid!");
return;
}
}
postDialHandler = owner.phone.mPostDialHandler;
Message notifyMessage;
if (postDialHandler != null
&& (notifyMessage = postDialHandler.messageForRegistrant()) != null) {
// The AsyncResult.result is the Connection object
PostDialState state = postDialState;
AsyncResult ar = AsyncResult.forMessage(notifyMessage);
ar.result = this;
ar.userObj = state;
// arg1 is the character that was/is being processed
notifyMessage.arg1 = c;
//Log.v("GSM", "##### processNextPostDialChar: send msg to postDialHandler, arg1=" + c);
notifyMessage.sendToTarget();
}
}
/** "connecting" means "has never been ACTIVE" for both incoming
* and outgoing calls
*/
private boolean
isConnectingInOrOut() {
return parent == null || parent == owner.ringingCall
|| parent.state == GsmCall.State.DIALING
|| parent.state == GsmCall.State.ALERTING;
}
private GsmCall
parentFromDCState (DriverCall.State state) {
switch (state) {
case ACTIVE:
case DIALING:
case ALERTING:
return owner.foregroundCall;
//break;
case HOLDING:
return owner.backgroundCall;
//break;
case INCOMING:
case WAITING:
return owner.ringingCall;
//break;
default:
throw new RuntimeException("illegal call state: " + state);
}
}
/**
* Set post dial state and acquire wake lock while switching to "started"
* state, the wake lock will be released if state switches out of "started"
* state or after WAKE_LOCK_TIMEOUT_MILLIS.
* @param s new PostDialState
*/
private void setPostDialState(PostDialState s) {
if (postDialState != PostDialState.STARTED
&& s == PostDialState.STARTED) {
acquireWakeLock();
Message msg = h.obtainMessage(EVENT_WAKE_LOCK_TIMEOUT);
h.sendMessageDelayed(msg, WAKE_LOCK_TIMEOUT_MILLIS);
} else if (postDialState == PostDialState.STARTED
&& s != PostDialState.STARTED) {
h.removeMessages(EVENT_WAKE_LOCK_TIMEOUT);
releaseWakeLock();
}
postDialState = s;
}
private void
createWakeLock(Context context) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOG_TAG);
}
private void
acquireWakeLock() {
log("acquireWakeLock");
mPartialWakeLock.acquire();
}
private void
releaseWakeLock() {
synchronized(mPartialWakeLock) {
if (mPartialWakeLock.isHeld()) {
log("releaseWakeLock");
mPartialWakeLock.release();
}
}
}
private void log(String msg) {
Log.d(LOG_TAG, "[GSMConn] " + msg);
}
@Override
public int getNumberPresentation() {
return numberPresentation;
}
@Override
public UUSInfo getUUSInfo() {
return uusInfo;
}
}
| false | true | DisconnectCause
disconnectCauseFromCode(int causeCode) {
/**
* See 22.001 Annex F.4 for mapping of cause codes
* to local tones
*/
switch (causeCode) {
case CallFailCause.USER_BUSY:
return DisconnectCause.BUSY;
case CallFailCause.NO_CIRCUIT_AVAIL:
case CallFailCause.TEMPORARY_FAILURE:
case CallFailCause.SWITCHING_CONGESTION:
case CallFailCause.CHANNEL_NOT_AVAIL:
case CallFailCause.QOS_NOT_AVAIL:
case CallFailCause.BEARER_NOT_AVAIL:
return DisconnectCause.CONGESTION;
case CallFailCause.ACM_LIMIT_EXCEEDED:
return DisconnectCause.LIMIT_EXCEEDED;
case CallFailCause.CALL_BARRED:
return DisconnectCause.CALL_BARRED;
case CallFailCause.FDN_BLOCKED:
return DisconnectCause.FDN_BLOCKED;
case CallFailCause.UNOBTAINABLE_NUMBER:
return DisconnectCause.UNOBTAINABLE_NUMBER;
case CallFailCause.ERROR_UNSPECIFIED:
case CallFailCause.NORMAL_CLEARING:
default:
GSMPhone phone = owner.phone;
int serviceState = phone.getServiceState().getState();
AppState uiccAppState = UiccController
.getInstance()
.getUiccCardApplication(UiccController.APP_FAM_3GPP)
.getState();
if (serviceState == ServiceState.STATE_POWER_OFF) {
return DisconnectCause.POWER_OFF;
} else if (serviceState == ServiceState.STATE_OUT_OF_SERVICE
|| serviceState == ServiceState.STATE_EMERGENCY_ONLY ) {
return DisconnectCause.OUT_OF_SERVICE;
} else if (uiccAppState != AppState.APPSTATE_READY) {
return DisconnectCause.ICC_ERROR;
} else if (causeCode == CallFailCause.ERROR_UNSPECIFIED) {
if (phone.mSST.mRestrictedState.isCsRestricted()) {
return DisconnectCause.CS_RESTRICTED;
} else if (phone.mSST.mRestrictedState.isCsEmergencyRestricted()) {
return DisconnectCause.CS_RESTRICTED_EMERGENCY;
} else if (phone.mSST.mRestrictedState.isCsNormalRestricted()) {
return DisconnectCause.CS_RESTRICTED_NORMAL;
} else {
return DisconnectCause.ERROR_UNSPECIFIED;
}
} else if (causeCode == CallFailCause.NORMAL_CLEARING) {
return DisconnectCause.NORMAL;
} else {
// If nothing else matches, report unknown call drop reason
// to app, not NORMAL call end.
return DisconnectCause.ERROR_UNSPECIFIED;
}
}
}
| DisconnectCause
disconnectCauseFromCode(int causeCode) {
/**
* See 22.001 Annex F.4 for mapping of cause codes
* to local tones
*/
switch (causeCode) {
case CallFailCause.USER_BUSY:
return DisconnectCause.BUSY;
case CallFailCause.NO_CIRCUIT_AVAIL:
case CallFailCause.TEMPORARY_FAILURE:
case CallFailCause.SWITCHING_CONGESTION:
case CallFailCause.CHANNEL_NOT_AVAIL:
case CallFailCause.QOS_NOT_AVAIL:
case CallFailCause.BEARER_NOT_AVAIL:
return DisconnectCause.CONGESTION;
case CallFailCause.ACM_LIMIT_EXCEEDED:
return DisconnectCause.LIMIT_EXCEEDED;
case CallFailCause.CALL_BARRED:
return DisconnectCause.CALL_BARRED;
case CallFailCause.FDN_BLOCKED:
return DisconnectCause.FDN_BLOCKED;
case CallFailCause.UNOBTAINABLE_NUMBER:
return DisconnectCause.UNOBTAINABLE_NUMBER;
case CallFailCause.ERROR_UNSPECIFIED:
case CallFailCause.NORMAL_CLEARING:
default:
GSMPhone phone = owner.phone;
int serviceState = phone.getServiceState().getState();
UiccCardApplication cardApp = UiccController
.getInstance()
.getUiccCardApplication(UiccController.APP_FAM_3GPP);
AppState uiccAppState = (cardApp != null) ? cardApp.getState() :
AppState.APPSTATE_UNKNOWN;
if (serviceState == ServiceState.STATE_POWER_OFF) {
return DisconnectCause.POWER_OFF;
} else if (serviceState == ServiceState.STATE_OUT_OF_SERVICE
|| serviceState == ServiceState.STATE_EMERGENCY_ONLY ) {
return DisconnectCause.OUT_OF_SERVICE;
} else if (uiccAppState != AppState.APPSTATE_READY) {
return DisconnectCause.ICC_ERROR;
} else if (causeCode == CallFailCause.ERROR_UNSPECIFIED) {
if (phone.mSST.mRestrictedState.isCsRestricted()) {
return DisconnectCause.CS_RESTRICTED;
} else if (phone.mSST.mRestrictedState.isCsEmergencyRestricted()) {
return DisconnectCause.CS_RESTRICTED_EMERGENCY;
} else if (phone.mSST.mRestrictedState.isCsNormalRestricted()) {
return DisconnectCause.CS_RESTRICTED_NORMAL;
} else {
return DisconnectCause.ERROR_UNSPECIFIED;
}
} else if (causeCode == CallFailCause.NORMAL_CLEARING) {
return DisconnectCause.NORMAL;
} else {
// If nothing else matches, report unknown call drop reason
// to app, not NORMAL call end.
return DisconnectCause.ERROR_UNSPECIFIED;
}
}
}
|
diff --git a/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ShowProperties.java b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ShowProperties.java
index 3ed0204..40734ab 100644
--- a/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ShowProperties.java
+++ b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ShowProperties.java
@@ -1,98 +1,100 @@
/*
* 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.commons.vfs2.example;
import java.text.DateFormat;
import java.util.Date;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.VFS;
/**
* A simple that prints the properties of the file passed as first parameter.
*/
public class ShowProperties
{
public static void main(String[] args)
{
if (args.length == 0)
{
System.err.println("Please pass the name of a file as parameter.");
System.err.println("e.g. java org.apache.commons.vfs2.example.ShowProperties LICENSE.txt");
return;
}
- for (String arg : args) {
+ for (String arg : args)
+ {
try
{
FileSystemManager mgr = VFS.getManager();
System.out.println();
System.out.println("Parsing: " + arg);
FileObject file = mgr.resolveFile(arg);
System.out.println("URL: " + file.getURL());
System.out.println("getName(): " + file.getName());
System.out.println("BaseName: " + file.getName().getBaseName());
System.out.println("Extension: " + file.getName().getExtension());
System.out.println("Path: " + file.getName().getPath());
System.out.println("Scheme: " + file.getName().getScheme());
System.out.println("URI: " + file.getName().getURI());
System.out.println("Root URI: " + file.getName().getRootURI());
System.out.println("Parent: " + file.getName().getParent());
System.out.println("Type: " + file.getType());
System.out.println("Exists: " + file.exists());
System.out.println("Readable: " + file.isReadable());
System.out.println("Writeable: " + file.isWriteable());
System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
if (file.exists())
{
if (file.getType().equals(FileType.FILE))
{
System.out.println("Size: " + file.getContent().getSize() + " bytes");
}
else if (file.getType().equals(FileType.FOLDER) && file.isReadable())
{
FileObject[] children = file.getChildren();
System.out.println("Directory with " + children.length + " files");
for (int iterChildren = 0; iterChildren < children.length; iterChildren++)
{
System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
if (iterChildren > 5)
{
break;
}
}
}
- System.out.println("Last modified: " + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())));
+ System.out.println("Last modified: " + DateFormat.getInstance().format(
+ new Date(file.getContent().getLastModifiedTime())));
}
else
{
System.out.println("The file does not exist");
}
file.close();
}
catch (FileSystemException ex)
{
ex.printStackTrace();
}
}
}
}
| false | true | public static void main(String[] args)
{
if (args.length == 0)
{
System.err.println("Please pass the name of a file as parameter.");
System.err.println("e.g. java org.apache.commons.vfs2.example.ShowProperties LICENSE.txt");
return;
}
for (String arg : args) {
try
{
FileSystemManager mgr = VFS.getManager();
System.out.println();
System.out.println("Parsing: " + arg);
FileObject file = mgr.resolveFile(arg);
System.out.println("URL: " + file.getURL());
System.out.println("getName(): " + file.getName());
System.out.println("BaseName: " + file.getName().getBaseName());
System.out.println("Extension: " + file.getName().getExtension());
System.out.println("Path: " + file.getName().getPath());
System.out.println("Scheme: " + file.getName().getScheme());
System.out.println("URI: " + file.getName().getURI());
System.out.println("Root URI: " + file.getName().getRootURI());
System.out.println("Parent: " + file.getName().getParent());
System.out.println("Type: " + file.getType());
System.out.println("Exists: " + file.exists());
System.out.println("Readable: " + file.isReadable());
System.out.println("Writeable: " + file.isWriteable());
System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
if (file.exists())
{
if (file.getType().equals(FileType.FILE))
{
System.out.println("Size: " + file.getContent().getSize() + " bytes");
}
else if (file.getType().equals(FileType.FOLDER) && file.isReadable())
{
FileObject[] children = file.getChildren();
System.out.println("Directory with " + children.length + " files");
for (int iterChildren = 0; iterChildren < children.length; iterChildren++)
{
System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
if (iterChildren > 5)
{
break;
}
}
}
System.out.println("Last modified: " + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())));
}
else
{
System.out.println("The file does not exist");
}
file.close();
}
catch (FileSystemException ex)
{
ex.printStackTrace();
}
}
}
| public static void main(String[] args)
{
if (args.length == 0)
{
System.err.println("Please pass the name of a file as parameter.");
System.err.println("e.g. java org.apache.commons.vfs2.example.ShowProperties LICENSE.txt");
return;
}
for (String arg : args)
{
try
{
FileSystemManager mgr = VFS.getManager();
System.out.println();
System.out.println("Parsing: " + arg);
FileObject file = mgr.resolveFile(arg);
System.out.println("URL: " + file.getURL());
System.out.println("getName(): " + file.getName());
System.out.println("BaseName: " + file.getName().getBaseName());
System.out.println("Extension: " + file.getName().getExtension());
System.out.println("Path: " + file.getName().getPath());
System.out.println("Scheme: " + file.getName().getScheme());
System.out.println("URI: " + file.getName().getURI());
System.out.println("Root URI: " + file.getName().getRootURI());
System.out.println("Parent: " + file.getName().getParent());
System.out.println("Type: " + file.getType());
System.out.println("Exists: " + file.exists());
System.out.println("Readable: " + file.isReadable());
System.out.println("Writeable: " + file.isWriteable());
System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
if (file.exists())
{
if (file.getType().equals(FileType.FILE))
{
System.out.println("Size: " + file.getContent().getSize() + " bytes");
}
else if (file.getType().equals(FileType.FOLDER) && file.isReadable())
{
FileObject[] children = file.getChildren();
System.out.println("Directory with " + children.length + " files");
for (int iterChildren = 0; iterChildren < children.length; iterChildren++)
{
System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
if (iterChildren > 5)
{
break;
}
}
}
System.out.println("Last modified: " + DateFormat.getInstance().format(
new Date(file.getContent().getLastModifiedTime())));
}
else
{
System.out.println("The file does not exist");
}
file.close();
}
catch (FileSystemException ex)
{
ex.printStackTrace();
}
}
}
|
diff --git a/marytts-builder/src/main/java/marytts/tools/dbselection/SimpleCoverageComputer.java b/marytts-builder/src/main/java/marytts/tools/dbselection/SimpleCoverageComputer.java
index 0b217fa6c..093abde79 100644
--- a/marytts-builder/src/main/java/marytts/tools/dbselection/SimpleCoverageComputer.java
+++ b/marytts-builder/src/main/java/marytts/tools/dbselection/SimpleCoverageComputer.java
@@ -1,77 +1,78 @@
/**
* Copyright 2011 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* This file is part of MARY TTS.
*
* MARY TTS 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, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package marytts.tools.dbselection;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Locale;
import marytts.features.FeatureDefinition;
import marytts.features.FeatureRegistry;
import marytts.util.MaryUtils;
/**
* This class takes a text file containing one sentence per line, and computes the phone, diphone and prosody coverage of the corpus.
* @author marc
*
*/
public class SimpleCoverageComputer {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), "UTF-8"));
PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(args[1]), "UTF-8"));
Locale locale = MaryUtils.string2locale(args[2]);
String featureNames = "phone next_phone selection_prosody";
ArrayList<String> lines = new ArrayList<String>();
String line;
while ((line = in.readLine()) != null) {
+ if (line.trim().isEmpty()) continue;
lines.add(line);
}
System.out.println("Computing coverage features for "+lines.size()+" sentences from "+args[0]+"...");
byte[][] coverageFeatures = new byte[lines.size()][];
for (int i=0, max=lines.size(); i<max; i++) {
coverageFeatures[i] = CoverageUtils.sentenceToFeatures(lines.get(i), locale, featureNames, false);
if (i%10 == 0) {
System.out.print("\r"+i+"/"+max);
}
}
System.out.println();
System.out.println("Computing coverage...");
CoverageFeatureProvider cfProvider = new InMemoryCFProvider(coverageFeatures, null);
FeatureDefinition featDef = FeatureRegistry.getTargetFeatureComputer(locale, featureNames).getFeatureDefinition();
CoverageDefinition coverageDefinition = new CoverageDefinition(featDef, cfProvider, null);
coverageDefinition.initialiseCoverage();
coverageDefinition.printTextCorpusStatistics(out);
out.close();
System.out.println("done -- see "+args[1]+" for results.");
}
}
| true | true | public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), "UTF-8"));
PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(args[1]), "UTF-8"));
Locale locale = MaryUtils.string2locale(args[2]);
String featureNames = "phone next_phone selection_prosody";
ArrayList<String> lines = new ArrayList<String>();
String line;
while ((line = in.readLine()) != null) {
lines.add(line);
}
System.out.println("Computing coverage features for "+lines.size()+" sentences from "+args[0]+"...");
byte[][] coverageFeatures = new byte[lines.size()][];
for (int i=0, max=lines.size(); i<max; i++) {
coverageFeatures[i] = CoverageUtils.sentenceToFeatures(lines.get(i), locale, featureNames, false);
if (i%10 == 0) {
System.out.print("\r"+i+"/"+max);
}
}
System.out.println();
System.out.println("Computing coverage...");
CoverageFeatureProvider cfProvider = new InMemoryCFProvider(coverageFeatures, null);
FeatureDefinition featDef = FeatureRegistry.getTargetFeatureComputer(locale, featureNames).getFeatureDefinition();
CoverageDefinition coverageDefinition = new CoverageDefinition(featDef, cfProvider, null);
coverageDefinition.initialiseCoverage();
coverageDefinition.printTextCorpusStatistics(out);
out.close();
System.out.println("done -- see "+args[1]+" for results.");
}
| public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), "UTF-8"));
PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(args[1]), "UTF-8"));
Locale locale = MaryUtils.string2locale(args[2]);
String featureNames = "phone next_phone selection_prosody";
ArrayList<String> lines = new ArrayList<String>();
String line;
while ((line = in.readLine()) != null) {
if (line.trim().isEmpty()) continue;
lines.add(line);
}
System.out.println("Computing coverage features for "+lines.size()+" sentences from "+args[0]+"...");
byte[][] coverageFeatures = new byte[lines.size()][];
for (int i=0, max=lines.size(); i<max; i++) {
coverageFeatures[i] = CoverageUtils.sentenceToFeatures(lines.get(i), locale, featureNames, false);
if (i%10 == 0) {
System.out.print("\r"+i+"/"+max);
}
}
System.out.println();
System.out.println("Computing coverage...");
CoverageFeatureProvider cfProvider = new InMemoryCFProvider(coverageFeatures, null);
FeatureDefinition featDef = FeatureRegistry.getTargetFeatureComputer(locale, featureNames).getFeatureDefinition();
CoverageDefinition coverageDefinition = new CoverageDefinition(featDef, cfProvider, null);
coverageDefinition.initialiseCoverage();
coverageDefinition.printTextCorpusStatistics(out);
out.close();
System.out.println("done -- see "+args[1]+" for results.");
}
|
diff --git a/nexus/nexus-migration-tool/nexus-repository-conversion-tool/src/main/java/org/sonatype/nexus/tools/repository/RepositoryConvertorCli.java b/nexus/nexus-migration-tool/nexus-repository-conversion-tool/src/main/java/org/sonatype/nexus/tools/repository/RepositoryConvertorCli.java
index 4a80927e2..547c6ad52 100644
--- a/nexus/nexus-migration-tool/nexus-repository-conversion-tool/src/main/java/org/sonatype/nexus/tools/repository/RepositoryConvertorCli.java
+++ b/nexus/nexus-migration-tool/nexus-repository-conversion-tool/src/main/java/org/sonatype/nexus/tools/repository/RepositoryConvertorCli.java
@@ -1,138 +1,138 @@
/*
* Nexus: Maven Repository Manager
* Copyright (C) 2008 Sonatype Inc.
*
* This file is part of Nexus.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
package org.sonatype.nexus.tools.repository;
import java.io.File;
import java.io.IOException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.tools.cli.AbstractCli;
/**
* @author Juven Xu
*/
public class RepositoryConvertorCli
extends AbstractCli
{
// ----------------------------------------------------------------------------
// Options
// ----------------------------------------------------------------------------
public static final char REPO = 'r';
public static final char OUTPUT = 'o';
public static final char TYPE = 't';
public static void main( String[] args )
throws Exception
{
new RepositoryConvertorCli().execute( args );
}
@Override
@SuppressWarnings( "static-access" )
public Options buildCliOptions( Options options )
{
options.addOption( OptionBuilder.withLongOpt( "repository" ).hasArg().withDescription(
"The repository to be converted." ).isRequired().create( REPO ) );
options.addOption( OptionBuilder.withLongOpt( "output" ).hasArg().withDescription(
"where the converted repositoris locate." ).isRequired().create( OUTPUT ) );
options.addOption( OptionBuilder.withLongOpt( "type" ).hasArg().withDescription(
"Type of the convertion, copy or move." ).create( TYPE ) );
return options;
}
@Override
public void invokePlexusComponent( CommandLine cli, PlexusContainer container )
throws Exception
{
if ( cli.hasOption( REPO ) && cli.hasOption( OUTPUT ) )
{
convert( cli, container );
}
else
{
displayHelp();
}
}
private void convert( CommandLine cli, PlexusContainer plexus )
throws IOException,
ComponentLookupException
{
if ( cli.hasOption( DEBUG ) )
{
plexus.getLoggerManager().setThresholds( Logger.LEVEL_DEBUG );
}
File repository = new File( cli.getOptionValue( REPO ) );
if ( !repository.exists() || !repository.canRead() || !repository.isDirectory() )
{
System.err.printf( "Invalid options. Repository '" + repository.getCanonicalPath()
+ "' (the repository directory) must exists and be readable!" );
return;
}
File output = new File( cli.getOptionValue( OUTPUT ) );
if ( !output.exists() || !output.canWrite() || !output.isDirectory() )
{
System.err.printf( "Invalid options. Output '" + output.getCanonicalPath()
+ "' (where the output repositories locate) must exists and be writale!" );
return;
}
RepositoryConvertor repositoryConvertor = (RepositoryConvertor) plexus.lookup( RepositoryConvertor.class );
try
{
if ( cli.hasOption( TYPE ) && cli.getOptionValue( TYPE ).toLowerCase().equals( "move" ) )
{
repositoryConvertor.convertRepositoryWithMove( repository, output );
}
else
{
repositoryConvertor.convertRepositoryWithCopy( repository, output );
}
}
catch ( IOException ioe )
{
- System.err.println( "Repository convertion failed!" );
+ System.err.println( "Repository conversion failed!" );
ioe.printStackTrace();
}
- System.out.println( "Repository convertion is succeful!" );
+ System.out.println( "Repository conversion is successful!" );
}
}
| false | true | private void convert( CommandLine cli, PlexusContainer plexus )
throws IOException,
ComponentLookupException
{
if ( cli.hasOption( DEBUG ) )
{
plexus.getLoggerManager().setThresholds( Logger.LEVEL_DEBUG );
}
File repository = new File( cli.getOptionValue( REPO ) );
if ( !repository.exists() || !repository.canRead() || !repository.isDirectory() )
{
System.err.printf( "Invalid options. Repository '" + repository.getCanonicalPath()
+ "' (the repository directory) must exists and be readable!" );
return;
}
File output = new File( cli.getOptionValue( OUTPUT ) );
if ( !output.exists() || !output.canWrite() || !output.isDirectory() )
{
System.err.printf( "Invalid options. Output '" + output.getCanonicalPath()
+ "' (where the output repositories locate) must exists and be writale!" );
return;
}
RepositoryConvertor repositoryConvertor = (RepositoryConvertor) plexus.lookup( RepositoryConvertor.class );
try
{
if ( cli.hasOption( TYPE ) && cli.getOptionValue( TYPE ).toLowerCase().equals( "move" ) )
{
repositoryConvertor.convertRepositoryWithMove( repository, output );
}
else
{
repositoryConvertor.convertRepositoryWithCopy( repository, output );
}
}
catch ( IOException ioe )
{
System.err.println( "Repository convertion failed!" );
ioe.printStackTrace();
}
System.out.println( "Repository convertion is succeful!" );
}
| private void convert( CommandLine cli, PlexusContainer plexus )
throws IOException,
ComponentLookupException
{
if ( cli.hasOption( DEBUG ) )
{
plexus.getLoggerManager().setThresholds( Logger.LEVEL_DEBUG );
}
File repository = new File( cli.getOptionValue( REPO ) );
if ( !repository.exists() || !repository.canRead() || !repository.isDirectory() )
{
System.err.printf( "Invalid options. Repository '" + repository.getCanonicalPath()
+ "' (the repository directory) must exists and be readable!" );
return;
}
File output = new File( cli.getOptionValue( OUTPUT ) );
if ( !output.exists() || !output.canWrite() || !output.isDirectory() )
{
System.err.printf( "Invalid options. Output '" + output.getCanonicalPath()
+ "' (where the output repositories locate) must exists and be writale!" );
return;
}
RepositoryConvertor repositoryConvertor = (RepositoryConvertor) plexus.lookup( RepositoryConvertor.class );
try
{
if ( cli.hasOption( TYPE ) && cli.getOptionValue( TYPE ).toLowerCase().equals( "move" ) )
{
repositoryConvertor.convertRepositoryWithMove( repository, output );
}
else
{
repositoryConvertor.convertRepositoryWithCopy( repository, output );
}
}
catch ( IOException ioe )
{
System.err.println( "Repository conversion failed!" );
ioe.printStackTrace();
}
System.out.println( "Repository conversion is successful!" );
}
|
diff --git a/src/org/apache/xerces/parsers/DOMParser.java b/src/org/apache/xerces/parsers/DOMParser.java
index 3be40f651..9e00802ce 100644
--- a/src/org/apache/xerces/parsers/DOMParser.java
+++ b/src/org/apache/xerces/parsers/DOMParser.java
@@ -1,3164 +1,3177 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999,2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.parsers;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import org.apache.xerces.dom.TextImpl;
import org.apache.xerces.framework.XMLAttrList;
import org.apache.xerces.framework.XMLContentSpec;
import org.apache.xerces.framework.XMLDocumentHandler;
import org.apache.xerces.framework.XMLParser;
import org.apache.xerces.readers.XMLEntityHandler;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.validators.common.XMLAttributeDecl;
import org.apache.xerces.validators.common.XMLElementDecl;
import org.apache.xerces.validators.schema.XUtil;
import org.apache.xerces.dom.DeferredDocumentImpl;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.dom.DocumentTypeImpl;
import org.apache.xerces.dom.NodeImpl;
import org.apache.xerces.dom.EntityImpl;
import org.apache.xerces.dom.NotationImpl;
import org.apache.xerces.dom.ElementDefinitionImpl;
import org.apache.xerces.dom.AttrImpl;
import org.apache.xerces.dom.TextImpl;
import org.apache.xerces.dom.ElementImpl;
import org.apache.xerces.dom.EntityImpl;
import org.apache.xerces.dom.EntityReferenceImpl;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.Entity;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
/**
* DOMParser provides a parser which produces a W3C DOM tree as its output
*
*
* @version $Id$
*/
public class DOMParser
extends XMLParser
implements XMLDocumentHandler
{
//
// Constants
//
// public
/** Default programmatic document class name (org.apache.xerces.dom.DocumentImpl). */
public static final String DEFAULT_DOCUMENT_CLASS_NAME = "org.apache.xerces.dom.DocumentImpl";
/** Default deferred document class name (org.apache.xerces.dom.DeferredDocumentImpl). */
public static final String DEFAULT_DEFERRED_DOCUMENT_CLASS_NAME = "org.apache.xerces.dom.DeferredDocumentImpl";
// debugging
/** Set to true to debug attribute list declaration calls. */
private static final boolean DEBUG_ATTLIST_DECL = false;
// features and properties
/** Features recognized by this parser. */
private static final String RECOGNIZED_FEATURES[] = {
// SAX2 core features
// Xerces features
"http://apache.org/xml/features/dom/defer-node-expansion",
"http://apache.org/xml/features/dom/create-entity-ref-nodes",
"http://apache.org/xml/features/dom/include-ignorable-whitespace",
// Experimental features
"http://apache.org/xml/features/domx/grammar-access",
};
/** Properties recognized by this parser. */
private static final String RECOGNIZED_PROPERTIES[] = {
// SAX2 core properties
// Xerces properties
"http://apache.org/xml/properties/dom/document-class-name",
"http://apache.org/xml/properties/dom/current-element-node",
};
//
// Data
//
// common data
protected Document fDocument;
// deferred expansion data
protected DeferredDocumentImpl fDeferredDocumentImpl;
protected int fDocumentIndex;
protected int fDocumentTypeIndex;
protected int fCurrentNodeIndex;
// full expansion data
protected DocumentImpl fDocumentImpl;
protected DocumentType fDocumentType;
protected Node fCurrentElementNode;
// state
protected boolean fInDTD;
protected boolean fWithinElement;
protected boolean fInCDATA;
// features
private boolean fGrammarAccess;
// properties
// REVISIT: Even though these have setters and getters, should they
// be protected visibility? -Ac
private String fDocumentClassName;
private boolean fDeferNodeExpansion;
private boolean fCreateEntityReferenceNodes;
private boolean fIncludeIgnorableWhitespace;
// built-in entities
protected int fAmpIndex;
protected int fLtIndex;
protected int fGtIndex;
protected int fAposIndex;
protected int fQuotIndex;
private boolean fSeenRootElement;
private boolean fStringPoolInUse;
private XMLAttrList fAttrList;
//
// Constructors
//
/** Default constructor. */
public DOMParser() {
initHandlers(false, this, this);
// setup parser state
init();
// set default values
try {
setDocumentClassName(DEFAULT_DOCUMENT_CLASS_NAME);
setCreateEntityReferenceNodes(true);
setDeferNodeExpansion(true);
setIncludeIgnorableWhitespace(true);
} catch (SAXException e) {
throw new RuntimeException("PAR001 Fatal error constructing DOMParser.");
}
} // <init>()
//
// Public methods
//
// document
/** Returns the document. */
public Document getDocument() {
if (fDocumentImpl != null) {
fDocumentImpl.setErrorChecking(true);
}
return fDocument;
}
// features and properties
/**
* Returns a list of features that this parser recognizes.
* This method will never return null; if no features are
* recognized, this method will return a zero length array.
*
* @see #isFeatureRecognized
* @see #setFeature
* @see #getFeature
*/
public String[] getFeaturesRecognized() {
// get features that super/this recognizes
String superRecognized[] = super.getFeaturesRecognized();
String thisRecognized[] = RECOGNIZED_FEATURES;
// is one or the other the empty set?
int thisLength = thisRecognized.length;
if (thisLength == 0) {
return superRecognized;
}
int superLength = superRecognized.length;
if (superLength == 0) {
return thisRecognized;
}
// combine the two lists and return
String recognized[] = new String[superLength + thisLength];
System.arraycopy(superRecognized, 0, recognized, 0, superLength);
System.arraycopy(thisRecognized, 0, recognized, superLength, thisLength);
return recognized;
} // getFeaturesRecognized():String[]
/**
* Returns a list of properties that this parser recognizes.
* This method will never return null; if no properties are
* recognized, this method will return a zero length array.
*
* @see #isPropertyRecognized
* @see #setProperty
* @see #getProperty
*/
public String[] getPropertiesRecognized() {
// get properties that super/this recognizes
String superRecognized[] = super.getPropertiesRecognized();
String thisRecognized[] = RECOGNIZED_PROPERTIES;
// is one or the other the empty set?
int thisLength = thisRecognized.length;
if (thisLength == 0) {
return superRecognized;
}
int superLength = superRecognized.length;
if (superLength == 0) {
return thisRecognized;
}
// combine the two lists and return
String recognized[] = new String[superLength + thisLength];
System.arraycopy(superRecognized, 0, recognized, 0, superLength);
System.arraycopy(thisRecognized, 0, recognized, superLength, thisLength);
return recognized;
}
// resetting
/** Resets the parser. */
public void reset() throws Exception {
if (fStringPoolInUse) {
// we can't reuse the string pool, let's create another one
fStringPool = new StringPool();
fStringPoolInUse = false;
}
super.reset();
init();
}
/** Resets or copies the parser. */
public void resetOrCopy() throws Exception {
super.resetOrCopy();
init();
}
//
// Protected methods
//
// initialization
/**
* Initializes the parser to a pre-parse state. This method is
* called between calls to <code>parse()</code>.
*/
protected void init() {
// init common
fDocument = null;
// init deferred expansion
fDeferredDocumentImpl = null;
fDocumentIndex = -1;
fDocumentTypeIndex = -1;
fCurrentNodeIndex = -1;
// init full expansion
fDocumentImpl = null;
fDocumentType = null;
fCurrentElementNode = null;
// state
fInDTD = false;
fWithinElement = false;
fInCDATA = false;
// built-in entities
fAmpIndex = fStringPool.addSymbol("amp");
fLtIndex = fStringPool.addSymbol("lt");
fGtIndex = fStringPool.addSymbol("gt");
fAposIndex = fStringPool.addSymbol("apos");
fQuotIndex = fStringPool.addSymbol("quot");
fSeenRootElement = false;
fStringPoolInUse = false;
fAttrList = new XMLAttrList(fStringPool);
} // init()
// features
/**
* This method sets whether the expansion of the nodes in the default
* DOM implementation are deferred.
*
* @see #getDeferNodeExpansion
* @see #setDocumentClassName
*/
protected void setDeferNodeExpansion(boolean deferNodeExpansion)
throws SAXNotRecognizedException, SAXNotSupportedException {
fDeferNodeExpansion = deferNodeExpansion;
}
/**
* Returns true if the expansion of the nodes in the default DOM
* implementation are deferred.
*
* @see #setDeferNodeExpansion
*/
protected boolean getDeferNodeExpansion()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fDeferNodeExpansion;
}
/**
* This feature determines whether entity references within
* the document are included in the document tree as
* EntityReference nodes.
* <p>
* Note: The children of the entity reference are always
* added to the document. This feature only affects
* whether an EntityReference node is also included
* as the parent of the entity reference children.
*
* @param create True to create entity reference nodes; false
* to only insert the entity reference children.
*
* @see #getCreateEntityReferenceNodes
*/
protected void setCreateEntityReferenceNodes(boolean create)
throws SAXNotRecognizedException, SAXNotSupportedException {
fCreateEntityReferenceNodes = create;
}
/**
* Returns true if entity references within the document are
* included in the document tree as EntityReference nodes.
*
* @see #setCreateEntityReferenceNodes
*/
public boolean getCreateEntityReferenceNodes()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fCreateEntityReferenceNodes;
}
/**
* This feature determines whether text nodes that can be
* considered "ignorable whitespace" are included in the DOM
* tree.
* <p>
* Note: The only way that the parser can determine if text
* is ignorable is by reading the associated grammar
* and having a content model for the document. When
* ignorable whitespace text nodes *are* included in
* the DOM tree, they will be flagged as ignorable.
* The ignorable flag can be queried by calling the
* TextImpl#isIgnorableWhitespace():boolean method.
*
* @param include True to include ignorable whitespace text nodes;
* false to not include ignorable whitespace text
* nodes.
*
* @see #getIncludeIgnorableWhitespace
*/
public void setIncludeIgnorableWhitespace(boolean include)
throws SAXNotRecognizedException, SAXNotSupportedException {
fIncludeIgnorableWhitespace = include;
}
/**
* Returns true if ignorable whitespace text nodes are included
* in the DOM tree.
*
* @see #setIncludeIgnorableWhitespace
*/
public boolean getIncludeIgnorableWhitespace()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fIncludeIgnorableWhitespace;
}
// properties
/**
* This method allows the programmer to decide which document
* factory to use when constructing the DOM tree. However, doing
* so will lose the functionality of the default factory. Also,
* a document class other than the default will lose the ability
* to defer node expansion on the DOM tree produced.
*
* @param documentClassName The fully qualified class name of the
* document factory to use when constructing
* the DOM tree.
*
* @see #getDocumentClassName
* @see #setDeferNodeExpansion
* @see #DEFAULT_DOCUMENT_CLASS_NAME
*/
protected void setDocumentClassName(String documentClassName)
throws SAXNotRecognizedException, SAXNotSupportedException {
// normalize class name
if (documentClassName == null) {
documentClassName = DEFAULT_DOCUMENT_CLASS_NAME;
}
// verify that this class exists and is of the right type
try {
Class _class = Class.forName(documentClassName);
//if (!_class.isAssignableFrom(Document.class)) {
if (!Document.class.isAssignableFrom(_class)) {
throw new IllegalArgumentException("PAR002 Class, \""+documentClassName+"\", is not of type org.w3c.dom.Document."+"\n"+documentClassName);
}
}
catch (ClassNotFoundException e) {
throw new IllegalArgumentException("PAR003 Class, \""+documentClassName+"\", not found."+"\n"+documentClassName);
}
// set document class name
fDocumentClassName = documentClassName;
if (!documentClassName.equals(DEFAULT_DOCUMENT_CLASS_NAME)) {
setDeferNodeExpansion(false);
}
} // setDocumentClassName(String)
/**
* Returns the fully qualified class name of the document factory
* used when constructing the DOM tree.
*
* @see #setDocumentClassName
*/
protected String getDocumentClassName()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fDocumentClassName;
}
/**
* Returns the current element node.
* <p>
* Note: This method is not supported when the "deferNodeExpansion"
* property is set to true and the document factory is set to
* the default factory.
*/
protected Element getCurrentElementNode()
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fCurrentElementNode != null &&
fCurrentElementNode.getNodeType() == Node.ELEMENT_NODE) {
return (Element)fCurrentElementNode;
}
return null;
} // getCurrentElementNode():Element
//
// Configurable methods
//
/**
* Set the state of any feature in a SAX2 parser. The parser
* might not recognize the feature, and if it does recognize
* it, it might not be able to fulfill the request.
*
* @param featureId The unique identifier (URI) of the feature.
* @param state The requested state of the feature (true or false).
*
* @exception SAXNotRecognizedException If the requested feature is
* not known.
* @exception SAXNotSupportedException If the requested feature is
* known, but the requested state
* is not supported.
*/
public void setFeature(String featureId, boolean state)
throws SAXNotRecognizedException, SAXNotSupportedException {
//
// SAX2 core features
//
if (featureId.startsWith(SAX2_FEATURES_PREFIX)) {
//
// No additional SAX properties defined for DOMParser.
// Pass request off to XMLParser for the common cases.
//
}
//
// Xerces features
//
else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) {
String feature = featureId.substring(XERCES_FEATURES_PREFIX.length());
//
// http://apache.org/xml/features/dom/defer-node-expansion
// Allows the document tree returned by getDocument()
// to be constructed lazily. In other words, the DOM
// nodes are constructed as the tree is traversed.
// This allows the document to be returned sooner with
// the expense of holding all of the blocks of character
// data held in memory. Then again, lots of DOM nodes
// use a lot of memory as well.
//
if (feature.equals("dom/defer-node-expansion")) {
if (fParseInProgress) {
throw new SAXNotSupportedException("PAR004 Cannot setFeature("+featureId + "): parse is in progress."+"\n"+featureId);
}
setDeferNodeExpansion(state);
return;
}
//
// http://apache.org/xml/features/dom/create-entity-ref-nodes
// This feature determines whether entity references within
// the document are included in the document tree as
// EntityReference nodes.
// Note: The children of the entity reference are always
// added to the document. This feature only affects
// whether an EntityReference node is also included
// as the parent of the entity reference children.
//
if (feature.equals("dom/create-entity-ref-nodes")) {
setCreateEntityReferenceNodes(state);
return;
}
//
// http://apache.org/xml/features/dom/include-ignorable-whitespace
// This feature determines whether text nodes that can be
// considered "ignorable whitespace" are included in the DOM
// tree.
// Note: The only way that the parser can determine if text
// is ignorable is by reading the associated grammar
// and having a content model for the document. When
// ignorable whitespace text nodes *are* included in
// the DOM tree, they will be flagged as ignorable.
// The ignorable flag can be queried by calling the
// TextImpl#isIgnorableWhitespace():boolean method.
//
if (feature.equals("dom/include-ignorable-whitespace")) {
setIncludeIgnorableWhitespace(state);
return;
}
//
// Experimental features
//
//
// http://apache.org/xml/features/domx/grammar-access
// Allows grammar access in the DOM tree. Currently, this
// means that there is an XML Schema document tree as a
// child of the Doctype node.
//
if (feature.equals("domx/grammar-access")) {
fGrammarAccess = state;
return;
}
//
// Pass request off to XMLParser for the common cases.
//
}
//
// Pass request off to XMLParser for the common cases.
//
super.setFeature(featureId, state);
} // setFeature(String,boolean)
/**
* Query the current state of any feature in a SAX2 parser. The
* parser might not recognize the feature.
*
* @param featureId The unique identifier (URI) of the feature
* being set.
*
* @return The current state of the feature.
*
* @exception SAXNotRecognizedException If the requested feature is
* not known.
*/
public boolean getFeature(String featureId)
throws SAXNotRecognizedException, SAXNotSupportedException {
//
// SAX2 core features
//
if (featureId.startsWith(SAX2_FEATURES_PREFIX)) {
//
// No additional SAX properties defined for DOMParser.
// Pass request off to XMLParser for the common cases.
//
}
//
// Xerces features
//
else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) {
String feature = featureId.substring(XERCES_FEATURES_PREFIX.length());
//
// http://apache.org/xml/features/dom/defer-node-expansion
// Allows the document tree returned by getDocument()
// to be constructed lazily. In other words, the DOM
// nodes are constructed as the tree is traversed.
// This allows the document to be returned sooner with
// the expense of holding all of the blocks of character
// data held in memory. Then again, lots of DOM nodes
// use a lot of memory as well.
//
if (feature.equals("dom/defer-node-expansion")) {
return getDeferNodeExpansion();
}
//
// http://apache.org/xml/features/dom/create-entity-ref-nodes
// This feature determines whether entity references within
// the document are included in the document tree as
// EntityReference nodes.
// Note: The children of the entity reference are always
// added to the document. This feature only affects
// whether an EntityReference node is also included
// as the parent of the entity reference children.
//
else if (feature.equals("dom/create-entity-ref-nodes")) {
return getCreateEntityReferenceNodes();
}
//
// http://apache.org/xml/features/dom/include-ignorable-whitespace
// This feature determines whether text nodes that can be
// considered "ignorable whitespace" are included in the DOM
// tree.
// Note: The only way that the parser can determine if text
// is ignorable is by reading the associated grammar
// and having a content model for the document. When
// ignorable whitespace text nodes *are* included in
// the DOM tree, they will be flagged as ignorable.
// The ignorable flag can be queried by calling the
// TextImpl#isIgnorableWhitespace():boolean method.
//
if (feature.equals("dom/include-ignorable-whitespace")) {
return getIncludeIgnorableWhitespace();
}
//
// Experimental features
//
//
// http://apache.org/xml/features/domx/grammar-access
// Allows grammar access in the DOM tree. Currently, this
// means that there is an XML Schema document tree as a
// child of the Doctype node.
//
if (feature.equals("domx/grammar-access")) {
return fGrammarAccess;
}
//
// Pass request off to XMLParser for the common cases.
//
}
//
// Pass request off to XMLParser for the common cases.
//
return super.getFeature(featureId);
} // getFeature(String):boolean
/**
* Set the value of any property in a SAX2 parser. The parser
* might not recognize the property, and if it does recognize
* it, it might not support the requested value.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
* @param Object The value to which the property is being set.
*
* @exception SAXNotRecognizedException If the requested property is
* not known.
* @exception SAXNotSupportedException If the requested property is
* known, but the requested
* value is not supported.
*/
public void setProperty(String propertyId, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException {
//
// Xerces properties
//
if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) {
String property = propertyId.substring(XERCES_PROPERTIES_PREFIX.length());
//
// http://apache.org/xml/properties/dom/current-element-node
// Returns the current element node as the DOM Parser is
// parsing. This property is useful for determining the
// relative location of the document when an error is
// encountered. Note that this feature does *not* work
// when the http://apache.org/xml/features/dom/defer-node-expansion
// is set to true.
//
if (property.equals("dom/current-element-node")) {
throw new SAXNotSupportedException("PAR005 Property, \""+propertyId+"\" is read-only.\n"+propertyId);
}
//
// http://apache.org/xml/properties/dom/document-class-name
// This property can be used to set/query the name of the
// document factory.
//
else if (property.equals("dom/document-class-name")) {
if (value != null && !(value instanceof String)) {
throw new SAXNotSupportedException("PAR006 Property value must be of type java.lang.String.");
}
setDocumentClassName((String)value);
return;
}
}
//
// Pass request off to XMLParser for the common cases.
//
super.setProperty(propertyId, value);
} // setProperty(String,Object)
/**
* Return the current value of a property in a SAX2 parser.
* The parser might not recognize the property.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
*
* @return The current value of the property.
*
* @exception SAXNotRecognizedException If the requested property is
* not known.
*
* @see Configurable#getProperty
*/
public Object getProperty(String propertyId)
throws SAXNotRecognizedException, SAXNotSupportedException {
//
// Xerces properties
//
if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) {
String property = propertyId.substring(XERCES_PROPERTIES_PREFIX.length());
//
// http://apache.org/xml/properties/dom/current-element-node
// Returns the current element node as the DOM Parser is
// parsing. This property is useful for determining the
// relative location of the document when an error is
// encountered. Note that this feature does *not* work
// when the http://apache.org/xml/features/dom/defer-node-expansion
// is set to true.
//
if (property.equals("dom/current-element-node")) {
boolean throwException = false;
try {
throwException = getFeature(XERCES_FEATURES_PREFIX+"dom/defer-node-expansion");
}
catch (SAXNotSupportedException e) {
// ignore
}
catch (SAXNotRecognizedException e) {
// ignore
}
if (throwException) {
throw new SAXNotSupportedException("PAR007 Current element node cannot be queried when node expansion is deferred.");
}
return getCurrentElementNode();
}
//
// http://apache.org/xml/properties/dom/document-class-name
// This property can be used to set/query the name of the
// document factory.
//
else if (property.equals("dom/document-class-name")) {
return getDocumentClassName();
}
}
//
// Pass request off to XMLParser for the common cases.
//
return super.getProperty(propertyId);
} // getProperty(String):Object
//
// XMLParser methods
//
/** Start document. */
public void startDocument() {
// deferred expansion
String documentClassName = null;
try {
documentClassName = getDocumentClassName();
} catch (SAXException e) {
throw new RuntimeException("PAR008 Fatal error getting document factory.");
}
boolean deferNodeExpansion = true;
try {
deferNodeExpansion = getDeferNodeExpansion();
} catch (SAXException e) {
throw new RuntimeException("PAR009 Fatal error reading expansion mode.");
}
try {
boolean isDocumentImpl = fDocumentClassName.equals(DEFAULT_DOCUMENT_CLASS_NAME);
boolean isDeferredImpl = fDocumentClassName.equals(DEFAULT_DEFERRED_DOCUMENT_CLASS_NAME);
if (deferNodeExpansion && (isDocumentImpl || isDeferredImpl)) {
boolean nsEnabled = false;
try { nsEnabled = getNamespaces(); }
catch (SAXException s) {}
fDeferredDocumentImpl = new DeferredDocumentImpl(fStringPool, nsEnabled, fGrammarAccess);
fStringPoolInUse = true;
fDocument = fDeferredDocumentImpl;
fDocumentIndex = fDeferredDocumentImpl.createDocument();
fCurrentNodeIndex = fDocumentIndex;
}
// full expansion
else {
Class docClass = Class.forName(documentClassName);
Class defaultDocClass = Class.forName(DEFAULT_DOCUMENT_CLASS_NAME);
if (isDocumentImpl) {
fDocument = new DocumentImpl(fGrammarAccess);
}
else {
try {
Class documentClass = Class.forName(documentClassName);
fDocument = (Document)documentClass.newInstance();
}
catch (Exception e) {
// REVISIT: We've already checked the type of the factory
// in the setDocumentClassName() method. The only
// exception that can occur here is if the class
// doesn't have a zero-arg constructor. -Ac
}
}
if (docClass.isAssignableFrom(defaultDocClass)) {
fDocumentImpl = (DocumentImpl)fDocument;
fDocumentImpl.setErrorChecking(false);
}
fCurrentElementNode = fDocument;
}
}
catch (ClassNotFoundException e) {
// REVISIT: Localize this message.
throw new RuntimeException(documentClassName);
}
} // startDocument()
/** End document. */
public void endDocument() throws Exception {}
/** XML declaration. */
public void xmlDecl(int versionIndex, int encodingIndex, int standaloneIndex) throws Exception {
// release strings
fStringPool.releaseString(versionIndex);
fStringPool.releaseString(encodingIndex);
fStringPool.releaseString(standaloneIndex);
}
/** Text declaration. */
public void textDecl(int versionIndex, int encodingIndex) throws Exception {
// release strings
fStringPool.releaseString(versionIndex);
fStringPool.releaseString(encodingIndex);
}
/** Report the start of the scope of a namespace declaration. */
public void startNamespaceDeclScope(int prefix, int uri) throws Exception {}
/** Report the end of the scope of a namespace declaration. */
public void endNamespaceDeclScope(int prefix) throws Exception {}
/** Start element. */
public void startElement(QName elementQName,
XMLAttrList xmlAttrList, int attrListIndex)
throws Exception {
// deferred expansion
if (fDeferredDocumentImpl != null) {
int element =
fDeferredDocumentImpl.createElement(elementQName.rawname,
elementQName.uri,
xmlAttrList,
attrListIndex);
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, element);
fCurrentNodeIndex = element;
fWithinElement = true;
// identifier registration
int index = xmlAttrList.getFirstAttr(attrListIndex);
while (index != -1) {
if (xmlAttrList.getAttType(index) == fStringPool.addSymbol("ID")) {
int nameIndex = xmlAttrList.getAttValue(index);
fDeferredDocumentImpl.putIdentifier(nameIndex, element);
}
index = xmlAttrList.getNextAttr(index);
}
// copy schema grammar, if needed
if (!fSeenRootElement) {
fSeenRootElement = true;
if (fDocumentTypeIndex == -1) {
fDocumentTypeIndex = fDeferredDocumentImpl.createDocumentType(elementQName.rawname, -1, -1);
fDeferredDocumentImpl.appendChild(0, fDocumentTypeIndex);
}
if (fGrammarAccess) {
// REVISIT: How do we know which grammar is in use?
//Document schemaDocument = fValidator.getSchemaDocument();
int size = fGrammarResolver.size();
if (size > 0) {
Enumeration schemas = fGrammarResolver.nameSpaceKeys();
Document schemaDocument = fGrammarResolver.getGrammar((String)schemas.nextElement()).getGrammarDocument();
if (schemaDocument != null) {
Element schema = schemaDocument.getDocumentElement();
copyInto(schema, fDocumentTypeIndex);
}
}
}
}
}
// full expansion
else {
boolean nsEnabled = false;
try { nsEnabled = getNamespaces(); }
catch (SAXException s) {}
String elementName = fStringPool.toString(elementQName.rawname);
Element e;
if (nsEnabled) {
e = fDocument.createElementNS(
// REVISIT: Make sure uri is filled in by caller.
fStringPool.toString(elementQName.uri),
fStringPool.toString(elementQName.localpart)
);
} else {
e = fDocument.createElement(elementName);
}
int attrHandle = xmlAttrList.getFirstAttr(attrListIndex);
while (attrHandle != -1) {
int attName = xmlAttrList.getAttrName(attrHandle);
String attrName = fStringPool.toString(attName);
String attrValue =
fStringPool.toString(xmlAttrList.getAttValue(attrHandle));
if (nsEnabled) {
int nsURIIndex = xmlAttrList.getAttrURI(attrHandle);
String namespaceURI = fStringPool.toString(nsURIIndex);
// DOM Level 2 wants all namespace declaration attributes
// to be bound to "http://www.w3.org/2000/xmlns/"
// So as long as the XML parser doesn't do it, it needs to
// done here.
int prefixIndex = xmlAttrList.getAttrPrefix(attrHandle);
String prefix = fStringPool.toString(prefixIndex);
if (namespaceURI == null) {
if (prefix != null) {
if (prefix.equals("xmlns")) {
namespaceURI = "http://www.w3.org/2000/xmlns/";
}
} else if (attrName.equals("xmlns")) {
namespaceURI = "http://www.w3.org/2000/xmlns/";
}
}
e.setAttributeNS(namespaceURI, attrName, attrValue);
} else {
e.setAttribute(attrName, attrValue);
}
if (!xmlAttrList.isSpecified(attrHandle)) {
((AttrImpl)e.getAttributeNode(attrName))
.setSpecified(false);
}
attrHandle = xmlAttrList.getNextAttr(attrHandle);
}
fCurrentElementNode.appendChild(e);
fCurrentElementNode = e;
fWithinElement = true;
// identifier registration
if (fDocumentImpl != null) {
int index = xmlAttrList.getFirstAttr(attrListIndex);
while (index != -1) {
if (xmlAttrList.getAttType(index) == fStringPool.addSymbol("ID")) {
String name = fStringPool.toString(xmlAttrList.getAttValue(index));
fDocumentImpl.putIdentifier(name, e);
}
index = xmlAttrList.getNextAttr(index);
}
}
xmlAttrList.releaseAttrList(attrListIndex);
// copy schema grammar, if needed
if (!fSeenRootElement) {
fSeenRootElement = true;
if (fDocumentImpl != null
&& fGrammarAccess && fGrammarResolver.size() > 0) {
if (fDocumentType == null) {
String rootName = elementName;
String systemId = ""; // REVISIT: How do we get this value? -Ac
String publicId = ""; // REVISIT: How do we get this value? -Ac
fDocumentType = fDocumentImpl.createDocumentType(rootName, publicId, systemId);
fDocument.appendChild(fDocumentType);
// REVISIT: We could use introspection to get the
// DOMImplementation#createDocumentType method
// for DOM Level 2 implementations. The only
// problem is that the owner document for the
// node created is null. How does it get set
// for document when appended? A cursory look
// at the DOM Level 2 CR didn't yield any
// information. -Ac
}
Enumeration schemas = fGrammarResolver.nameSpaceKeys();
Document schemaDocument = fGrammarResolver.getGrammar((String)schemas.nextElement()).getGrammarDocument();
if (schemaDocument != null) {
Element schema = schemaDocument.getDocumentElement();
XUtil.copyInto(schema, fDocumentType);
}
}
}
}
} // startElement(QName,XMLAttrList,int)
/** End element. */
public void endElement(QName elementQName)
throws Exception {
// deferred node expansion
if (fDeferredDocumentImpl != null) {
fCurrentNodeIndex = fDeferredDocumentImpl.getParentNode(fCurrentNodeIndex, false);
fWithinElement = false;
}
// full node expansion
else {
fCurrentElementNode = fCurrentElementNode.getParentNode();
fWithinElement = false;
}
} // endElement(QName)
/** Characters. */
public void characters(int dataIndex)
throws Exception {
// deferred node expansion
if (fDeferredDocumentImpl != null) {
int text;
if (fInCDATA) {
text = fDeferredDocumentImpl.createCDATASection(dataIndex, false);
} else {
// The Text normalization is taken care of within the Text Node
// in the DEFERRED case.
text = fDeferredDocumentImpl.createTextNode(dataIndex, false);
}
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, text);
}
// full node expansion
else {
Text text;
if (fInCDATA) {
text = fDocument.createCDATASection(fStringPool.orphanString(dataIndex));
}
else {
if (fWithinElement && fCurrentElementNode.getNodeType() == Node.ELEMENT_NODE) {
Node lastChild = fCurrentElementNode.getLastChild();
if (lastChild != null
&& lastChild.getNodeType() == Node.TEXT_NODE) {
// Normalization of Text Nodes - append rather than create.
((Text)lastChild).appendData(fStringPool.orphanString(dataIndex));
return;
}
}
text = fDocument.createTextNode(fStringPool.orphanString(dataIndex));
}
fCurrentElementNode.appendChild(text);
}
} // characters(int)
/** Ignorable whitespace. */
public void ignorableWhitespace(int dataIndex) throws Exception {
// ignore the whitespace
if (!fIncludeIgnorableWhitespace) {
fStringPool.orphanString(dataIndex);
return;
}
// deferred node expansion
if (fDeferredDocumentImpl != null) {
int text;
if (fInCDATA) {
text = fDeferredDocumentImpl.createCDATASection(dataIndex, true);
} else {
// The Text normalization is taken care of within the Text Node
// in the DEFERRED case.
text = fDeferredDocumentImpl.createTextNode(dataIndex, true);
}
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, text);
}
// full node expansion
else {
Text text;
if (fInCDATA) {
text = fDocument.createCDATASection(fStringPool.orphanString(dataIndex));
}
else {
if (fWithinElement && fCurrentElementNode.getNodeType() == Node.ELEMENT_NODE) {
Node lastChild = fCurrentElementNode.getLastChild();
if (lastChild != null
&& lastChild.getNodeType() == Node.TEXT_NODE) {
// Normalization of Text Nodes - append rather than create.
((Text)lastChild).appendData(fStringPool.orphanString(dataIndex));
return;
}
}
text = fDocument.createTextNode(fStringPool.orphanString(dataIndex));
}
if (fDocumentImpl != null) {
((TextImpl)text).setIgnorableWhitespace(true);
}
fCurrentElementNode.appendChild(text);
}
} // ignorableWhitespace(int)
/** Processing instruction. */
public void processingInstruction(int targetIndex, int dataIndex)
throws Exception {
// deferred node expansion
if (fDeferredDocumentImpl != null) {
int pi = fDeferredDocumentImpl.createProcessingInstruction(targetIndex, dataIndex);
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, pi);
}
// full node expansion
else {
String target = fStringPool.orphanString(targetIndex);
String data = fStringPool.orphanString(dataIndex);
ProcessingInstruction pi = fDocument.createProcessingInstruction(target, data);
fCurrentElementNode.appendChild(pi);
}
} // processingInstruction(int,int)
/** Comment. */
public void comment(int dataIndex) throws Exception {
if (fInDTD && !fGrammarAccess) {
fStringPool.orphanString(dataIndex);
}
else {
// deferred node expansion
if (fDeferredDocumentImpl != null) {
int comment = fDeferredDocumentImpl.createComment(dataIndex);
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, comment);
}
// full node expansion
else {
Comment comment = fDocument.createComment(fStringPool.orphanString(dataIndex));
fCurrentElementNode.appendChild(comment);
}
}
} // comment(int)
/** Not called. */
public void characters(char ch[], int start, int length) throws Exception {}
/** Not called. */
public void ignorableWhitespace(char ch[], int start, int length) throws Exception {}
//
// XMLDocumentScanner methods
//
/** Start CDATA section. */
public void startCDATA() throws Exception {
fInCDATA = true;
}
/** End CDATA section. */
public void endCDATA() throws Exception {
fInCDATA = false;
}
//
// XMLEntityHandler methods
//
/** Start entity reference. */
public void startEntityReference(int entityName, int entityType,
int entityContext) throws Exception {
// are we ignoring entity reference nodes?
if (!fCreateEntityReferenceNodes) {
return;
}
// ignore built-in entities
if (entityName == fAmpIndex ||
entityName == fGtIndex ||
entityName == fLtIndex ||
entityName == fAposIndex ||
entityName == fQuotIndex) {
return;
}
// we only support one context for entity references right now...
if (entityContext != XMLEntityHandler.ENTITYREF_IN_CONTENT) {
return;
}
// deferred node expansion
if (fDeferredDocumentImpl != null) {
int entityRefIndex = fDeferredDocumentImpl.createEntityReference(entityName);
fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, entityRefIndex);
fCurrentNodeIndex = entityRefIndex;
}
// full node expansion
else {
EntityReference er =
fDocument.createEntityReference(fStringPool.toString(entityName));
fCurrentElementNode.appendChild(er);
fCurrentElementNode = er;
try {
EntityReferenceImpl xer = (EntityReferenceImpl) er;
xer.setReadOnly(false, false);
} catch (Exception e) {
// we aren't building against Xerces - do nothing
}
}
} // startEntityReference(int,int,int)
/** End entity reference. */
public void endEntityReference(int entityName, int entityType,
int entityContext) throws Exception {
// are we ignoring entity reference nodes?
if (!fCreateEntityReferenceNodes) {
return;
}
// ignore built-in entities
if (entityName == fAmpIndex ||
entityName == fGtIndex ||
entityName == fLtIndex ||
entityName == fAposIndex ||
entityName == fQuotIndex) {
return;
}
// we only support one context for entity references right now...
if (entityContext != XMLEntityHandler.ENTITYREF_IN_CONTENT) {
return;
}
// deferred node expansion
if (fDeferredDocumentImpl != null) {
String name = fStringPool.toString(entityName);
int erChild = fCurrentNodeIndex;
fCurrentNodeIndex = fDeferredDocumentImpl.getParentNode(erChild, false);
// should never be true - we should not return here.
if (fDeferredDocumentImpl.getNodeType(erChild, false) != Node.ENTITY_REFERENCE_NODE) return;
erChild = fDeferredDocumentImpl.getLastChild(erChild, false); // first Child of EntityReference
if (fDocumentTypeIndex != -1) {
// find Entity decl for this EntityReference.
int entityDecl = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false);
while (entityDecl != -1) {
if (fDeferredDocumentImpl.getNodeType(entityDecl, false) == Node.ENTITY_NODE
&& fDeferredDocumentImpl.getNodeNameString(entityDecl, false).equals(name)) // string compare...
{
break;
}
entityDecl = fDeferredDocumentImpl.getPrevSibling(entityDecl, false);
}
if (entityDecl != -1
&& fDeferredDocumentImpl.getLastChild(entityDecl, false) == -1) {
// found entityDecl with same name as this reference
// AND it doesn't have any children.
// we don't need to iterate, because the whole structure
// should already be connected to the 1st child.
fDeferredDocumentImpl.setAsLastChild(entityDecl, erChild);
}
}
}
// full node expansion
else {
Node erNode = fCurrentElementNode;//fCurrentElementNode.getParentNode();
fCurrentElementNode = erNode.getParentNode();
try {
EntityReferenceImpl xer = (EntityReferenceImpl) erNode;
xer.setReadOnly(false, false);
// if necessary populate the related entity now
if (fDocumentImpl != null) {
NamedNodeMap entities = fDocumentType.getEntities();
String name = fStringPool.toString(entityName);
Node entityNode = entities.getNamedItem(name);
// We could simply return here if there is no entity for
// the reference or if the entity is already populated.
if (entityNode == null || entityNode.hasChildNodes()) {
return;
}
EntityImpl entity = (EntityImpl) entityNode;
entity.setReadOnly(false, false);
for (Node child = erNode.getFirstChild();
child != null;
child = child.getNextSibling()) {
Node childClone = child.cloneNode(true);
entity.appendChild(childClone);
}
entity.setReadOnly(true, true);
}
} catch (Exception e) {
// we aren't building against Xerces - do nothing
}
}
} // endEntityReference(int,int,int)
//
// DTDValidator.EventHandler methods
//
/**
* This function will be called when a <!DOCTYPE...> declaration is
* encountered.
*/
public void startDTD(QName rootElement, int publicId, int systemId)
throws Exception {
fInDTD = true;
// full expansion
if (fDocumentImpl != null) {
String rootElementName = fStringPool.toString(rootElement.rawname);
String publicString = fStringPool.toString(publicId);
String systemString = fStringPool.toString(systemId);
fDocumentType = fDocumentImpl.
createDocumentType(rootElementName, publicString, systemString);
fDocumentImpl.appendChild(fDocumentType);
if (fGrammarAccess) {
Element schema = fDocument.createElement("schema");
// REVISIT: What should the namespace be? -Ac
schema.setAttribute("xmlns", "http://www.w3.org/1999/XMLSchema");
((AttrImpl)schema.getAttributeNode("xmlns")).setSpecified(false);
schema.setAttribute("finalDefault", "");
((AttrImpl)schema.getAttributeNode("finalDefault")).setSpecified(false);
schema.setAttribute("exactDefault", "");
((AttrImpl)schema.getAttributeNode("exactDefault")).setSpecified(false);
fDocumentType.appendChild(schema);
fCurrentElementNode = schema;
}
}
// deferred expansion
else if (fDeferredDocumentImpl != null) {
fDocumentTypeIndex =
fDeferredDocumentImpl.
createDocumentType(rootElement.rawname, publicId, systemId);
fDeferredDocumentImpl.appendChild(fDocumentIndex, fDocumentTypeIndex);
if (fGrammarAccess) {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("xmlns"),
fStringPool.addString("http://www.w3.org/1999/XMLSchema"),
fStringPool.addSymbol("CDATA"),
false,
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("finalDefault"),
fStringPool.addString(""),
fStringPool.addSymbol("CDATA"),
false,
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("exactDefault"),
fStringPool.addString(""),
fStringPool.addSymbol("CDATA"),
false,
false); // search
fAttrList.endAttrList();
int schemaIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("schema"), fAttrList, handle);
// REVISIT: What should the namespace be? -Ac
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, schemaIndex);
fCurrentNodeIndex = schemaIndex;
}
}
} // startDTD(int,int,int)
/**
* Supports DOM Level 2 internalSubset additions.
* Called when the internal subset is completely scanned.
*/
public void internalSubset(int internalSubset) {
//System.out.println("internalSubset callback:"+fStringPool.toString(internalSubset));
// full expansion
if (fDocumentImpl != null && fDocumentType != null) {
((DocumentTypeImpl)fDocumentType).setInternalSubset(fStringPool.toString(internalSubset));
}
// deferred expansion
else if (fDeferredDocumentImpl != null) {
fDeferredDocumentImpl.setInternalSubset(fDocumentTypeIndex, internalSubset);
}
}
/**
* This function will be called at the end of the DTD.
*/
public void endDTD() throws Exception {
fInDTD = false;
if (fGrammarAccess) {
if (fDocumentImpl != null) {
fCurrentElementNode = fDocumentImpl;
}
else if (fDeferredDocumentImpl != null) {
fCurrentNodeIndex = 0;
}
}
} // endDTD()
/**
* <!ELEMENT Name contentspec>
*/
public void elementDecl(QName elementDecl,
int contentSpecType,
int contentSpecIndex,
XMLContentSpec.Provider contentSpecProvider) throws Exception {
if (DEBUG_ATTLIST_DECL) {
String contentModel = XMLContentSpec.toString(contentSpecProvider, fStringPool, contentSpecIndex);
System.out.println("elementDecl(" + fStringPool.toString(elementDecl.rawname) + ", " +
contentModel + ")");
}
//
// Create element declaration
//
if (fGrammarAccess) {
if (fDeferredDocumentImpl != null) {
//
// Build element
//
// get element declaration; create if necessary
int schemaIndex = getLastChildElement(fDocumentTypeIndex, "schema");
String elementName = fStringPool.toString(elementDecl.rawname);
int elementIndex = getLastChildElement(schemaIndex, "element", "name", elementName);
if (elementIndex == -1) {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("name"),
fStringPool.addString(elementName),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("minOccurs"), // name
fStringPool.addString("1"), // value
fStringPool.addSymbol("NMTOKEN"), // type
false, // specified
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("nullable"), // name
fStringPool.addString("false"), // value
fStringPool.addSymbol("ENUMERATION"), // type
false, // specified
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("abstract"), // name
fStringPool.addString("false"), // value
fStringPool.addSymbol("ENUMERATION"), // type
false, // specified
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("final"), // name
fStringPool.addString("false"), // value
fStringPool.addSymbol("ENUMERATION"), // type
false, // specified
false); // search
fAttrList.endAttrList();
elementIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("element"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(schemaIndex, elementIndex);
}
//
// Build content model
//
// get type element; create if necessary
int typeIndex = getLastChildElement(elementIndex, "complexType");
if (typeIndex == -1 && contentSpecType != XMLElementDecl.TYPE_MIXED) {
typeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("complexType"), null, -1);
// REVISIT: Check for type redeclaration? -Ac
fDeferredDocumentImpl.insertBefore(elementIndex, typeIndex, getFirstChildElement(elementIndex));
}
// create models
switch (contentSpecType) {
case XMLElementDecl.TYPE_EMPTY: {
int attributeIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("content"), fStringPool.addString("empty"), true);
fDeferredDocumentImpl.setAttributeNode(typeIndex, attributeIndex);
break;
}
case XMLElementDecl.TYPE_ANY: {
int anyIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("any"), null, -1);
fDeferredDocumentImpl.insertBefore(typeIndex, anyIndex, getFirstChildElement(typeIndex));
break;
}
case XMLElementDecl.TYPE_MIXED: {
XMLContentSpec contentSpec = new XMLContentSpec();
contentSpecProvider.getContentSpec(contentSpecIndex, contentSpec);
contentSpecIndex = contentSpec.value;
if (contentSpecIndex == -1) {
int attributeIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("type"), fStringPool.addString("string"), true);
fDeferredDocumentImpl.setAttributeNode(elementIndex, attributeIndex);
}
else {
if (typeIndex == -1) {
typeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("complexType"), null, -1);
// REVISIT: Check for type redeclaration? -Ac
fDeferredDocumentImpl.insertBefore(elementIndex, typeIndex, getFirstChildElement(elementIndex));
}
int attributeIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("content"), fStringPool.addString("mixed"), true);
fDeferredDocumentImpl.setAttributeNode(typeIndex, attributeIndex);
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("minOccurs"),
fStringPool.addString("0"),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("maxOccurs"),
fStringPool.addString("unbounded"),
fStringPool.addSymbol("CDATA"),
true,
false); // search
fAttrList.endAttrList();
int choiceIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("choice"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(typeIndex, choiceIndex);
while (contentSpecIndex != -1) {
// get node
contentSpecProvider.getContentSpec(contentSpecIndex, contentSpec);
int type = contentSpec.type;
int left = contentSpec.value;
int right = contentSpec.otherValue;
// if leaf, skip "#PCDATA" and stop
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF) {
break;
}
// add right hand leaf
contentSpecProvider.getContentSpec(right, contentSpec);
handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("ref"),
fStringPool.addString(fStringPool.toString(contentSpec.value)),
fStringPool.addSymbol("NMTOKEN"),
true,
false); //search
fAttrList.endAttrList();
int rightIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("element"), fAttrList, handle);
int refIndex = getFirstChildElement(choiceIndex);
fDeferredDocumentImpl.insertBefore(choiceIndex, rightIndex, refIndex);
// go to next node
contentSpecIndex = left;
}
}
break;
}
case XMLElementDecl.TYPE_CHILDREN: {
int attributeIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("content"), fStringPool.addString("elementOnly"), true);
fDeferredDocumentImpl.setAttributeNode(typeIndex, attributeIndex);
int children = createChildren(contentSpecProvider,
contentSpecIndex,
new XMLContentSpec(),
fDeferredDocumentImpl,
-1);
fDeferredDocumentImpl.insertBefore(typeIndex, children, getFirstChildElement(typeIndex));
break;
}
}
} // if defer-node-expansion
else if (fDocumentImpl != null) {
//
// Build element
//
// get element declaration; create if necessary
Element schema = XUtil.getLastChildElement(fDocumentType, "schema");
String elementName = fStringPool.toString(elementDecl.rawname);
Element element = XUtil.getLastChildElement(schema, "element", "name", elementName);
if (element == null) {
element = fDocumentImpl.createElement("element");
element.setAttribute("name", elementName);
element.setAttribute("minOccurs", "1");
((AttrImpl)element.getAttributeNode("minOccurs")).setSpecified(false);
element.setAttribute("nullable", "false");
((AttrImpl)element.getAttributeNode("nullable")).setSpecified(false);
element.setAttribute("abstract", "false");
((AttrImpl)element.getAttributeNode("abstract")).setSpecified(false);
element.setAttribute("final", "false");
((AttrImpl)element.getAttributeNode("final")).setSpecified(false);
schema.appendChild(element);
}
//
// Build content model
//
// get type element; create if necessary
Element type = XUtil.getLastChildElement(element, "complexType");
if (type == null && contentSpecType != XMLElementDecl.TYPE_MIXED) {
type = fDocumentImpl.createElement("complexType");
// REVISIT: Check for type redeclaration? -Ac
element.insertBefore(type, XUtil.getFirstChildElement(element));
}
// create models
switch (contentSpecType) {
case XMLElementDecl.TYPE_EMPTY: {
type.setAttribute("content", "empty");
break;
}
case XMLElementDecl.TYPE_ANY: {
Element any = fDocumentImpl.createElement("any");
type.insertBefore(any, XUtil.getFirstChildElement(type));
break;
}
case XMLElementDecl.TYPE_MIXED: {
XMLContentSpec contentSpec = new XMLContentSpec();
contentSpecProvider.getContentSpec(contentSpecIndex, contentSpec);
contentSpecIndex = contentSpec.value;
if (contentSpecIndex == -1) {
element.setAttribute("type", "string");
}
else {
if (type == null) {
type = fDocumentImpl.createElement("complexType");
// REVISIT: Check for type redeclaration? -Ac
element.insertBefore(type, XUtil.getFirstChildElement(element));
}
type.setAttribute("content", "mixed");
Element choice = fDocumentImpl.createElement("choice");
choice.setAttribute("minOccurs", "0");
choice.setAttribute("maxOccurs", "unbounded");
type.appendChild(choice);
while (contentSpecIndex != -1) {
// get node
contentSpecProvider.getContentSpec(contentSpecIndex, contentSpec);
int cstype = contentSpec.type;
int csleft = contentSpec.value;
int csright = contentSpec.otherValue;
// if leaf, skip "#PCDATA" and stop
if (cstype == XMLContentSpec.CONTENTSPECNODE_LEAF) {
break;
}
// add right hand leaf
contentSpecProvider.getContentSpec(csright, contentSpec);
Element right = fDocumentImpl.createElement("element");
right.setAttribute("ref", fStringPool.toString(contentSpec.value));
Element ref = XUtil.getFirstChildElement(choice);
choice.insertBefore(right, ref);
// go to next node
contentSpecIndex = csleft;
}
}
break;
}
case XMLElementDecl.TYPE_CHILDREN: {
type.setAttribute("content", "elementOnly");
Element children = createChildren(contentSpecProvider,
contentSpecIndex,
new XMLContentSpec(),
fDocumentImpl,
null);
type.insertBefore(children, XUtil.getFirstChildElement(type));
break;
}
}
} // if NOT defer-node-expansion
} // if grammar-access
} // elementDecl(int,String)
/**
* <!ATTLIST Name AttDef>
*/
public void attlistDecl(QName elementDecl, QName attributeDecl,
int attType, boolean attList, String enumString,
int attDefaultType, int attDefaultValue)
throws Exception {
if (DEBUG_ATTLIST_DECL) {
System.out.println("attlistDecl(" + fStringPool.toString(elementDecl.rawname) + ", " +
fStringPool.toString(attributeDecl.rawname) + ", " +
fStringPool.toString(attType) + ", " +
enumString + ", " +
fStringPool.toString(attDefaultType) + ", " +
fStringPool.toString(attDefaultValue) + ")");
}
// deferred expansion
if (fDeferredDocumentImpl != null) {
// get the default value
if (attDefaultValue != -1) {
if (DEBUG_ATTLIST_DECL) {
System.out.println(" adding default attribute value: "+
fStringPool.toString(attDefaultValue));
}
// get element definition
int elementDefIndex = fDeferredDocumentImpl.lookupElementDefinition(elementDecl.rawname);
// create element definition if not already there
if (elementDefIndex == -1) {
elementDefIndex = fDeferredDocumentImpl.createElementDefinition(elementDecl.rawname);
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, elementDefIndex);
}
// add default attribute
int attrIndex =
fDeferredDocumentImpl.createAttribute(attributeDecl.rawname,
attributeDecl.uri,
attDefaultValue,
false);
fDeferredDocumentImpl.appendChild(elementDefIndex, attrIndex);
}
//
// Create attribute declaration
//
if (fGrammarAccess) {
// get element declaration; create it if necessary
int schemaIndex = getLastChildElement(fDocumentTypeIndex, "schema");
String elementName = fStringPool.toString(elementDecl.rawname);
int elementIndex = getLastChildElement(schemaIndex, "element", "name", elementName);
if (elementIndex == -1) {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("name"),
fStringPool.addString(elementName),
fStringPool.addSymbol("NMTOKEN"),
true,
false); //search
fAttrList.endAttrList();
elementIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("element"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(schemaIndex, elementIndex);
}
// get type element; create it if necessary
int typeIndex = getLastChildElement(elementIndex, "complexType");
if (typeIndex == -1) {
typeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("complexType"), null, -1);
fDeferredDocumentImpl.insertBefore(elementIndex, typeIndex, getLastChildElement(elementIndex));
}
// create attribute and set its attributes
String attributeName = fStringPool.toString(attributeDecl.rawname);
int attributeIndex = getLastChildElement(elementIndex, "attribute", "name", attributeName);
if (attributeIndex == -1) {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("name"),
fStringPool.addString(attributeName),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("maxOccurs"),
fStringPool.addString("1"),
fStringPool.addSymbol("CDATA"),
false,
false); // search
fAttrList.endAttrList();
attributeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("attribute"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(typeIndex, attributeIndex);
// attribute type: CDATA, ENTITY, ... , NMTOKENS; ENUMERATION
if (attType == XMLAttributeDecl.TYPE_ENUMERATION) {
handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("base"),
fStringPool.addString("NMTOKEN"),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
fAttrList.endAttrList();
int simpleTypeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("simpleType"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(attributeIndex, simpleTypeIndex);
String tokenizerString = enumString.substring(1, enumString.length() - 1);
StringTokenizer tokenizer = new StringTokenizer(tokenizerString, "|");
while (tokenizer.hasMoreTokens()) {
handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("value"),
fStringPool.addString(tokenizer.nextToken()),
fStringPool.addSymbol("CDATA"),
true,
false); // search
fAttrList.endAttrList();
int enumerationIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("enumeration"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(simpleTypeIndex, enumerationIndex);
}
}
else {
int typeNameIndex = -1;
switch (attType) {
case XMLAttributeDecl.TYPE_ENTITY: {
typeNameIndex = fStringPool.addString(attList?"ENTITIES":"ENTITY");
break;
}
case XMLAttributeDecl.TYPE_ID: {
typeNameIndex = fStringPool.addString("ID");
break;
}
case XMLAttributeDecl.TYPE_IDREF: {
typeNameIndex = fStringPool.addString(attList?"IDREFS":"IDREF");
break;
}
case XMLAttributeDecl.TYPE_NMTOKEN: {
typeNameIndex = fStringPool.addString(attList?"NMTOKENS":"NMTOKEN");
break;
}
case XMLAttributeDecl.TYPE_NOTATION: {
typeNameIndex = fStringPool.addString("NOTATION");
break;
}
case XMLAttributeDecl.TYPE_CDATA:
default: {
typeNameIndex = fStringPool.addString("string");
break;
}
}
int attrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("type"), typeNameIndex, true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, attrIndex);
}
// attribute default type: #IMPLIED, #REQUIRED, #FIXED
boolean fixed = false;
switch (attDefaultType) {
case XMLAttributeDecl.DEFAULT_TYPE_REQUIRED: {
int useAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("use"), fStringPool.addString("required"), true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, useAttrIndex);
break;
}
case XMLAttributeDecl.DEFAULT_TYPE_FIXED: {
fixed = true;
int useAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("use"), fStringPool.addString("fixed"), true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, useAttrIndex);
break;
}
}
// attribute default value
if (attDefaultValue != -1) {
if (!fixed) {
int useAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("use"), fStringPool.addString("default"), true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, useAttrIndex);
}
int valueAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("value"), attDefaultValue, true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, valueAttrIndex);
}
}
}
}
// full expansion
else if (fDocumentImpl != null) {
// get the default value
if (attDefaultValue != -1) {
if (DEBUG_ATTLIST_DECL) {
System.out.println(" adding default attribute value: "+
fStringPool.toString(attDefaultValue));
}
// get element name
String elementName = fStringPool.toString(elementDecl.rawname);
// get element definition node
NamedNodeMap elements = ((DocumentTypeImpl)fDocumentType).getElements();
ElementDefinitionImpl elementDef = (ElementDefinitionImpl)elements.getNamedItem(elementName);
if (elementDef == null) {
elementDef = fDocumentImpl.createElementDefinition(elementName);
((DocumentTypeImpl)fDocumentType).getElements().setNamedItem(elementDef);
}
// REVISIT: Check for uniqueness of element name? -Ac
- // REVISIT: what about default attributes with URI? -ALH
// get attribute name and value index
String attrName = fStringPool.toString(attributeDecl.rawname);
String attrValue = fStringPool.toString(attDefaultValue);
// create attribute and set properties
- AttrImpl attr = (AttrImpl)fDocumentImpl.createAttribute(attrName);
+ boolean nsEnabled = false;
+ try { nsEnabled = getNamespaces(); }
+ catch (SAXException s) {}
+ AttrImpl attr;
+ if (nsEnabled) {
+ attr = (AttrImpl)fDocumentImpl.createAttributeNS(fStringPool.toString(attributeDecl.uri),attrName);
+ }
+ else{
+ attr = (AttrImpl)fDocumentImpl.createAttribute(attrName);
+ }
attr.setValue(attrValue);
attr.setSpecified(false);
// add default attribute to element definition
- elementDef.getAttributes().setNamedItem(attr);
+ if(nsEnabled){
+ elementDef.getAttributes().setNamedItemNS(attr);
+ }
+ else{
+ elementDef.getAttributes().setNamedItem(attr);
+ }
}
//
// Create attribute declaration
//
try {
if (fGrammarAccess) {
// get element declaration; create it if necessary
Element schema = XUtil.getLastChildElement(fDocumentType, "schema");
String elementName = fStringPool.toString(elementDecl.rawname);
Element element = XUtil.getLastChildElement(schema, "element", "name", elementName);
if (element == null) {
element = fDocumentImpl.createElement("element");
element.setAttribute("name", elementName);
schema.appendChild(element);
}
// get type element; create it if necessary
Element type = XUtil.getLastChildElement(element, "complexType");
if (type == null) {
type = fDocumentImpl.createElement("complexType");
element.insertBefore(type, XUtil.getLastChildElement(element));
}
// create attribute and set its attributes
String attributeName = fStringPool.toString(attributeDecl.rawname);
Element attribute = XUtil.getLastChildElement(element, "attribute", "name", attributeName);
if (attribute == null) {
attribute = fDocumentImpl.createElement("attribute");
attribute.setAttribute("name", attributeName);
attribute.setAttribute("maxOccurs", "1");
((AttrImpl)attribute.getAttributeNode("maxOccurs")).setSpecified(false);
type.appendChild(attribute);
// attribute type: CDATA, ENTITY, ... , NMTOKENS; ENUMERATION
if (attType == XMLAttributeDecl.TYPE_ENUMERATION) {
Element simpleType = fDocumentImpl.createElement("simpleType");
simpleType.setAttribute("base", "NMTOKEN");
attribute.appendChild(simpleType);
String tokenizerString = enumString.substring(1, enumString.length() - 1);
StringTokenizer tokenizer = new StringTokenizer(tokenizerString, "|");
while (tokenizer.hasMoreTokens()) {
Element enumeration = fDocumentImpl.createElement("enumeration");
enumeration.setAttribute("value", tokenizer.nextToken());
simpleType.appendChild(enumeration);
}
}
else {
String typeName = null;
switch (attType) {
case XMLAttributeDecl.TYPE_ENTITY: {
typeName = attList ? "ENTITIES" : "ENTITY";
break;
}
case XMLAttributeDecl.TYPE_ID: {
typeName = "ID";
break;
}
case XMLAttributeDecl.TYPE_IDREF: {
typeName = attList ? "IDREFS" : "IDREF";
break;
}
case XMLAttributeDecl.TYPE_NMTOKEN: {
typeName = attList ? "NMTOKENS" : "NMTOKEN";
break;
}
case XMLAttributeDecl.TYPE_NOTATION: {
typeName = "NOTATION";
break;
}
case XMLAttributeDecl.TYPE_CDATA:
default: {
typeName = "string";
break;
}
}
attribute.setAttribute("type", typeName);
}
// attribute default type: #IMPLIED, #REQUIRED, #FIXED
boolean fixed = false;
switch (attDefaultType) {
case XMLAttributeDecl.DEFAULT_TYPE_REQUIRED: {
attribute.setAttribute("use", "required");
break;
}
case XMLAttributeDecl.DEFAULT_TYPE_FIXED: {
attribute.setAttribute("use", "fixed");
fixed = true;
break;
}
}
// attribute default value
if (attDefaultValue != -1) {
if (!fixed) {
attribute.setAttribute("use", "default");
}
attribute.setAttribute("value", fStringPool.toString(attDefaultValue));
}
}
}
}
catch (Exception e) {
e.printStackTrace(System.err);
}
} // if NOT defer-node-expansion
} // attlistDecl(int,int,int,String,int,int)
/**
* <!ENTITY % Name EntityValue> (internal)
*/
public void internalPEDecl(int entityNameIndex, int entityValueIndex) throws Exception {
if (fDeferredDocumentImpl != null) {
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY % ");
str.append(fStringPool.toString(entityNameIndex));
str.append(" \"");
str.append(fStringPool.toString(entityValueIndex));
str.append("\">");
int commentIndex = fStringPool.addString(str.toString());
int internalPEEntityIndex = fDeferredDocumentImpl.createComment(commentIndex);
int schemaIndex = getFirstChildElement(fDocumentTypeIndex, "schema");
fDeferredDocumentImpl.appendChild(schemaIndex, internalPEEntityIndex);
}
}
else if (fDocumentImpl != null) {
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY % ");
str.append(fStringPool.toString(entityNameIndex));
str.append(" \"");
str.append(fStringPool.orphanString(entityValueIndex));
str.append("\">");
Node internalPEEntity = fDocumentImpl.createComment(str.toString());
Node schema = XUtil.getFirstChildElement(fDocumentType, "schema");
schema.appendChild(internalPEEntity);
}
}
else {
fStringPool.orphanString(entityValueIndex);
}
}
/**
* <!ENTITY % Name ExternalID> (external)
*/
public void externalPEDecl(int entityNameIndex, int publicIdIndex, int systemIdIndex) throws Exception {
if (fDeferredDocumentImpl != null) {
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY ");
str.append(fStringPool.toString(entityNameIndex));
str.append(' ');
if (publicIdIndex != -1) {
str.append("PUBLIC \"");
str.append(fStringPool.toString(publicIdIndex));
str.append('"');
if (systemIdIndex != -1) {
str.append(" \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
}
else if (systemIdIndex != -1) {
str.append("SYSTEM \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
str.append('>');
int commentIndex = fStringPool.addString(str.toString());
int externalPEEntityIndex = fDeferredDocumentImpl.createComment(commentIndex);
int schemaIndex = getFirstChildElement(fDocumentTypeIndex, "schema");
fDeferredDocumentImpl.appendChild(schemaIndex, externalPEEntityIndex);
}
}
else if (fDocumentImpl != null) {
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY ");
str.append(fStringPool.toString(entityNameIndex));
str.append(' ');
if (publicIdIndex != -1) {
str.append("PUBLIC \"");
str.append(fStringPool.toString(publicIdIndex));
str.append('"');
if (systemIdIndex != -1) {
str.append(" \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
}
else if (systemIdIndex != -1) {
str.append("SYSTEM \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
str.append('>');
Node externalPEEntity = fDocumentImpl.createComment(str.toString());
Node schema = XUtil.getFirstChildElement(fDocumentType, "schema");
schema.appendChild(externalPEEntity);
}
}
}
/**
* <!ENTITY Name EntityValue> (internal)
*/
public void internalEntityDecl(int entityNameIndex, int entityValueIndex)
throws Exception {
// deferred expansion
if (fDeferredDocumentImpl != null) {
if (fDocumentTypeIndex == -1) return; //revisit: should never happen. Exception?
//revisit: how to check if entity was already declared.
// XML spec says that 1st Entity decl is binding.
int newEntityIndex = fDeferredDocumentImpl.createEntity(entityNameIndex, -1, -1, -1);
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, newEntityIndex);
// REVISIT: Entities were removed from latest working draft. -Ac
// create internal entity declaration
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY ");
str.append(fStringPool.toString(entityNameIndex));
str.append(" \"");
str.append(fStringPool.toString(entityValueIndex));
str.append("\">");
int commentIndex = fStringPool.addString(str.toString());
int textEntityIndex = fDeferredDocumentImpl.createComment(commentIndex);
int schemaIndex = getFirstChildElement(fDocumentTypeIndex, "schema");
fDeferredDocumentImpl.appendChild(schemaIndex, textEntityIndex);
}
}
// full expansion
else if (fDocumentImpl != null) {
if (fDocumentType == null) return; //revisit: should never happen. Exception?
//revisit: how to check if entity was already declared.
// XML spec says that 1st Entity decl is binding.
String entityName = fStringPool.toString(entityNameIndex);
Entity entity = fDocumentImpl.createEntity(entityName);
fDocumentType.getEntities().setNamedItem(entity);
// REVISIT: Entities were removed from latest working draft. -Ac
// create internal entity declaration
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY ");
str.append(fStringPool.toString(entityNameIndex));
str.append(" \"");
str.append(fStringPool.toString(entityValueIndex));
str.append("\">");
Node textEntity = fDocumentImpl.createComment(str.toString());
Node schema = XUtil.getFirstChildElement(fDocumentType, "schema");
schema.appendChild(textEntity);
}
}
} // internalEntityDecl(int,int)
/**
* <!ENTITY Name ExternalID> (external)
*/
public void externalEntityDecl(int entityNameIndex, int publicIdIndex, int systemIdIndex)
throws Exception {
// deferred expansion
if (fDeferredDocumentImpl != null) {
//revisit: how to check if entity was already declared.
// XML spec says that 1st Entity decl is binding.
int newEntityIndex = fDeferredDocumentImpl.createEntity(entityNameIndex, publicIdIndex, systemIdIndex, -1);
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, newEntityIndex);
// REVISIT: Entities were removed from latest working draft. -Ac
// create external entity declaration
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY ");
str.append(fStringPool.toString(entityNameIndex));
str.append(' ');
if (publicIdIndex != -1) {
str.append("PUBLIC \"");
str.append(fStringPool.toString(publicIdIndex));
str.append('"');
if (systemIdIndex != -1) {
str.append(" \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
}
else if (systemIdIndex != -1) {
str.append("SYSTEM \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
str.append('>');
int commentIndex = fStringPool.addString(str.toString());
int externalEntityIndex = fDeferredDocumentImpl.createComment(commentIndex);
int schemaIndex = getFirstChildElement(fDocumentTypeIndex, "schema");
fDeferredDocumentImpl.appendChild(schemaIndex, externalEntityIndex);
}
}
// full expansion
else if (fDocumentImpl != null) {
//revisit: how to check if entity was already declared.
// XML spec says that 1st Entity decl is binding.
String entityName = fStringPool.toString(entityNameIndex);
String publicId = fStringPool.toString(publicIdIndex);
String systemId = fStringPool.toString(systemIdIndex);
EntityImpl entity = (EntityImpl)fDocumentImpl.createEntity(entityName);
if (publicIdIndex != -1) {
entity.setPublicId(publicId);
}
entity.setSystemId(systemId);
fDocumentType.getEntities().setNamedItem(entity);
// REVISIT: Entities were removed from latest working draft. -Ac
// create external entity declaration
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY ");
str.append(fStringPool.toString(entityNameIndex));
str.append(' ');
if (publicIdIndex != -1) {
str.append("PUBLIC \"");
str.append(fStringPool.toString(publicIdIndex));
str.append('"');
if (systemIdIndex != -1) {
str.append(" \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
}
else if (systemIdIndex != -1) {
str.append("SYSTEM \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
str.append('>');
Node externalEntity = fDocumentImpl.createComment(str.toString());
Node schema = XUtil.getFirstChildElement(fDocumentType, "schema");
schema.appendChild(externalEntity);
}
}
} // externalEntityDecl(int,int,int)
/**
* <!ENTITY Name ExternalID NDataDecl> (unparsed)
*/
public void unparsedEntityDecl(int entityNameIndex,
int publicIdIndex, int systemIdIndex,
int notationNameIndex) throws Exception {
// deferred expansion
if (fDeferredDocumentImpl != null) {
//revisit: how to check if entity was already declared.
// XML spec says that 1st Entity decl is binding.
int newEntityIndex = fDeferredDocumentImpl.createEntity(entityNameIndex, publicIdIndex, systemIdIndex, notationNameIndex);
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, newEntityIndex);
// REVISIT: Entities were removed from latest working draft. -Ac
// add unparsed entity declaration
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY ");
str.append(fStringPool.toString(entityNameIndex));
str.append(' ');
if (publicIdIndex != -1) {
str.append("PUBLIC \"");
str.append(fStringPool.toString(publicIdIndex));
str.append('"');
if (systemIdIndex != -1) {
str.append(" \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
}
else if (systemIdIndex != -1) {
str.append("SYSTEM \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
str.append(" NDATA ");
str.append(fStringPool.toString(notationNameIndex));
str.append('>');
int commentIndex = fStringPool.addString(str.toString());
int unparsedEntityIndex = fDeferredDocumentImpl.createComment(commentIndex);
int schemaIndex = getFirstChildElement(fDocumentTypeIndex, "schema");
fDeferredDocumentImpl.appendChild(schemaIndex, unparsedEntityIndex);
}
}
// full expansion
else if (fDocumentImpl != null) {
//revisit: how to check if entity was already declared.
// XML spec says that 1st Entity decl is binding.
String entityName = fStringPool.toString(entityNameIndex);
String publicId = fStringPool.toString(publicIdIndex);
String systemId = fStringPool.toString(systemIdIndex);
String notationName = fStringPool.toString(notationNameIndex);
EntityImpl entity = (EntityImpl)fDocumentImpl.createEntity(entityName);
if (publicIdIndex != -1) {
entity.setPublicId(publicId);
}
entity.setSystemId(systemId);
entity.setNotationName(notationName);
fDocumentType.getEntities().setNamedItem(entity);
// REVISIT: Entities were removed from latest working draft. -Ac
// add unparsed entity declaration
if (fGrammarAccess) {
StringBuffer str = new StringBuffer();
str.append("<!ENTITY ");
str.append(fStringPool.toString(entityNameIndex));
str.append(' ');
if (publicIdIndex != -1) {
str.append("PUBLIC \"");
str.append(fStringPool.toString(publicIdIndex));
str.append('"');
if (systemIdIndex != -1) {
str.append(" \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
}
else if (systemIdIndex != -1) {
str.append("SYSTEM \"");
str.append(fStringPool.toString(systemIdIndex));
str.append('"');
}
str.append(" NDATA ");
str.append(fStringPool.toString(notationNameIndex));
str.append('>');
Node unparsedEntity = fDocumentImpl.createComment(str.toString());
Node schema = XUtil.getFirstChildElement(fDocumentType, "schema");
schema.appendChild(unparsedEntity);
}
}
} // unparsedEntityDecl(int,int,int,int)
/**
* <!NOTATION Name ExternalId>
*/
public void notationDecl(int notationNameIndex, int publicIdIndex, int systemIdIndex)
throws Exception {
// deferred expansion
if (fDeferredDocumentImpl != null) {
//revisit: how to check if entity was already declared.
// XML spec says that 1st Entity decl is binding.
int newNotationIndex = fDeferredDocumentImpl.createNotation(notationNameIndex, publicIdIndex, systemIdIndex);
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, newNotationIndex);
// create notation declaration
if (fGrammarAccess) {
int schemaIndex = getLastChildElement(fDocumentTypeIndex, "schema");
String notationName = fStringPool.toString(notationNameIndex);
int notationIndex = getLastChildElement(schemaIndex, "notation", "name", notationName);
if (notationIndex == -1) {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("name"),
fStringPool.addString(notationName),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
if (publicIdIndex != -1) {
fAttrList.addAttr(
fStringPool.addSymbol("public"),
publicIdIndex,
fStringPool.addSymbol("CDATA"),
true,
false); // search
}
if (systemIdIndex != -1) {
fAttrList.addAttr(
fStringPool.addSymbol("system"),
systemIdIndex,
fStringPool.addSymbol("CDATA"),
true,
false); // search
}
fAttrList.endAttrList();
notationIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("notation"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(schemaIndex, notationIndex);
}
}
}
// full expansion
else if (fDocumentImpl != null) {
// REVISIT: how to check if entity was already declared.
// XML spec says that 1st Entity decl is binding.
String notationName = fStringPool.toString(notationNameIndex);
String publicId = fStringPool.toString(publicIdIndex);
String systemId = fStringPool.toString(systemIdIndex);
NotationImpl notationImpl = (NotationImpl)fDocumentImpl.createNotation(notationName);
notationImpl.setPublicId(publicId);
if (systemIdIndex != -1) {
notationImpl.setSystemId(systemId);
}
fDocumentType.getNotations().setNamedItem(notationImpl);
// create notation declaration
if (fGrammarAccess) {
Element schema = XUtil.getFirstChildElement(fDocumentType, "schema");
Element notation = XUtil.getFirstChildElement(schema, "notation", "name", notationName);
if (notation == null) {
notation = fDocument.createElement("notation");
notation.setAttribute("name", notationName);
//notation.setAttribute("export", "true");
//((AttrImpl)notation.getAttributeNode("export")).setSpecified(false);
if (publicId != null) {
notation.setAttribute("public", publicId);
}
if (systemIdIndex != -1) {
notation.setAttribute("system", systemId);
}
schema.appendChild(notation);
}
}
}
} // notationDecl(int,int,int)
//
// Private methods
//
/** Returns the first child element of the specified node. */
private int getFirstChildElement(int nodeIndex) {
int childIndex = getLastChildElement(nodeIndex);
while (childIndex != -1) {
int prevIndex = getPrevSiblingElement(childIndex);
if (prevIndex == -1) {
break;
}
childIndex = prevIndex;
}
return childIndex;
}
/** Returns the first child element of the specified node. */
private int getFirstChildElement(int nodeIndex, String name) {
int childIndex = getLastChildElement(nodeIndex);
if (childIndex != -1) {
int nameIndex = fStringPool.addSymbol(name);
while (childIndex != -1) {
if (fDeferredDocumentImpl.getNodeName(childIndex, false) == nameIndex) {
break;
}
int prevIndex = getPrevSiblingElement(childIndex);
childIndex = prevIndex;
}
}
return childIndex;
}
/** Returns the last child element of the specified node. */
private int getLastChildElement(int nodeIndex) {
int childIndex = fDeferredDocumentImpl.getLastChild(nodeIndex, false);
while (childIndex != -1) {
if (fDeferredDocumentImpl.getNodeType(childIndex, false) == Node.ELEMENT_NODE) {
return childIndex;
}
childIndex = fDeferredDocumentImpl.getPrevSibling(childIndex, false);
}
return -1;
}
/** Returns the previous sibling element of the specified node. */
private int getPrevSiblingElement(int nodeIndex) {
int siblingIndex = fDeferredDocumentImpl.getPrevSibling(nodeIndex, false);
while (siblingIndex != -1) {
if (fDeferredDocumentImpl.getNodeType(siblingIndex, false) == Node.ELEMENT_NODE) {
return siblingIndex;
}
siblingIndex = fDeferredDocumentImpl.getPrevSibling(siblingIndex, false);
}
return -1;
}
/** Returns the first child element with the given name. */
private int getLastChildElement(int nodeIndex, String elementName) {
int childIndex = getLastChildElement(nodeIndex);
if (childIndex != -1) {
while (childIndex != -1) {
String nodeName = fDeferredDocumentImpl.getNodeNameString(childIndex, false);
if (nodeName.equals(elementName)) {
return childIndex;
}
childIndex = getPrevSiblingElement(childIndex);
}
}
return -1;
}
/** Returns the next sibling element with the given name. */
private int getPrevSiblingElement(int nodeIndex, String elementName) {
int siblingIndex = getPrevSiblingElement(nodeIndex);
if (siblingIndex != -1) {
while (siblingIndex != -1) {
String nodeName = fDeferredDocumentImpl.getNodeNameString(siblingIndex, false);
if (nodeName.equals(elementName)) {
return siblingIndex;
}
siblingIndex = getPrevSiblingElement(siblingIndex);
}
}
return -1;
}
/** Returns the first child element with the given name. */
private int getLastChildElement(int nodeIndex, String elemName, String attrName, String attrValue) {
int childIndex = getLastChildElement(nodeIndex, elemName);
if (childIndex != -1) {
while (childIndex != -1) {
int attrIndex = fDeferredDocumentImpl.getNodeValue(childIndex, false);
while (attrIndex != -1) {
String nodeName = fDeferredDocumentImpl.getNodeNameString(attrIndex, false);
if (nodeName.equals(attrName)) {
// REVISIT: Do we need to normalize the text? -Ac
int textIndex = fDeferredDocumentImpl.getLastChild(attrIndex, false);
String nodeValue = fDeferredDocumentImpl.getNodeValueString(textIndex, false);
if (nodeValue.equals(attrValue)) {
return childIndex;
}
}
attrIndex = fDeferredDocumentImpl.getPrevSibling(attrIndex, false);
}
childIndex = getPrevSiblingElement(childIndex, elemName);
}
}
return -1;
}
/** Returns the next sibling element with the given name and attribute. */
private int getPrevSiblingElement(int nodeIndex, String elemName, String attrName, String attrValue) {
int siblingIndex = getPrevSiblingElement(nodeIndex, elemName);
if (siblingIndex != -1) {
int attributeNameIndex = fStringPool.addSymbol(attrName);
while (siblingIndex != -1) {
int attrIndex = fDeferredDocumentImpl.getNodeValue(siblingIndex, false);
while (attrIndex != -1) {
int attrValueIndex = fDeferredDocumentImpl.getNodeValue(attrIndex, false);
if (attrValue.equals(fStringPool.toString(attrValueIndex))) {
return siblingIndex;
}
attrIndex = fDeferredDocumentImpl.getPrevSibling(attrIndex, false);
}
siblingIndex = getPrevSiblingElement(siblingIndex, elemName);
}
}
return -1;
}
/**
* Copies the source tree into the specified place in a destination
* tree. The source node and its children are appended as children
* of the destination node.
* <p>
* <em>Note:</em> This is an iterative implementation.
*/
private void copyInto(Node src, int destIndex) throws Exception {
// for ignorable whitespace features
boolean domimpl = src != null && src instanceof DocumentImpl;
// placement variables
Node start = src;
Node parent = src;
Node place = src;
// traverse source tree
while (place != null) {
// copy this node
int nodeIndex = -1;
short type = place.getNodeType();
switch (type) {
case Node.CDATA_SECTION_NODE: {
boolean ignorable = domimpl && ((TextImpl)place).isIgnorableWhitespace();
nodeIndex = fDeferredDocumentImpl.createCDATASection(fStringPool.addString(place.getNodeValue()), ignorable);
break;
}
case Node.COMMENT_NODE: {
nodeIndex = fDeferredDocumentImpl.createComment(fStringPool.addString(place.getNodeValue()));
break;
}
case Node.ELEMENT_NODE: {
XMLAttrList attrList = null;
int handle = -1;
NamedNodeMap attrs = place.getAttributes();
if (attrs != null) {
int length = attrs.getLength();
if (length > 0) {
handle = fAttrList.startAttrList();
for (int i = 0; i < length; i++) {
Attr attr = (Attr)attrs.item(i);
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
fAttrList.addAttr(
fStringPool.addSymbol(attrName),
fStringPool.addString(attrValue),
fStringPool.addSymbol("CDATA"), // REVISIT
attr.getSpecified(),
false); // search
}
fAttrList.endAttrList();
attrList = fAttrList;
}
}
nodeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol(place.getNodeName()), attrList, handle);
break;
}
case Node.ENTITY_REFERENCE_NODE: {
nodeIndex = fDeferredDocumentImpl.createEntityReference(fStringPool.addSymbol(place.getNodeName()));
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
nodeIndex = fDeferredDocumentImpl.createProcessingInstruction(fStringPool.addSymbol(place.getNodeName()), fStringPool.addString(place.getNodeValue()));
break;
}
case Node.TEXT_NODE: {
boolean ignorable = domimpl && ((TextImpl)place).isIgnorableWhitespace();
nodeIndex = fDeferredDocumentImpl.createTextNode(fStringPool.addString(place.getNodeValue()), ignorable);
break;
}
default: {
throw new IllegalArgumentException("PAR010 Can't copy node type, "+
type+" ("+
place.getNodeName()+')'
+"\n"+type+"\t"+place.getNodeName());
}
}
fDeferredDocumentImpl.appendChild(destIndex, nodeIndex);
// iterate over children
if (place.hasChildNodes()) {
parent = place;
place = place.getFirstChild();
destIndex = nodeIndex;
}
// advance
else {
place = place.getNextSibling();
while (place == null && parent != start) {
place = parent.getNextSibling();
parent = parent.getParentNode();
destIndex = fDeferredDocumentImpl.getParentNode(destIndex, false);
}
}
}
} // copyInto(Node,int)
/**
* Sets the appropriate occurrence count attributes on the specified
* model element.
*/
private void setOccurrenceCount(Element model, int minOccur, int maxOccur) {
// min
model.setAttribute("minOccurs", Integer.toString(minOccur));
if (minOccur == 1) {
((AttrImpl)model.getAttributeNode("minOccurs")).setSpecified(false);
}
// max
if (maxOccur == -1) {
model.setAttribute("maxOccurs", "*");
}
else if (maxOccur != 1) {
model.setAttribute("maxOccurs", Integer.toString(maxOccur));
}
} // setOccurrenceCount(Element,int,int)
/** Creates the children for the element decl. */
private Element createChildren(XMLContentSpec.Provider provider,
int index, XMLContentSpec node,
DocumentImpl factory,
Element parent) throws Exception {
// get occurrence count
provider.getContentSpec(index, node);
int occurs = -1;
switch (node.type) {
case XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE: {
occurs = '+';
provider.getContentSpec(node.value, node);
break;
}
case XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE: {
occurs = '*';
provider.getContentSpec(node.value, node);
break;
}
case XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE: {
occurs = '?';
provider.getContentSpec(node.value, node);
break;
}
}
// flatten model
int nodeType = node.type;
switch (nodeType) {
// CHOICE or SEQUENCE
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ: {
// go down left side
int leftIndex = node.value;
int rightIndex = node.otherValue;
Element left = createChildren(provider, leftIndex, node,
factory, parent);
// go down right side
Element right = createChildren(provider, rightIndex, node,
factory, null);
// append left children
boolean choice = nodeType == XMLContentSpec.CONTENTSPECNODE_CHOICE;
String type = choice ? "choice" : "sequence";
Element model = left;
if (!left.getNodeName().equals(type)) {
String minOccurs = left.getAttribute("minOccurs");
String maxOccurs = left.getAttribute("maxOccurs");
boolean min1 = minOccurs.length() == 0 || minOccurs.equals("1");
boolean max1 = maxOccurs.length() == 0 || maxOccurs.equals("1");
if (parent == null || (min1 && max1)) {
model = factory.createElement(type);
model.appendChild(left);
}
else {
model = parent;
}
}
// set occurrence count
switch (occurs) {
case '+': {
model.setAttribute("maxOccurs", "unbounded");
break;
}
case '*': {
model.setAttribute("minOccurs", "0");
model.setAttribute("maxOccurs", "unbounded");
break;
}
case '?': {
model.setAttribute("minOccurs", "0");
break;
}
}
// append right children
model.appendChild(right);
// return model
return model;
}
// LEAF
case XMLContentSpec.CONTENTSPECNODE_LEAF: {
Element leaf = factory.createElement("element");
leaf.setAttribute("ref", fStringPool.toString(node.value));
switch (occurs) {
case '+': {
leaf.setAttribute("maxOccurs", "unbounded");
break;
}
case '*': {
leaf.setAttribute("minOccurs", "0");
leaf.setAttribute("maxOccurs", "unbounded");
break;
}
case '?': {
leaf.setAttribute("minOccurs", "0");
break;
}
}
return leaf;
}
} // switch node type
// error
return null;
} // createChildren(XMLContentSpec.Provider,int,XMLContentSpec,DocumentImpl,Element):Element
/** Creates the children for the deferred element decl. */
private int createChildren(XMLContentSpec.Provider provider,
int index, XMLContentSpec node,
DeferredDocumentImpl factory,
int parent) throws Exception {
// get occurrence count
provider.getContentSpec(index, node);
int occurs = -1;
switch (node.type) {
case XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE: {
occurs = '+';
provider.getContentSpec(node.value, node);
break;
}
case XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE: {
occurs = '*';
provider.getContentSpec(node.value, node);
break;
}
case XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE: {
occurs = '?';
provider.getContentSpec(node.value, node);
break;
}
}
// flatten model
int nodeType = node.type;
switch (nodeType) {
// CHOICE or SEQUENCE
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ: {
// go down left side
int leftIndex = node.value;
int rightIndex = node.otherValue;
int left = createChildren(provider, leftIndex, node,
factory, parent);
// go down right side
int right = createChildren(provider, rightIndex, node,
factory, -1);
// append left children
boolean choice = nodeType == XMLContentSpec.CONTENTSPECNODE_CHOICE;
int type = fStringPool.addSymbol(choice ? "choice" : "sequence");
int model = left;
if (factory.getNodeName(left, false) != type) {
int minOccurs = factory.getAttribute(left, fStringPool.addSymbol("minOccurs"));
int maxOccurs = factory.getAttribute(left, fStringPool.addSymbol("maxOccurs"));
boolean min1 = minOccurs == -1 || fStringPool.toString(minOccurs).equals("1");
boolean max1 = maxOccurs == -1 || fStringPool.toString(maxOccurs).equals("1");
if (parent == -1 || (min1 && max1)) {
model = factory.createElement(type, null, -1);
factory.appendChild(model, left);
}
else {
model = parent;
}
}
// set occurrence count
switch (occurs) {
case '+': {
int maxOccurs = factory.createAttribute(fStringPool.addSymbol("maxOccurs"),
fStringPool.addString("unbounded"),
true);
factory.setAttributeNode(model, maxOccurs);
break;
}
case '*': {
int minOccurs = factory.createAttribute(fStringPool.addSymbol("minOccurs"),
fStringPool.addString("0"),
true);
factory.setAttributeNode(model, minOccurs);
int maxOccurs = factory.createAttribute(fStringPool.addSymbol("maxOccurs"),
fStringPool.addString("unbounded"),
true);
factory.setAttributeNode(model, maxOccurs);
break;
}
case '?': {
int minOccurs = factory.createAttribute(fStringPool.addSymbol("minOccurs"),
fStringPool.addString("0"),
true);
factory.setAttributeNode(model, minOccurs);
break;
}
}
// append right children
factory.appendChild(model, right);
// return model
return model;
}
// LEAF
case XMLContentSpec.CONTENTSPECNODE_LEAF: {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("ref"),
fStringPool.addString(fStringPool.toString(node.value)),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
switch (occurs) {
case '+': {
fAttrList.addAttr(
fStringPool.addSymbol("maxOccurs"),
fStringPool.addString("unbounded"),
fStringPool.addSymbol("CDATA"),
true,
false); // search
break;
}
case '*': {
fAttrList.addAttr(
fStringPool.addSymbol("minOccurs"),
fStringPool.addString("0"),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("maxOccurs"),
fStringPool.addString("unbounded"),
fStringPool.addSymbol("CDATA"),
true,
false); // search
break;
}
case '?': {
fAttrList.addAttr(
fStringPool.addSymbol("minOccurs"),
fStringPool.addString("0"),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
break;
}
}
fAttrList.endAttrList();
int leaf = factory.createElement(fStringPool.addSymbol("element"), fAttrList, handle);
return leaf;
}
} // switch node type
// error
return -1;
} // createChildren(XMLContentSpec.Provider,int,XMLContentSpec,DeferredDocumentImpl,int):int
} // class DOMParser
| false | true | public void attlistDecl(QName elementDecl, QName attributeDecl,
int attType, boolean attList, String enumString,
int attDefaultType, int attDefaultValue)
throws Exception {
if (DEBUG_ATTLIST_DECL) {
System.out.println("attlistDecl(" + fStringPool.toString(elementDecl.rawname) + ", " +
fStringPool.toString(attributeDecl.rawname) + ", " +
fStringPool.toString(attType) + ", " +
enumString + ", " +
fStringPool.toString(attDefaultType) + ", " +
fStringPool.toString(attDefaultValue) + ")");
}
// deferred expansion
if (fDeferredDocumentImpl != null) {
// get the default value
if (attDefaultValue != -1) {
if (DEBUG_ATTLIST_DECL) {
System.out.println(" adding default attribute value: "+
fStringPool.toString(attDefaultValue));
}
// get element definition
int elementDefIndex = fDeferredDocumentImpl.lookupElementDefinition(elementDecl.rawname);
// create element definition if not already there
if (elementDefIndex == -1) {
elementDefIndex = fDeferredDocumentImpl.createElementDefinition(elementDecl.rawname);
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, elementDefIndex);
}
// add default attribute
int attrIndex =
fDeferredDocumentImpl.createAttribute(attributeDecl.rawname,
attributeDecl.uri,
attDefaultValue,
false);
fDeferredDocumentImpl.appendChild(elementDefIndex, attrIndex);
}
//
// Create attribute declaration
//
if (fGrammarAccess) {
// get element declaration; create it if necessary
int schemaIndex = getLastChildElement(fDocumentTypeIndex, "schema");
String elementName = fStringPool.toString(elementDecl.rawname);
int elementIndex = getLastChildElement(schemaIndex, "element", "name", elementName);
if (elementIndex == -1) {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("name"),
fStringPool.addString(elementName),
fStringPool.addSymbol("NMTOKEN"),
true,
false); //search
fAttrList.endAttrList();
elementIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("element"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(schemaIndex, elementIndex);
}
// get type element; create it if necessary
int typeIndex = getLastChildElement(elementIndex, "complexType");
if (typeIndex == -1) {
typeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("complexType"), null, -1);
fDeferredDocumentImpl.insertBefore(elementIndex, typeIndex, getLastChildElement(elementIndex));
}
// create attribute and set its attributes
String attributeName = fStringPool.toString(attributeDecl.rawname);
int attributeIndex = getLastChildElement(elementIndex, "attribute", "name", attributeName);
if (attributeIndex == -1) {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("name"),
fStringPool.addString(attributeName),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("maxOccurs"),
fStringPool.addString("1"),
fStringPool.addSymbol("CDATA"),
false,
false); // search
fAttrList.endAttrList();
attributeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("attribute"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(typeIndex, attributeIndex);
// attribute type: CDATA, ENTITY, ... , NMTOKENS; ENUMERATION
if (attType == XMLAttributeDecl.TYPE_ENUMERATION) {
handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("base"),
fStringPool.addString("NMTOKEN"),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
fAttrList.endAttrList();
int simpleTypeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("simpleType"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(attributeIndex, simpleTypeIndex);
String tokenizerString = enumString.substring(1, enumString.length() - 1);
StringTokenizer tokenizer = new StringTokenizer(tokenizerString, "|");
while (tokenizer.hasMoreTokens()) {
handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("value"),
fStringPool.addString(tokenizer.nextToken()),
fStringPool.addSymbol("CDATA"),
true,
false); // search
fAttrList.endAttrList();
int enumerationIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("enumeration"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(simpleTypeIndex, enumerationIndex);
}
}
else {
int typeNameIndex = -1;
switch (attType) {
case XMLAttributeDecl.TYPE_ENTITY: {
typeNameIndex = fStringPool.addString(attList?"ENTITIES":"ENTITY");
break;
}
case XMLAttributeDecl.TYPE_ID: {
typeNameIndex = fStringPool.addString("ID");
break;
}
case XMLAttributeDecl.TYPE_IDREF: {
typeNameIndex = fStringPool.addString(attList?"IDREFS":"IDREF");
break;
}
case XMLAttributeDecl.TYPE_NMTOKEN: {
typeNameIndex = fStringPool.addString(attList?"NMTOKENS":"NMTOKEN");
break;
}
case XMLAttributeDecl.TYPE_NOTATION: {
typeNameIndex = fStringPool.addString("NOTATION");
break;
}
case XMLAttributeDecl.TYPE_CDATA:
default: {
typeNameIndex = fStringPool.addString("string");
break;
}
}
int attrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("type"), typeNameIndex, true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, attrIndex);
}
// attribute default type: #IMPLIED, #REQUIRED, #FIXED
boolean fixed = false;
switch (attDefaultType) {
case XMLAttributeDecl.DEFAULT_TYPE_REQUIRED: {
int useAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("use"), fStringPool.addString("required"), true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, useAttrIndex);
break;
}
case XMLAttributeDecl.DEFAULT_TYPE_FIXED: {
fixed = true;
int useAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("use"), fStringPool.addString("fixed"), true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, useAttrIndex);
break;
}
}
// attribute default value
if (attDefaultValue != -1) {
if (!fixed) {
int useAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("use"), fStringPool.addString("default"), true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, useAttrIndex);
}
int valueAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("value"), attDefaultValue, true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, valueAttrIndex);
}
}
}
}
// full expansion
else if (fDocumentImpl != null) {
// get the default value
if (attDefaultValue != -1) {
if (DEBUG_ATTLIST_DECL) {
System.out.println(" adding default attribute value: "+
fStringPool.toString(attDefaultValue));
}
// get element name
String elementName = fStringPool.toString(elementDecl.rawname);
// get element definition node
NamedNodeMap elements = ((DocumentTypeImpl)fDocumentType).getElements();
ElementDefinitionImpl elementDef = (ElementDefinitionImpl)elements.getNamedItem(elementName);
if (elementDef == null) {
elementDef = fDocumentImpl.createElementDefinition(elementName);
((DocumentTypeImpl)fDocumentType).getElements().setNamedItem(elementDef);
}
// REVISIT: Check for uniqueness of element name? -Ac
// REVISIT: what about default attributes with URI? -ALH
// get attribute name and value index
String attrName = fStringPool.toString(attributeDecl.rawname);
String attrValue = fStringPool.toString(attDefaultValue);
// create attribute and set properties
AttrImpl attr = (AttrImpl)fDocumentImpl.createAttribute(attrName);
attr.setValue(attrValue);
attr.setSpecified(false);
// add default attribute to element definition
elementDef.getAttributes().setNamedItem(attr);
}
//
// Create attribute declaration
//
try {
if (fGrammarAccess) {
// get element declaration; create it if necessary
Element schema = XUtil.getLastChildElement(fDocumentType, "schema");
String elementName = fStringPool.toString(elementDecl.rawname);
Element element = XUtil.getLastChildElement(schema, "element", "name", elementName);
if (element == null) {
element = fDocumentImpl.createElement("element");
element.setAttribute("name", elementName);
schema.appendChild(element);
}
// get type element; create it if necessary
Element type = XUtil.getLastChildElement(element, "complexType");
if (type == null) {
type = fDocumentImpl.createElement("complexType");
element.insertBefore(type, XUtil.getLastChildElement(element));
}
// create attribute and set its attributes
String attributeName = fStringPool.toString(attributeDecl.rawname);
Element attribute = XUtil.getLastChildElement(element, "attribute", "name", attributeName);
if (attribute == null) {
attribute = fDocumentImpl.createElement("attribute");
attribute.setAttribute("name", attributeName);
attribute.setAttribute("maxOccurs", "1");
((AttrImpl)attribute.getAttributeNode("maxOccurs")).setSpecified(false);
type.appendChild(attribute);
// attribute type: CDATA, ENTITY, ... , NMTOKENS; ENUMERATION
if (attType == XMLAttributeDecl.TYPE_ENUMERATION) {
Element simpleType = fDocumentImpl.createElement("simpleType");
simpleType.setAttribute("base", "NMTOKEN");
attribute.appendChild(simpleType);
String tokenizerString = enumString.substring(1, enumString.length() - 1);
StringTokenizer tokenizer = new StringTokenizer(tokenizerString, "|");
while (tokenizer.hasMoreTokens()) {
Element enumeration = fDocumentImpl.createElement("enumeration");
enumeration.setAttribute("value", tokenizer.nextToken());
simpleType.appendChild(enumeration);
}
}
else {
String typeName = null;
switch (attType) {
case XMLAttributeDecl.TYPE_ENTITY: {
typeName = attList ? "ENTITIES" : "ENTITY";
break;
}
case XMLAttributeDecl.TYPE_ID: {
typeName = "ID";
break;
}
case XMLAttributeDecl.TYPE_IDREF: {
typeName = attList ? "IDREFS" : "IDREF";
break;
}
case XMLAttributeDecl.TYPE_NMTOKEN: {
typeName = attList ? "NMTOKENS" : "NMTOKEN";
break;
}
case XMLAttributeDecl.TYPE_NOTATION: {
typeName = "NOTATION";
break;
}
case XMLAttributeDecl.TYPE_CDATA:
default: {
typeName = "string";
break;
}
}
attribute.setAttribute("type", typeName);
}
// attribute default type: #IMPLIED, #REQUIRED, #FIXED
boolean fixed = false;
switch (attDefaultType) {
case XMLAttributeDecl.DEFAULT_TYPE_REQUIRED: {
attribute.setAttribute("use", "required");
break;
}
case XMLAttributeDecl.DEFAULT_TYPE_FIXED: {
attribute.setAttribute("use", "fixed");
fixed = true;
break;
}
}
// attribute default value
if (attDefaultValue != -1) {
if (!fixed) {
attribute.setAttribute("use", "default");
}
attribute.setAttribute("value", fStringPool.toString(attDefaultValue));
}
}
}
}
catch (Exception e) {
e.printStackTrace(System.err);
}
} // if NOT defer-node-expansion
} // attlistDecl(int,int,int,String,int,int)
| public void attlistDecl(QName elementDecl, QName attributeDecl,
int attType, boolean attList, String enumString,
int attDefaultType, int attDefaultValue)
throws Exception {
if (DEBUG_ATTLIST_DECL) {
System.out.println("attlistDecl(" + fStringPool.toString(elementDecl.rawname) + ", " +
fStringPool.toString(attributeDecl.rawname) + ", " +
fStringPool.toString(attType) + ", " +
enumString + ", " +
fStringPool.toString(attDefaultType) + ", " +
fStringPool.toString(attDefaultValue) + ")");
}
// deferred expansion
if (fDeferredDocumentImpl != null) {
// get the default value
if (attDefaultValue != -1) {
if (DEBUG_ATTLIST_DECL) {
System.out.println(" adding default attribute value: "+
fStringPool.toString(attDefaultValue));
}
// get element definition
int elementDefIndex = fDeferredDocumentImpl.lookupElementDefinition(elementDecl.rawname);
// create element definition if not already there
if (elementDefIndex == -1) {
elementDefIndex = fDeferredDocumentImpl.createElementDefinition(elementDecl.rawname);
fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, elementDefIndex);
}
// add default attribute
int attrIndex =
fDeferredDocumentImpl.createAttribute(attributeDecl.rawname,
attributeDecl.uri,
attDefaultValue,
false);
fDeferredDocumentImpl.appendChild(elementDefIndex, attrIndex);
}
//
// Create attribute declaration
//
if (fGrammarAccess) {
// get element declaration; create it if necessary
int schemaIndex = getLastChildElement(fDocumentTypeIndex, "schema");
String elementName = fStringPool.toString(elementDecl.rawname);
int elementIndex = getLastChildElement(schemaIndex, "element", "name", elementName);
if (elementIndex == -1) {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("name"),
fStringPool.addString(elementName),
fStringPool.addSymbol("NMTOKEN"),
true,
false); //search
fAttrList.endAttrList();
elementIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("element"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(schemaIndex, elementIndex);
}
// get type element; create it if necessary
int typeIndex = getLastChildElement(elementIndex, "complexType");
if (typeIndex == -1) {
typeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("complexType"), null, -1);
fDeferredDocumentImpl.insertBefore(elementIndex, typeIndex, getLastChildElement(elementIndex));
}
// create attribute and set its attributes
String attributeName = fStringPool.toString(attributeDecl.rawname);
int attributeIndex = getLastChildElement(elementIndex, "attribute", "name", attributeName);
if (attributeIndex == -1) {
int handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("name"),
fStringPool.addString(attributeName),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
fAttrList.addAttr(
fStringPool.addSymbol("maxOccurs"),
fStringPool.addString("1"),
fStringPool.addSymbol("CDATA"),
false,
false); // search
fAttrList.endAttrList();
attributeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("attribute"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(typeIndex, attributeIndex);
// attribute type: CDATA, ENTITY, ... , NMTOKENS; ENUMERATION
if (attType == XMLAttributeDecl.TYPE_ENUMERATION) {
handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("base"),
fStringPool.addString("NMTOKEN"),
fStringPool.addSymbol("NMTOKEN"),
true,
false); // search
fAttrList.endAttrList();
int simpleTypeIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("simpleType"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(attributeIndex, simpleTypeIndex);
String tokenizerString = enumString.substring(1, enumString.length() - 1);
StringTokenizer tokenizer = new StringTokenizer(tokenizerString, "|");
while (tokenizer.hasMoreTokens()) {
handle = fAttrList.startAttrList();
fAttrList.addAttr(
fStringPool.addSymbol("value"),
fStringPool.addString(tokenizer.nextToken()),
fStringPool.addSymbol("CDATA"),
true,
false); // search
fAttrList.endAttrList();
int enumerationIndex = fDeferredDocumentImpl.createElement(fStringPool.addSymbol("enumeration"), fAttrList, handle);
fDeferredDocumentImpl.appendChild(simpleTypeIndex, enumerationIndex);
}
}
else {
int typeNameIndex = -1;
switch (attType) {
case XMLAttributeDecl.TYPE_ENTITY: {
typeNameIndex = fStringPool.addString(attList?"ENTITIES":"ENTITY");
break;
}
case XMLAttributeDecl.TYPE_ID: {
typeNameIndex = fStringPool.addString("ID");
break;
}
case XMLAttributeDecl.TYPE_IDREF: {
typeNameIndex = fStringPool.addString(attList?"IDREFS":"IDREF");
break;
}
case XMLAttributeDecl.TYPE_NMTOKEN: {
typeNameIndex = fStringPool.addString(attList?"NMTOKENS":"NMTOKEN");
break;
}
case XMLAttributeDecl.TYPE_NOTATION: {
typeNameIndex = fStringPool.addString("NOTATION");
break;
}
case XMLAttributeDecl.TYPE_CDATA:
default: {
typeNameIndex = fStringPool.addString("string");
break;
}
}
int attrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("type"), typeNameIndex, true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, attrIndex);
}
// attribute default type: #IMPLIED, #REQUIRED, #FIXED
boolean fixed = false;
switch (attDefaultType) {
case XMLAttributeDecl.DEFAULT_TYPE_REQUIRED: {
int useAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("use"), fStringPool.addString("required"), true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, useAttrIndex);
break;
}
case XMLAttributeDecl.DEFAULT_TYPE_FIXED: {
fixed = true;
int useAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("use"), fStringPool.addString("fixed"), true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, useAttrIndex);
break;
}
}
// attribute default value
if (attDefaultValue != -1) {
if (!fixed) {
int useAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("use"), fStringPool.addString("default"), true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, useAttrIndex);
}
int valueAttrIndex = fDeferredDocumentImpl.createAttribute(fStringPool.addSymbol("value"), attDefaultValue, true);
fDeferredDocumentImpl.setAttributeNode(attributeIndex, valueAttrIndex);
}
}
}
}
// full expansion
else if (fDocumentImpl != null) {
// get the default value
if (attDefaultValue != -1) {
if (DEBUG_ATTLIST_DECL) {
System.out.println(" adding default attribute value: "+
fStringPool.toString(attDefaultValue));
}
// get element name
String elementName = fStringPool.toString(elementDecl.rawname);
// get element definition node
NamedNodeMap elements = ((DocumentTypeImpl)fDocumentType).getElements();
ElementDefinitionImpl elementDef = (ElementDefinitionImpl)elements.getNamedItem(elementName);
if (elementDef == null) {
elementDef = fDocumentImpl.createElementDefinition(elementName);
((DocumentTypeImpl)fDocumentType).getElements().setNamedItem(elementDef);
}
// REVISIT: Check for uniqueness of element name? -Ac
// get attribute name and value index
String attrName = fStringPool.toString(attributeDecl.rawname);
String attrValue = fStringPool.toString(attDefaultValue);
// create attribute and set properties
boolean nsEnabled = false;
try { nsEnabled = getNamespaces(); }
catch (SAXException s) {}
AttrImpl attr;
if (nsEnabled) {
attr = (AttrImpl)fDocumentImpl.createAttributeNS(fStringPool.toString(attributeDecl.uri),attrName);
}
else{
attr = (AttrImpl)fDocumentImpl.createAttribute(attrName);
}
attr.setValue(attrValue);
attr.setSpecified(false);
// add default attribute to element definition
if(nsEnabled){
elementDef.getAttributes().setNamedItemNS(attr);
}
else{
elementDef.getAttributes().setNamedItem(attr);
}
}
//
// Create attribute declaration
//
try {
if (fGrammarAccess) {
// get element declaration; create it if necessary
Element schema = XUtil.getLastChildElement(fDocumentType, "schema");
String elementName = fStringPool.toString(elementDecl.rawname);
Element element = XUtil.getLastChildElement(schema, "element", "name", elementName);
if (element == null) {
element = fDocumentImpl.createElement("element");
element.setAttribute("name", elementName);
schema.appendChild(element);
}
// get type element; create it if necessary
Element type = XUtil.getLastChildElement(element, "complexType");
if (type == null) {
type = fDocumentImpl.createElement("complexType");
element.insertBefore(type, XUtil.getLastChildElement(element));
}
// create attribute and set its attributes
String attributeName = fStringPool.toString(attributeDecl.rawname);
Element attribute = XUtil.getLastChildElement(element, "attribute", "name", attributeName);
if (attribute == null) {
attribute = fDocumentImpl.createElement("attribute");
attribute.setAttribute("name", attributeName);
attribute.setAttribute("maxOccurs", "1");
((AttrImpl)attribute.getAttributeNode("maxOccurs")).setSpecified(false);
type.appendChild(attribute);
// attribute type: CDATA, ENTITY, ... , NMTOKENS; ENUMERATION
if (attType == XMLAttributeDecl.TYPE_ENUMERATION) {
Element simpleType = fDocumentImpl.createElement("simpleType");
simpleType.setAttribute("base", "NMTOKEN");
attribute.appendChild(simpleType);
String tokenizerString = enumString.substring(1, enumString.length() - 1);
StringTokenizer tokenizer = new StringTokenizer(tokenizerString, "|");
while (tokenizer.hasMoreTokens()) {
Element enumeration = fDocumentImpl.createElement("enumeration");
enumeration.setAttribute("value", tokenizer.nextToken());
simpleType.appendChild(enumeration);
}
}
else {
String typeName = null;
switch (attType) {
case XMLAttributeDecl.TYPE_ENTITY: {
typeName = attList ? "ENTITIES" : "ENTITY";
break;
}
case XMLAttributeDecl.TYPE_ID: {
typeName = "ID";
break;
}
case XMLAttributeDecl.TYPE_IDREF: {
typeName = attList ? "IDREFS" : "IDREF";
break;
}
case XMLAttributeDecl.TYPE_NMTOKEN: {
typeName = attList ? "NMTOKENS" : "NMTOKEN";
break;
}
case XMLAttributeDecl.TYPE_NOTATION: {
typeName = "NOTATION";
break;
}
case XMLAttributeDecl.TYPE_CDATA:
default: {
typeName = "string";
break;
}
}
attribute.setAttribute("type", typeName);
}
// attribute default type: #IMPLIED, #REQUIRED, #FIXED
boolean fixed = false;
switch (attDefaultType) {
case XMLAttributeDecl.DEFAULT_TYPE_REQUIRED: {
attribute.setAttribute("use", "required");
break;
}
case XMLAttributeDecl.DEFAULT_TYPE_FIXED: {
attribute.setAttribute("use", "fixed");
fixed = true;
break;
}
}
// attribute default value
if (attDefaultValue != -1) {
if (!fixed) {
attribute.setAttribute("use", "default");
}
attribute.setAttribute("value", fStringPool.toString(attDefaultValue));
}
}
}
}
catch (Exception e) {
e.printStackTrace(System.err);
}
} // if NOT defer-node-expansion
} // attlistDecl(int,int,int,String,int,int)
|
diff --git a/drools-clips/src/test/java/org/drools/clp/LhsClpParserTest.java b/drools-clips/src/test/java/org/drools/clp/LhsClpParserTest.java
index 25f9a1d0e..69ab15409 100644
--- a/drools-clips/src/test/java/org/drools/clp/LhsClpParserTest.java
+++ b/drools-clips/src/test/java/org/drools/clp/LhsClpParserTest.java
@@ -1,425 +1,425 @@
package org.drools.clp;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import junit.framework.TestCase;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.Lexer;
import org.antlr.runtime.TokenStream;
import org.drools.clp.valuehandlers.DoubleValueHandler;
import org.drools.clp.valuehandlers.FunctionCaller;
import org.drools.clp.valuehandlers.LongValueHandler;
import org.drools.lang.descr.AndDescr;
import org.drools.lang.descr.AttributeDescr;
import org.drools.lang.descr.EvalDescr;
import org.drools.lang.descr.ExistsDescr;
import org.drools.lang.descr.FieldConstraintDescr;
import org.drools.lang.descr.LiteralRestrictionDescr;
import org.drools.lang.descr.NotDescr;
import org.drools.lang.descr.OrDescr;
import org.drools.lang.descr.PatternDescr;
import org.drools.lang.descr.PredicateDescr;
import org.drools.lang.descr.RestrictionConnectiveDescr;
import org.drools.lang.descr.ReturnValueRestrictionDescr;
import org.drools.lang.descr.RuleDescr;
import org.drools.lang.descr.VariableRestrictionDescr;
public class LhsClpParserTest extends TestCase {
private CLPParser parser;
FunctionRegistry registry;
public void setUp() {
this.registry = new FunctionRegistry( BuiltinFunctions.getInstance() );
}
protected void tearDown() throws Exception {
super.tearDown();
this.parser = null;
}
public void testParseFunction() throws Exception {
BuildContext context = new ExecutionBuildContext( new CLPPredicate(), this.registry );
FunctionCaller fc = ( FunctionCaller ) parse( "(< 1 2)" ).lisp_list( context, new LispForm(context) );
assertEquals( "<", fc.getName() );
assertEquals( new LongValueHandler( 1 ), fc.getParameters()[0] );
assertEquals( new LongValueHandler( 2 ), fc.getParameters()[1] );
}
public void testPatternsRule() throws Exception {
// the first pattern bellowshould generate a descriptor tree like that:
//
// FC[person name]
// |
// OR
// +----------|------------+
// AND LR RVR
// / \
// LR VR
// MARK: is it valid to add a predicate restriction as part of a field constraint? I mean, shouldn't
// the predicate be out of the (name ...) scope?
RuleDescr rule = parse( "(defrule xxx ?b <- (person (name \"yyy\"&?bf|~\"zzz\"|~=(+ 2 3)&:(< 1 2)) ) ?c <- (hobby (type ?bf2&~iii) (rating fivestar) ) => )" ).defrule();
assertEquals( "xxx",
rule.getName() );
AndDescr lhs = rule.getLhs();
List lhsList = lhs.getDescrs();
assertEquals( 2,
lhsList.size() );
// Parse the first column
PatternDescr col = (PatternDescr) lhsList.get( 0 );
assertEquals( "?b",
col.getIdentifier() );
assertEquals( "person",
col.getObjectType() );
List colList = col.getDescrs();
assertEquals( 2,
colList.size() );
FieldConstraintDescr fieldConstraintDescr = (FieldConstraintDescr) colList.get( 0 );
assertEquals( "name",
fieldConstraintDescr.getFieldName() );
// @todo the 7th one has no constraint, as its a predicate, have to figure out how to handle this
assertEquals( RestrictionConnectiveDescr.OR,
fieldConstraintDescr.getRestriction().getConnective() );
List restrictionList = fieldConstraintDescr.getRestrictions();
assertEquals( 3,
restrictionList.size() );
RestrictionConnectiveDescr andRestr = (RestrictionConnectiveDescr) restrictionList.get( 0 );
assertEquals( RestrictionConnectiveDescr.AND,
andRestr.getConnective() );
assertEquals( 2,
andRestr.getRestrictions().size() );
LiteralRestrictionDescr litDescr = (LiteralRestrictionDescr) andRestr.getRestrictions().get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "yyy",
litDescr.getText() );
VariableRestrictionDescr varDescr = (VariableRestrictionDescr) restrictionList.get( 1 );
assertEquals( "==",
varDescr.getEvaluator() );
assertEquals( "?bf",
varDescr.getIdentifier() );
litDescr = (LiteralRestrictionDescr) restrictionList.get( 1 );
assertEquals( "!=",
litDescr.getEvaluator() );
assertEquals( "zzz",
litDescr.getText() );
ReturnValueRestrictionDescr retDescr = (ReturnValueRestrictionDescr) restrictionList.get( 2 );
assertEquals( "!=",
retDescr.getEvaluator() );
CLPReturnValue clprv = ( CLPReturnValue ) retDescr.getContent();
FunctionCaller fc = clprv.getFunctions()[0];
assertEquals( "+", fc.getName() );
assertEquals( new LongValueHandler( 2 ), fc.getParameters()[0] );
assertEquals( new LongValueHandler( 3 ), fc.getParameters()[1] );
// ----------------
- // TIRELLI NOTE's: not sure what to do with the predicate bellow
+ // this is how it would be compatible to our core engine
PredicateDescr predicateDescr = (PredicateDescr) colList.get( 1 );
CLPPredicate clpp = ( CLPPredicate ) predicateDescr.getContent();
fc = clpp.getFunctions()[0];
assertEquals( "<", fc.getName() );
assertEquals( new LongValueHandler( 1 ), fc.getParameters()[0] );
assertEquals( new LongValueHandler( 2 ), fc.getParameters()[1] );
// -----------------
// Parse the second column
col = (PatternDescr) lhsList.get( 1 );
assertEquals( "?c",
col.getIdentifier() );
assertEquals( "hobby",
col.getObjectType() );
colList = col.getDescrs();
assertEquals( 2,
colList.size() );
fieldConstraintDescr = (FieldConstraintDescr) colList.get( 0 );
restrictionList = fieldConstraintDescr.getRestrictions();
assertEquals( "type",
fieldConstraintDescr.getFieldName() );
assertEquals( RestrictionConnectiveDescr.AND,
fieldConstraintDescr.getRestriction().getConnective() );
varDescr = (VariableRestrictionDescr) restrictionList.get( 0 );
assertEquals( "==",
varDescr.getEvaluator() );
assertEquals( "?bf2",
varDescr.getIdentifier() );
litDescr = (LiteralRestrictionDescr) restrictionList.get( 1 );
assertEquals( "!=",
litDescr.getEvaluator() );
assertEquals( "iii",
litDescr.getText() );
fieldConstraintDescr = (FieldConstraintDescr) colList.get( 1 );
restrictionList = fieldConstraintDescr.getRestrictions();
assertEquals( "rating",
fieldConstraintDescr.getFieldName() );
litDescr = (LiteralRestrictionDescr) restrictionList.get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "fivestar",
litDescr.getText() );
}
public void testNestedCERule() throws Exception {
RuleDescr rule = parse( "(defrule xxx ?b <- (person (name yyy)) (or (and (hobby1 (type qqq1)) (hobby2 (type ~qqq2))) (food (veg ~shroom) ) ) => )" ).defrule();
assertEquals( "xxx",
rule.getName() );
AndDescr lhs = rule.getLhs();
List lhsList = lhs.getDescrs();
assertEquals( 2,
lhsList.size() );
// Parse the first column
PatternDescr col = (PatternDescr) lhsList.get( 0 );
assertEquals( "?b",
col.getIdentifier() );
assertEquals( "person",
col.getObjectType() );
FieldConstraintDescr fieldConstraintDescr = (FieldConstraintDescr) col.getDescrs().get( 0 );
assertEquals( "name",
fieldConstraintDescr.getFieldName() ); //
LiteralRestrictionDescr litDescr = (LiteralRestrictionDescr) fieldConstraintDescr.getRestrictions().get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "yyy",
litDescr.getText() );
OrDescr orDescr = (OrDescr) lhsList.get( 1 );
assertEquals( 2,
orDescr.getDescrs().size() );
AndDescr andDescr = (AndDescr) orDescr.getDescrs().get( 0 );
col = (PatternDescr) andDescr.getDescrs().get( 0 );
assertEquals( "hobby1",
col.getObjectType() );
fieldConstraintDescr = (FieldConstraintDescr) col.getDescrs().get( 0 );
assertEquals( "type",
fieldConstraintDescr.getFieldName() ); //
litDescr = (LiteralRestrictionDescr) fieldConstraintDescr.getRestrictions().get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "qqq1",
litDescr.getText() );
col = (PatternDescr) andDescr.getDescrs().get( 1 );
assertEquals( "hobby2",
col.getObjectType() );
fieldConstraintDescr = (FieldConstraintDescr) col.getDescrs().get( 0 );
assertEquals( "type",
fieldConstraintDescr.getFieldName() ); //
litDescr = (LiteralRestrictionDescr) fieldConstraintDescr.getRestrictions().get( 0 );
assertEquals( "!=",
litDescr.getEvaluator() );
assertEquals( "qqq2",
litDescr.getText() );
col = (PatternDescr) orDescr.getDescrs().get( 1 );
assertEquals( "food",
col.getObjectType() );
fieldConstraintDescr = (FieldConstraintDescr) col.getDescrs().get( 0 );
assertEquals( "veg",
fieldConstraintDescr.getFieldName() ); //
litDescr = (LiteralRestrictionDescr) fieldConstraintDescr.getRestrictions().get( 0 );
assertEquals( "!=",
litDescr.getEvaluator() );
assertEquals( "shroom",
litDescr.getText() );
}
public void testNotExistsRule() throws Exception {
RuleDescr rule = parse( "(defrule xxx (or (hobby1 (type qqq1)) (not (and (exists (person (name ppp))) (person (name yyy))))) => )" ).defrule();
assertEquals( "xxx",
rule.getName() );
AndDescr lhs = rule.getLhs();
List lhsList = lhs.getDescrs();
assertEquals( 1,
lhsList.size() );
OrDescr orDescr = (OrDescr) lhsList.get( 0 );
assertEquals( 2,
orDescr.getDescrs().size() );
PatternDescr col = (PatternDescr) orDescr.getDescrs().get( 0 );
assertEquals( "hobby1",
col.getObjectType() );
FieldConstraintDescr fieldConstraintDescr = (FieldConstraintDescr) col.getDescrs().get( 0 );
assertEquals( "type",
fieldConstraintDescr.getFieldName() ); //
LiteralRestrictionDescr litDescr = (LiteralRestrictionDescr) fieldConstraintDescr.getRestrictions().get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "qqq1",
litDescr.getText() );
NotDescr notDescr = (NotDescr) orDescr.getDescrs().get( 1 );
assertEquals( 1,
notDescr.getDescrs().size() );
AndDescr andDescr = (AndDescr) notDescr.getDescrs().get( 0 );
assertEquals( 2, andDescr.getDescrs().size() );
ExistsDescr existsDescr = (ExistsDescr) andDescr.getDescrs().get( 0 );
col = (PatternDescr) existsDescr.getDescrs().get( 0 );
assertEquals( "person",
col.getObjectType() );
fieldConstraintDescr = (FieldConstraintDescr) col.getDescrs().get( 0 );
assertEquals( "name",
fieldConstraintDescr.getFieldName() ); //
litDescr = (LiteralRestrictionDescr) fieldConstraintDescr.getRestrictions().get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "ppp",
litDescr.getText() );
col = (PatternDescr) andDescr.getDescrs().get( 1 );
assertEquals( "person",
col.getObjectType() );
fieldConstraintDescr = (FieldConstraintDescr) col.getDescrs().get( 0 );
assertEquals( "name",
fieldConstraintDescr.getFieldName() ); //
litDescr = (LiteralRestrictionDescr) fieldConstraintDescr.getRestrictions().get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "yyy",
litDescr.getText() );
}
public void testTestRule() throws Exception {
RuleDescr rule = parse( "(defrule xxx (test (< 9.0 1.3) ) => )" ).defrule();
assertEquals( "xxx",
rule.getName() );
AndDescr lhs = rule.getLhs();
List lhsList = lhs.getDescrs();
assertEquals( 1,
lhsList.size() );
EvalDescr evalDescr = (EvalDescr) lhsList.get( 0 );
CLPEval clpe = ( CLPEval ) evalDescr.getContent();
FunctionCaller f = clpe.getFunctions()[0];
assertEquals( "<", f.getName() );
assertEquals( new DoubleValueHandler( 9.0 ), f.getParameters()[0] );
assertEquals( new DoubleValueHandler( 1.3 ), f.getParameters()[1] );
}
public void testRuleHeader() throws Exception {
RuleDescr rule = parse( "(defrule MAIN::name \"docs\"(declare (salience -100) ) => )" ).defrule();
List attributes = rule.getAttributes();
AttributeDescr module = ( AttributeDescr ) attributes.get( 0 );
assertEquals( "agenda-group", module.getName() );
assertEquals( "MAIN", module.getValue() );
assertEquals("name", rule.getName() );
AttributeDescr dialect = ( AttributeDescr ) attributes.get( 1 );
assertEquals( "dialect", dialect.getName() );
assertEquals( "clips", dialect.getValue() );
AttributeDescr salience = ( AttributeDescr ) attributes.get( 2 );
assertEquals( "salience", salience.getName() );
assertEquals( "-100", salience.getValue() );
}
private CLPParser parse(final String text) throws Exception {
this.parser = newParser( newTokenStream( newLexer( newCharStream( text ) ) ) );
return this.parser;
}
private CLPParser parse(final String source,
final String text) throws Exception {
this.parser = newParser( newTokenStream( newLexer( newCharStream( text ) ) ) );
this.parser.setSource( source );
return this.parser;
}
private Reader getReader(final String name) throws Exception {
final InputStream in = getClass().getResourceAsStream( name );
return new InputStreamReader( in );
}
private CLPParser parseResource(final String name) throws Exception {
// System.err.println( getClass().getResource( name ) );
Reader reader = getReader( name );
final StringBuffer text = new StringBuffer();
final char[] buf = new char[1024];
int len = 0;
while ( (len = reader.read( buf )) >= 0 ) {
text.append( buf,
0,
len );
}
return parse( name,
text.toString() );
}
private CharStream newCharStream(final String text) {
return new ANTLRStringStream( text );
}
private CLPLexer newLexer(final CharStream charStream) {
return new CLPLexer( charStream );
}
private TokenStream newTokenStream(final Lexer lexer) {
return new CommonTokenStream( lexer );
}
private CLPParser newParser(final TokenStream tokenStream) {
final CLPParser p = new CLPParser( tokenStream );
p.setFunctionRegistry( new FunctionRegistry( BuiltinFunctions.getInstance() ) );
//p.setParserDebug( true );
return p;
}
private void assertEqualsIgnoreWhitespace(final String expected,
final String actual) {
final String cleanExpected = expected.replaceAll( "\\s+",
"" );
final String cleanActual = actual.replaceAll( "\\s+",
"" );
assertEquals( cleanExpected,
cleanActual );
}
}
| true | true | public void testPatternsRule() throws Exception {
// the first pattern bellowshould generate a descriptor tree like that:
//
// FC[person name]
// |
// OR
// +----------|------------+
// AND LR RVR
// / \
// LR VR
// MARK: is it valid to add a predicate restriction as part of a field constraint? I mean, shouldn't
// the predicate be out of the (name ...) scope?
RuleDescr rule = parse( "(defrule xxx ?b <- (person (name \"yyy\"&?bf|~\"zzz\"|~=(+ 2 3)&:(< 1 2)) ) ?c <- (hobby (type ?bf2&~iii) (rating fivestar) ) => )" ).defrule();
assertEquals( "xxx",
rule.getName() );
AndDescr lhs = rule.getLhs();
List lhsList = lhs.getDescrs();
assertEquals( 2,
lhsList.size() );
// Parse the first column
PatternDescr col = (PatternDescr) lhsList.get( 0 );
assertEquals( "?b",
col.getIdentifier() );
assertEquals( "person",
col.getObjectType() );
List colList = col.getDescrs();
assertEquals( 2,
colList.size() );
FieldConstraintDescr fieldConstraintDescr = (FieldConstraintDescr) colList.get( 0 );
assertEquals( "name",
fieldConstraintDescr.getFieldName() );
// @todo the 7th one has no constraint, as its a predicate, have to figure out how to handle this
assertEquals( RestrictionConnectiveDescr.OR,
fieldConstraintDescr.getRestriction().getConnective() );
List restrictionList = fieldConstraintDescr.getRestrictions();
assertEquals( 3,
restrictionList.size() );
RestrictionConnectiveDescr andRestr = (RestrictionConnectiveDescr) restrictionList.get( 0 );
assertEquals( RestrictionConnectiveDescr.AND,
andRestr.getConnective() );
assertEquals( 2,
andRestr.getRestrictions().size() );
LiteralRestrictionDescr litDescr = (LiteralRestrictionDescr) andRestr.getRestrictions().get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "yyy",
litDescr.getText() );
VariableRestrictionDescr varDescr = (VariableRestrictionDescr) restrictionList.get( 1 );
assertEquals( "==",
varDescr.getEvaluator() );
assertEquals( "?bf",
varDescr.getIdentifier() );
litDescr = (LiteralRestrictionDescr) restrictionList.get( 1 );
assertEquals( "!=",
litDescr.getEvaluator() );
assertEquals( "zzz",
litDescr.getText() );
ReturnValueRestrictionDescr retDescr = (ReturnValueRestrictionDescr) restrictionList.get( 2 );
assertEquals( "!=",
retDescr.getEvaluator() );
CLPReturnValue clprv = ( CLPReturnValue ) retDescr.getContent();
FunctionCaller fc = clprv.getFunctions()[0];
assertEquals( "+", fc.getName() );
assertEquals( new LongValueHandler( 2 ), fc.getParameters()[0] );
assertEquals( new LongValueHandler( 3 ), fc.getParameters()[1] );
// ----------------
// TIRELLI NOTE's: not sure what to do with the predicate bellow
PredicateDescr predicateDescr = (PredicateDescr) colList.get( 1 );
CLPPredicate clpp = ( CLPPredicate ) predicateDescr.getContent();
fc = clpp.getFunctions()[0];
assertEquals( "<", fc.getName() );
assertEquals( new LongValueHandler( 1 ), fc.getParameters()[0] );
assertEquals( new LongValueHandler( 2 ), fc.getParameters()[1] );
// -----------------
// Parse the second column
col = (PatternDescr) lhsList.get( 1 );
assertEquals( "?c",
col.getIdentifier() );
assertEquals( "hobby",
col.getObjectType() );
colList = col.getDescrs();
assertEquals( 2,
colList.size() );
fieldConstraintDescr = (FieldConstraintDescr) colList.get( 0 );
restrictionList = fieldConstraintDescr.getRestrictions();
assertEquals( "type",
fieldConstraintDescr.getFieldName() );
assertEquals( RestrictionConnectiveDescr.AND,
fieldConstraintDescr.getRestriction().getConnective() );
varDescr = (VariableRestrictionDescr) restrictionList.get( 0 );
assertEquals( "==",
varDescr.getEvaluator() );
assertEquals( "?bf2",
varDescr.getIdentifier() );
litDescr = (LiteralRestrictionDescr) restrictionList.get( 1 );
assertEquals( "!=",
litDescr.getEvaluator() );
assertEquals( "iii",
litDescr.getText() );
fieldConstraintDescr = (FieldConstraintDescr) colList.get( 1 );
restrictionList = fieldConstraintDescr.getRestrictions();
assertEquals( "rating",
fieldConstraintDescr.getFieldName() );
litDescr = (LiteralRestrictionDescr) restrictionList.get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "fivestar",
litDescr.getText() );
}
| public void testPatternsRule() throws Exception {
// the first pattern bellowshould generate a descriptor tree like that:
//
// FC[person name]
// |
// OR
// +----------|------------+
// AND LR RVR
// / \
// LR VR
// MARK: is it valid to add a predicate restriction as part of a field constraint? I mean, shouldn't
// the predicate be out of the (name ...) scope?
RuleDescr rule = parse( "(defrule xxx ?b <- (person (name \"yyy\"&?bf|~\"zzz\"|~=(+ 2 3)&:(< 1 2)) ) ?c <- (hobby (type ?bf2&~iii) (rating fivestar) ) => )" ).defrule();
assertEquals( "xxx",
rule.getName() );
AndDescr lhs = rule.getLhs();
List lhsList = lhs.getDescrs();
assertEquals( 2,
lhsList.size() );
// Parse the first column
PatternDescr col = (PatternDescr) lhsList.get( 0 );
assertEquals( "?b",
col.getIdentifier() );
assertEquals( "person",
col.getObjectType() );
List colList = col.getDescrs();
assertEquals( 2,
colList.size() );
FieldConstraintDescr fieldConstraintDescr = (FieldConstraintDescr) colList.get( 0 );
assertEquals( "name",
fieldConstraintDescr.getFieldName() );
// @todo the 7th one has no constraint, as its a predicate, have to figure out how to handle this
assertEquals( RestrictionConnectiveDescr.OR,
fieldConstraintDescr.getRestriction().getConnective() );
List restrictionList = fieldConstraintDescr.getRestrictions();
assertEquals( 3,
restrictionList.size() );
RestrictionConnectiveDescr andRestr = (RestrictionConnectiveDescr) restrictionList.get( 0 );
assertEquals( RestrictionConnectiveDescr.AND,
andRestr.getConnective() );
assertEquals( 2,
andRestr.getRestrictions().size() );
LiteralRestrictionDescr litDescr = (LiteralRestrictionDescr) andRestr.getRestrictions().get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "yyy",
litDescr.getText() );
VariableRestrictionDescr varDescr = (VariableRestrictionDescr) restrictionList.get( 1 );
assertEquals( "==",
varDescr.getEvaluator() );
assertEquals( "?bf",
varDescr.getIdentifier() );
litDescr = (LiteralRestrictionDescr) restrictionList.get( 1 );
assertEquals( "!=",
litDescr.getEvaluator() );
assertEquals( "zzz",
litDescr.getText() );
ReturnValueRestrictionDescr retDescr = (ReturnValueRestrictionDescr) restrictionList.get( 2 );
assertEquals( "!=",
retDescr.getEvaluator() );
CLPReturnValue clprv = ( CLPReturnValue ) retDescr.getContent();
FunctionCaller fc = clprv.getFunctions()[0];
assertEquals( "+", fc.getName() );
assertEquals( new LongValueHandler( 2 ), fc.getParameters()[0] );
assertEquals( new LongValueHandler( 3 ), fc.getParameters()[1] );
// ----------------
// this is how it would be compatible to our core engine
PredicateDescr predicateDescr = (PredicateDescr) colList.get( 1 );
CLPPredicate clpp = ( CLPPredicate ) predicateDescr.getContent();
fc = clpp.getFunctions()[0];
assertEquals( "<", fc.getName() );
assertEquals( new LongValueHandler( 1 ), fc.getParameters()[0] );
assertEquals( new LongValueHandler( 2 ), fc.getParameters()[1] );
// -----------------
// Parse the second column
col = (PatternDescr) lhsList.get( 1 );
assertEquals( "?c",
col.getIdentifier() );
assertEquals( "hobby",
col.getObjectType() );
colList = col.getDescrs();
assertEquals( 2,
colList.size() );
fieldConstraintDescr = (FieldConstraintDescr) colList.get( 0 );
restrictionList = fieldConstraintDescr.getRestrictions();
assertEquals( "type",
fieldConstraintDescr.getFieldName() );
assertEquals( RestrictionConnectiveDescr.AND,
fieldConstraintDescr.getRestriction().getConnective() );
varDescr = (VariableRestrictionDescr) restrictionList.get( 0 );
assertEquals( "==",
varDescr.getEvaluator() );
assertEquals( "?bf2",
varDescr.getIdentifier() );
litDescr = (LiteralRestrictionDescr) restrictionList.get( 1 );
assertEquals( "!=",
litDescr.getEvaluator() );
assertEquals( "iii",
litDescr.getText() );
fieldConstraintDescr = (FieldConstraintDescr) colList.get( 1 );
restrictionList = fieldConstraintDescr.getRestrictions();
assertEquals( "rating",
fieldConstraintDescr.getFieldName() );
litDescr = (LiteralRestrictionDescr) restrictionList.get( 0 );
assertEquals( "==",
litDescr.getEvaluator() );
assertEquals( "fivestar",
litDescr.getText() );
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/cache/AbstractBroadcasterCache.java b/modules/cpr/src/main/java/org/atmosphere/cache/AbstractBroadcasterCache.java
index 5130322f0..ccd8f3166 100644
--- a/modules/cpr/src/main/java/org/atmosphere/cache/AbstractBroadcasterCache.java
+++ b/modules/cpr/src/main/java/org/atmosphere/cache/AbstractBroadcasterCache.java
@@ -1,194 +1,194 @@
/*
* Copyright 2012 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.cache;
import org.atmosphere.cpr.BroadcasterCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Abstract {@link org.atmosphere.cpr.BroadcasterCache} which is used to implement headers or query parameters or
* session based caching.
*
* @author Paul Khodchenkov
* @author Jeanfrancois Arcand
*/
public abstract class AbstractBroadcasterCache implements BroadcasterCache {
private final Logger logger = LoggerFactory.getLogger(AbstractBroadcasterCache.class);
protected final List<CacheMessage> messages = new LinkedList<CacheMessage>();
protected final Set<String> messagesIds = new HashSet<String>();
protected final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
protected ScheduledFuture scheduledFuture;
protected long maxCacheTime = TimeUnit.MINUTES.toMillis(2);//2 minutes
protected long invalidateCacheInterval = TimeUnit.MINUTES.toMillis(1);//1 minute
protected ScheduledExecutorService reaper = Executors.newSingleThreadScheduledExecutor();
protected boolean isShared = false;
protected final List<BroadcasterCacheInspector> inspectors = new LinkedList<BroadcasterCacheInspector>();
@Override
public void start() {
reaper.scheduleAtFixedRate(new Runnable() {
public void run() {
readWriteLock.writeLock().lock();
try {
long now = System.nanoTime();
List<CacheMessage> expiredMessages = new ArrayList<CacheMessage>();
for (CacheMessage message : messages) {
if (TimeUnit.NANOSECONDS.toMillis(now - message.getCreateTime()) > maxCacheTime) {
expiredMessages.add(message);
}
}
for (CacheMessage expiredMessage : expiredMessages) {
messages.remove(expiredMessage);
messagesIds.remove(expiredMessage.getId());
}
} finally {
readWriteLock.writeLock().unlock();
}
}
- }, 0, invalidateCacheInterval, TimeUnit.MINUTES);
+ }, 0, invalidateCacheInterval, TimeUnit.MILLISECONDS);
}
@Override
public void stop() {
if (scheduledFuture != null) {
scheduledFuture.cancel(false);
scheduledFuture = null;
}
if (!isShared) {
reaper.shutdown();
}
}
protected void put(Message message, Long now) {
if (!inspect(message)) return;
logger.trace("Caching message {} for Broadcaster {}", message.message);
readWriteLock.writeLock().lock();
try {
boolean hasMessageWithSameId = messagesIds.contains(message.id);
if (!hasMessageWithSameId) {
CacheMessage cacheMessage = new CacheMessage(message.id, now, message.message);
messages.add(cacheMessage);
messagesIds.add(message.id);
}
} finally {
readWriteLock.writeLock().unlock();
}
}
protected List<Object> get(long cacheHeaderTime) {
List<Object> result = new ArrayList<Object>();
readWriteLock.readLock().lock();
try {
for (CacheMessage cacheMessage : messages) {
if (cacheMessage.getCreateTime() > cacheHeaderTime) {
result.add(cacheMessage.getMessage());
}
}
} finally {
readWriteLock.readLock().unlock();
}
logger.trace("Retrieved messages {}", result);
return result;
}
/**
* Set to true the associated {@link #getReaper()} is shared amongs {@link BroadcasterCache}
*
* @param isShared to true if shared. False by default.
* @return this
*/
public AbstractBroadcasterCache setShared(boolean isShared) {
this.isShared = isShared;
return this;
}
/**
* Set the {@link ScheduledExecutorService} to clear the cached message.
*
* @param reaper the {@link ScheduledExecutorService} to clear the cached message.
* @return this
*/
public AbstractBroadcasterCache setReaper(ScheduledExecutorService reaper) {
this.reaper = reaper;
return this;
}
/**
* Return the {@link ScheduledExecutorService}
*
* @return the {@link ScheduledExecutorService}
*/
public ScheduledExecutorService getReaper() {
return reaper;
}
/**
* Set the time, in millisecond, the cache will be checked and purged.
*
* @param invalidateCacheInterval
* @return this
*/
public AbstractBroadcasterCache setInvalidateCacheInterval(long invalidateCacheInterval) {
this.invalidateCacheInterval = invalidateCacheInterval;
return this;
}
/**
* Set the maxium time, in millisecond, a message stay alive in the cache.
*
* @param maxCacheTime the maxium time, in millisecond, a message stay alive in the cache.
* @return this
*/
public AbstractBroadcasterCache setMaxCacheTime(long maxCacheTime) {
this.maxCacheTime = maxCacheTime;
return this;
}
@Override
public BroadcasterCache inspector(BroadcasterCacheInspector b) {
inspectors.add(b);
return this;
}
protected boolean inspect(Message m) {
for (BroadcasterCacheInspector b : inspectors) {
if (!b.inspect(m)) return false;
}
return true;
}
}
| true | true | public void start() {
reaper.scheduleAtFixedRate(new Runnable() {
public void run() {
readWriteLock.writeLock().lock();
try {
long now = System.nanoTime();
List<CacheMessage> expiredMessages = new ArrayList<CacheMessage>();
for (CacheMessage message : messages) {
if (TimeUnit.NANOSECONDS.toMillis(now - message.getCreateTime()) > maxCacheTime) {
expiredMessages.add(message);
}
}
for (CacheMessage expiredMessage : expiredMessages) {
messages.remove(expiredMessage);
messagesIds.remove(expiredMessage.getId());
}
} finally {
readWriteLock.writeLock().unlock();
}
}
}, 0, invalidateCacheInterval, TimeUnit.MINUTES);
}
| public void start() {
reaper.scheduleAtFixedRate(new Runnable() {
public void run() {
readWriteLock.writeLock().lock();
try {
long now = System.nanoTime();
List<CacheMessage> expiredMessages = new ArrayList<CacheMessage>();
for (CacheMessage message : messages) {
if (TimeUnit.NANOSECONDS.toMillis(now - message.getCreateTime()) > maxCacheTime) {
expiredMessages.add(message);
}
}
for (CacheMessage expiredMessage : expiredMessages) {
messages.remove(expiredMessage);
messagesIds.remove(expiredMessage.getId());
}
} finally {
readWriteLock.writeLock().unlock();
}
}
}, 0, invalidateCacheInterval, TimeUnit.MILLISECONDS);
}
|
diff --git a/phone/com/android/internal/policy/impl/LockScreen.java b/phone/com/android/internal/policy/impl/LockScreen.java
index 6da03ab..7514cc2 100644
--- a/phone/com/android/internal/policy/impl/LockScreen.java
+++ b/phone/com/android/internal/policy/impl/LockScreen.java
@@ -1,588 +1,588 @@
/*
* 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.internal.policy.impl;
import com.android.internal.R;
import com.android.internal.telephony.IccCard;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.SlidingTab;
import android.content.Context;
import android.content.res.Resources;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.media.AudioManager;
import android.os.SystemProperties;
import java.util.Date;
import java.io.File;
/**
* The screen within {@link LockPatternKeyguardView} that shows general
* information about the device depending on its state, and how to get
* past it, as applicable.
*/
class LockScreen extends LinearLayout implements KeyguardScreen, KeyguardUpdateMonitor.InfoCallback,
KeyguardUpdateMonitor.SimStateCallback, KeyguardUpdateMonitor.ConfigurationChangeCallback,
SlidingTab.OnTriggerListener {
private static final boolean DBG = false;
private static final String TAG = "LockScreen";
private static final String ENABLE_MENU_KEY_FILE = "/data/local/enable_menu_key";
private Status mStatus = Status.Normal;
private final LockPatternUtils mLockPatternUtils;
private final KeyguardUpdateMonitor mUpdateMonitor;
private final KeyguardScreenCallback mCallback;
private TextView mCarrier;
private SlidingTab mSelector;
private TextView mTime;
private TextView mDate;
private TextView mStatus1;
private TextView mStatus2;
private TextView mScreenLocked;
private Button mEmergencyCallButton;
// are we showing battery information?
private boolean mShowingBatteryInfo = false;
// last known plugged in state
private boolean mPluggedIn = false;
// last known battery level
private int mBatteryLevel = 100;
private String mNextAlarm = null;
private Drawable mAlarmIcon = null;
private String mCharging = null;
private Drawable mChargingIcon = null;
private boolean mSilentMode;
private AudioManager mAudioManager;
private String mDateFormatString;
private java.text.DateFormat mTimeFormat;
private boolean mCreatedInPortrait;
private boolean mEnableMenuKeyInLockScreen;
/**
* The status of this lock screen.
*/
enum Status {
/**
* Normal case (sim card present, it's not locked)
*/
Normal(true),
/**
* The sim card is 'network locked'.
*/
NetworkLocked(true),
/**
* The sim card is missing.
*/
SimMissing(false),
/**
* The sim card is missing, and this is the device isn't provisioned, so we don't let
* them get past the screen.
*/
SimMissingLocked(false),
/**
* The sim card is PUK locked, meaning they've entered the wrong sim unlock code too many
* times.
*/
SimPukLocked(false),
/**
* The sim card is locked.
*/
SimLocked(true);
private final boolean mShowStatusLines;
Status(boolean mShowStatusLines) {
this.mShowStatusLines = mShowStatusLines;
}
/**
* @return Whether the status lines (battery level and / or next alarm) are shown while
* in this state. Mostly dictated by whether this is room for them.
*/
public boolean showStatusLines() {
return mShowStatusLines;
}
}
/**
* In general, we enable unlocking the insecure key guard with the menu key. However, there are
* some cases where we wish to disable it, notably when the menu button placement or technology
* is prone to false positives.
*
* @return true if the menu key should be enabled
*/
private boolean shouldEnableMenuKey() {
final Resources res = getResources();
final boolean configDisabled = res.getBoolean(R.bool.config_disableMenuKeyInLockScreen);
final boolean isMonkey = SystemProperties.getBoolean("ro.monkey", false);
final boolean fileOverride = (new File(ENABLE_MENU_KEY_FILE)).exists();
return !configDisabled || isMonkey || fileOverride;
}
/**
* @param context Used to setup the view.
* @param lockPatternUtils Used to know the state of the lock pattern settings.
* @param updateMonitor Used to register for updates on various keyguard related
* state, and query the initial state at setup.
* @param callback Used to communicate back to the host keyguard view.
*/
LockScreen(Context context, LockPatternUtils lockPatternUtils,
KeyguardUpdateMonitor updateMonitor,
KeyguardScreenCallback callback) {
super(context);
mLockPatternUtils = lockPatternUtils;
mUpdateMonitor = updateMonitor;
mCallback = callback;
mEnableMenuKeyInLockScreen = shouldEnableMenuKey();
mCreatedInPortrait = updateMonitor.isInPortrait();
final LayoutInflater inflater = LayoutInflater.from(context);
if (mCreatedInPortrait) {
inflater.inflate(R.layout.keyguard_screen_tab_unlock, this, true);
} else {
inflater.inflate(R.layout.keyguard_screen_tab_unlock_land, this, true);
}
mCarrier = (TextView) findViewById(R.id.carrier);
mDate = (TextView) findViewById(R.id.date);
mStatus1 = (TextView) findViewById(R.id.status1);
mStatus2 = (TextView) findViewById(R.id.status2);
mEmergencyCallButton = (Button) findViewById(R.id.emergencyCallButton);
mEmergencyCallButton.setText(R.string.lockscreen_emergency_call);
mScreenLocked = (TextView) findViewById(R.id.screenLocked);
mSelector = (SlidingTab) findViewById(R.id.tab_selector);
mSelector.setHoldAfterTrigger(true, false);
mSelector.setLeftHintText(R.string.lockscreen_unlock_label);
mEmergencyCallButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallback.takeEmergencyCallAction();
}
});
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
updateMonitor.registerInfoCallback(this);
updateMonitor.registerSimStateCallback(this);
updateMonitor.registerConfigurationChangeCallback(this);
mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mSilentMode = isSilentMode();
mSelector.setLeftTabResources(
R.drawable.ic_jog_dial_unlock,
R.drawable.jog_tab_target_green,
R.drawable.jog_tab_bar_left_unlock,
R.drawable.jog_tab_left_unlock);
updateRightTabResources();
mSelector.setOnTriggerListener(this);
resetStatusInfo(updateMonitor);
}
private boolean isSilentMode() {
return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
}
private void updateRightTabResources() {
mSelector.setRightTabResources(
mSilentMode ? R.drawable.ic_jog_dial_sound_off : R.drawable.ic_jog_dial_sound_on,
mSilentMode ? R.drawable.jog_tab_target_yellow : R.drawable.jog_tab_target_gray,
mSilentMode ? R.drawable.jog_tab_bar_right_sound_on
: R.drawable.jog_tab_bar_right_sound_off,
mSilentMode ? R.drawable.jog_tab_right_sound_on
: R.drawable.jog_tab_right_sound_off);
}
private void resetStatusInfo(KeyguardUpdateMonitor updateMonitor) {
mShowingBatteryInfo = updateMonitor.shouldShowBatteryInfo();
mPluggedIn = updateMonitor.isDevicePluggedIn();
mBatteryLevel = updateMonitor.getBatteryLevel();
mStatus = getCurrentStatus(updateMonitor.getSimState());
updateLayout(mStatus);
refreshBatteryStringAndIcon();
refreshAlarmDisplay();
mTimeFormat = DateFormat.getTimeFormat(getContext());
mDateFormatString = getContext().getString(R.string.full_wday_month_day_no_year);
refreshTimeAndDateDisplay();
updateStatusLines();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mEnableMenuKeyInLockScreen) {
mCallback.goToUnlockScreen();
}
return false;
}
/** {@inheritDoc} */
public void onTrigger(View v, int whichHandle) {
if (whichHandle == SlidingTab.OnTriggerListener.LEFT_HANDLE) {
mCallback.goToUnlockScreen();
} else if (whichHandle == SlidingTab.OnTriggerListener.RIGHT_HANDLE) {
// toggle silent mode
mSilentMode = !mSilentMode;
mAudioManager.setRingerMode(mSilentMode ? AudioManager.RINGER_MODE_SILENT
: AudioManager.RINGER_MODE_NORMAL);
updateRightTabResources();
String message = mSilentMode ?
getContext().getString(R.string.global_action_silent_mode_on_status) :
getContext().getString(R.string.global_action_silent_mode_off_status);
final int toastIcon = mSilentMode ? R.drawable.ic_lock_ringer_off
: R.drawable.ic_lock_ringer_on;
toastMessage(mScreenLocked, message, toastIcon);
mCallback.pokeWakelock();
}
}
/** {@inheritDoc} */
public void onGrabbedStateChange(View v, int grabbedState) {
if (grabbedState == SlidingTab.OnTriggerListener.RIGHT_HANDLE) {
mSilentMode = isSilentMode();
mSelector.setRightHintText(mSilentMode ? R.string.lockscreen_sound_on_label
: R.string.lockscreen_sound_off_label);
}
mCallback.pokeWakelock();
}
/**
* Displays a message in a text view and then removes it.
* @param textView The text view.
* @param text The text.
* @param iconResourceId The left hand icon.
*/
private void toastMessage(final TextView textView, final String text, final int iconResourceId) {
if (mPendingR1 != null) {
textView.removeCallbacks(mPendingR1);
mPendingR1 = null;
}
if (mPendingR2 != null) {
textView.removeCallbacks(mPendingR2);
mPendingR2 = null;
}
mPendingR1 = new Runnable() {
public void run() {
textView.setText(text);
textView.setCompoundDrawablesWithIntrinsicBounds(iconResourceId, 0, 0, 0);
textView.setCompoundDrawablePadding(4);
}
};
textView.postDelayed(mPendingR1, 0);
mPendingR2 = new Runnable() {
public void run() {
textView.setText("");
textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
};
textView.postDelayed(mPendingR2, 3500);
}
private Runnable mPendingR1;
private Runnable mPendingR2;
private void refreshAlarmDisplay() {
mNextAlarm = mLockPatternUtils.getNextAlarm();
if (mNextAlarm != null) {
mAlarmIcon = getContext().getResources().getDrawable(R.drawable.ic_lock_idle_alarm);
}
updateStatusLines();
}
/** {@inheritDoc} */
public void onRefreshBatteryInfo(boolean showBatteryInfo, boolean pluggedIn,
int batteryLevel) {
if (DBG) Log.d(TAG, "onRefreshBatteryInfo(" + showBatteryInfo + ", " + pluggedIn + ")");
mShowingBatteryInfo = showBatteryInfo;
mPluggedIn = pluggedIn;
mBatteryLevel = batteryLevel;
refreshBatteryStringAndIcon();
updateStatusLines();
}
private void refreshBatteryStringAndIcon() {
if (!mShowingBatteryInfo) {
mCharging = null;
return;
}
if (mChargingIcon == null) {
mChargingIcon =
getContext().getResources().getDrawable(R.drawable.ic_lock_idle_charging);
}
if (mPluggedIn) {
if (mBatteryLevel >= 100) {
mCharging = getContext().getString(R.string.lockscreen_charged);
} else {
mCharging = getContext().getString(R.string.lockscreen_plugged_in, mBatteryLevel);
}
} else {
mCharging = getContext().getString(R.string.lockscreen_low_battery);
}
}
/** {@inheritDoc} */
public void onTimeChanged() {
refreshTimeAndDateDisplay();
}
private void refreshTimeAndDateDisplay() {
mDate.setText(DateFormat.format(mDateFormatString, new Date()));
}
private void updateStatusLines() {
if (!mStatus.showStatusLines()
|| (mCharging == null && mNextAlarm == null)) {
mStatus1.setVisibility(View.INVISIBLE);
mStatus2.setVisibility(View.INVISIBLE);
} else if (mCharging != null && mNextAlarm == null) {
// charging only
mStatus1.setVisibility(View.VISIBLE);
mStatus2.setVisibility(View.INVISIBLE);
mStatus1.setText(mCharging);
mStatus1.setCompoundDrawablesWithIntrinsicBounds(mChargingIcon, null, null, null);
} else if (mNextAlarm != null && mCharging == null) {
// next alarm only
mStatus1.setVisibility(View.VISIBLE);
mStatus2.setVisibility(View.INVISIBLE);
mStatus1.setText(mNextAlarm);
mStatus1.setCompoundDrawablesWithIntrinsicBounds(mAlarmIcon, null, null, null);
} else if (mCharging != null && mNextAlarm != null) {
// both charging and next alarm
mStatus1.setVisibility(View.VISIBLE);
mStatus2.setVisibility(View.VISIBLE);
mStatus1.setText(mCharging);
mStatus1.setCompoundDrawablesWithIntrinsicBounds(mChargingIcon, null, null, null);
mStatus2.setText(mNextAlarm);
mStatus2.setCompoundDrawablesWithIntrinsicBounds(mAlarmIcon, null, null, null);
}
}
/** {@inheritDoc} */
public void onRefreshCarrierInfo(CharSequence plmn, CharSequence spn) {
if (DBG) Log.d(TAG, "onRefreshCarrierInfo(" + plmn + ", " + spn + ")");
updateLayout(mStatus);
}
private void putEmergencyBelow(int viewId) {
final RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) mEmergencyCallButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.BELOW, viewId);
mEmergencyCallButton.setLayoutParams(layoutParams);
}
/**
* Determine the current status of the lock screen given the sim state and other stuff.
*/
private Status getCurrentStatus(IccCard.State simState) {
boolean missingAndNotProvisioned = (!mUpdateMonitor.isDeviceProvisioned()
&& simState == IccCard.State.ABSENT);
if (missingAndNotProvisioned) {
return Status.SimMissingLocked;
}
switch (simState) {
case ABSENT:
return Status.SimMissing;
case NETWORK_LOCKED:
return Status.SimMissingLocked;
case NOT_READY:
return Status.SimMissing;
case PIN_REQUIRED:
return Status.SimLocked;
case PUK_REQUIRED:
return Status.SimPukLocked;
case READY:
return Status.Normal;
case UNKNOWN:
return Status.SimMissing;
}
return Status.SimMissing;
}
/**
* Update the layout to match the current status.
*/
private void updateLayout(Status status) {
switch (status) {
case Normal:
// text
mCarrier.setText(
getCarrierString(
mUpdateMonitor.getTelephonyPlmn(),
mUpdateMonitor.getTelephonySpn()));
// mScreenLocked.setText(R.string.lockscreen_screen_locked);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.GONE);
break;
case NetworkLocked:
// text
mCarrier.setText(R.string.lockscreen_network_locked_message);
mScreenLocked.setText(R.string.lockscreen_instructions_when_pattern_disabled);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.GONE);
break;
case SimMissing:
// text
mCarrier.setText(R.string.lockscreen_missing_sim_message_short);
mScreenLocked.setText(R.string.lockscreen_instructions_when_pattern_disabled);
// layout
mScreenLocked.setVisibility(View.INVISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
- putEmergencyBelow(R.id.divider);
+ putEmergencyBelow(R.id.screenLocked);
break;
case SimMissingLocked:
// text
mCarrier.setText(R.string.lockscreen_missing_sim_message_short);
mScreenLocked.setText(R.string.lockscreen_missing_sim_instructions);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.GONE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
putEmergencyBelow(R.id.screenLocked);
break;
case SimLocked:
// text
mCarrier.setText(R.string.lockscreen_sim_locked_message);
// layout
mScreenLocked.setVisibility(View.INVISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.GONE);
break;
case SimPukLocked:
// text
mCarrier.setText(R.string.lockscreen_sim_puk_locked_message);
mScreenLocked.setText(R.string.lockscreen_sim_puk_locked_instructions);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.GONE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
putEmergencyBelow(R.id.screenLocked);
break;
}
}
static CharSequence getCarrierString(CharSequence telephonyPlmn, CharSequence telephonySpn) {
if (telephonyPlmn != null && telephonySpn == null) {
return telephonyPlmn;
} else if (telephonyPlmn != null && telephonySpn != null) {
return telephonyPlmn + "\n" + telephonySpn;
} else if (telephonyPlmn == null && telephonySpn != null) {
return telephonySpn;
} else {
return "";
}
}
public void onSimStateChanged(IccCard.State simState) {
if (DBG) Log.d(TAG, "onSimStateChanged(" + simState + ")");
mStatus = getCurrentStatus(simState);
updateLayout(mStatus);
updateStatusLines();
}
public void onOrientationChange(boolean inPortrait) {
if (inPortrait != mCreatedInPortrait) {
mCallback.recreateMe();
}
}
public void onKeyboardChange(boolean isKeyboardOpen) {
if (mUpdateMonitor.isKeyguardBypassEnabled() && isKeyboardOpen) {
mCallback.goToUnlockScreen();
}
}
/** {@inheritDoc} */
public boolean needsInput() {
return false;
}
/** {@inheritDoc} */
public void onPause() {
}
/** {@inheritDoc} */
public void onResume() {
resetStatusInfo(mUpdateMonitor);
}
/** {@inheritDoc} */
public void cleanUp() {
mUpdateMonitor.removeCallback(this);
}
/** {@inheritDoc} */
public void onRingerModeChanged(int state) {
boolean silent = AudioManager.RINGER_MODE_SILENT == state;
if (silent != mSilentMode) {
mSilentMode = silent;
updateRightTabResources();
}
}
}
| true | true | private void updateLayout(Status status) {
switch (status) {
case Normal:
// text
mCarrier.setText(
getCarrierString(
mUpdateMonitor.getTelephonyPlmn(),
mUpdateMonitor.getTelephonySpn()));
// mScreenLocked.setText(R.string.lockscreen_screen_locked);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.GONE);
break;
case NetworkLocked:
// text
mCarrier.setText(R.string.lockscreen_network_locked_message);
mScreenLocked.setText(R.string.lockscreen_instructions_when_pattern_disabled);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.GONE);
break;
case SimMissing:
// text
mCarrier.setText(R.string.lockscreen_missing_sim_message_short);
mScreenLocked.setText(R.string.lockscreen_instructions_when_pattern_disabled);
// layout
mScreenLocked.setVisibility(View.INVISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
putEmergencyBelow(R.id.divider);
break;
case SimMissingLocked:
// text
mCarrier.setText(R.string.lockscreen_missing_sim_message_short);
mScreenLocked.setText(R.string.lockscreen_missing_sim_instructions);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.GONE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
putEmergencyBelow(R.id.screenLocked);
break;
case SimLocked:
// text
mCarrier.setText(R.string.lockscreen_sim_locked_message);
// layout
mScreenLocked.setVisibility(View.INVISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.GONE);
break;
case SimPukLocked:
// text
mCarrier.setText(R.string.lockscreen_sim_puk_locked_message);
mScreenLocked.setText(R.string.lockscreen_sim_puk_locked_instructions);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.GONE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
putEmergencyBelow(R.id.screenLocked);
break;
}
}
| private void updateLayout(Status status) {
switch (status) {
case Normal:
// text
mCarrier.setText(
getCarrierString(
mUpdateMonitor.getTelephonyPlmn(),
mUpdateMonitor.getTelephonySpn()));
// mScreenLocked.setText(R.string.lockscreen_screen_locked);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.GONE);
break;
case NetworkLocked:
// text
mCarrier.setText(R.string.lockscreen_network_locked_message);
mScreenLocked.setText(R.string.lockscreen_instructions_when_pattern_disabled);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.GONE);
break;
case SimMissing:
// text
mCarrier.setText(R.string.lockscreen_missing_sim_message_short);
mScreenLocked.setText(R.string.lockscreen_instructions_when_pattern_disabled);
// layout
mScreenLocked.setVisibility(View.INVISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
putEmergencyBelow(R.id.screenLocked);
break;
case SimMissingLocked:
// text
mCarrier.setText(R.string.lockscreen_missing_sim_message_short);
mScreenLocked.setText(R.string.lockscreen_missing_sim_instructions);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.GONE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
putEmergencyBelow(R.id.screenLocked);
break;
case SimLocked:
// text
mCarrier.setText(R.string.lockscreen_sim_locked_message);
// layout
mScreenLocked.setVisibility(View.INVISIBLE);
mSelector.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.GONE);
break;
case SimPukLocked:
// text
mCarrier.setText(R.string.lockscreen_sim_puk_locked_message);
mScreenLocked.setText(R.string.lockscreen_sim_puk_locked_instructions);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.GONE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
putEmergencyBelow(R.id.screenLocked);
break;
}
}
|
diff --git a/src/org/ebookdroid/ui/viewer/viewers/FullScreenCallback.java b/src/org/ebookdroid/ui/viewer/viewers/FullScreenCallback.java
index 51a7753a..b1e59fcc 100644
--- a/src/org/ebookdroid/ui/viewer/viewers/FullScreenCallback.java
+++ b/src/org/ebookdroid/ui/viewer/viewers/FullScreenCallback.java
@@ -1,92 +1,91 @@
package org.ebookdroid.ui.viewer.viewers;
import org.ebookdroid.common.settings.AppSettings;
import android.app.Activity;
import android.os.Handler;
import android.view.View;
import java.util.concurrent.atomic.AtomicBoolean;
import org.emdev.common.android.AndroidVersion;
import org.emdev.ui.uimanager.IUIManager;
public class FullScreenCallback implements Runnable {
private static final int TIMEOUT = 2000;
protected final AtomicBoolean added = new AtomicBoolean();
protected final Activity activity;
protected final View view;
protected volatile long time;
private FullScreenCallback(final Activity activity, final View view) {
this.activity = activity;
this.view = view;
}
public static FullScreenCallback get(final Activity activity, final View view) {
return AndroidVersion.is4x ?
/* Creates full-screen callback devices with Android 4.x */
new FullScreenCallback(activity, view) : null;
}
@Override
public void run() {
if (!AppSettings.current().fullScreen) {
// System.out.println("fullScreenCallback: full-screen mode off");
added.set(false);
return;
}
final long now = System.currentTimeMillis();
// Check if checkFullScreenMode() was called
if (added.compareAndSet(false, true)) {
// Only adds delayed message
this.time = System.currentTimeMillis();
// System.out.println("fullScreenCallback: postDelayed(): " + TIMEOUT);
- if (view != null) {
- view.getHandler().postDelayed(this, TIMEOUT);
+ final Handler handler = view != null ? view.getHandler() : null;
+ if (handler != null) {
+ handler.postDelayed(this, TIMEOUT);
}
return;
}
// Process delayed message
final long expected = time + TIMEOUT;
if (expected <= now) {
// System.out.println("fullScreenCallback: setFullScreenMode()");
if (view != null) {
IUIManager.instance.setFullScreenMode(activity, view, true);
}
added.set(false);
return;
}
- if (view != null) {
- final Handler handler = view.getHandler();
- if (handler != null) {
- added.set(true);
- final long delta = expected - now;
- // System.out.println("fullScreenCallback: postDelayed(): " + delta);
- handler.postDelayed(this, delta);
- return;
- }
+ final Handler handler = view != null ? view.getHandler() : null;
+ if (handler != null) {
+ added.set(true);
+ final long delta = expected - now;
+ // System.out.println("fullScreenCallback: postDelayed(): " + delta);
+ handler.postDelayed(this, delta);
+ return;
}
added.set(false);
}
public void checkFullScreenMode() {
// System.out.println("fullScreenCallback: checkFullScreenMode()");
this.time = System.currentTimeMillis();
if (!added.get()) {
if (view != null) {
view.post(this);
}
}
}
}
| false | true | public void run() {
if (!AppSettings.current().fullScreen) {
// System.out.println("fullScreenCallback: full-screen mode off");
added.set(false);
return;
}
final long now = System.currentTimeMillis();
// Check if checkFullScreenMode() was called
if (added.compareAndSet(false, true)) {
// Only adds delayed message
this.time = System.currentTimeMillis();
// System.out.println("fullScreenCallback: postDelayed(): " + TIMEOUT);
if (view != null) {
view.getHandler().postDelayed(this, TIMEOUT);
}
return;
}
// Process delayed message
final long expected = time + TIMEOUT;
if (expected <= now) {
// System.out.println("fullScreenCallback: setFullScreenMode()");
if (view != null) {
IUIManager.instance.setFullScreenMode(activity, view, true);
}
added.set(false);
return;
}
if (view != null) {
final Handler handler = view.getHandler();
if (handler != null) {
added.set(true);
final long delta = expected - now;
// System.out.println("fullScreenCallback: postDelayed(): " + delta);
handler.postDelayed(this, delta);
return;
}
}
added.set(false);
}
| public void run() {
if (!AppSettings.current().fullScreen) {
// System.out.println("fullScreenCallback: full-screen mode off");
added.set(false);
return;
}
final long now = System.currentTimeMillis();
// Check if checkFullScreenMode() was called
if (added.compareAndSet(false, true)) {
// Only adds delayed message
this.time = System.currentTimeMillis();
// System.out.println("fullScreenCallback: postDelayed(): " + TIMEOUT);
final Handler handler = view != null ? view.getHandler() : null;
if (handler != null) {
handler.postDelayed(this, TIMEOUT);
}
return;
}
// Process delayed message
final long expected = time + TIMEOUT;
if (expected <= now) {
// System.out.println("fullScreenCallback: setFullScreenMode()");
if (view != null) {
IUIManager.instance.setFullScreenMode(activity, view, true);
}
added.set(false);
return;
}
final Handler handler = view != null ? view.getHandler() : null;
if (handler != null) {
added.set(true);
final long delta = expected - now;
// System.out.println("fullScreenCallback: postDelayed(): " + delta);
handler.postDelayed(this, delta);
return;
}
added.set(false);
}
|
diff --git a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/jbosscache/JBossCacheIndexChangesFilter.java b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/jbosscache/JBossCacheIndexChangesFilter.java
index 69ac81fb3..897887eaf 100644
--- a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/jbosscache/JBossCacheIndexChangesFilter.java
+++ b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/jbosscache/JBossCacheIndexChangesFilter.java
@@ -1,183 +1,183 @@
/*
* 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.services.jcr.impl.core.query.jbosscache;
import org.exoplatform.container.configuration.ConfigurationManager;
import org.exoplatform.services.jcr.config.QueryHandlerEntry;
import org.exoplatform.services.jcr.config.QueryHandlerParams;
import org.exoplatform.services.jcr.config.RepositoryConfigurationException;
import org.exoplatform.services.jcr.config.TemplateConfigurationHelper;
import org.exoplatform.services.jcr.impl.core.query.IndexerChangesFilter;
import org.exoplatform.services.jcr.impl.core.query.IndexerIoMode;
import org.exoplatform.services.jcr.impl.core.query.IndexerIoModeHandler;
import org.exoplatform.services.jcr.impl.core.query.IndexingTree;
import org.exoplatform.services.jcr.impl.core.query.QueryHandler;
import org.exoplatform.services.jcr.impl.core.query.SearchManager;
import org.exoplatform.services.jcr.jbosscache.ExoJBossCacheFactory;
import org.exoplatform.services.jcr.util.IdGenerator;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.jboss.cache.Cache;
import org.jboss.cache.CacheException;
import org.jboss.cache.CacheFactory;
import org.jboss.cache.CacheSPI;
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.config.CacheLoaderConfig;
import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig.SingletonStoreConfig;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;
import java.util.Set;
import javax.jcr.RepositoryException;
/**
* @author <a href="mailto:[email protected]">Sergey Kabashnyuk</a>
* @version $Id: exo-jboss-codetemplates.xml 34360 2009-07-22 23:58:59Z ksm $
*
*/
public class JBossCacheIndexChangesFilter extends IndexerChangesFilter
{
/**
* Logger instance for this class
*/
private final Log log = ExoLogger.getLogger(JBossCacheIndexChangesFilter.class);
private final Cache<Serializable, Object> cache;
public static final String LISTWRAPPER = "$lists".intern();
/**
* @param searchManager
* @param config
* @param indexingTree
* @throws RepositoryConfigurationException
*/
public JBossCacheIndexChangesFilter(SearchManager searchManager, SearchManager parentSearchManager,
QueryHandlerEntry config, IndexingTree indexingTree, IndexingTree parentIndexingTree, QueryHandler handler,
QueryHandler parentHandler, ConfigurationManager cfm) throws IOException, RepositoryException,
RepositoryConfigurationException
{
super(searchManager, parentSearchManager, config, indexingTree, parentIndexingTree, handler, parentHandler, cfm);
// create cache using custom factory
ExoJBossCacheFactory<Serializable, Object> factory = new ExoJBossCacheFactory<Serializable, Object>(cfm);
this.cache = factory.createCache(config);
// initialize IndexerCacheLoader
IndexerCacheLoader indexerCacheLoader = new IndexerCacheLoader();
// inject dependencies
indexerCacheLoader.init(searchManager, parentSearchManager, handler, parentHandler);
// set SingltonStoreCacheLoader
SingletonStoreConfig singletonStoreConfig = new SingletonStoreConfig();
singletonStoreConfig.setSingletonStoreClass(IndexerSingletonStoreCacheLoader.class.getName());
//singletonStoreConfig.setSingletonStoreClass(SingletonStoreCacheLoader.class.getName());
Properties singletonStoreProperties = new Properties();
// try to get pushState parameters, since they are set programmatically only
Boolean pushState = config.getParameterBoolean(QueryHandlerParams.PARAM_JBOSSCACHE_PUSHSTATE, false);
- Integer pushStateTimeOut = config.getParameterInteger(QueryHandlerParams.PARAM_JBOSSCACHE_PUSHSTATE, 10000);
+ Integer pushStateTimeOut = config.getParameterInteger(QueryHandlerParams.PARAM_JBOSSCACHE_PUSHSTATE_TIMEOUT, 10000);
singletonStoreProperties.setProperty("pushStateWhenCoordinator", pushState.toString());
singletonStoreProperties.setProperty("pushStateWhenCoordinatorTimeout", pushStateTimeOut.toString());
singletonStoreConfig.setProperties(singletonStoreProperties);
singletonStoreConfig.setSingletonStoreEnabled(true);
// create CacheLoaderConfig
IndividualCacheLoaderConfig individualCacheLoaderConfig = new IndividualCacheLoaderConfig();
// set SingletonStoreConfig
individualCacheLoaderConfig.setSingletonStoreConfig(singletonStoreConfig);
// set CacheLoader
individualCacheLoaderConfig.setCacheLoader(indexerCacheLoader);
// set parameters
individualCacheLoaderConfig.setFetchPersistentState(false);
individualCacheLoaderConfig.setAsync(false);
individualCacheLoaderConfig.setIgnoreModifications(false);
individualCacheLoaderConfig.setPurgeOnStartup(false);
// create CacheLoaderConfig
CacheLoaderConfig cacheLoaderConfig = new CacheLoaderConfig();
cacheLoaderConfig.setShared(false);
cacheLoaderConfig.setPassivation(false);
cacheLoaderConfig.addIndividualCacheLoaderConfig(individualCacheLoaderConfig);
// insert CacheLoaderConfig
this.cache.getConfiguration().setCacheLoaderConfig(cacheLoaderConfig);
this.cache.create();
this.cache.start();
// start will invoke cache listener which will notify handler that mode is changed
IndexerIoMode ioMode =
((CacheSPI)cache).getRPCManager().isCoordinator() ? IndexerIoMode.READ_WRITE : IndexerIoMode.READ_ONLY;
IndexerIoModeHandler modeHandler = indexerCacheLoader.getModeHandler();
handler.setIndexerIoModeHandler(modeHandler);
parentHandler.setIndexerIoModeHandler(modeHandler);
if (!parentHandler.isInitialized())
{
parentHandler.setIndexInfos(new JBossCacheIndexInfos(cache, true, modeHandler));
parentHandler.setIndexUpdateMonitor(new JBossCacheIndexUpdateMonitor(cache, modeHandler));
parentHandler.init();
}
if (!handler.isInitialized())
{
handler.setIndexInfos(new JBossCacheIndexInfos(cache, false, modeHandler));
handler.setIndexUpdateMonitor(new JBossCacheIndexUpdateMonitor(cache, modeHandler));
handler.init();
}
}
/**
* @see org.exoplatform.services.jcr.impl.core.query.IndexerChangesFilter#doUpdateIndex(java.util.Set, java.util.Set, java.util.Set, java.util.Set)
*/
@Override
protected void doUpdateIndex(Set<String> removedNodes, Set<String> addedNodes, Set<String> parentRemovedNodes,
Set<String> parentAddedNodes)
{
String id = IdGenerator.generate();
try
{
cache.put(id, LISTWRAPPER, new ChangesFilterListsWrapper(addedNodes, removedNodes, parentAddedNodes,
parentRemovedNodes));
}
catch (CacheException e)
{
logErrorChanges(handler, removedNodes, addedNodes);
logErrorChanges(parentHandler, parentRemovedNodes, parentAddedNodes);
}
}
/**
* Log errors
* @param logHandler
* @param removedNodes
* @param addedNodes
*/
private void logErrorChanges(QueryHandler logHandler, Set<String> removedNodes, Set<String> addedNodes)
{
try
{
logHandler.logErrorChanges(addedNodes, removedNodes);
}
catch (IOException ioe)
{
log.warn("Exception occure when errorLog writed. Error log is not complete. " + ioe, ioe);
}
}
}
| true | true | public JBossCacheIndexChangesFilter(SearchManager searchManager, SearchManager parentSearchManager,
QueryHandlerEntry config, IndexingTree indexingTree, IndexingTree parentIndexingTree, QueryHandler handler,
QueryHandler parentHandler, ConfigurationManager cfm) throws IOException, RepositoryException,
RepositoryConfigurationException
{
super(searchManager, parentSearchManager, config, indexingTree, parentIndexingTree, handler, parentHandler, cfm);
// create cache using custom factory
ExoJBossCacheFactory<Serializable, Object> factory = new ExoJBossCacheFactory<Serializable, Object>(cfm);
this.cache = factory.createCache(config);
// initialize IndexerCacheLoader
IndexerCacheLoader indexerCacheLoader = new IndexerCacheLoader();
// inject dependencies
indexerCacheLoader.init(searchManager, parentSearchManager, handler, parentHandler);
// set SingltonStoreCacheLoader
SingletonStoreConfig singletonStoreConfig = new SingletonStoreConfig();
singletonStoreConfig.setSingletonStoreClass(IndexerSingletonStoreCacheLoader.class.getName());
//singletonStoreConfig.setSingletonStoreClass(SingletonStoreCacheLoader.class.getName());
Properties singletonStoreProperties = new Properties();
// try to get pushState parameters, since they are set programmatically only
Boolean pushState = config.getParameterBoolean(QueryHandlerParams.PARAM_JBOSSCACHE_PUSHSTATE, false);
Integer pushStateTimeOut = config.getParameterInteger(QueryHandlerParams.PARAM_JBOSSCACHE_PUSHSTATE, 10000);
singletonStoreProperties.setProperty("pushStateWhenCoordinator", pushState.toString());
singletonStoreProperties.setProperty("pushStateWhenCoordinatorTimeout", pushStateTimeOut.toString());
singletonStoreConfig.setProperties(singletonStoreProperties);
singletonStoreConfig.setSingletonStoreEnabled(true);
// create CacheLoaderConfig
IndividualCacheLoaderConfig individualCacheLoaderConfig = new IndividualCacheLoaderConfig();
// set SingletonStoreConfig
individualCacheLoaderConfig.setSingletonStoreConfig(singletonStoreConfig);
// set CacheLoader
individualCacheLoaderConfig.setCacheLoader(indexerCacheLoader);
// set parameters
individualCacheLoaderConfig.setFetchPersistentState(false);
individualCacheLoaderConfig.setAsync(false);
individualCacheLoaderConfig.setIgnoreModifications(false);
individualCacheLoaderConfig.setPurgeOnStartup(false);
// create CacheLoaderConfig
CacheLoaderConfig cacheLoaderConfig = new CacheLoaderConfig();
cacheLoaderConfig.setShared(false);
cacheLoaderConfig.setPassivation(false);
cacheLoaderConfig.addIndividualCacheLoaderConfig(individualCacheLoaderConfig);
// insert CacheLoaderConfig
this.cache.getConfiguration().setCacheLoaderConfig(cacheLoaderConfig);
this.cache.create();
this.cache.start();
// start will invoke cache listener which will notify handler that mode is changed
IndexerIoMode ioMode =
((CacheSPI)cache).getRPCManager().isCoordinator() ? IndexerIoMode.READ_WRITE : IndexerIoMode.READ_ONLY;
IndexerIoModeHandler modeHandler = indexerCacheLoader.getModeHandler();
handler.setIndexerIoModeHandler(modeHandler);
parentHandler.setIndexerIoModeHandler(modeHandler);
if (!parentHandler.isInitialized())
{
parentHandler.setIndexInfos(new JBossCacheIndexInfos(cache, true, modeHandler));
parentHandler.setIndexUpdateMonitor(new JBossCacheIndexUpdateMonitor(cache, modeHandler));
parentHandler.init();
}
if (!handler.isInitialized())
{
handler.setIndexInfos(new JBossCacheIndexInfos(cache, false, modeHandler));
handler.setIndexUpdateMonitor(new JBossCacheIndexUpdateMonitor(cache, modeHandler));
handler.init();
}
}
| public JBossCacheIndexChangesFilter(SearchManager searchManager, SearchManager parentSearchManager,
QueryHandlerEntry config, IndexingTree indexingTree, IndexingTree parentIndexingTree, QueryHandler handler,
QueryHandler parentHandler, ConfigurationManager cfm) throws IOException, RepositoryException,
RepositoryConfigurationException
{
super(searchManager, parentSearchManager, config, indexingTree, parentIndexingTree, handler, parentHandler, cfm);
// create cache using custom factory
ExoJBossCacheFactory<Serializable, Object> factory = new ExoJBossCacheFactory<Serializable, Object>(cfm);
this.cache = factory.createCache(config);
// initialize IndexerCacheLoader
IndexerCacheLoader indexerCacheLoader = new IndexerCacheLoader();
// inject dependencies
indexerCacheLoader.init(searchManager, parentSearchManager, handler, parentHandler);
// set SingltonStoreCacheLoader
SingletonStoreConfig singletonStoreConfig = new SingletonStoreConfig();
singletonStoreConfig.setSingletonStoreClass(IndexerSingletonStoreCacheLoader.class.getName());
//singletonStoreConfig.setSingletonStoreClass(SingletonStoreCacheLoader.class.getName());
Properties singletonStoreProperties = new Properties();
// try to get pushState parameters, since they are set programmatically only
Boolean pushState = config.getParameterBoolean(QueryHandlerParams.PARAM_JBOSSCACHE_PUSHSTATE, false);
Integer pushStateTimeOut = config.getParameterInteger(QueryHandlerParams.PARAM_JBOSSCACHE_PUSHSTATE_TIMEOUT, 10000);
singletonStoreProperties.setProperty("pushStateWhenCoordinator", pushState.toString());
singletonStoreProperties.setProperty("pushStateWhenCoordinatorTimeout", pushStateTimeOut.toString());
singletonStoreConfig.setProperties(singletonStoreProperties);
singletonStoreConfig.setSingletonStoreEnabled(true);
// create CacheLoaderConfig
IndividualCacheLoaderConfig individualCacheLoaderConfig = new IndividualCacheLoaderConfig();
// set SingletonStoreConfig
individualCacheLoaderConfig.setSingletonStoreConfig(singletonStoreConfig);
// set CacheLoader
individualCacheLoaderConfig.setCacheLoader(indexerCacheLoader);
// set parameters
individualCacheLoaderConfig.setFetchPersistentState(false);
individualCacheLoaderConfig.setAsync(false);
individualCacheLoaderConfig.setIgnoreModifications(false);
individualCacheLoaderConfig.setPurgeOnStartup(false);
// create CacheLoaderConfig
CacheLoaderConfig cacheLoaderConfig = new CacheLoaderConfig();
cacheLoaderConfig.setShared(false);
cacheLoaderConfig.setPassivation(false);
cacheLoaderConfig.addIndividualCacheLoaderConfig(individualCacheLoaderConfig);
// insert CacheLoaderConfig
this.cache.getConfiguration().setCacheLoaderConfig(cacheLoaderConfig);
this.cache.create();
this.cache.start();
// start will invoke cache listener which will notify handler that mode is changed
IndexerIoMode ioMode =
((CacheSPI)cache).getRPCManager().isCoordinator() ? IndexerIoMode.READ_WRITE : IndexerIoMode.READ_ONLY;
IndexerIoModeHandler modeHandler = indexerCacheLoader.getModeHandler();
handler.setIndexerIoModeHandler(modeHandler);
parentHandler.setIndexerIoModeHandler(modeHandler);
if (!parentHandler.isInitialized())
{
parentHandler.setIndexInfos(new JBossCacheIndexInfos(cache, true, modeHandler));
parentHandler.setIndexUpdateMonitor(new JBossCacheIndexUpdateMonitor(cache, modeHandler));
parentHandler.init();
}
if (!handler.isInitialized())
{
handler.setIndexInfos(new JBossCacheIndexInfos(cache, false, modeHandler));
handler.setIndexUpdateMonitor(new JBossCacheIndexUpdateMonitor(cache, modeHandler));
handler.init();
}
}
|
diff --git a/choco-solver/src/main/java/util/objects/setDataStructures/SetFactory.java b/choco-solver/src/main/java/util/objects/setDataStructures/SetFactory.java
index 765639f52..f6f88515a 100644
--- a/choco-solver/src/main/java/util/objects/setDataStructures/SetFactory.java
+++ b/choco-solver/src/main/java/util/objects/setDataStructures/SetFactory.java
@@ -1,191 +1,191 @@
/**
* Copyright (c) 1999-2011, Ecole des Mines de Nantes
* 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 Ecole des Mines de Nantes 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 REGENTS 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 REGENTS AND 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.
*/
/**
* Created by IntelliJ IDEA.
* User: Jean-Guillaume Fages
* Date: 27/10/12
* Time: 01:56
*/
package util.objects.setDataStructures;
import memory.IEnvironment;
import memory.copy.EnvironmentCopying;
import memory.trailing.EnvironmentTrailing;
import util.objects.setDataStructures.linkedlist.Set_2LinkedList;
import util.objects.setDataStructures.linkedlist.Set_LinkedList;
import util.objects.setDataStructures.linkedlist.Set_Std_2LinkedList;
import util.objects.setDataStructures.linkedlist.Set_Std_LinkedList;
import util.objects.setDataStructures.matrix.Set_Array;
import util.objects.setDataStructures.matrix.Set_BitSet;
import util.objects.setDataStructures.matrix.Set_Std_Array;
import util.objects.setDataStructures.swapList.Set_Std_Swap_Array;
import util.objects.setDataStructures.swapList.Set_Std_Swap_Hash;
import util.objects.setDataStructures.swapList.Set_Swap_Array;
import util.objects.setDataStructures.swapList.Set_Swap_Hash;
/**
* Factory for creating sets
*
* @author Jean-Guillaume Fages
* @since Oct 2012
*/
public class SetFactory {
//***********************************************************************************
// FACTORY - STORED SET
//***********************************************************************************
public static boolean HARD_CODED = true;
/**
* Make a stored set of integers in the range [0,maximumSize-1]
* Such a set is restored after a backtrack
*
* @param type of set data structure
* @param maximumSize of the set (maximum value -1)
* @param environment solver environment
* @return a new set which can be restored during search, after some backtracks
*/
public static ISet makeStoredSet(SetType type, int maximumSize, IEnvironment environment) {
if (HARD_CODED)
switch (type) {
case SWAP_ARRAY:
return new Set_Std_Swap_Array(environment, maximumSize);
case SWAP_HASH:
return new Set_Std_Swap_Hash(environment, maximumSize);
case LINKED_LIST:
return new Set_Std_LinkedList(environment);
case DOUBLE_LINKED_LIST:
return new Set_Std_2LinkedList(environment);
case BITSET:
- new Set_Std_BitSet(environment, maximumSize);
+ return new Set_Std_BitSet(environment, maximumSize);
case BOOL_ARRAY:
return new Set_Std_Array(environment, maximumSize);
}
if (environment instanceof EnvironmentTrailing) {
return new Set_Trail((EnvironmentTrailing) environment, makeSet(type, maximumSize));
} else if (environment instanceof EnvironmentCopying) {
return new Set_Copy((EnvironmentCopying) environment, makeSet(type, maximumSize));
} else {
throw new UnsupportedOperationException("not implemented yet");
}
}
//***********************************************************************************
// FACTORY - SET
//***********************************************************************************
/**
* Make a set of integers in the range [0,maximumSize-1]
*
* @param type of set data structure
* @param maximumSize of the set (maximum value -1)
* @return a new set
*/
public static ISet makeSet(SetType type, int maximumSize) {
switch (type) {
case SWAP_ARRAY:
return makeSwap(maximumSize, false);
case SWAP_HASH:
return makeSwap(maximumSize, true);
case LINKED_LIST:
return makeLinkedList(false);
case DOUBLE_LINKED_LIST:
return makeLinkedList(true);
case BITSET:
return makeBitSet(maximumSize);
case BOOL_ARRAY:
return makeArray(maximumSize);
}
throw new UnsupportedOperationException("unknown SetType");
}
/**
* Creates a set based on a linked list
* appropriate when the set has only a few elements
*
* @param doubleLink
* @return a new set
*/
public static ISet makeLinkedList(boolean doubleLink) {
if (doubleLink) {
return new Set_2LinkedList();
} else {
return new Set_LinkedList();
}
}
/**
* Creates a stored set based on a BitSet
*
* @param n maximal size of the set
* @return a new set
*/
public static ISet makeBitSet(int n) {
return new Set_BitSet(n);
}
/**
* Creates a set based on a boolean array
*
* @param n maximal size of the set
* @return a new set
*/
public static ISet makeArray(int n) {
return new Set_Array(n);
}
/**
* Creates a set that will ALWAYS contain all values from 0 to n-1
*
* @param n size of the set
* @return a new set that must always be full
*/
public static ISet makeFullSet(int n) {
return new Set_Full(n);
}
/**
* Creates a set based on swaps
* Optimal complexity
*
* @param n maximal size of the set
* @param hash lighter in memory by slower (false is recommended)
* @return a new set
*/
public static ISet makeSwap(int n, boolean hash) {
if (hash) {
return new Set_Swap_Hash(n);
} else {
return new Set_Swap_Array(n);
}
}
}
| true | true | public static ISet makeStoredSet(SetType type, int maximumSize, IEnvironment environment) {
if (HARD_CODED)
switch (type) {
case SWAP_ARRAY:
return new Set_Std_Swap_Array(environment, maximumSize);
case SWAP_HASH:
return new Set_Std_Swap_Hash(environment, maximumSize);
case LINKED_LIST:
return new Set_Std_LinkedList(environment);
case DOUBLE_LINKED_LIST:
return new Set_Std_2LinkedList(environment);
case BITSET:
new Set_Std_BitSet(environment, maximumSize);
case BOOL_ARRAY:
return new Set_Std_Array(environment, maximumSize);
}
if (environment instanceof EnvironmentTrailing) {
return new Set_Trail((EnvironmentTrailing) environment, makeSet(type, maximumSize));
} else if (environment instanceof EnvironmentCopying) {
return new Set_Copy((EnvironmentCopying) environment, makeSet(type, maximumSize));
} else {
throw new UnsupportedOperationException("not implemented yet");
}
}
| public static ISet makeStoredSet(SetType type, int maximumSize, IEnvironment environment) {
if (HARD_CODED)
switch (type) {
case SWAP_ARRAY:
return new Set_Std_Swap_Array(environment, maximumSize);
case SWAP_HASH:
return new Set_Std_Swap_Hash(environment, maximumSize);
case LINKED_LIST:
return new Set_Std_LinkedList(environment);
case DOUBLE_LINKED_LIST:
return new Set_Std_2LinkedList(environment);
case BITSET:
return new Set_Std_BitSet(environment, maximumSize);
case BOOL_ARRAY:
return new Set_Std_Array(environment, maximumSize);
}
if (environment instanceof EnvironmentTrailing) {
return new Set_Trail((EnvironmentTrailing) environment, makeSet(type, maximumSize));
} else if (environment instanceof EnvironmentCopying) {
return new Set_Copy((EnvironmentCopying) environment, makeSet(type, maximumSize));
} else {
throw new UnsupportedOperationException("not implemented yet");
}
}
|
diff --git a/src/main/java/org/datacite/mds/web/ui/controller/DatasetController.java b/src/main/java/org/datacite/mds/web/ui/controller/DatasetController.java
index 20f75d2..eabc908 100644
--- a/src/main/java/org/datacite/mds/web/ui/controller/DatasetController.java
+++ b/src/main/java/org/datacite/mds/web/ui/controller/DatasetController.java
@@ -1,239 +1,239 @@
package org.datacite.mds.web.ui.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import javax.validation.ValidationException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.datacite.mds.domain.Allocator;
import org.datacite.mds.domain.AllocatorOrDatacentre;
import org.datacite.mds.domain.Datacentre;
import org.datacite.mds.domain.Dataset;
import org.datacite.mds.domain.Media;
import org.datacite.mds.domain.Metadata;
import org.datacite.mds.service.HandleException;
import org.datacite.mds.service.HandleService;
import org.datacite.mds.service.SecurityException;
import org.datacite.mds.util.SecurityUtils;
import org.datacite.mds.util.Utils;
import org.datacite.mds.util.ValidationUtils;
import org.datacite.mds.validation.ValidationHelper;
import org.datacite.mds.web.api.NotFoundException;
import org.datacite.mds.web.ui.UiController;
import org.datacite.mds.web.ui.model.CreateDatasetModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
@RooWebScaffold(path = "datasets", formBackingObject = Dataset.class, delete = false, populateMethods = false)
@RequestMapping("/datasets")
@Controller
public class DatasetController implements UiController {
private static Logger log = Logger.getLogger(DatasetController.class);
@Autowired
HandleService handleService;
@Autowired
ValidationHelper validationHelper;
@InitBinder
void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String show(@PathVariable("id") Long id, Model model) {
Dataset dataset = Dataset.findDataset(id);
model.addAttribute("dataset", dataset);
List<Media> medias = Media.findMediasByDataset(dataset).getResultList();
model.addAttribute("medias", medias);
List<Metadata> metadatas = Metadata.findMetadatasByDataset(dataset).getResultList();
model.addAttribute("metadatas", metadatas);
try {
Metadata metadata = metadatas.get(0);
model.addAttribute("metadata", metadata);
byte[] xml = metadata.getXml();
model.addAttribute("prettyxml", Utils.formatXML(xml));
} catch (Exception e) {
}
model.addAttribute("resolvedUrl", resolveDoi(dataset));
model.addAttribute("itemId", id);
return "datasets/show";
}
private String resolveDoi(Dataset dataset) {
try {
String url = handleService.resolve(dataset.getDoi());
return url;
} catch (NotFoundException e) {
return "not resolveable";
} catch (HandleException e) {
return "handle error";
}
}
@ModelAttribute("datacentres")
public Collection<Datacentre> populateDatacentres() throws SecurityException {
if (SecurityUtils.isLoggedInAsDatacentre()) {
Datacentre datacentre = SecurityUtils.getCurrentDatacentre();
return Arrays.asList(datacentre);
} else {
Allocator allocator = SecurityUtils.getCurrentAllocator();
return Datacentre.findAllDatacentresByAllocator(allocator);
}
}
@RequestMapping(method = RequestMethod.GET)
public String list(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "size", required = false) Integer size, Model model) throws SecurityException {
AllocatorOrDatacentre user = SecurityUtils.getCurrentAllocatorOrDatacentre();
if (page != null || size != null) {
int sizeNo = size == null ? 10 : size.intValue();
model.addAttribute("datasets", Dataset.findDatasetEntriesByAllocatorOrDatacentre(user, page == null ? 0 : (page
.intValue() - 1)
* sizeNo, sizeNo));
float nrOfPages = (float) Dataset.countDatasetsByAllocatorOrDatacentre(user) / sizeNo;
model.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
: nrOfPages));
} else {
model.addAttribute("datasets", Dataset.findDatasetsByAllocatorOrDatacentre(user));
}
return "datasets/list";
}
@RequestMapping(params = "form", method = RequestMethod.GET)
public String createForm(Model uiModel) {
uiModel.addAttribute("createDatasetModel", new CreateDatasetModel());
return "datasets/create";
}
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid CreateDatasetModel createDatasetModel, BindingResult result, Model model) {
Dataset dataset = new Dataset();
Metadata metadata = new Metadata();
dataset.setDoi(createDatasetModel.getDoi());
dataset.setDatacentre(createDatasetModel.getDatacentre());
dataset.setUrl(createDatasetModel.getUrl());
metadata.setDataset(dataset);
if (!result.hasErrors()) {
try {
byte[] xml = createDatasetModel.getXml();
if (xml.length > 0)
metadata.setXml(createDatasetModel.getXml());
else
throw new ValidationException("may not be empty");
} catch (ValidationException e) {
- result.addError(new FieldError("", "xml", e.getMessage()));
+ result.rejectValue("xml", null, e.getMessage());
}
}
if (!result.hasErrors()) {
try {
SecurityUtils.checkQuota(dataset.getDatacentre());
} catch (SecurityException e) {
ObjectError error = new ObjectError("", e.getMessage());
result.addError(error);
}
}
if (!result.hasErrors()) {
validationHelper.validateTo(result, dataset, metadata);
}
if (!result.hasErrors()) {
try {
handleService.create(dataset.getDoi(), dataset.getUrl());
dataset.setMinted(new Date());
log.info(dataset.getDatacentre().getSymbol() + " successfuly minted (via UI) " + dataset.getDoi());
} catch (HandleException e) {
log.debug("minting DOI failed; try to update it");
try {
handleService.update(dataset.getDoi(), dataset.getUrl());
log.info(dataset.getDatacentre().getSymbol() + " successfuly updated (via UI) " + dataset.getDoi());
} catch (HandleException ee) {
String message = "HandleService: " + ee.getMessage();
FieldError error = new FieldError("", "doi", dataset.getDoi(), false, null, null, message);
result.addError(error);
}
}
}
if (result.hasErrors()) {
model.addAttribute("createDatasetModel", createDatasetModel);
return "datasets/create";
}
dataset.persist();
dataset.getDatacentre().incQuotaUsed(Datacentre.ForceRefresh.YES);
metadata.persist();
model.asMap().clear();
return "redirect:/datasets/" + dataset.getId().toString();
}
@RequestMapping(method = RequestMethod.PUT)
public String update(@Valid Dataset dataset, BindingResult result, Model model) {
if (!dataset.getUrl().isEmpty() && !result.hasErrors()) {
try {
handleService.update(dataset.getDoi(), dataset.getUrl());
log.info(dataset.getDatacentre().getSymbol() + " successfuly updated (via UI) " + dataset.getDoi());
} catch (HandleException e) {
log.debug("updating DOI failed; try to mint it");
try {
handleService.create(dataset.getDoi(), dataset.getUrl());
dataset.setMinted(new Date());
log.info(dataset.getDatacentre().getSymbol() + " successfuly minted (via UI) " + dataset.getDoi());
} catch (HandleException e1) {
ObjectError error = new ObjectError("", "HandleService: " + e.getMessage());
result.addError(error);
}
}
}
if (result.hasErrors()) {
model.addAttribute("dataset", dataset);
return "datasets/update";
}
dataset.merge();
model.asMap().clear();
return "redirect:/datasets/" + dataset.getId().toString();
}
@RequestMapping(params = "find=ByDoiEquals", method = RequestMethod.GET)
public String findDatasetsByDoiEquals(@RequestParam("doi") String doi, Model model) {
Dataset dataset = Dataset.findDatasetByDoi(doi);
model.asMap().clear();
return (dataset == null) ? "datasets/show" : "redirect:/datasets/" + dataset.getId();
}
@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
public String updateForm(@PathVariable("id") Long id, Model model) {
Dataset dataset = Dataset.findDataset(id);
model.addAttribute("dataset", dataset);
model.addAttribute("resolvedUrl", resolveDoi(dataset));
return "datasets/update";
}
}
| true | true | public String create(@Valid CreateDatasetModel createDatasetModel, BindingResult result, Model model) {
Dataset dataset = new Dataset();
Metadata metadata = new Metadata();
dataset.setDoi(createDatasetModel.getDoi());
dataset.setDatacentre(createDatasetModel.getDatacentre());
dataset.setUrl(createDatasetModel.getUrl());
metadata.setDataset(dataset);
if (!result.hasErrors()) {
try {
byte[] xml = createDatasetModel.getXml();
if (xml.length > 0)
metadata.setXml(createDatasetModel.getXml());
else
throw new ValidationException("may not be empty");
} catch (ValidationException e) {
result.addError(new FieldError("", "xml", e.getMessage()));
}
}
if (!result.hasErrors()) {
try {
SecurityUtils.checkQuota(dataset.getDatacentre());
} catch (SecurityException e) {
ObjectError error = new ObjectError("", e.getMessage());
result.addError(error);
}
}
if (!result.hasErrors()) {
validationHelper.validateTo(result, dataset, metadata);
}
if (!result.hasErrors()) {
try {
handleService.create(dataset.getDoi(), dataset.getUrl());
dataset.setMinted(new Date());
log.info(dataset.getDatacentre().getSymbol() + " successfuly minted (via UI) " + dataset.getDoi());
} catch (HandleException e) {
log.debug("minting DOI failed; try to update it");
try {
handleService.update(dataset.getDoi(), dataset.getUrl());
log.info(dataset.getDatacentre().getSymbol() + " successfuly updated (via UI) " + dataset.getDoi());
} catch (HandleException ee) {
String message = "HandleService: " + ee.getMessage();
FieldError error = new FieldError("", "doi", dataset.getDoi(), false, null, null, message);
result.addError(error);
}
}
}
if (result.hasErrors()) {
model.addAttribute("createDatasetModel", createDatasetModel);
return "datasets/create";
}
dataset.persist();
dataset.getDatacentre().incQuotaUsed(Datacentre.ForceRefresh.YES);
metadata.persist();
model.asMap().clear();
return "redirect:/datasets/" + dataset.getId().toString();
}
| public String create(@Valid CreateDatasetModel createDatasetModel, BindingResult result, Model model) {
Dataset dataset = new Dataset();
Metadata metadata = new Metadata();
dataset.setDoi(createDatasetModel.getDoi());
dataset.setDatacentre(createDatasetModel.getDatacentre());
dataset.setUrl(createDatasetModel.getUrl());
metadata.setDataset(dataset);
if (!result.hasErrors()) {
try {
byte[] xml = createDatasetModel.getXml();
if (xml.length > 0)
metadata.setXml(createDatasetModel.getXml());
else
throw new ValidationException("may not be empty");
} catch (ValidationException e) {
result.rejectValue("xml", null, e.getMessage());
}
}
if (!result.hasErrors()) {
try {
SecurityUtils.checkQuota(dataset.getDatacentre());
} catch (SecurityException e) {
ObjectError error = new ObjectError("", e.getMessage());
result.addError(error);
}
}
if (!result.hasErrors()) {
validationHelper.validateTo(result, dataset, metadata);
}
if (!result.hasErrors()) {
try {
handleService.create(dataset.getDoi(), dataset.getUrl());
dataset.setMinted(new Date());
log.info(dataset.getDatacentre().getSymbol() + " successfuly minted (via UI) " + dataset.getDoi());
} catch (HandleException e) {
log.debug("minting DOI failed; try to update it");
try {
handleService.update(dataset.getDoi(), dataset.getUrl());
log.info(dataset.getDatacentre().getSymbol() + " successfuly updated (via UI) " + dataset.getDoi());
} catch (HandleException ee) {
String message = "HandleService: " + ee.getMessage();
FieldError error = new FieldError("", "doi", dataset.getDoi(), false, null, null, message);
result.addError(error);
}
}
}
if (result.hasErrors()) {
model.addAttribute("createDatasetModel", createDatasetModel);
return "datasets/create";
}
dataset.persist();
dataset.getDatacentre().incQuotaUsed(Datacentre.ForceRefresh.YES);
metadata.persist();
model.asMap().clear();
return "redirect:/datasets/" + dataset.getId().toString();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.