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/libraries/javalib/gnu/java/net/protocol/http/Headers.java b/libraries/javalib/gnu/java/net/protocol/http/Headers.java index 0db9a552a..9968b2e77 100644 --- a/libraries/javalib/gnu/java/net/protocol/http/Headers.java +++ b/libraries/javalib/gnu/java/net/protocol/http/Headers.java @@ -1,363 +1,369 @@ /* Headers.java -- Copyright (C) 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.java.net.protocol.http; import gnu.java.net.LineInputStream; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.ParseException; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; /** * A collection of HTTP header names and associated values. * Retrieval of values is case insensitive. An iteration over the keys * returns the header names in the order they were received. * * @author Chris Burdess ([email protected]) */ public class Headers implements Map { static final DateFormat dateFormat = new HTTPDateFormat(); static class Header { final String name; Header(String name) { if (name == null || name.length() == 0) { throw new IllegalArgumentException(name); } this.name = name; } public int hashCode() { return name.toLowerCase().hashCode(); } public boolean equals(Object other) { if (other instanceof Header) { return ((Header) other).name.equalsIgnoreCase(name); } return false; } public String toString() { return name; } } static class HeaderEntry implements Map.Entry { final Map.Entry entry; HeaderEntry(Map.Entry entry) { this.entry = entry; } public Object getKey() { return ((Header) entry.getKey()).name; } public Object getValue() { return entry.getValue(); } public Object setValue(Object value) { return entry.setValue(value); } public int hashCode() { return entry.hashCode(); } public boolean equals(Object other) { return entry.equals(other); } public String toString() { return getKey().toString() + "=" + getValue(); } } private LinkedHashMap headers; public Headers() { headers = new LinkedHashMap(); } public int size() { return headers.size(); } public boolean isEmpty() { return headers.isEmpty(); } public boolean containsKey(Object key) { return headers.containsKey(new Header((String) key)); } public boolean containsValue(Object value) { return headers.containsValue(value); } public Object get(Object key) { return headers.get(new Header((String) key)); } /** * Returns the value of the specified header as a string. */ public String getValue(String header) { return (String) headers.get(new Header(header)); } /** * Returns the value of the specified header as an integer, * or -1 if the header is not present or not an integer. */ public int getIntValue(String header) { String val = getValue(header); if (val == null) { return -1; } try { return Integer.parseInt(val); } catch (NumberFormatException e) { } return -1; } /** * Returns the value of the specified header as a date, * or <code>null</code> if the header is not present or not a date. */ public Date getDateValue(String header) { String val = getValue(header); if (val == null) { return null; } try { return dateFormat.parse(val); } catch (ParseException e) { return null; } } public Object put(Object key, Object value) { return headers.put(new Header((String) key), value); } public Object remove(Object key) { return headers.remove(new Header((String) key)); } public void putAll(Map t) { for (Iterator i = t.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); String value = (String) t.get(key); headers.put(new Header(key), value); } } public void clear() { headers.clear(); } public Set keySet() { Set keys = headers.keySet(); Set ret = new LinkedHashSet(); for (Iterator i = keys.iterator(); i.hasNext(); ) { ret.add(((Header) i.next()).name); } return ret; } public Collection values() { return headers.values(); } public Set entrySet() { Set entries = headers.entrySet(); Set ret = new LinkedHashSet(); for (Iterator i = entries.iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry) i.next(); ret.add(new HeaderEntry(entry)); } return ret; } public boolean equals(Object other) { return headers.equals(other); } public int hashCode() { return headers.hashCode(); } /** * Parse the specified input stream, adding headers to this collection. */ public void parse(InputStream in) throws IOException { LineInputStream lin = (in instanceof LineInputStream) ? (LineInputStream) in : new LineInputStream(in); String name = null; StringBuffer value = new StringBuffer(); while (true) { String line = lin.readLine(); if (line == null) { if (name != null) { addValue(name, value.toString()); } break; } int len = line.length(); if (len < 2) { if (name != null) { addValue(name, value.toString()); } break; } char c1 = line.charAt(0); if (c1 == ' ' || c1 == '\t') { // Continuation - value.append(line.substring(0, len - 1)); + int last = len - 1; + if (line.charAt(last) != '\r') + ++last; + value.append(line.substring(0, last)); } else { if (name != null) { addValue(name, value.toString()); } int di = line.indexOf(':'); name = line.substring(0, di); value.setLength(0); do { di++; } while (di < len && line.charAt(di) == ' '); - value.append(line.substring(di, len - 1)); + int last = len - 1; + if (line.charAt(last) != '\r') + ++last; + value.append(line.substring(di, last)); } } } private void addValue(String name, String value) { Header key = new Header(name); String old = (String) headers.get(key); if (old == null) { headers.put(key, value); } else { headers.put(key, old + ", " + value); } } }
false
true
public void parse(InputStream in) throws IOException { LineInputStream lin = (in instanceof LineInputStream) ? (LineInputStream) in : new LineInputStream(in); String name = null; StringBuffer value = new StringBuffer(); while (true) { String line = lin.readLine(); if (line == null) { if (name != null) { addValue(name, value.toString()); } break; } int len = line.length(); if (len < 2) { if (name != null) { addValue(name, value.toString()); } break; } char c1 = line.charAt(0); if (c1 == ' ' || c1 == '\t') { // Continuation value.append(line.substring(0, len - 1)); } else { if (name != null) { addValue(name, value.toString()); } int di = line.indexOf(':'); name = line.substring(0, di); value.setLength(0); do { di++; } while (di < len && line.charAt(di) == ' '); value.append(line.substring(di, len - 1)); } } }
public void parse(InputStream in) throws IOException { LineInputStream lin = (in instanceof LineInputStream) ? (LineInputStream) in : new LineInputStream(in); String name = null; StringBuffer value = new StringBuffer(); while (true) { String line = lin.readLine(); if (line == null) { if (name != null) { addValue(name, value.toString()); } break; } int len = line.length(); if (len < 2) { if (name != null) { addValue(name, value.toString()); } break; } char c1 = line.charAt(0); if (c1 == ' ' || c1 == '\t') { // Continuation int last = len - 1; if (line.charAt(last) != '\r') ++last; value.append(line.substring(0, last)); } else { if (name != null) { addValue(name, value.toString()); } int di = line.indexOf(':'); name = line.substring(0, di); value.setLength(0); do { di++; } while (di < len && line.charAt(di) == ' '); int last = len - 1; if (line.charAt(last) != '\r') ++last; value.append(line.substring(di, last)); } } }
diff --git a/illaclient/src/illarion/client/gui/controller/game/GUIChatHandler.java b/illaclient/src/illarion/client/gui/controller/game/GUIChatHandler.java index 15d7573b..85085ea1 100644 --- a/illaclient/src/illarion/client/gui/controller/game/GUIChatHandler.java +++ b/illaclient/src/illarion/client/gui/controller/game/GUIChatHandler.java @@ -1,396 +1,394 @@ /* * This file is part of the Illarion Client. * * Copyright © 2012 - Illarion e.V. * * The Illarion Client 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. * * The Illarion Client 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 the Illarion Client. If not, see <http://www.gnu.org/licenses/>. */ package illarion.client.gui.controller.game; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.NiftyEventSubscriber; import de.lessvoid.nifty.builder.ElementBuilder; import de.lessvoid.nifty.controls.ButtonClickedEvent; import de.lessvoid.nifty.controls.ScrollPanel; import de.lessvoid.nifty.controls.TextField; import de.lessvoid.nifty.controls.label.builder.LabelBuilder; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.input.NiftyStandardInputEvent; import de.lessvoid.nifty.screen.KeyInputHandler; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.screen.ScreenController; import de.lessvoid.nifty.tools.Color; import de.lessvoid.nifty.tools.SizeValue; import illarion.client.input.InputReceiver; import illarion.client.net.CommandFactory; import illarion.client.net.CommandList; import illarion.client.net.client.SayCmd; import illarion.client.net.server.events.BroadcastInformReceivedEvent; import illarion.client.net.server.events.ScriptInformReceivedEvent; import illarion.client.net.server.events.TextToInformReceivedEvent; import illarion.client.util.Lang; import illarion.client.world.events.CharTalkingEvent; import javolution.text.TextBuilder; import org.bushe.swing.event.EventBus; import org.bushe.swing.event.EventSubscriber; import org.bushe.swing.event.EventTopicSubscriber; import org.newdawn.slick.GameContainer; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * This class takes care to receive chat input from the GUI and sends it to the server. Also it receives chat from the * server and takes care for displaying it on the GUI. * * @author Martin Karing &lt;[email protected]&gt; */ public final class GUIChatHandler implements KeyInputHandler, EventTopicSubscriber<String>, EventSubscriber<CharTalkingEvent>, ScreenController, UpdatableHandler { /** * This utility class is used to store the entries that are not yet displayed in the queue until the GUI is * updated. * * @author Martin Karing &lt;[email protected]&gt; */ private static final class MessageEntry { /** * The text of the entry. */ private final String text; /** * The color of the entry. */ private final Color color; /** * Constructor for the entry. * * @param msgText the text stored in the entry * @param msgColor the color of the entry */ MessageEntry(final String msgText, final Color msgColor) { text = msgText; color = msgColor; } /** * Get the text that is supposed to be displayed. * * @return the text to display */ public String getText() { return text; } /** * Get the color of the entry to display. * * @return the color of the entry */ public Color getColor() { return color; } } /** * The default color of text entries. */ private static final Color COLOR_DEFAULT = new Color("#FFFFFF"); /** * The color of shouted or important messages */ private static final Color COLOR_SHOUT = new Color("#f000f0"); /** * The color of whispered text. */ private static final Color COLOR_WHISPER = new Color("#C0C0C0"); /** * The color of emoted. */ private static final Color COLOR_EMOTE = new Color("#00C0C0"); /** * The log that is used to display the text. */ private ScrollPanel chatLog; /** * The input field that holds the text that is yet to be send. */ private TextField chatMsg; /** * The screen that displays the GUI. */ private Screen screen; /** * The nifty instance of this chat handler. */ private Nifty nifty; /** * The Queue of strings that yet need to be written to the GUI. */ private final Queue<GUIChatHandler.MessageEntry> messageQueue; /** * The inform handler for the broadcast inform messages. */ private final EventSubscriber<BroadcastInformReceivedEvent> bcInformEventHandler = new EventSubscriber<BroadcastInformReceivedEvent>() { @Override public void onEvent(final BroadcastInformReceivedEvent event) { final TextBuilder textBuilder = TextBuilder.newInstance(); try { textBuilder.append(Lang.getMsg("chat.broadcast")); textBuilder.append(": "); textBuilder.append(event.getMessage()); messageQueue.offer(new GUIChatHandler.MessageEntry(textBuilder.toString(), COLOR_DEFAULT)); } finally { TextBuilder.recycle(textBuilder); } } }; /** * The inform handler for the text to inform messages. */ private final EventSubscriber<TextToInformReceivedEvent> ttInformEventHandler = new EventSubscriber<TextToInformReceivedEvent>() { @Override public void onEvent(final TextToInformReceivedEvent event) { final TextBuilder textBuilder = TextBuilder.newInstance(); try { textBuilder.append(Lang.getMsg("chat.textto")); textBuilder.append(": "); textBuilder.append(event.getMessage()); messageQueue.offer(new GUIChatHandler.MessageEntry(textBuilder.toString(), COLOR_DEFAULT)); } finally { TextBuilder.recycle(textBuilder); } } }; /** * The inform handler for the text to inform messages. */ private final EventSubscriber<ScriptInformReceivedEvent> scriptInformEventHandler = new EventSubscriber<ScriptInformReceivedEvent>() { @Override public void onEvent(final ScriptInformReceivedEvent event) { if (event.getInformPriority() == 0) { return; } final TextBuilder textBuilder = TextBuilder.newInstance(); try { final Color usedColor; if (event.getInformPriority() == 1) { usedColor = COLOR_DEFAULT; } else { usedColor = COLOR_SHOUT; } textBuilder.append(Lang.getMsg("chat.scriptInform")); textBuilder.append(": "); textBuilder.append(event.getMessage()); messageQueue.offer(new GUIChatHandler.MessageEntry(textBuilder.toString(), usedColor)); } finally { TextBuilder.recycle(textBuilder); } } }; /** * The default constructor. */ public GUIChatHandler() { messageQueue = new ConcurrentLinkedQueue<GUIChatHandler.MessageEntry>(); } @Override public void bind(final Nifty nifty, final Screen screen) { this.screen = screen; this.nifty = nifty; chatMsg = screen.findNiftyControl("chatMsg", TextField.class); chatLog = screen.findNiftyControl("chatPanel", ScrollPanel.class); chatMsg.getElement().addInputHandler(this); } @NiftyEventSubscriber(id = "expandTextLogBtn") public void onInventoryButtonClicked(final String topic, final ButtonClickedEvent data) { toggleChatLog(); } private static final SizeValue CHAT_EXPANDED_HEIGHT = SizeValue.px(500); private static final SizeValue CHAT_COLLAPSED_HEIGHT = SizeValue.px(170); private void toggleChatLog() { final Element chatScroll = screen.findElementByName("chatPanel"); if (chatScroll.getConstraintHeight().equals(CHAT_COLLAPSED_HEIGHT)) { chatScroll.setConstraintHeight(CHAT_EXPANDED_HEIGHT); } else { chatScroll.setConstraintHeight(CHAT_COLLAPSED_HEIGHT); } screen.findElementByName("mainLayer").layoutElements(); } @Override public void onStartScreen() { toggleChatLog(); EventBus.subscribe(CharTalkingEvent.class, this); EventBus.subscribe(InputReceiver.EB_TOPIC, this); EventBus.subscribe(BroadcastInformReceivedEvent.class, bcInformEventHandler); EventBus.subscribe(TextToInformReceivedEvent.class, ttInformEventHandler); EventBus.subscribe(ScriptInformReceivedEvent.class, scriptInformEventHandler); nifty.subscribeAnnotations(this); } @Override public void onEndScreen() { EventBus.unsubscribe(CharTalkingEvent.class, this); EventBus.unsubscribe(InputReceiver.EB_TOPIC, this); EventBus.unsubscribe(BroadcastInformReceivedEvent.class, bcInformEventHandler); EventBus.unsubscribe(TextToInformReceivedEvent.class, ttInformEventHandler); EventBus.unsubscribe(ScriptInformReceivedEvent.class, scriptInformEventHandler); nifty.unsubscribeAnnotations(this); } /** * Receive a Input event from the GUI and send a text in case this event applies. */ @Override public boolean keyEvent(final NiftyInputEvent inputEvent) { if (inputEvent == NiftyStandardInputEvent.SubmitText) { if (chatMsg.hasFocus()) { if (chatMsg.getDisplayedText().isEmpty()) { screen.getFocusHandler().setKeyFocus(null); } else { sendText(chatMsg.getDisplayedText()); chatMsg.setText(""); } } else { chatMsg.setFocus(); } return true; } return false; } /** * Send the text as talking text to the server. * * @param text the text to send */ private static void sendText(final String text) { final SayCmd cmd = CommandFactory.getInstance().getCommand(CommandList.CMD_SAY, SayCmd.class); cmd.setText(text); cmd.send(); } /** * Handle the events this handler subscribed to. * * @param topic the event topic * @param data the data that was delivered along with this event */ @Override public void onEvent(final String topic, final String data) { if (topic.equals(InputReceiver.EB_TOPIC)) { if (data.equals("SelectChat")) { chatMsg.setFocus(); } } } @Override public void update(final GameContainer container, final int delta) { Element contentPane = null; while (true) { final GUIChatHandler.MessageEntry message = messageQueue.poll(); if (message == null) { break; } if (contentPane == null) { contentPane = chatLog.getElement().findElementByName("chatLog"); } final LabelBuilder label = new LabelBuilder(); label.font("chatFont"); label.text(message.getText()); label.color(message.getColor()); label.textHAlign(ElementBuilder.Align.Left); label.parameter("wrap", "true"); - label.width(label.percentage(100)); + label.width(contentPane.getConstraintWidth().toString()); label.build(contentPane.getNifty(), screen, contentPane); } if (contentPane != null) { final int entryCount = contentPane.getElements().size(); for (int i = 0; i < (entryCount - 200); i++) { contentPane.getElements().get(i).markForRemoval(); } - } - if (contentPane != null) { chatLog.setAutoScroll(ScrollPanel.AutoScroll.BOTTOM); chatLog.setAutoScroll(ScrollPanel.AutoScroll.OFF); } } @Override public void onEvent(final CharTalkingEvent event) { Color usedColor = null; switch (event.getMode()) { case emote: usedColor = COLOR_EMOTE; break; case normal: usedColor = COLOR_DEFAULT; break; case ooc: usedColor = COLOR_WHISPER; break; case shout: usedColor = COLOR_SHOUT; break; case whisper: usedColor = COLOR_WHISPER; break; } if (usedColor == null) { throw new IllegalStateException("No color was selected. This can't be happening!"); } messageQueue.offer(new GUIChatHandler.MessageEntry(event.getLoggedText(), usedColor)); } }
false
true
public void update(final GameContainer container, final int delta) { Element contentPane = null; while (true) { final GUIChatHandler.MessageEntry message = messageQueue.poll(); if (message == null) { break; } if (contentPane == null) { contentPane = chatLog.getElement().findElementByName("chatLog"); } final LabelBuilder label = new LabelBuilder(); label.font("chatFont"); label.text(message.getText()); label.color(message.getColor()); label.textHAlign(ElementBuilder.Align.Left); label.parameter("wrap", "true"); label.width(label.percentage(100)); label.build(contentPane.getNifty(), screen, contentPane); } if (contentPane != null) { final int entryCount = contentPane.getElements().size(); for (int i = 0; i < (entryCount - 200); i++) { contentPane.getElements().get(i).markForRemoval(); } } if (contentPane != null) { chatLog.setAutoScroll(ScrollPanel.AutoScroll.BOTTOM); chatLog.setAutoScroll(ScrollPanel.AutoScroll.OFF); } }
public void update(final GameContainer container, final int delta) { Element contentPane = null; while (true) { final GUIChatHandler.MessageEntry message = messageQueue.poll(); if (message == null) { break; } if (contentPane == null) { contentPane = chatLog.getElement().findElementByName("chatLog"); } final LabelBuilder label = new LabelBuilder(); label.font("chatFont"); label.text(message.getText()); label.color(message.getColor()); label.textHAlign(ElementBuilder.Align.Left); label.parameter("wrap", "true"); label.width(contentPane.getConstraintWidth().toString()); label.build(contentPane.getNifty(), screen, contentPane); } if (contentPane != null) { final int entryCount = contentPane.getElements().size(); for (int i = 0; i < (entryCount - 200); i++) { contentPane.getElements().get(i).markForRemoval(); } chatLog.setAutoScroll(ScrollPanel.AutoScroll.BOTTOM); chatLog.setAutoScroll(ScrollPanel.AutoScroll.OFF); } }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/BreakpointRenameTypeParticipant.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/BreakpointRenameTypeParticipant.java index ad62a658e..4c04ec8ef 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/BreakpointRenameTypeParticipant.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/BreakpointRenameTypeParticipant.java @@ -1,118 +1,118 @@ /******************************************************************************* * Copyright (c) 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.core.refactoring; import java.util.List; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.refactoring.IJavaElementMapper; import org.eclipse.jdt.core.refactoring.RenameTypeArguments; import org.eclipse.jdt.debug.core.IJavaBreakpoint; import org.eclipse.jdt.debug.core.IJavaWatchpoint; import org.eclipse.jdt.internal.debug.ui.BreakpointUtils; import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; /** * Breakpoint participant for type rename. * * @since 3.2 */ public class BreakpointRenameTypeParticipant extends BreakpointRenameParticipant { /* * (non-Javadoc) * * @see org.eclipse.jdt.internal.debug.core.refactoring.BreakpointRenameParticipant#accepts(org.eclipse.jdt.core.IJavaElement) */ protected boolean accepts(IJavaElement element) { return element instanceof IType; } /* * (non-Javadoc) * * @see org.eclipse.jdt.internal.debug.core.refactoring.BreakpointRenameParticipant#gatherChanges(org.eclipse.core.resources.IMarker[], * java.util.List, java.lang.String) */ protected void gatherChanges(IMarker[] markers, List changes, String simpleDestName) throws CoreException, OperationCanceledException { IType originalType = (IType) getOriginalElement(); ICompilationUnit originalCU = originalType.getCompilationUnit(); ICompilationUnit destCU = null; IJavaElement affectedContainer = null; IType primaryType = originalCU.findPrimaryType(); if (originalType.isMember() || primaryType == null || !primaryType.equals(originalType)) { destCU = originalCU; affectedContainer = originalType; } else if (primaryType.equals(originalType)) { String ext = ".java"; //$NON-NLS-1$ // assume extension is same as original IResource res = originalCU.getResource(); if (res != null) { ext = '.' + res.getFileExtension(); } destCU = originalType.getPackageFragment().getCompilationUnit(simpleDestName + ext); affectedContainer = originalCU; } RenameTypeArguments arguments = (RenameTypeArguments) getArguments(); IJavaElement[] similarDeclarations = arguments.getSimilarDeclarations(); for (int i = 0; i < markers.length; i++) { IMarker marker = markers[i]; IBreakpoint breakpoint = getBreakpoint(marker); if (breakpoint instanceof IJavaBreakpoint) { IJavaBreakpoint javaBreakpoint = (IJavaBreakpoint) breakpoint; IType breakpointType = BreakpointUtils.getType(javaBreakpoint); + IType destType = null; if (breakpointType != null && isContained(affectedContainer, breakpointType)) { - IType destType = null; String[] names = breakpointType.getTypeQualifiedName().split("\\$"); //$NON-NLS-1$ if (isContained(originalType, breakpointType)) { String[] oldNames = originalType.getTypeQualifiedName().split("\\$"); //$NON-NLS-1$ names[oldNames.length - 1] = simpleDestName; } destType = destCU.getType(names[0]); for (int j = 1; j < names.length; j++) { destType = destType.getType(names[j]); } changes.add(createTypeChange(javaBreakpoint, destType, breakpointType)); } if (breakpoint instanceof IJavaWatchpoint && similarDeclarations != null) { IJavaWatchpoint watchpoint = (IJavaWatchpoint) breakpoint; String fieldName = watchpoint.getFieldName(); for (int j = 0; j < similarDeclarations.length; j++) { IJavaElement element = similarDeclarations[j]; String elementName = element.getElementName(); if (elementName.equals(fieldName)) { RefactoringProcessor processor2 = getProcessor(); IJavaElementMapper elementMapper = (IJavaElementMapper) processor2.getAdapter(IJavaElementMapper.class); IJavaElement refactoredJavaElement = elementMapper.getRefactoredJavaElement(element); String newName = refactoredJavaElement.getElementName(); - IField destField = breakpointType.getField(newName); + IField destField = destType.getField(newName); IField origField = breakpointType.getField(fieldName); changes.add(new WatchpointFieldChange(watchpoint, destField, origField)); } } } } } } }
false
true
protected void gatherChanges(IMarker[] markers, List changes, String simpleDestName) throws CoreException, OperationCanceledException { IType originalType = (IType) getOriginalElement(); ICompilationUnit originalCU = originalType.getCompilationUnit(); ICompilationUnit destCU = null; IJavaElement affectedContainer = null; IType primaryType = originalCU.findPrimaryType(); if (originalType.isMember() || primaryType == null || !primaryType.equals(originalType)) { destCU = originalCU; affectedContainer = originalType; } else if (primaryType.equals(originalType)) { String ext = ".java"; //$NON-NLS-1$ // assume extension is same as original IResource res = originalCU.getResource(); if (res != null) { ext = '.' + res.getFileExtension(); } destCU = originalType.getPackageFragment().getCompilationUnit(simpleDestName + ext); affectedContainer = originalCU; } RenameTypeArguments arguments = (RenameTypeArguments) getArguments(); IJavaElement[] similarDeclarations = arguments.getSimilarDeclarations(); for (int i = 0; i < markers.length; i++) { IMarker marker = markers[i]; IBreakpoint breakpoint = getBreakpoint(marker); if (breakpoint instanceof IJavaBreakpoint) { IJavaBreakpoint javaBreakpoint = (IJavaBreakpoint) breakpoint; IType breakpointType = BreakpointUtils.getType(javaBreakpoint); if (breakpointType != null && isContained(affectedContainer, breakpointType)) { IType destType = null; String[] names = breakpointType.getTypeQualifiedName().split("\\$"); //$NON-NLS-1$ if (isContained(originalType, breakpointType)) { String[] oldNames = originalType.getTypeQualifiedName().split("\\$"); //$NON-NLS-1$ names[oldNames.length - 1] = simpleDestName; } destType = destCU.getType(names[0]); for (int j = 1; j < names.length; j++) { destType = destType.getType(names[j]); } changes.add(createTypeChange(javaBreakpoint, destType, breakpointType)); } if (breakpoint instanceof IJavaWatchpoint && similarDeclarations != null) { IJavaWatchpoint watchpoint = (IJavaWatchpoint) breakpoint; String fieldName = watchpoint.getFieldName(); for (int j = 0; j < similarDeclarations.length; j++) { IJavaElement element = similarDeclarations[j]; String elementName = element.getElementName(); if (elementName.equals(fieldName)) { RefactoringProcessor processor2 = getProcessor(); IJavaElementMapper elementMapper = (IJavaElementMapper) processor2.getAdapter(IJavaElementMapper.class); IJavaElement refactoredJavaElement = elementMapper.getRefactoredJavaElement(element); String newName = refactoredJavaElement.getElementName(); IField destField = breakpointType.getField(newName); IField origField = breakpointType.getField(fieldName); changes.add(new WatchpointFieldChange(watchpoint, destField, origField)); } } } } } }
protected void gatherChanges(IMarker[] markers, List changes, String simpleDestName) throws CoreException, OperationCanceledException { IType originalType = (IType) getOriginalElement(); ICompilationUnit originalCU = originalType.getCompilationUnit(); ICompilationUnit destCU = null; IJavaElement affectedContainer = null; IType primaryType = originalCU.findPrimaryType(); if (originalType.isMember() || primaryType == null || !primaryType.equals(originalType)) { destCU = originalCU; affectedContainer = originalType; } else if (primaryType.equals(originalType)) { String ext = ".java"; //$NON-NLS-1$ // assume extension is same as original IResource res = originalCU.getResource(); if (res != null) { ext = '.' + res.getFileExtension(); } destCU = originalType.getPackageFragment().getCompilationUnit(simpleDestName + ext); affectedContainer = originalCU; } RenameTypeArguments arguments = (RenameTypeArguments) getArguments(); IJavaElement[] similarDeclarations = arguments.getSimilarDeclarations(); for (int i = 0; i < markers.length; i++) { IMarker marker = markers[i]; IBreakpoint breakpoint = getBreakpoint(marker); if (breakpoint instanceof IJavaBreakpoint) { IJavaBreakpoint javaBreakpoint = (IJavaBreakpoint) breakpoint; IType breakpointType = BreakpointUtils.getType(javaBreakpoint); IType destType = null; if (breakpointType != null && isContained(affectedContainer, breakpointType)) { String[] names = breakpointType.getTypeQualifiedName().split("\\$"); //$NON-NLS-1$ if (isContained(originalType, breakpointType)) { String[] oldNames = originalType.getTypeQualifiedName().split("\\$"); //$NON-NLS-1$ names[oldNames.length - 1] = simpleDestName; } destType = destCU.getType(names[0]); for (int j = 1; j < names.length; j++) { destType = destType.getType(names[j]); } changes.add(createTypeChange(javaBreakpoint, destType, breakpointType)); } if (breakpoint instanceof IJavaWatchpoint && similarDeclarations != null) { IJavaWatchpoint watchpoint = (IJavaWatchpoint) breakpoint; String fieldName = watchpoint.getFieldName(); for (int j = 0; j < similarDeclarations.length; j++) { IJavaElement element = similarDeclarations[j]; String elementName = element.getElementName(); if (elementName.equals(fieldName)) { RefactoringProcessor processor2 = getProcessor(); IJavaElementMapper elementMapper = (IJavaElementMapper) processor2.getAdapter(IJavaElementMapper.class); IJavaElement refactoredJavaElement = elementMapper.getRefactoredJavaElement(element); String newName = refactoredJavaElement.getElementName(); IField destField = destType.getField(newName); IField origField = breakpointType.getField(fieldName); changes.add(new WatchpointFieldChange(watchpoint, destField, origField)); } } } } } }
diff --git a/src/main/java/vazkii/tinkerer/common/AutoCrashReporter.java b/src/main/java/vazkii/tinkerer/common/AutoCrashReporter.java index 279777fa..ce88c222 100644 --- a/src/main/java/vazkii/tinkerer/common/AutoCrashReporter.java +++ b/src/main/java/vazkii/tinkerer/common/AutoCrashReporter.java @@ -1,103 +1,103 @@ package vazkii.tinkerer.common; import cpw.mods.fml.common.FMLLog; import vazkii.tinkerer.common.lib.GMailAuthenticator; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.*; import java.util.Properties; import java.util.logging.Handler; import java.util.logging.LogRecord; //Original code from Minechem //Heavilt based on code from RichardG public class AutoCrashReporter extends Handler { public AutoCrashReporter() { FMLLog.getLogger().addHandler(this); } public static String readFileToString(File f) throws FileNotFoundException, IOException { BufferedReader reader = new BufferedReader(new FileReader(f)); String ret = ""; char[] buffer = new char[1024]; int read = 0; while ((read = reader.read(buffer)) != -1) { ret += String.valueOf(buffer, 0, read); } reader.close(); return ret; } @Override public void publish(LogRecord record) { if (record.getMessage().startsWith("This crash report has been saved to: ")) { String report; try { report = readFileToString(new File(record.getMessage().substring(37))); } catch (Throwable e) { StringWriter writer = new StringWriter(); writer.write("Crash report could not be read!\r\n\r\n"); e.printStackTrace(new PrintWriter(writer)); report = writer.toString(); } call(report); } } @Override public void flush() { } @Override public void close() throws SecurityException { } public void call(String crash) { - if (crash.contains("minechem") && crash.indexOf("System Details") > crash.indexOf("minechem") && !crash.contains("occupied by")) { + if (crash.contains("vazkii.tinkerer") && crash.indexOf("System Details") > crash.indexOf("vazkii.tinkerer") && !crash.contains("occupied by")) { String to = "[email protected]"; String neko = "[email protected]"; String from = "[email protected]"; String host = "smtp.gmail.com"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.auth", "true"); String pw = "INSERTPASSWORDHERE"; Session session = Session.getDefaultInstance(properties, new GMailAuthenticator("thaumiccrashes", pw)); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(neko)); message.setSubject("Thaunic Tinkerer Crash crash"); message.setText(crash); Transport.send(message); } catch (Exception mex) { mex.printStackTrace(); } } } }
true
true
public void call(String crash) { if (crash.contains("minechem") && crash.indexOf("System Details") > crash.indexOf("minechem") && !crash.contains("occupied by")) { String to = "[email protected]"; String neko = "[email protected]"; String from = "[email protected]"; String host = "smtp.gmail.com"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.auth", "true"); String pw = "INSERTPASSWORDHERE"; Session session = Session.getDefaultInstance(properties, new GMailAuthenticator("thaumiccrashes", pw)); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(neko)); message.setSubject("Thaunic Tinkerer Crash crash"); message.setText(crash); Transport.send(message); } catch (Exception mex) { mex.printStackTrace(); } } }
public void call(String crash) { if (crash.contains("vazkii.tinkerer") && crash.indexOf("System Details") > crash.indexOf("vazkii.tinkerer") && !crash.contains("occupied by")) { String to = "[email protected]"; String neko = "[email protected]"; String from = "[email protected]"; String host = "smtp.gmail.com"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.auth", "true"); String pw = "INSERTPASSWORDHERE"; Session session = Session.getDefaultInstance(properties, new GMailAuthenticator("thaumiccrashes", pw)); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(neko)); message.setSubject("Thaunic Tinkerer Crash crash"); message.setText(crash); Transport.send(message); } catch (Exception mex) { mex.printStackTrace(); } } }
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java index da15adf0..937baad5 100644 --- a/media/java/android/media/AudioService.java +++ b/media/java/android/media/AudioService.java @@ -1,1434 +1,1434 @@ /* * 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 android.media; import android.app.ActivityManagerNative; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.ContentObserver; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.os.Binder; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.RemoteException; import android.os.ServiceManager; import android.provider.Settings; import android.provider.Settings.System; import android.util.Log; import android.view.VolumePanel; import com.android.internal.telephony.ITelephony; import java.io.IOException; import java.util.ArrayList; /** * The implementation of the volume manager service. * <p> * This implementation focuses on delivering a responsive UI. Most methods are * asynchronous to external calls. For example, the task of setting a volume * will update our internal state, but in a separate thread will set the system * volume and later persist to the database. Similarly, setting the ringer mode * will update the state and broadcast a change and in a separate thread later * persist the ringer mode. * * @hide */ public class AudioService extends IAudioService.Stub { private static final String TAG = "AudioService"; /** How long to delay before persisting a change in volume/ringer mode. */ private static final int PERSIST_DELAY = 3000; private Context mContext; private ContentResolver mContentResolver; /** The UI */ private VolumePanel mVolumePanel; // sendMsg() flags /** Used when a message should be shared across all stream types. */ private static final int SHARED_MSG = -1; /** If the msg is already queued, replace it with this one. */ private static final int SENDMSG_REPLACE = 0; /** If the msg is already queued, ignore this one and leave the old. */ private static final int SENDMSG_NOOP = 1; /** If the msg is already queued, queue this one and leave the old. */ private static final int SENDMSG_QUEUE = 2; // AudioHandler message.whats private static final int MSG_SET_SYSTEM_VOLUME = 0; private static final int MSG_PERSIST_VOLUME = 1; private static final int MSG_PERSIST_RINGER_MODE = 3; private static final int MSG_PERSIST_VIBRATE_SETTING = 4; private static final int MSG_MEDIA_SERVER_DIED = 5; private static final int MSG_MEDIA_SERVER_STARTED = 6; private static final int MSG_PLAY_SOUND_EFFECT = 7; /** @see AudioSystemThread */ private AudioSystemThread mAudioSystemThread; /** @see AudioHandler */ private AudioHandler mAudioHandler; /** @see VolumeStreamState */ private VolumeStreamState[] mStreamStates; private SettingsObserver mSettingsObserver; private boolean mMicMute; private int mMode; private int[] mRoutes = new int[AudioSystem.NUM_MODES]; private Object mSettingsLock = new Object(); private boolean mMediaServerOk; private boolean mSpeakerIsOn; private boolean mBluetoothScoIsConnected; private boolean mHeadsetIsConnected; private boolean mBluetoothA2dpIsConnected; private SoundPool mSoundPool; private Object mSoundEffectsLock = new Object(); private static final int NUM_SOUNDPOOL_CHANNELS = 4; private static final int SOUND_EFFECT_VOLUME = 1000; /* Sound effect file names */ private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/"; private static final String[] SOUND_EFFECT_FILES = new String[] { "Effect_Tick.ogg", "KeypressStandard.ogg", "KeypressSpacebar.ogg", "KeypressDelete.ogg", "KeypressReturn.ogg" }; /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect * uses soundpool (second column) */ private int[][] SOUND_EFFECT_FILES_MAP = new int[][] { {0, -1}, // FX_KEY_CLICK {0, -1}, // FX_FOCUS_NAVIGATION_UP {0, -1}, // FX_FOCUS_NAVIGATION_DOWN {0, -1}, // FX_FOCUS_NAVIGATION_LEFT {0, -1}, // FX_FOCUS_NAVIGATION_RIGHT {1, -1}, // FX_KEYPRESS_STANDARD {2, -1}, // FX_KEYPRESS_SPACEBAR {3, -1}, // FX_FOCUS_DELETE {4, -1} // FX_FOCUS_RETURN }; private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() { public void onError(int error) { switch (error) { case AudioSystem.AUDIO_STATUS_SERVER_DIED: if (mMediaServerOk) { sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0, null, 1500); } break; case AudioSystem.AUDIO_STATUS_OK: if (!mMediaServerOk) { sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SHARED_MSG, SENDMSG_NOOP, 0, 0, null, 0); } break; default: break; } } }; /** * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL}, * {@link AudioManager#RINGER_MODE_SILENT}, or * {@link AudioManager#RINGER_MODE_VIBRATE}. */ private int mRingerMode; /** @see System#MODE_RINGER_STREAMS_AFFECTED */ private int mRingerModeAffectedStreams; /** @see System#MUTE_STREAMS_AFFECTED */ private int mMuteAffectedStreams; /** * Has multiple bits per vibrate type to indicate the type's vibrate * setting. See {@link #setVibrateSetting(int, int)}. * <p> * NOTE: This is not the final decision of whether vibrate is on/off for the * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}. */ private int mVibrateSetting; /////////////////////////////////////////////////////////////////////////// // Construction /////////////////////////////////////////////////////////////////////////// /** @hide */ public AudioService(Context context) { mContext = context; mContentResolver = context.getContentResolver(); mVolumePanel = new VolumePanel(context, this); mSettingsObserver = new SettingsObserver(); createAudioSystemThread(); createStreamStates(); readPersistedSettings(); readAudioSettings(); mMediaServerOk = true; AudioSystem.setErrorCallback(mAudioSystemCallback); loadSoundEffects(); mSpeakerIsOn = false; mBluetoothScoIsConnected = false; mHeadsetIsConnected = false; mBluetoothA2dpIsConnected = false; } private void createAudioSystemThread() { mAudioSystemThread = new AudioSystemThread(); mAudioSystemThread.start(); waitForAudioHandlerCreation(); } /** Waits for the volume handler to be created by the other thread. */ private void waitForAudioHandlerCreation() { synchronized(this) { while (mAudioHandler == null) { try { // Wait for mAudioHandler to be set by the other thread wait(); } catch (InterruptedException e) { Log.e(TAG, "Interrupted while waiting on volume handler."); } } } } private void createStreamStates() { final int[] volumeLevelsPhone = createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_VOICE_CALL]); final int[] volumeLevelsCoarse = createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_SYSTEM]); final int[] volumeLevelsFine = createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_MUSIC]); final int[] volumeLevelsBtPhone = createVolumeLevels(0, AudioManager.MAX_STREAM_VOLUME[AudioManager.STREAM_BLUETOOTH_SCO]); int numStreamTypes = AudioSystem.getNumStreamTypes(); VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes]; for (int i = 0; i < numStreamTypes; i++) { final int[] levels; switch (i) { case AudioSystem.STREAM_MUSIC: levels = volumeLevelsFine; break; case AudioSystem.STREAM_VOICE_CALL: levels = volumeLevelsPhone; break; case AudioSystem.STREAM_BLUETOOTH_SCO: levels = volumeLevelsBtPhone; break; default: levels = volumeLevelsCoarse; break; } if (i == AudioSystem.STREAM_BLUETOOTH_SCO) { streams[i] = new VolumeStreamState(AudioManager.DEFAULT_STREAM_VOLUME[i], i,levels); } else { streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[i], i, levels); } } } private static int[] createVolumeLevels(int offset, int numlevels) { double curve = 1.0f; // 1.4f int [] volumes = new int[numlevels + offset]; for (int i = 0; i < offset; i++) { volumes[i] = 0; } double val = 0; double max = Math.pow(numlevels - 1, curve); for (int i = 0; i < numlevels; i++) { val = Math.pow(i, curve) / max; volumes[offset + i] = (int) (val * 100.0f); } return volumes; } private void readPersistedSettings() { final ContentResolver cr = mContentResolver; mRingerMode = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL); mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0); mRingerModeAffectedStreams = Settings.System.getInt(cr, Settings.System.MODE_RINGER_STREAMS_AFFECTED, ((1 << AudioManager.STREAM_RING)|(1 << AudioManager.STREAM_NOTIFICATION)|(1 << AudioManager.STREAM_SYSTEM))); mMuteAffectedStreams = System.getInt(cr, System.MUTE_STREAMS_AFFECTED, ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM))); // Each stream will read its own persisted settings // Broadcast the sticky intent broadcastRingerMode(); // Broadcast vibrate settings broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER); broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION); } private void readAudioSettings() { synchronized (mSettingsLock) { mMicMute = AudioSystem.isMicrophoneMuted(); mMode = AudioSystem.getMode(); for (int mode = 0; mode < AudioSystem.NUM_MODES; mode++) { mRoutes[mode] = AudioSystem.getRouting(mode); } } } private void applyAudioSettings() { synchronized (mSettingsLock) { AudioSystem.muteMicrophone(mMicMute); AudioSystem.setMode(mMode); for (int mode = 0; mode < AudioSystem.NUM_MODES; mode++) { AudioSystem.setRouting(mode, mRoutes[mode], AudioSystem.ROUTE_ALL); } } } /////////////////////////////////////////////////////////////////////////// // IPC methods /////////////////////////////////////////////////////////////////////////// /** @see AudioManager#adjustVolume(int, int) */ public void adjustVolume(int direction, int flags) { adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags); } /** @see AudioManager#adjustVolume(int, int, int) */ public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) { int streamType = getActiveStreamType(suggestedStreamType); // Don't play sound on other streams if (streamType != AudioSystem.STREAM_RING && (flags & AudioManager.FLAG_PLAY_SOUND) != 0) { flags &= ~AudioManager.FLAG_PLAY_SOUND; } adjustStreamVolume(streamType, direction, flags); } /** @see AudioManager#adjustStreamVolume(int, int, int) */ public void adjustStreamVolume(int streamType, int direction, int flags) { ensureValidDirection(direction); ensureValidStreamType(streamType); boolean notificationsUseRingVolume = Settings.System.getInt(mContentResolver, Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1) == 1; if (notificationsUseRingVolume && streamType == AudioManager.STREAM_NOTIFICATION) { // Redirect the volume change to the ring stream streamType = AudioManager.STREAM_RING; } VolumeStreamState streamState = mStreamStates[streamType]; final int oldIndex = streamState.mIndex; boolean adjustVolume = true; // If either the client forces allowing ringer modes for this adjustment, // or the stream type is one that is affected by ringer modes if ((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0 || streamType == AudioManager.STREAM_RING) { // Check if the ringer mode changes with this volume adjustment. If // it does, it will handle adjusting the volume, so we won't below adjustVolume = checkForRingerModeChange(oldIndex, direction); } if (adjustVolume && streamState.adjustIndex(direction)) { boolean alsoUpdateNotificationVolume = notificationsUseRingVolume && streamType == AudioManager.STREAM_RING; if (alsoUpdateNotificationVolume) { mStreamStates[AudioManager.STREAM_NOTIFICATION].adjustIndex(direction); } // Post message to set system volume (it in turn will post a message // to persist). Do not change volume if stream is muted. if (streamState.muteCount() == 0) { sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0, streamState, 0); if (alsoUpdateNotificationVolume) { sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, AudioManager.STREAM_NOTIFICATION, SENDMSG_NOOP, 0, 0, mStreamStates[AudioManager.STREAM_NOTIFICATION], 0); } } } // UI mVolumePanel.postVolumeChanged(streamType, flags); // Broadcast Intent sendVolumeUpdate(streamType); } /** @see AudioManager#setStreamVolume(int, int, int) */ public void setStreamVolume(int streamType, int index, int flags) { ensureValidStreamType(streamType); syncRingerAndNotificationStreamVolume(streamType, index, false); setStreamVolumeInt(streamType, index, false, true); // UI, etc. mVolumePanel.postVolumeChanged(streamType, flags); // Broadcast Intent sendVolumeUpdate(streamType); } private void sendVolumeUpdate(int streamType) { Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION); intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType); intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, getStreamVolume(streamType)); // Currently, sending the intent only when the stream is BLUETOOTH_SCO if (streamType == AudioManager.STREAM_BLUETOOTH_SCO) { mContext.sendBroadcast(intent); } } /** * Sync the STREAM_RING and STREAM_NOTIFICATION volumes if mandated by the * value in Settings. * * @param streamType Type of the stream * @param index Volume index for the stream * @param force If true, set the volume even if the current and desired * volume as same */ private void syncRingerAndNotificationStreamVolume(int streamType, int index, boolean force) { boolean notificationsUseRingVolume = Settings.System.getInt(mContentResolver, Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1) == 1; if (notificationsUseRingVolume) { if (streamType == AudioManager.STREAM_NOTIFICATION) { // Redirect the volume change to the ring stream streamType = AudioManager.STREAM_RING; } if (streamType == AudioManager.STREAM_RING) { // One-off to sync notification volume to ringer volume setStreamVolumeInt(AudioManager.STREAM_NOTIFICATION, index, force, true); } } } /** * Sets the stream state's index, and posts a message to set system volume. * This will not call out to the UI. Assumes a valid stream type. * * @param streamType Type of the stream * @param index Desired volume index of the stream * @param force If true, set the volume even if the desired volume is same * as the current volume. * @param lastAudible If true, stores new index as last audible one */ private void setStreamVolumeInt(int streamType, int index, boolean force, boolean lastAudible) { VolumeStreamState streamState = mStreamStates[streamType]; if (streamState.setIndex(index, lastAudible) || force) { // Post message to set system volume (it in turn will post a message // to persist). Do not change volume if stream is muted. if (streamState.muteCount() == 0) { sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0, streamState, 0); } } } /** @see AudioManager#setStreamSolo(int, boolean) */ public void setStreamSolo(int streamType, boolean state, IBinder cb) { for (int stream = 0; stream < mStreamStates.length; stream++) { if (!isStreamAffectedByMute(stream) || stream == streamType) continue; // Bring back last audible volume mStreamStates[stream].mute(cb, state); } } /** @see AudioManager#setStreamMute(int, boolean) */ public void setStreamMute(int streamType, boolean state, IBinder cb) { if (isStreamAffectedByMute(streamType)) { mStreamStates[streamType].mute(cb, state); } } /** @see AudioManager#getStreamVolume(int) */ public int getStreamVolume(int streamType) { ensureValidStreamType(streamType); return mStreamStates[streamType].mIndex; } /** @see AudioManager#getStreamMaxVolume(int) */ public int getStreamMaxVolume(int streamType) { ensureValidStreamType(streamType); return mStreamStates[streamType].getMaxIndex(); } /** @see AudioManager#getRingerMode() */ public int getRingerMode() { return mRingerMode; } /** @see AudioManager#setRingerMode(int) */ public void setRingerMode(int ringerMode) { if (ringerMode != mRingerMode) { setRingerModeInt(ringerMode); // Send sticky broadcast broadcastRingerMode(); } } private void setRingerModeInt(int ringerMode) { mRingerMode = ringerMode; // Adjust volumes via posting message int numStreamTypes = AudioSystem.getNumStreamTypes(); if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) { for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { if (!isStreamAffectedByRingerMode(streamType)) continue; // Bring back last audible volume setStreamVolumeInt(streamType, mStreamStates[streamType].mLastAudibleIndex, false, false); } } else { for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { if (isStreamAffectedByRingerMode(streamType)) { // Either silent or vibrate, either way volume is 0 setStreamVolumeInt(streamType, 0, false, false); } else { // restore stream volume in the case the stream changed from affected // to non affected by ringer mode. Does not arm to do it for streams that // are not affected as well. setStreamVolumeInt(streamType, mStreamStates[streamType].mLastAudibleIndex, false, false); } } } // Post a persist ringer mode msg sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG, SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY); } /** @see AudioManager#shouldVibrate(int) */ public boolean shouldVibrate(int vibrateType) { switch (getVibrateSetting(vibrateType)) { case AudioManager.VIBRATE_SETTING_ON: return mRingerMode != AudioManager.RINGER_MODE_SILENT; case AudioManager.VIBRATE_SETTING_ONLY_SILENT: return mRingerMode == AudioManager.RINGER_MODE_VIBRATE; case AudioManager.VIBRATE_SETTING_OFF: // Phone ringer should always vibrate in vibrate mode if (vibrateType == AudioManager.VIBRATE_TYPE_RINGER) { return mRingerMode == AudioManager.RINGER_MODE_VIBRATE; } default: return false; } } /** @see AudioManager#getVibrateSetting(int) */ public int getVibrateSetting(int vibrateType) { return (mVibrateSetting >> (vibrateType * 2)) & 3; } /** @see AudioManager#setVibrateSetting(int, int) */ public void setVibrateSetting(int vibrateType, int vibrateSetting) { mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting); // Broadcast change broadcastVibrateSetting(vibrateType); // Post message to set ringer mode (it in turn will post a message // to persist) sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SHARED_MSG, SENDMSG_NOOP, 0, 0, null, 0); } /** * @see #setVibrateSetting(int, int) */ public static int getValueForVibrateSetting(int existingValue, int vibrateType, int vibrateSetting) { // First clear the existing setting. Each vibrate type has two bits in // the value. Note '3' is '11' in binary. existingValue &= ~(3 << (vibrateType * 2)); // Set into the old value existingValue |= (vibrateSetting & 3) << (vibrateType * 2); return existingValue; } /** @see AudioManager#setMicrophoneMute(boolean) */ public void setMicrophoneMute(boolean on) { if (!checkAudioSettingsPermission("setMicrophoneMute()")) { return; } synchronized (mSettingsLock) { if (on != mMicMute) { AudioSystem.muteMicrophone(on); mMicMute = on; } } } /** @see AudioManager#isMicrophoneMute() */ public boolean isMicrophoneMute() { return mMicMute; } /** @see AudioManager#setMode(int) */ public void setMode(int mode) { if (!checkAudioSettingsPermission("setMode()")) { return; } synchronized (mSettingsLock) { if (mode != mMode) { if (AudioSystem.setMode(mode) == AudioSystem.AUDIO_STATUS_OK) { mMode = mode; } } int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); int index = mStreamStates[streamType].mIndex; syncRingerAndNotificationStreamVolume(streamType, index, true); setStreamVolumeInt(streamType, index, true, true); } } /** @see AudioManager#getMode() */ public int getMode() { return mMode; } /** @see AudioManager#setRouting(int, int, int) */ public void setRouting(int mode, int routes, int mask) { int incallMask = 0; int ringtoneMask = 0; int normalMask = 0; if (!checkAudioSettingsPermission("setRouting()")) { return; } synchronized (mSettingsLock) { // Temporary fix for issue #1713090 until audio routing is refactored in eclair release. // mode AudioSystem.MODE_INVALID is used only by the following AudioManager methods: // setWiredHeadsetOn(), setBluetoothA2dpOn(), setBluetoothScoOn() and setSpeakerphoneOn(). // If applications are using AudioManager.setRouting() that is now deprecated, the routing // command will be ignored. if (mode == AudioSystem.MODE_INVALID) { switch (mask) { case AudioSystem.ROUTE_SPEAKER: // handle setSpeakerphoneOn() if (routes != 0 && !mSpeakerIsOn) { mSpeakerIsOn = true; mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER; incallMask = AudioSystem.ROUTE_ALL; - } else if (mSpeakerIsOn) { + } else if (routes == 0 && mSpeakerIsOn) { mSpeakerIsOn = false; if (mBluetoothScoIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_BLUETOOTH_SCO; } else if (mHeadsetIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET; } else { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE; } incallMask = AudioSystem.ROUTE_ALL; } break; case AudioSystem.ROUTE_BLUETOOTH_SCO: // handle setBluetoothScoOn() if (routes != 0 && !mBluetoothScoIsConnected) { mBluetoothScoIsConnected = true; mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_BLUETOOTH_SCO; mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_BLUETOOTH_SCO; mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_BLUETOOTH_SCO; incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than SCO headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; - } else if (mBluetoothScoIsConnected) { + } else if (routes == 0 && mBluetoothScoIsConnected) { mBluetoothScoIsConnected = false; if (mHeadsetIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET; mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | (AudioSystem.ROUTE_HEADSET|AudioSystem.ROUTE_SPEAKER); mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_HEADSET; } else { if (mSpeakerIsOn) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER; } else { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE; } mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; } incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than SCO headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } break; case AudioSystem.ROUTE_HEADSET: // handle setWiredHeadsetOn() if (routes != 0 && !mHeadsetIsConnected) { mHeadsetIsConnected = true; // do not act upon headset connection if bluetooth SCO is connected to match phone app behavior if (!mBluetoothScoIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET; mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | (AudioSystem.ROUTE_HEADSET|AudioSystem.ROUTE_SPEAKER); mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_HEADSET; incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than wired headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } - } else if (mHeadsetIsConnected) { + } else if (routes == 0 && mHeadsetIsConnected) { mHeadsetIsConnected = false; // do not act upon headset disconnection if bluetooth SCO is connected to match phone app behavior if (!mBluetoothScoIsConnected) { if (mSpeakerIsOn) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER; } else { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE; } mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than wired headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } } break; case AudioSystem.ROUTE_BLUETOOTH_A2DP: // handle setBluetoothA2dpOn() if (routes != 0 && !mBluetoothA2dpIsConnected) { mBluetoothA2dpIsConnected = true; mRoutes[AudioSystem.MODE_RINGTONE] |= AudioSystem.ROUTE_BLUETOOTH_A2DP; mRoutes[AudioSystem.MODE_NORMAL] |= AudioSystem.ROUTE_BLUETOOTH_A2DP; // the audio flinger chooses A2DP as a higher priority, // so there is no need to disable other routes. ringtoneMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; - } else if (mBluetoothA2dpIsConnected) { + } else if (routes == 0 && mBluetoothA2dpIsConnected) { mBluetoothA2dpIsConnected = false; mRoutes[AudioSystem.MODE_RINGTONE] &= ~AudioSystem.ROUTE_BLUETOOTH_A2DP; mRoutes[AudioSystem.MODE_NORMAL] &= ~AudioSystem.ROUTE_BLUETOOTH_A2DP; // the audio flinger chooses A2DP as a higher priority, // so there is no need to disable other routes. ringtoneMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; } break; } // incallMask is != 0 means we must apply ne routing to MODE_IN_CALL mode if (incallMask != 0) { AudioSystem.setRouting(AudioSystem.MODE_IN_CALL, mRoutes[AudioSystem.MODE_IN_CALL], incallMask); } // ringtoneMask is != 0 means we must apply ne routing to MODE_RINGTONE mode if (ringtoneMask != 0) { AudioSystem.setRouting(AudioSystem.MODE_RINGTONE, mRoutes[AudioSystem.MODE_RINGTONE], ringtoneMask); } // normalMask is != 0 means we must apply ne routing to MODE_NORMAL mode if (normalMask != 0) { AudioSystem.setRouting(AudioSystem.MODE_NORMAL, mRoutes[AudioSystem.MODE_NORMAL], normalMask); } int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); int index = mStreamStates[streamType].mIndex; syncRingerAndNotificationStreamVolume(streamType, index, true); setStreamVolumeInt(streamType, index, true, true); } } } /** @see AudioManager#getRouting(int) */ public int getRouting(int mode) { return mRoutes[mode]; } /** @see AudioManager#isMusicActive() */ public boolean isMusicActive() { return AudioSystem.isMusicActive(); } /** @see AudioManager#setParameter(String, String) */ public void setParameter(String key, String value) { AudioSystem.setParameter(key, value); } /** @see AudioManager#playSoundEffect(int) */ public void playSoundEffect(int effectType) { sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP, effectType, SOUND_EFFECT_VOLUME, null, 0); } /** @see AudioManager#playSoundEffect(int, float) */ public void playSoundEffectVolume(int effectType, float volume) { sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP, effectType, (int) (volume * 1000), null, 0); } /** * Loads samples into the soundpool. * This method must be called at when sound effects are enabled */ public boolean loadSoundEffects() { synchronized (mSoundEffectsLock) { mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0); if (mSoundPool == null) { return false; } /* * poolId table: The value -1 in this table indicates that corresponding * file (same index in SOUND_EFFECT_FILES[] has not been loaded. * Once loaded, the value in poolId is the sample ID and the same * sample can be reused for another effect using the same file. */ int[] poolId = new int[SOUND_EFFECT_FILES.length]; for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { poolId[fileIdx] = -1; } /* * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded. * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0: * this indicates we have a valid sample loaded for this effect. */ for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { // Do not load sample if this effect uses the MediaPlayer if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) { continue; } if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) { String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]]; int sampleId = mSoundPool.load(filePath, 0); SOUND_EFFECT_FILES_MAP[effect][1] = sampleId; poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId; if (sampleId <= 0) { Log.w(TAG, "Soundpool could not load file: "+filePath); } } else { SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]]; } } } return true; } /** * Unloads samples from the sound pool. * This method can be called to free some memory when * sound effects are disabled. */ public void unloadSoundEffects() { synchronized (mSoundEffectsLock) { if (mSoundPool == null) { return; } int[] poolId = new int[SOUND_EFFECT_FILES.length]; for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { poolId[fileIdx] = 0; } for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) { continue; } if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) { mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]); SOUND_EFFECT_FILES_MAP[effect][1] = -1; poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1; } } mSoundPool = null; } } /////////////////////////////////////////////////////////////////////////// // Internal methods /////////////////////////////////////////////////////////////////////////// /** * Checks if the adjustment should change ringer mode instead of just * adjusting volume. If so, this will set the proper ringer mode and volume * indices on the stream states. */ private boolean checkForRingerModeChange(int oldIndex, int direction) { boolean adjustVolumeIndex = true; int newRingerMode = mRingerMode; if (mRingerMode == AudioManager.RINGER_MODE_NORMAL && oldIndex == 1 && direction == AudioManager.ADJUST_LOWER) { newRingerMode = AudioManager.RINGER_MODE_VIBRATE; } else if (mRingerMode == AudioManager.RINGER_MODE_VIBRATE) { if (direction == AudioManager.ADJUST_RAISE) { newRingerMode = AudioManager.RINGER_MODE_NORMAL; } else if (direction == AudioManager.ADJUST_LOWER) { newRingerMode = AudioManager.RINGER_MODE_SILENT; } } else if (direction == AudioManager.ADJUST_RAISE && mRingerMode == AudioManager.RINGER_MODE_SILENT) { newRingerMode = AudioManager.RINGER_MODE_VIBRATE; } if (newRingerMode != mRingerMode) { setRingerMode(newRingerMode); /* * If we are changing ringer modes, do not increment/decrement the * volume index. Instead, the handler for the message above will * take care of changing the index. */ adjustVolumeIndex = false; } return adjustVolumeIndex; } public boolean isStreamAffectedByRingerMode(int streamType) { return (mRingerModeAffectedStreams & (1 << streamType)) != 0; } public boolean isStreamAffectedByMute(int streamType) { return (mMuteAffectedStreams & (1 << streamType)) != 0; } private void ensureValidDirection(int direction) { if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) { throw new IllegalArgumentException("Bad direction " + direction); } } private void ensureValidStreamType(int streamType) { if (streamType < 0 || streamType >= mStreamStates.length) { throw new IllegalArgumentException("Bad stream type " + streamType); } } private int getActiveStreamType(int suggestedStreamType) { boolean isOffhook = false; try { ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")); if (phone != null) isOffhook = phone.isOffhook(); } catch (RemoteException e) { Log.w(TAG, "Couldn't connect to phone service", e); } if ((getRouting(AudioSystem.MODE_IN_CALL) & AudioSystem.ROUTE_BLUETOOTH_SCO) != 0) { // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO..."); return AudioSystem.STREAM_BLUETOOTH_SCO; } else if (isOffhook) { // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL..."); return AudioSystem.STREAM_VOICE_CALL; } else if (AudioSystem.isMusicActive()) { // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC..."); return AudioSystem.STREAM_MUSIC; } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) { // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING..."); return AudioSystem.STREAM_RING; } else { // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType); return suggestedStreamType; } } private void broadcastRingerMode() { // Send sticky broadcast if (ActivityManagerNative.isSystemReady()) { Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION); broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode); long origCallerIdentityToken = Binder.clearCallingIdentity(); mContext.sendStickyBroadcast(broadcast); Binder.restoreCallingIdentity(origCallerIdentityToken); } } private void broadcastVibrateSetting(int vibrateType) { // Send broadcast if (ActivityManagerNative.isSystemReady()) { Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION); broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType); broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType)); mContext.sendBroadcast(broadcast); } } // Message helper methods private static int getMsg(int baseMsg, int streamType) { return (baseMsg & 0xffff) | streamType << 16; } private static int getMsgBase(int msg) { return msg & 0xffff; } private static void sendMsg(Handler handler, int baseMsg, int streamType, int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) { int msg = (streamType == SHARED_MSG) ? baseMsg : getMsg(baseMsg, streamType); if (existingMsgPolicy == SENDMSG_REPLACE) { handler.removeMessages(msg); } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) { return; } handler .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay); } boolean checkAudioSettingsPermission(String method) { if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS") == PackageManager.PERMISSION_GRANTED) { return true; } String msg = "Audio Settings Permission Denial: " + method + " from pid=" + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid(); Log.w(TAG, msg); return false; } /////////////////////////////////////////////////////////////////////////// // Inner classes /////////////////////////////////////////////////////////////////////////// public class VolumeStreamState { private final String mVolumeIndexSettingName; private final String mLastAudibleVolumeIndexSettingName; private final int mStreamType; private final int[] mVolumes; private int mIndex; private int mLastAudibleIndex; private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death private VolumeStreamState(String settingName, int streamType, int[] volumes) { mVolumeIndexSettingName = settingName; mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE; mStreamType = streamType; mVolumes = volumes; final ContentResolver cr = mContentResolver; mIndex = getValidIndex(Settings.System.getInt(cr, mVolumeIndexSettingName, AudioManager.DEFAULT_STREAM_VOLUME[streamType])); mLastAudibleIndex = getValidIndex(Settings.System.getInt(cr, mLastAudibleVolumeIndexSettingName, mIndex > 0 ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType])); AudioSystem.setVolume(streamType, volumes[mIndex]); mDeathHandlers = new ArrayList<VolumeDeathHandler>(); } /** * Constructor to be used when there is no setting associated with the VolumeStreamState. * * @param defaultVolume Default volume of the stream to use. * @param streamType Type of the stream. * @param volumes Volumes levels associated with this stream. */ private VolumeStreamState(int defaultVolume, int streamType, int[] volumes) { mVolumeIndexSettingName = null; mLastAudibleVolumeIndexSettingName = null; mIndex = mLastAudibleIndex = defaultVolume; mStreamType = streamType; mVolumes = volumes; AudioSystem.setVolume(mStreamType, defaultVolume); mDeathHandlers = new ArrayList<VolumeDeathHandler>(); } public boolean adjustIndex(int deltaIndex) { return setIndex(mIndex + deltaIndex, true); } public boolean setIndex(int index, boolean lastAudible) { int oldIndex = mIndex; mIndex = getValidIndex(index); if (oldIndex != mIndex) { if (lastAudible) { mLastAudibleIndex = mIndex; } return true; } else { return false; } } public int getMaxIndex() { return mVolumes.length - 1; } public void mute(IBinder cb, boolean state) { VolumeDeathHandler handler = getDeathHandler(cb, state); if (handler == null) { Log.e(TAG, "Could not get client death handler for stream: "+mStreamType); return; } handler.mute(state); } private int getValidIndex(int index) { if (index < 0) { return 0; } else if (index >= mVolumes.length) { return mVolumes.length - 1; } return index; } private class VolumeDeathHandler implements IBinder.DeathRecipient { private IBinder mICallback; // To be notified of client's death private int mMuteCount; // Number of active mutes for this client VolumeDeathHandler(IBinder cb) { mICallback = cb; } public void mute(boolean state) { synchronized(mDeathHandlers) { if (state) { if (mMuteCount == 0) { // Register for client death notification try { mICallback.linkToDeath(this, 0); mDeathHandlers.add(this); // If the stream is not yet muted by any client, set lvel to 0 if (muteCount() == 0) { setIndex(0, false); sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0, VolumeStreamState.this, 0); } } catch (RemoteException e) { // Client has died! binderDied(); mDeathHandlers.notify(); return; } } else { Log.w(TAG, "stream: "+mStreamType+" was already muted by this client"); } mMuteCount++; } else { if (mMuteCount == 0) { Log.e(TAG, "unexpected unmute for stream: "+mStreamType); } else { mMuteCount--; if (mMuteCount == 0) { // Unregistr from client death notification mDeathHandlers.remove(this); mICallback.unlinkToDeath(this, 0); if (muteCount() == 0) { // If the stream is not mut any more, restore it's volume if // ringer mode allows it if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) { setIndex(mLastAudibleIndex, false); sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0, VolumeStreamState.this, 0); } } } } } mDeathHandlers.notify(); } } public void binderDied() { Log.w(TAG, "Volume service client died for stream: "+mStreamType); if (mMuteCount != 0) { // Reset all active mute requests from this client. mMuteCount = 1; mute(false); } } } private int muteCount() { int count = 0; int size = mDeathHandlers.size(); for (int i = 0; i < size; i++) { count += mDeathHandlers.get(i).mMuteCount; } return count; } private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) { synchronized(mDeathHandlers) { VolumeDeathHandler handler; int size = mDeathHandlers.size(); for (int i = 0; i < size; i++) { handler = mDeathHandlers.get(i); if (cb.equals(handler.mICallback)) { return handler; } } // If this is the first mute request for this client, create a new // client death handler. Otherwise, it is an out of sequence unmute request. if (state) { handler = new VolumeDeathHandler(cb); } else { Log.w(TAG, "stream was not muted by this client"); handler = null; } return handler; } } } /** Thread that handles native AudioSystem control. */ private class AudioSystemThread extends Thread { AudioSystemThread() { super("AudioService"); } @Override public void run() { // Set this thread up so the handler will work on it Looper.prepare(); synchronized(AudioService.this) { mAudioHandler = new AudioHandler(); // Notify that the handler has been created AudioService.this.notify(); } // Listen for volume change requests that are set by VolumePanel Looper.loop(); } } /** Handles internal volume messages in separate volume thread. */ private class AudioHandler extends Handler { private void setSystemVolume(VolumeStreamState streamState) { // Adjust volume AudioSystem .setVolume(streamState.mStreamType, streamState.mVolumes[streamState.mIndex]); // Post a persist volume msg sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType, SENDMSG_REPLACE, 0, 0, streamState, PERSIST_DELAY); } private void persistVolume(VolumeStreamState streamState) { System.putInt(mContentResolver, streamState.mVolumeIndexSettingName, streamState.mIndex); System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName, streamState.mLastAudibleIndex); } private void persistRingerMode() { System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode); } private void persistVibrateSetting() { System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting); } private void playSoundEffect(int effectType, int volume) { synchronized (mSoundEffectsLock) { if (mSoundPool == null) { return; } if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) { float v = (float) volume / 1000.0f; mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], v, v, 0, 0, 1.0f); } else { MediaPlayer mediaPlayer = new MediaPlayer(); if (mediaPlayer != null) { try { String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]]; mediaPlayer.setDataSource(filePath); mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM); mediaPlayer.prepare(); mediaPlayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { cleanupPlayer(mp); } }); mediaPlayer.setOnErrorListener(new OnErrorListener() { public boolean onError(MediaPlayer mp, int what, int extra) { cleanupPlayer(mp); return true; } }); mediaPlayer.start(); } catch (IOException ex) { Log.w(TAG, "MediaPlayer IOException: "+ex); } catch (IllegalArgumentException ex) { Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex); } catch (IllegalStateException ex) { Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); } } } } } private void cleanupPlayer(MediaPlayer mp) { if (mp != null) { try { mp.stop(); mp.release(); } catch (IllegalStateException ex) { Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); } } } @Override public void handleMessage(Message msg) { int baseMsgWhat = getMsgBase(msg.what); switch (baseMsgWhat) { case MSG_SET_SYSTEM_VOLUME: setSystemVolume((VolumeStreamState) msg.obj); break; case MSG_PERSIST_VOLUME: persistVolume((VolumeStreamState) msg.obj); break; case MSG_PERSIST_RINGER_MODE: persistRingerMode(); break; case MSG_PERSIST_VIBRATE_SETTING: persistVibrateSetting(); break; case MSG_MEDIA_SERVER_DIED: Log.e(TAG, "Media server died."); // Force creation of new IAudioflinger interface mMediaServerOk = false; AudioSystem.getMode(); break; case MSG_MEDIA_SERVER_STARTED: Log.e(TAG, "Media server started."); // Restore audio routing and stream volumes applyAudioSettings(); int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { int volume; VolumeStreamState streamState = mStreamStates[streamType]; if (streamState.muteCount() == 0) { volume = streamState.mVolumes[streamState.mIndex]; } else { volume = streamState.mVolumes[0]; } AudioSystem.setVolume(streamType, volume); } setRingerMode(mRingerMode); mMediaServerOk = true; break; case MSG_PLAY_SOUND_EFFECT: playSoundEffect(msg.arg1, msg.arg2); break; } } } private class SettingsObserver extends ContentObserver { SettingsObserver() { super(new Handler()); mContentResolver.registerContentObserver(Settings.System.getUriFor( Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); mRingerModeAffectedStreams = Settings.System.getInt(mContentResolver, Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); /* * Ensure all stream types that should be affected by ringer mode * are in the proper state. */ setRingerModeInt(getRingerMode()); } } }
false
true
public void setRouting(int mode, int routes, int mask) { int incallMask = 0; int ringtoneMask = 0; int normalMask = 0; if (!checkAudioSettingsPermission("setRouting()")) { return; } synchronized (mSettingsLock) { // Temporary fix for issue #1713090 until audio routing is refactored in eclair release. // mode AudioSystem.MODE_INVALID is used only by the following AudioManager methods: // setWiredHeadsetOn(), setBluetoothA2dpOn(), setBluetoothScoOn() and setSpeakerphoneOn(). // If applications are using AudioManager.setRouting() that is now deprecated, the routing // command will be ignored. if (mode == AudioSystem.MODE_INVALID) { switch (mask) { case AudioSystem.ROUTE_SPEAKER: // handle setSpeakerphoneOn() if (routes != 0 && !mSpeakerIsOn) { mSpeakerIsOn = true; mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER; incallMask = AudioSystem.ROUTE_ALL; } else if (mSpeakerIsOn) { mSpeakerIsOn = false; if (mBluetoothScoIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_BLUETOOTH_SCO; } else if (mHeadsetIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET; } else { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE; } incallMask = AudioSystem.ROUTE_ALL; } break; case AudioSystem.ROUTE_BLUETOOTH_SCO: // handle setBluetoothScoOn() if (routes != 0 && !mBluetoothScoIsConnected) { mBluetoothScoIsConnected = true; mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_BLUETOOTH_SCO; mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_BLUETOOTH_SCO; mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_BLUETOOTH_SCO; incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than SCO headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } else if (mBluetoothScoIsConnected) { mBluetoothScoIsConnected = false; if (mHeadsetIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET; mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | (AudioSystem.ROUTE_HEADSET|AudioSystem.ROUTE_SPEAKER); mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_HEADSET; } else { if (mSpeakerIsOn) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER; } else { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE; } mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; } incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than SCO headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } break; case AudioSystem.ROUTE_HEADSET: // handle setWiredHeadsetOn() if (routes != 0 && !mHeadsetIsConnected) { mHeadsetIsConnected = true; // do not act upon headset connection if bluetooth SCO is connected to match phone app behavior if (!mBluetoothScoIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET; mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | (AudioSystem.ROUTE_HEADSET|AudioSystem.ROUTE_SPEAKER); mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_HEADSET; incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than wired headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } } else if (mHeadsetIsConnected) { mHeadsetIsConnected = false; // do not act upon headset disconnection if bluetooth SCO is connected to match phone app behavior if (!mBluetoothScoIsConnected) { if (mSpeakerIsOn) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER; } else { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE; } mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than wired headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } } break; case AudioSystem.ROUTE_BLUETOOTH_A2DP: // handle setBluetoothA2dpOn() if (routes != 0 && !mBluetoothA2dpIsConnected) { mBluetoothA2dpIsConnected = true; mRoutes[AudioSystem.MODE_RINGTONE] |= AudioSystem.ROUTE_BLUETOOTH_A2DP; mRoutes[AudioSystem.MODE_NORMAL] |= AudioSystem.ROUTE_BLUETOOTH_A2DP; // the audio flinger chooses A2DP as a higher priority, // so there is no need to disable other routes. ringtoneMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; } else if (mBluetoothA2dpIsConnected) { mBluetoothA2dpIsConnected = false; mRoutes[AudioSystem.MODE_RINGTONE] &= ~AudioSystem.ROUTE_BLUETOOTH_A2DP; mRoutes[AudioSystem.MODE_NORMAL] &= ~AudioSystem.ROUTE_BLUETOOTH_A2DP; // the audio flinger chooses A2DP as a higher priority, // so there is no need to disable other routes. ringtoneMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; } break; } // incallMask is != 0 means we must apply ne routing to MODE_IN_CALL mode if (incallMask != 0) { AudioSystem.setRouting(AudioSystem.MODE_IN_CALL, mRoutes[AudioSystem.MODE_IN_CALL], incallMask); } // ringtoneMask is != 0 means we must apply ne routing to MODE_RINGTONE mode if (ringtoneMask != 0) { AudioSystem.setRouting(AudioSystem.MODE_RINGTONE, mRoutes[AudioSystem.MODE_RINGTONE], ringtoneMask); } // normalMask is != 0 means we must apply ne routing to MODE_NORMAL mode if (normalMask != 0) { AudioSystem.setRouting(AudioSystem.MODE_NORMAL, mRoutes[AudioSystem.MODE_NORMAL], normalMask); } int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); int index = mStreamStates[streamType].mIndex; syncRingerAndNotificationStreamVolume(streamType, index, true); setStreamVolumeInt(streamType, index, true, true); } } }
public void setRouting(int mode, int routes, int mask) { int incallMask = 0; int ringtoneMask = 0; int normalMask = 0; if (!checkAudioSettingsPermission("setRouting()")) { return; } synchronized (mSettingsLock) { // Temporary fix for issue #1713090 until audio routing is refactored in eclair release. // mode AudioSystem.MODE_INVALID is used only by the following AudioManager methods: // setWiredHeadsetOn(), setBluetoothA2dpOn(), setBluetoothScoOn() and setSpeakerphoneOn(). // If applications are using AudioManager.setRouting() that is now deprecated, the routing // command will be ignored. if (mode == AudioSystem.MODE_INVALID) { switch (mask) { case AudioSystem.ROUTE_SPEAKER: // handle setSpeakerphoneOn() if (routes != 0 && !mSpeakerIsOn) { mSpeakerIsOn = true; mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER; incallMask = AudioSystem.ROUTE_ALL; } else if (routes == 0 && mSpeakerIsOn) { mSpeakerIsOn = false; if (mBluetoothScoIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_BLUETOOTH_SCO; } else if (mHeadsetIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET; } else { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE; } incallMask = AudioSystem.ROUTE_ALL; } break; case AudioSystem.ROUTE_BLUETOOTH_SCO: // handle setBluetoothScoOn() if (routes != 0 && !mBluetoothScoIsConnected) { mBluetoothScoIsConnected = true; mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_BLUETOOTH_SCO; mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_BLUETOOTH_SCO; mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_BLUETOOTH_SCO; incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than SCO headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } else if (routes == 0 && mBluetoothScoIsConnected) { mBluetoothScoIsConnected = false; if (mHeadsetIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET; mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | (AudioSystem.ROUTE_HEADSET|AudioSystem.ROUTE_SPEAKER); mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_HEADSET; } else { if (mSpeakerIsOn) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER; } else { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE; } mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; } incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than SCO headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } break; case AudioSystem.ROUTE_HEADSET: // handle setWiredHeadsetOn() if (routes != 0 && !mHeadsetIsConnected) { mHeadsetIsConnected = true; // do not act upon headset connection if bluetooth SCO is connected to match phone app behavior if (!mBluetoothScoIsConnected) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_HEADSET; mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | (AudioSystem.ROUTE_HEADSET|AudioSystem.ROUTE_SPEAKER); mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_HEADSET; incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than wired headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } } else if (routes == 0 && mHeadsetIsConnected) { mHeadsetIsConnected = false; // do not act upon headset disconnection if bluetooth SCO is connected to match phone app behavior if (!mBluetoothScoIsConnected) { if (mSpeakerIsOn) { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_SPEAKER; } else { mRoutes[AudioSystem.MODE_IN_CALL] = AudioSystem.ROUTE_EARPIECE; } mRoutes[AudioSystem.MODE_RINGTONE] = (mRoutes[AudioSystem.MODE_RINGTONE] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; mRoutes[AudioSystem.MODE_NORMAL] = (mRoutes[AudioSystem.MODE_NORMAL] & AudioSystem.ROUTE_BLUETOOTH_A2DP) | AudioSystem.ROUTE_SPEAKER; incallMask = AudioSystem.ROUTE_ALL; // A2DP has higher priority than wired headset, so headset connect/disconnect events // should not affect A2DP routing ringtoneMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_ALL & ~AudioSystem.ROUTE_BLUETOOTH_A2DP; } } break; case AudioSystem.ROUTE_BLUETOOTH_A2DP: // handle setBluetoothA2dpOn() if (routes != 0 && !mBluetoothA2dpIsConnected) { mBluetoothA2dpIsConnected = true; mRoutes[AudioSystem.MODE_RINGTONE] |= AudioSystem.ROUTE_BLUETOOTH_A2DP; mRoutes[AudioSystem.MODE_NORMAL] |= AudioSystem.ROUTE_BLUETOOTH_A2DP; // the audio flinger chooses A2DP as a higher priority, // so there is no need to disable other routes. ringtoneMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; } else if (routes == 0 && mBluetoothA2dpIsConnected) { mBluetoothA2dpIsConnected = false; mRoutes[AudioSystem.MODE_RINGTONE] &= ~AudioSystem.ROUTE_BLUETOOTH_A2DP; mRoutes[AudioSystem.MODE_NORMAL] &= ~AudioSystem.ROUTE_BLUETOOTH_A2DP; // the audio flinger chooses A2DP as a higher priority, // so there is no need to disable other routes. ringtoneMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; normalMask = AudioSystem.ROUTE_BLUETOOTH_A2DP; } break; } // incallMask is != 0 means we must apply ne routing to MODE_IN_CALL mode if (incallMask != 0) { AudioSystem.setRouting(AudioSystem.MODE_IN_CALL, mRoutes[AudioSystem.MODE_IN_CALL], incallMask); } // ringtoneMask is != 0 means we must apply ne routing to MODE_RINGTONE mode if (ringtoneMask != 0) { AudioSystem.setRouting(AudioSystem.MODE_RINGTONE, mRoutes[AudioSystem.MODE_RINGTONE], ringtoneMask); } // normalMask is != 0 means we must apply ne routing to MODE_NORMAL mode if (normalMask != 0) { AudioSystem.setRouting(AudioSystem.MODE_NORMAL, mRoutes[AudioSystem.MODE_NORMAL], normalMask); } int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); int index = mStreamStates[streamType].mIndex; syncRingerAndNotificationStreamVolume(streamType, index, true); setStreamVolumeInt(streamType, index, true, true); } } }
diff --git a/ldapstudio-schemas-plugin/src/main/java/org/apache/directory/ldapstudio/schemas/controller/actions/ExportSchemaForADSAction.java b/ldapstudio-schemas-plugin/src/main/java/org/apache/directory/ldapstudio/schemas/controller/actions/ExportSchemaForADSAction.java index 45aeeec02..9fa94dc81 100644 --- a/ldapstudio-schemas-plugin/src/main/java/org/apache/directory/ldapstudio/schemas/controller/actions/ExportSchemaForADSAction.java +++ b/ldapstudio-schemas-plugin/src/main/java/org/apache/directory/ldapstudio/schemas/controller/actions/ExportSchemaForADSAction.java @@ -1,311 +1,311 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.ldapstudio.schemas.controller.actions; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.naming.NamingException; import org.apache.directory.ldapstudio.schemas.Activator; import org.apache.directory.ldapstudio.schemas.PluginConstants; import org.apache.directory.ldapstudio.schemas.model.AttributeType; import org.apache.directory.ldapstudio.schemas.model.ObjectClass; import org.apache.directory.ldapstudio.schemas.model.Schema; import org.apache.directory.ldapstudio.schemas.view.ViewUtils; import org.apache.directory.ldapstudio.schemas.view.views.SchemasView; import org.apache.directory.ldapstudio.schemas.view.views.wrappers.SchemaWrapper; import org.apache.directory.shared.converter.schema.AttributeTypeHolder; import org.apache.directory.shared.converter.schema.ObjectClassHolder; import org.apache.log4j.Logger; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.plugin.AbstractUIPlugin; /** * This class implements the Action for Exporting a schema For ADS. */ public class ExportSchemaForADSAction extends Action { private static Logger logger = Logger.getLogger( ExportSchemaForADSAction.class ); /** The associated view */ private SchemasView view; /** * Creates a new instance of ExportSchemaForADSAction. * * @param view * the associated view */ public ExportSchemaForADSAction( SchemasView view ) { super( "Export For Apache DS..." ); this.view = view; setToolTipText( getText() ); setId( PluginConstants.CMD_EXPORT_FOR_ADS ); setImageDescriptor( AbstractUIPlugin.imageDescriptorFromPlugin( Activator.PLUGIN_ID, PluginConstants.IMG_EXPORT_SCHEMA_FOR_ADS ) ); setEnabled( true ); } /* (non-Javadoc) * @see org.eclipse.jface.action.Action#run() */ public void run() { Object selection = ( ( TreeSelection ) view.getViewer().getSelection() ).getFirstElement(); if ( selection != null ) { if ( selection instanceof SchemaWrapper ) { Schema schema = ( ( SchemaWrapper ) selection ).getMySchema(); // Opening the FileDialog to let the user choose the destination file FileDialog fd = new FileDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE ); fd.setText( "Select a file" ); fd.setFilterPath( Activator.getDefault().getPreferenceStore().getString( PluginConstants.PREFS_SAVE_FILE_DIALOG ) ); fd.setFileName( schema.getName() + ".ldif" ); //$NON-NLS-1$ fd.setFilterExtensions( new String[] { "*.ldif", "*.*" } ); //$NON-NLS-1$ //$NON-NLS-2$ fd.setFilterNames( new String[] { "LDIF files", "All_files" } ); String savePath = fd.open(); if ( savePath != null ) { File selectedFile = new File( savePath ); if ( selectedFile.exists() ) { int response = ViewUtils.displayQuestionMessageBox( SWT.OK | SWT.CANCEL, "Overwrite existing file ?", "The file you have choosen already exists. Do you want to overwrite it?" ); if ( response == SWT.CANCEL ) { return; } } StringBuffer sb = new StringBuffer(); sb.append( "# " + schema.getName() + "\n" ); DateFormat format = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.MEDIUM ); Date date = new Date(); sb.append( "# Generated by LDAP Studio on " + format.format( date ) + "\n" ); sb.append( "\n" ); // Generation the Schema Node sb.append( "dn: cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: metaSchema\n" ); sb.append( "objectclass: top\n" ); sb.append( "cn: " + schema.getName() + "\n" ); sb.append( "\n" ); try { // Generation the Attribute Types Node sb.append( "dn: ou=attributeTypes, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: attributetypes\n" ); sb.append( "\n" ); // Generating LDIF for Attributes Types for ( AttributeType at : schema.getAttributeTypesAsArray() ) { AttributeTypeHolder holder = new AttributeTypeHolder( at.getOid() ); holder.setCollective( at.isCollective() ); holder.setDescription( at.getDescription() ); holder.setEquality( at.getEquality() ); List<String> names = new ArrayList<String>(); for ( String name : at.getNames() ) { names.add( name ); } holder.setNames( names ); holder.setNoUserModification( at.isNoUserModification() ); holder.setObsolete( at.isObsolete() ); holder.setOrdering( at.getOrdering() ); holder.setSingleValue( at.isSingleValue() ); holder.setSubstr( at.getSubstr() ); holder.setSuperior( at.getSuperior() ); holder.setSyntax( at.getSyntax() ); holder.setOidLen( at.getLength() ); holder.setUsage( at.getUsage() ); sb.append( holder.toLdif( schema.getName() ) + "\n" ); } // Generation the Comparators Node sb.append( "dn: ou=comparators, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: comparators\n" ); sb.append( "\n" ); // Generation the DIT Content Rules Node sb.append( "dn: ou=ditContentRules, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: ditcontentrules\n" ); sb.append( "\n" ); // Generation the DIT Structure RulesNode sb.append( "dn: ou=ditStructureRules, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: ditstructurerules\n" ); sb.append( "\n" ); // Generation the Matching Rules Node - sb.append( "dn: ou=macthingRules, cn=" + schema.getName() + ", ou=schema\n" ); + sb.append( "dn: ou=matchingRules, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: matchingrules\n" ); sb.append( "\n" ); // Generation the Matching Rule Use Node sb.append( "dn: ou=matchingRuleUse, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: matchingruleuse\n" ); sb.append( "\n" ); // Generation the Name Forms Node sb.append( "dn: ou=nameForms, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: nameforms\n" ); sb.append( "\n" ); // Generation the Normalizers Node sb.append( "dn: ou=normalizers, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: normalizers\n" ); sb.append( "\n" ); // Generation the Object Classes Node sb.append( "dn: ou=objectClasses, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: objectClasses\n" ); sb.append( "\n" ); // Generating LDIF for Object Classes for ( ObjectClass oc : schema.getObjectClassesAsArray() ) { ObjectClassHolder holder = new ObjectClassHolder( oc.getOid() ); holder.setClassType( oc.getClassType() ); holder.setDescription( oc.getDescription() ); List<String> mayList = new ArrayList<String>(); for ( String may : oc.getMay() ) { mayList.add( may ); } holder.setMay( mayList ); List<String> mustList = new ArrayList<String>(); for ( String must : oc.getMust() ) { mustList.add( must ); } holder.setMust( mustList ); List<String> names = new ArrayList<String>(); for ( String name : oc.getNames() ) { names.add( name ); } holder.setNames( names ); List<String> superiorList = new ArrayList<String>(); for ( String superior : oc.getSuperiors() ) { superiorList.add( superior ); } holder.setSuperiors( superiorList ); holder.setObsolete( oc.isObsolete() ); sb.append( holder.toLdif( schema.getName() ) + "\n" ); } // Generation the Syntax Checkers Node sb.append( "dn: ou=syntaxCheckers, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: syntaxcheckers\n" ); sb.append( "\n" ); // Generation the Syntaxes Node sb.append( "dn: ou=syntaxes, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: syntaxes\n" ); sb.append( "\n" ); } catch ( NamingException e ) { logger.error( "An error occurred when generating the LDIF associated to the schema.", e ); ViewUtils .displayErrorMessageBox( "Export Failed!", "The file couldn't be saved. An error occurred when generating the LDIF associated to the schema." ); return; } // Writing generated LDIF to the specified file BufferedWriter bufferedWriter; try { bufferedWriter = new BufferedWriter( new FileWriter( savePath ) ); bufferedWriter.write( sb.toString() ); bufferedWriter.close(); } catch ( IOException e ) { logger.error( "The file couldn't be saved. An error occurred when writing file to disk.", e ); ViewUtils.displayErrorMessageBox( "Export Failed!", "The file couldn't be saved. An error occurred when writing file to disk." ); return; } // Export Successful ViewUtils.displayInformationMessageBox( "Export Successful", "The schema has been sucessfully exported." ); Activator.getDefault().getPreferenceStore().putValue( PluginConstants.PREFS_SAVE_FILE_DIALOG, selectedFile.getParent() ); } } } } }
true
true
public void run() { Object selection = ( ( TreeSelection ) view.getViewer().getSelection() ).getFirstElement(); if ( selection != null ) { if ( selection instanceof SchemaWrapper ) { Schema schema = ( ( SchemaWrapper ) selection ).getMySchema(); // Opening the FileDialog to let the user choose the destination file FileDialog fd = new FileDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE ); fd.setText( "Select a file" ); fd.setFilterPath( Activator.getDefault().getPreferenceStore().getString( PluginConstants.PREFS_SAVE_FILE_DIALOG ) ); fd.setFileName( schema.getName() + ".ldif" ); //$NON-NLS-1$ fd.setFilterExtensions( new String[] { "*.ldif", "*.*" } ); //$NON-NLS-1$ //$NON-NLS-2$ fd.setFilterNames( new String[] { "LDIF files", "All_files" } ); String savePath = fd.open(); if ( savePath != null ) { File selectedFile = new File( savePath ); if ( selectedFile.exists() ) { int response = ViewUtils.displayQuestionMessageBox( SWT.OK | SWT.CANCEL, "Overwrite existing file ?", "The file you have choosen already exists. Do you want to overwrite it?" ); if ( response == SWT.CANCEL ) { return; } } StringBuffer sb = new StringBuffer(); sb.append( "# " + schema.getName() + "\n" ); DateFormat format = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.MEDIUM ); Date date = new Date(); sb.append( "# Generated by LDAP Studio on " + format.format( date ) + "\n" ); sb.append( "\n" ); // Generation the Schema Node sb.append( "dn: cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: metaSchema\n" ); sb.append( "objectclass: top\n" ); sb.append( "cn: " + schema.getName() + "\n" ); sb.append( "\n" ); try { // Generation the Attribute Types Node sb.append( "dn: ou=attributeTypes, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: attributetypes\n" ); sb.append( "\n" ); // Generating LDIF for Attributes Types for ( AttributeType at : schema.getAttributeTypesAsArray() ) { AttributeTypeHolder holder = new AttributeTypeHolder( at.getOid() ); holder.setCollective( at.isCollective() ); holder.setDescription( at.getDescription() ); holder.setEquality( at.getEquality() ); List<String> names = new ArrayList<String>(); for ( String name : at.getNames() ) { names.add( name ); } holder.setNames( names ); holder.setNoUserModification( at.isNoUserModification() ); holder.setObsolete( at.isObsolete() ); holder.setOrdering( at.getOrdering() ); holder.setSingleValue( at.isSingleValue() ); holder.setSubstr( at.getSubstr() ); holder.setSuperior( at.getSuperior() ); holder.setSyntax( at.getSyntax() ); holder.setOidLen( at.getLength() ); holder.setUsage( at.getUsage() ); sb.append( holder.toLdif( schema.getName() ) + "\n" ); } // Generation the Comparators Node sb.append( "dn: ou=comparators, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: comparators\n" ); sb.append( "\n" ); // Generation the DIT Content Rules Node sb.append( "dn: ou=ditContentRules, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: ditcontentrules\n" ); sb.append( "\n" ); // Generation the DIT Structure RulesNode sb.append( "dn: ou=ditStructureRules, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: ditstructurerules\n" ); sb.append( "\n" ); // Generation the Matching Rules Node sb.append( "dn: ou=macthingRules, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: matchingrules\n" ); sb.append( "\n" ); // Generation the Matching Rule Use Node sb.append( "dn: ou=matchingRuleUse, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: matchingruleuse\n" ); sb.append( "\n" ); // Generation the Name Forms Node sb.append( "dn: ou=nameForms, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: nameforms\n" ); sb.append( "\n" ); // Generation the Normalizers Node sb.append( "dn: ou=normalizers, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: normalizers\n" ); sb.append( "\n" ); // Generation the Object Classes Node sb.append( "dn: ou=objectClasses, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: objectClasses\n" ); sb.append( "\n" ); // Generating LDIF for Object Classes for ( ObjectClass oc : schema.getObjectClassesAsArray() ) { ObjectClassHolder holder = new ObjectClassHolder( oc.getOid() ); holder.setClassType( oc.getClassType() ); holder.setDescription( oc.getDescription() ); List<String> mayList = new ArrayList<String>(); for ( String may : oc.getMay() ) { mayList.add( may ); } holder.setMay( mayList ); List<String> mustList = new ArrayList<String>(); for ( String must : oc.getMust() ) { mustList.add( must ); } holder.setMust( mustList ); List<String> names = new ArrayList<String>(); for ( String name : oc.getNames() ) { names.add( name ); } holder.setNames( names ); List<String> superiorList = new ArrayList<String>(); for ( String superior : oc.getSuperiors() ) { superiorList.add( superior ); } holder.setSuperiors( superiorList ); holder.setObsolete( oc.isObsolete() ); sb.append( holder.toLdif( schema.getName() ) + "\n" ); } // Generation the Syntax Checkers Node sb.append( "dn: ou=syntaxCheckers, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: syntaxcheckers\n" ); sb.append( "\n" ); // Generation the Syntaxes Node sb.append( "dn: ou=syntaxes, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: syntaxes\n" ); sb.append( "\n" ); } catch ( NamingException e ) { logger.error( "An error occurred when generating the LDIF associated to the schema.", e ); ViewUtils .displayErrorMessageBox( "Export Failed!", "The file couldn't be saved. An error occurred when generating the LDIF associated to the schema." ); return; } // Writing generated LDIF to the specified file BufferedWriter bufferedWriter; try { bufferedWriter = new BufferedWriter( new FileWriter( savePath ) ); bufferedWriter.write( sb.toString() ); bufferedWriter.close(); } catch ( IOException e ) { logger.error( "The file couldn't be saved. An error occurred when writing file to disk.", e ); ViewUtils.displayErrorMessageBox( "Export Failed!", "The file couldn't be saved. An error occurred when writing file to disk." ); return; } // Export Successful ViewUtils.displayInformationMessageBox( "Export Successful", "The schema has been sucessfully exported." ); Activator.getDefault().getPreferenceStore().putValue( PluginConstants.PREFS_SAVE_FILE_DIALOG, selectedFile.getParent() ); } } } }
public void run() { Object selection = ( ( TreeSelection ) view.getViewer().getSelection() ).getFirstElement(); if ( selection != null ) { if ( selection instanceof SchemaWrapper ) { Schema schema = ( ( SchemaWrapper ) selection ).getMySchema(); // Opening the FileDialog to let the user choose the destination file FileDialog fd = new FileDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE ); fd.setText( "Select a file" ); fd.setFilterPath( Activator.getDefault().getPreferenceStore().getString( PluginConstants.PREFS_SAVE_FILE_DIALOG ) ); fd.setFileName( schema.getName() + ".ldif" ); //$NON-NLS-1$ fd.setFilterExtensions( new String[] { "*.ldif", "*.*" } ); //$NON-NLS-1$ //$NON-NLS-2$ fd.setFilterNames( new String[] { "LDIF files", "All_files" } ); String savePath = fd.open(); if ( savePath != null ) { File selectedFile = new File( savePath ); if ( selectedFile.exists() ) { int response = ViewUtils.displayQuestionMessageBox( SWT.OK | SWT.CANCEL, "Overwrite existing file ?", "The file you have choosen already exists. Do you want to overwrite it?" ); if ( response == SWT.CANCEL ) { return; } } StringBuffer sb = new StringBuffer(); sb.append( "# " + schema.getName() + "\n" ); DateFormat format = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.MEDIUM ); Date date = new Date(); sb.append( "# Generated by LDAP Studio on " + format.format( date ) + "\n" ); sb.append( "\n" ); // Generation the Schema Node sb.append( "dn: cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: metaSchema\n" ); sb.append( "objectclass: top\n" ); sb.append( "cn: " + schema.getName() + "\n" ); sb.append( "\n" ); try { // Generation the Attribute Types Node sb.append( "dn: ou=attributeTypes, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: attributetypes\n" ); sb.append( "\n" ); // Generating LDIF for Attributes Types for ( AttributeType at : schema.getAttributeTypesAsArray() ) { AttributeTypeHolder holder = new AttributeTypeHolder( at.getOid() ); holder.setCollective( at.isCollective() ); holder.setDescription( at.getDescription() ); holder.setEquality( at.getEquality() ); List<String> names = new ArrayList<String>(); for ( String name : at.getNames() ) { names.add( name ); } holder.setNames( names ); holder.setNoUserModification( at.isNoUserModification() ); holder.setObsolete( at.isObsolete() ); holder.setOrdering( at.getOrdering() ); holder.setSingleValue( at.isSingleValue() ); holder.setSubstr( at.getSubstr() ); holder.setSuperior( at.getSuperior() ); holder.setSyntax( at.getSyntax() ); holder.setOidLen( at.getLength() ); holder.setUsage( at.getUsage() ); sb.append( holder.toLdif( schema.getName() ) + "\n" ); } // Generation the Comparators Node sb.append( "dn: ou=comparators, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: comparators\n" ); sb.append( "\n" ); // Generation the DIT Content Rules Node sb.append( "dn: ou=ditContentRules, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: ditcontentrules\n" ); sb.append( "\n" ); // Generation the DIT Structure RulesNode sb.append( "dn: ou=ditStructureRules, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: ditstructurerules\n" ); sb.append( "\n" ); // Generation the Matching Rules Node sb.append( "dn: ou=matchingRules, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: matchingrules\n" ); sb.append( "\n" ); // Generation the Matching Rule Use Node sb.append( "dn: ou=matchingRuleUse, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: matchingruleuse\n" ); sb.append( "\n" ); // Generation the Name Forms Node sb.append( "dn: ou=nameForms, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: nameforms\n" ); sb.append( "\n" ); // Generation the Normalizers Node sb.append( "dn: ou=normalizers, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: normalizers\n" ); sb.append( "\n" ); // Generation the Object Classes Node sb.append( "dn: ou=objectClasses, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: objectClasses\n" ); sb.append( "\n" ); // Generating LDIF for Object Classes for ( ObjectClass oc : schema.getObjectClassesAsArray() ) { ObjectClassHolder holder = new ObjectClassHolder( oc.getOid() ); holder.setClassType( oc.getClassType() ); holder.setDescription( oc.getDescription() ); List<String> mayList = new ArrayList<String>(); for ( String may : oc.getMay() ) { mayList.add( may ); } holder.setMay( mayList ); List<String> mustList = new ArrayList<String>(); for ( String must : oc.getMust() ) { mustList.add( must ); } holder.setMust( mustList ); List<String> names = new ArrayList<String>(); for ( String name : oc.getNames() ) { names.add( name ); } holder.setNames( names ); List<String> superiorList = new ArrayList<String>(); for ( String superior : oc.getSuperiors() ) { superiorList.add( superior ); } holder.setSuperiors( superiorList ); holder.setObsolete( oc.isObsolete() ); sb.append( holder.toLdif( schema.getName() ) + "\n" ); } // Generation the Syntax Checkers Node sb.append( "dn: ou=syntaxCheckers, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: syntaxcheckers\n" ); sb.append( "\n" ); // Generation the Syntaxes Node sb.append( "dn: ou=syntaxes, cn=" + schema.getName() + ", ou=schema\n" ); sb.append( "objectclass: organizationalUnit\n" ); sb.append( "objectclass: top\n" ); sb.append( "ou: syntaxes\n" ); sb.append( "\n" ); } catch ( NamingException e ) { logger.error( "An error occurred when generating the LDIF associated to the schema.", e ); ViewUtils .displayErrorMessageBox( "Export Failed!", "The file couldn't be saved. An error occurred when generating the LDIF associated to the schema." ); return; } // Writing generated LDIF to the specified file BufferedWriter bufferedWriter; try { bufferedWriter = new BufferedWriter( new FileWriter( savePath ) ); bufferedWriter.write( sb.toString() ); bufferedWriter.close(); } catch ( IOException e ) { logger.error( "The file couldn't be saved. An error occurred when writing file to disk.", e ); ViewUtils.displayErrorMessageBox( "Export Failed!", "The file couldn't be saved. An error occurred when writing file to disk." ); return; } // Export Successful ViewUtils.displayInformationMessageBox( "Export Successful", "The schema has been sucessfully exported." ); Activator.getDefault().getPreferenceStore().putValue( PluginConstants.PREFS_SAVE_FILE_DIALOG, selectedFile.getParent() ); } } } }
diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java index 65ba74c5..7e3722f4 100644 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java +++ b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java @@ -1,956 +1,952 @@ /* Copyright (c) 2009-2013 Olivier Chafik, All Rights Reserved This file is part of JNAerator (http://jnaerator.googlecode.com/). JNAerator 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. JNAerator 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 JNAerator. If not, see <http://www.gnu.org/licenses/>. */ package com.ochafik.lang.jnaerator; import org.bridj.ann.Name; import org.bridj.BridJ; import org.bridj.FlagSet; import org.bridj.IntValuedEnum; import org.bridj.StructObject; import org.bridj.cpp.CPPObject; import org.bridj.cpp.com.IUnknown; import com.ochafik.lang.jnaerator.BridJTypeConversion.NL4JConversion; import com.ochafik.lang.jnaerator.TypeConversion.ConvType; import com.ochafik.lang.jnaerator.TypeConversion.EnumItemResult; //import org.bridj.structs.StructIO; //import org.bridj.structs.Array; import java.io.IOException; import java.util.*; import com.ochafik.lang.jnaerator.parser.*; import com.ochafik.lang.jnaerator.parser.Enum; import com.ochafik.lang.jnaerator.parser.Statement.Block; import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; import com.ochafik.lang.jnaerator.parser.Struct.MemberVisibility; import com.ochafik.lang.jnaerator.parser.TypeRef.*; import com.ochafik.lang.jnaerator.parser.Expression.*; import com.ochafik.lang.jnaerator.parser.Function.Type; import com.ochafik.lang.jnaerator.parser.DeclarationsHolder.ListWrapper; import com.ochafik.lang.jnaerator.parser.Declarator.*; import com.ochafik.util.listenable.Pair; import com.ochafik.util.string.StringUtils; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; import com.ochafik.lang.jnaerator.parser.Function.SignatureType; import org.bridj.*; import org.bridj.ann.Convention; import org.bridj.ann.Optional; import org.bridj.cpp.CPPRuntime; import org.bridj.objc.NSObject; public class BridJDeclarationsConverter extends DeclarationsConverter { public BridJDeclarationsConverter(Result result) { super(result); } public void annotateActualName(ModifiableElement e, Identifier name) { e.addAnnotation(new Annotation(org.bridj.ann.Name.class, expr(name.toString()))); } @Override public Struct convertCallback(FunctionSignature functionSignature, Signatures signatures, Identifier callerLibraryName) { Struct decl = super.convertCallback(functionSignature, signatures, callerLibraryName); if (decl != null) { decl.setParents(Arrays.asList((SimpleTypeRef) (FunctionSignature.Type.ObjCBlock.equals(functionSignature.getType()) ? result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ObjCBlock) : (SimpleTypeRef) typeRef(ident(result.config.runtime.callbackClass, expr(typeRef(decl.getTag().clone()))))))); //addCallingConventionAnnotation(functionSignature.getFunction(), decl); } return decl; } @Override public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { if (e.isForwardDeclaration()) { return; } Identifier rawEnumName = getActualTaggedTypeName(e); Map<String, EnumItemResult> results = result.typeConverter.getEnumValuesAndCommentsByName(e, libraryClassName); boolean hasEnumClass = false; if (rawEnumName != null && rawEnumName.resolveLastSimpleIdentifier().getName() != null) { hasEnumClass = true; Identifier enumName = result.typeConverter.getValidJavaIdentifier(rawEnumName); if (!signatures.addClass(enumName)) { return; } signatures = new Signatures(); Enum en = new Enum(); if (result.config.forceNames || !rawEnumName.equals(enumName)) annotateActualName(en, rawEnumName); addParentNamespaceAnnotation(en, e.getParentNamespace()); if (!result.config.noComments) { en.importComments(e, "enum values", getFileCommentContent(e)); } en.setType(Enum.Type.Java); en.setTag(enumName.clone()); en.addModifiers(ModifierType.Public); out.addDeclaration(new TaggedTypeRefDeclaration(en)); Struct body = new Struct(); en.setBody(body); boolean hasValidItem = false; for (EnumItemResult er : results.values()) { if (er.errorElement != null) { out.addDeclaration(er.errorElement); continue; } String itemName = result.typeConverter.getValidJavaIdentifierString(ident(er.originalItem.getName())); Enum.EnumItem item = new Enum.EnumItem(itemName, er.convertedValue); en.addItem(item); hasValidItem = true; if (!result.config.noComments) { if (item != null) {// && hasEnumClass) { item.importComments(er.originalItem); } } } if (hasValidItem) { en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); String valueArgName = "value"; body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName)))))); body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)))).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( new Statement.Return( methodCall( methodCall( expr(typeRef(Collections.class)), MemberRefStyle.Dot, "singleton", thisRef()), MemberRefStyle.Dot, "iterator")))).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( new Statement.Return( methodCall( expr(typeRef(FlagSet.class)), MemberRefStyle.Dot, "fromValue", varRef(valueArgName), methodCall( "values"))))).addModifiers(ModifierType.Public, ModifierType.Static)); } } else { outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); } } void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { Convention.Style cc = null; if (originalFunction.hasModifier(ModifierType.__stdcall)) { cc = Convention.Style.StdCall; } else if (originalFunction.hasModifier(ModifierType.__fastcall)) { cc = Convention.Style.FastCall; } else if (originalFunction.hasModifier(ModifierType.__thiscall)) { cc = Convention.Style.ThisCall; } else if (originalFunction.hasModifier(ModifierType.__pascal)) { cc = Convention.Style.Pascal; } if (cc != null) { target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); } } @Override public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder declarations, DeclarationsHolder implementations, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { assert implementations != null; boolean extractingDeclarations = declarations != null && implementations != declarations; Element parent = function.getParentElement(); MemberVisibility visibility = function.getVisibility(); boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); boolean isInStruct = parent instanceof Struct; if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) { return; } boolean isStatic = function.hasModifier(ModifierType.Static); boolean isConstructor = iConstructor != -1; Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); if (result.config.synchronizedMethods && !isCallback) { nativeMethod.addModifiers(ModifierType.Synchronized); } addCallingConventionAnnotation(function, nativeMethod); - if (function.getName() != null && !functionName.toString().equals(function.getName().toString()) && !isCallback) { - TypeRef mgc = result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name); - if (mgc != null) { - nativeMethod.addAnnotation(new Annotation(mgc, "(\"" + function.getName() + "\")")); - } + if (function.getName() != null && !isCallback && + (!functionName.toString().equals(function.getName().toString()) || result.config.forceNames)) + { + annotateActualName(nativeMethod, function.getName()); } Function rawMethod = nativeMethod.clone(); //Map<String, NL4JConversion> argTypes = new LinkedHashMap<String, NL4JConversion>(); boolean isObjectiveC = function.getType() == Type.ObjCMethod; int iArg = 1; Set<String> argNames = new TreeSet<String>(); List<Expression> superConstructorArgs = null; if (isConstructor) { superConstructorArgs = new ArrayList<Expression>(); superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); superConstructorArgs.add(expr(iConstructor)); } Identifier varArgType = null; String varArgName = null; NL4JConversion returnType = null; List<NL4JConversion> paramTypes = new ArrayList<NL4JConversion>(); List<String> paramNames = new ArrayList<String>(); if (!isConstructor) { returnType = ((BridJTypeConversion) result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); } for (Arg arg : function.getArgs()) { String paramName; if (arg.isVarArg()) { assert arg.getValueType() == null; paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); varArgType = ident(isObjectiveC ? NSObject.class : Object.class); } else { paramName = chooseJavaArgName(arg.getName(), iArg, argNames); paramTypes.add(((BridJTypeConversion) result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); } paramNames.add(paramName); if (isConstructor) { superConstructorArgs.add(varRef(paramName)); } iArg++; } fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); List<Declaration> extractibleDecls = new ArrayList<Declaration>(); Block convertedBody = null; if (isConstructor) { convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); } else if (result.config.convertBodies && function.getBody() != null) { try { Pair<Element, List<Declaration>> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); convertedBody = (Block) bodyAndExtraDeclarations.getFirst(); for (Declaration d : bodyAndExtraDeclarations.getSecond()) { implementations.addDeclaration(d); // extractibleDecls.add(d); } } catch (Exception ex) { ex.printStackTrace(System.out); nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); } } if (!result.config.noComments) { nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); } boolean generateStaticMethod = (isStatic || !isCallback && !isInStruct) && (declarations == null || implementations == declarations); nativeMethod.addModifiers( isProtected && !extractingDeclarations && !result.config.publicRawBindings ? ModifierType.Protected : ModifierType.Public, generateStaticMethod ? ModifierType.Static : null); boolean isOptional = isOptionalFunction(function.getName() + ""); implementations.addDeclaration(nativeMethod); boolean forwardedToRaw = false; if (convertedBody == null) { if (result.config.genRawBindings) {// && !isCallback) { // Function rawMethod = nativeMethod.clone(); rawMethod.setArgs(Collections.EMPTY_LIST); fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); rawMethod.addModifiers( extractingDeclarations || isCallback || result.config.publicRawBindings ? ModifierType.Public : ModifierType.Protected, isCallback ? ModifierType.Abstract : ModifierType.Native); if (generateStaticMethod) { rawMethod.addModifiers(ModifierType.Static); } if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { implementations.addDeclaration(rawMethod); extractibleDecls.add(rawMethod); if (isOptional && !isCallback) { rawMethod.addAnnotation(new Annotation(typeRef(Optional.class))); } List<Expression> followedArgs = new ArrayList<Expression>(); for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); Expression followedArg; switch (paramType.type) { case Pointer: followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); break; case Enum: followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); break; // case NativeSize: // case NativeLong: // followedArg = methodCall(varRef(paramName), "longValue"); // break; default: followedArg = varRef(paramName); break; } followedArgs.add(followedArg); } if (varArgType != null) { followedArgs.add(varRef(varArgName)); } Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); if (isVoid) { nativeMethod.setBody(block(stat(followedCall))); } else { switch (returnType.type) { case Pointer: if (returnType.isTypedPointer) { followedCall = new New(nativeMethod.getValueType(), followedCall); } else { Expression ptrExpr = expr(typeRef(org.bridj.Pointer.class)); Expression targetTypeExpr = result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType())); if (targetTypeExpr == null || (returnType.targetTypeConversion != null && returnType.targetTypeConversion.type == ConvType.Void)) { followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall); } else { followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, targetTypeExpr); } } break; case Enum: followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); break; case NativeLong: case NativeSize: if (!rawMethod.getValueType().toString().equals("long")) { followedCall = new New(nativeMethod.getValueType().clone(), followedCall); } default: break; } nativeMethod.setBody(block(new Statement.Return(followedCall))); } forwardedToRaw = true; } } if (!forwardedToRaw) { nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); if (isOptional && !isCallback) { nativeMethod.addAnnotation(new Annotation(typeRef(Optional.class))); } } else if (isCallback) { nativeMethod.addModifiers(ModifierType.Final); } } else { nativeMethod.setBody(convertedBody); } if (!forwardedToRaw && convertedBody == null) { extractibleDecls.add(nativeMethod); } for (Declaration d : extractibleDecls) { if (extractingDeclarations) { if (d instanceof Function) { Function m = (Function)d.clone(); m.setBody(null); m.removeModifiers(ModifierType.Abstract, ModifierType.Final, ModifierType.Static, ModifierType.Native, ModifierType.Public, ModifierType.Protected); declarations.addDeclaration(m); // d.addAnnotation(new Annotation(typeRef(Override.class))); } } } } private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List<NL4JConversion> paramTypes, List<String> paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); } if (varArgType != null) { nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); } if (returnType != null) { returnType.annotateTypedType(nativeMethod, useRawTypes); nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); } String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); if (!javaMethodName.equals(functionName)) { nativeMethod.setName(javaMethodName); } - if (!isCallback && !javaMethodName.equals(functionName) || returnType != null && result.config.forceNames) { - annotateActualName(nativeMethod, functionName); - } } @Override public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { Identifier structName = getActualTaggedTypeName(struct); if (structName == null) { return null; } //if (structName.toString().contains("MonoObject")) // structName.toString(); if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) { return null; } if (!signatures.addClass(structName)) { return null; } boolean isUnion = struct.getType() == Struct.Type.CUnion; boolean inheritsFromStruct = false; Identifier baseClass = null; int parentFieldsCount = 0; List<String> preComments = new ArrayList<String>(); for (SimpleTypeRef parentName : struct.getParents()) { Struct parent = result.structsByName.get(parentName.getName()); if (parent == null) { // TODO report error continue; } try { parentFieldsCount += countFieldsInStruct(parent); } catch (UnsupportedConversionException ex) { preComments.add("Error: " + ex); } baseClass = result.typeConverter.getTaggedTypeIdentifierInJava(parent); if (baseClass != null) { inheritsFromStruct = true; break; // TODO handle multiple and virtual inheritage } } boolean hasMemberFunctions = false; for (Declaration d : struct.getDeclarations()) { if (d instanceof Function) { hasMemberFunctions = true; break; } } Constant uuid = (Constant) struct.getModifierValue(ModifierType.UUID); if (baseClass == null) { switch (struct.getType()) { case CStruct: case CUnion: if (!hasMemberFunctions) { baseClass = ident(StructObject.class); break; } case CPPClass: baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); result.hasCPlusPlus = true; break; default: throw new UnsupportedOperationException(); } } Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); if (!result.config.noStaticInit) structJavaClass.addDeclaration(newStaticInit()); //if (result.config.microsoftCOM) { if (uuid != null) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); } if (result.config.forceNames) annotateActualName(structJavaClass, structName); addParentNamespaceAnnotation(structJavaClass, struct.getParentNamespace()); structJavaClass.addToCommentBefore(preComments); //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); final int iChild[] = new int[]{parentFieldsCount}; //cl.addDeclaration(new EmptyDeclaration()) Signatures childSignatures = new Signatures(); /*if (isVirtual(struct) && !onlyFields) { String vptrName = DEFAULT_VPTR_NAME; VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); vptr.addModifiers(ModifierType.Public); structJavaClass.addDeclaration(vptr); childSignatures.variablesSignatures.add(vptrName); // TODO add vptr grabber to constructor ! }*/ // private static StructIO<MyStruct> io = StructIO.getInstance(MyStruct.class); if (isUnion) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); } int iVirtual = 0, iConstructor = 0; //List<Declaration> children = new ArrayList<Declaration>(); boolean succeeded = true; for (Declaration d : struct.getDeclarations()) { //if (isUnion) // iChild[0] = 0; if (d instanceof VariablesDeclaration) { succeeded = convertVariablesDeclaration((VariablesDeclaration) d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary) && succeeded; } else if (!onlyFields) { if (d instanceof TaggedTypeRefDeclaration) { TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); if (tr instanceof Struct) { outputConvertedStruct((Struct) tr, childSignatures, structJavaClass, callerLibrary, false); } else if (tr instanceof Enum) { convertEnum((Enum) tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (d instanceof TypeDef) { TypeDef td = (TypeDef) d; TypeRef tr = td.getValueType(); if (tr instanceof Struct) { outputConvertedStruct((Struct) tr, childSignatures, structJavaClass, callerLibrary, false); } else { FunctionSignature fs = null; if (tr instanceof FunctionSignature) { fs = (FunctionSignature) tr; } else if (tr instanceof TypeRef.Pointer) { TypeRef target = ((TypeRef.Pointer) tr).getTarget(); if (target instanceof FunctionSignature) { fs = (FunctionSignature) target; } } if (fs != null) { convertCallback(fs, childSignatures, structJavaClass); } } } else if (result.config.genCPlusPlus && d instanceof Function) { Function f = (Function) d; boolean isVirtual = f.hasModifier(ModifierType.Virtual); boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); if (isConstructor && f.getArgs().isEmpty()) { continue; // default constructor was already generated } String library = result.getLibrary(struct); if (library == null) { continue; } List<Declaration> decls = new ArrayList<Declaration>(); DeclarationsHolder out = new ListWrapper(decls); convertFunction(f, childSignatures, false, out, out, callerLibraryClass, isConstructor ? iConstructor : -1); for (Declaration md : decls) { if (!(md instanceof Function)) { continue; } Function method = (Function) md; boolean commentOut = false; if (isVirtual) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); } else if (method.getValueType() == null) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); isConstructor = true; } if (method.getName().toString().equals("operator")) { commentOut = true; } if (commentOut) { structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); } else { structJavaClass.addDeclaration(method); } } if (isVirtual) { iVirtual++; } if (isConstructor) { iConstructor++; } } } } if (succeeded) { Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(defaultConstructor)) { structJavaClass.addDeclaration(defaultConstructor); } String ptrName = "pointer"; Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(castConstructor)) { structJavaClass.addDeclaration(castConstructor); } } else { structJavaClass.addModifiers(ModifierType.Abstract); } return structJavaClass; } Map<Identifier, Boolean> structsVirtuality = new HashMap<Identifier, Boolean>(); public boolean isVirtual(Struct struct) { Identifier name = getActualTaggedTypeName(struct); Boolean bVirtual = structsVirtuality.get(name); if (bVirtual == null) { boolean hasVirtualParent = false, hasVirtualMembers = false; for (SimpleTypeRef parentName : struct.getParents()) { Struct parentStruct = result.structsByName.get(parentName.getName()); if (parentStruct == null) { if (result.config.verbose) { System.out.println("Failed to resolve parent '" + parentName + "' for struct '" + name + "'"); } continue; } if (isVirtual(parentStruct)) { hasVirtualParent = true; break; } } for (Declaration mb : struct.getDeclarations()) { if (mb.hasModifier(ModifierType.Virtual)) { hasVirtualMembers = true; break; } } bVirtual = hasVirtualMembers && !hasVirtualParent; structsVirtuality.put(name, bVirtual); } return bVirtual; } protected String ioVarName = "io", ioStaticVarName = "IO"; public List<Declaration> convertVariablesDeclarationToBridJ(String name, TypeRef mutatedType, int[] iChild, int bits, boolean isGlobal, Identifier holderName, Identifier callerLibraryName, String callerLibrary, Element... toImportDetailsFrom) throws UnsupportedConversionException { name = result.typeConverter.getValidJavaArgumentName(ident(name)).toString(); //convertVariablesDeclaration(name, mutatedType, out, iChild, callerLibraryName); final boolean useRawTypes = false; //Expression initVal = null; int fieldIndex = iChild[0]; //convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structPeerExpr, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { NL4JConversion conv = ((BridJTypeConversion) result.typeConverter).convertTypeToNL4J( mutatedType, callerLibraryName, thisField("io"), varRef(name), fieldIndex, bits); if (conv == null) { throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java"); } else if (conv.isUndefined) { throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java (undefined type)"); } else if ("void".equals(String.valueOf(conv.getTypeRef(useRawTypes)))) { throw new UnsupportedConversionException(mutatedType, "void type !"); //out.add(new EmptyDeclaration("SKIPPED:", v.formatComments("", true, true, false), v.toString())); } Function convDecl = new Function(); conv.annotateTypedType(convDecl, useRawTypes); convDecl.setType(Type.JavaMethod); convDecl.addModifiers(ModifierType.Public); if (conv.arrayLengths != null) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Length), "({" + StringUtils.implode(conv.arrayLengths, ", ") + "})")); } if (conv.bits != null) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), conv.bits)); } if (conv.byValue) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ByValue))); } for (Element e : toImportDetailsFrom) { convDecl.importDetails(e, false); } convDecl.importDetails(mutatedType, true); //convDecl.importDetails(javaType, true); // convDecl.importDetails(v, false); // convDecl.importDetails(vs, false); // convDecl.importDetails(valueType, false); // valueType.stripDetails(); convDecl.moveAllCommentsBefore(); convDecl.setName(ident(name)); if (!isGlobal) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Field), expr(fieldIndex))); } convDecl.setValueType(conv.getTypeRef(useRawTypes)); TypeRef javaType = convDecl.getValueType(); String pointerGetSetMethodSuffix = StringUtils.capitalize(javaType.toString()); Expression getGlobalPointerExpr = null; if (isGlobal) { getGlobalPointerExpr = methodCall(methodCall(methodCall(expr(typeRef(BridJ.class)), "getNativeLibrary", expr(callerLibrary)), "getSymbolPointer", expr(name)), "as", result.typeConverter.typeLiteral(javaType.clone())); } List<Declaration> out = new ArrayList<Declaration>(); boolean addedGetterOrSetter = false; if (conv.getExpr != null) { Function getter = convDecl.clone(); if (isGlobal) { getter.setBody(block( tryRethrow(new Statement.Return(cast(javaType.clone(), methodCall(getGlobalPointerExpr, "get")))))); } else { getter.setBody(block( new Statement.Return(conv.getExpr))); } out.add(getter); addedGetterOrSetter = true; } if (!conv.readOnly && conv.setExpr != null) { Function setter = convDecl.clone(); setter.setValueType(typeRef(holderName.clone()));//Void.TYPE)); setter.addArg(new Arg(name, javaType)); //setter.addModifiers(ModifierType.Native); if (isGlobal) { setter.setBody(block( tryRethrow(block( stat(methodCall(getGlobalPointerExpr, "set", varRef(name))), new Statement.Return(thisRef()))))); } else { setter.setBody(block( stat(conv.setExpr), new Statement.Return(thisRef()))); } out.add(setter); addedGetterOrSetter = true; if (result.config.scalaStructSetters) { setter = new Function(); setter.setType(Type.JavaMethod); setter.setName(ident(name + "_$eq")); setter.setValueType(javaType.clone()); setter.addArg(new Arg(name, javaType.clone())); setter.addModifiers(ModifierType.Public, ModifierType.Final); setter.setBody(block( stat(methodCall(name, varRef(name))), new Statement.Return(varRef(name)))); out.add(setter); } } if (!addedGetterOrSetter) { out.add(new EmptyDeclaration("Failed to convert value " + name + " of type " + mutatedType)); } return out; } @Override public boolean convertVariablesDeclaration(VariablesDeclaration v, Signatures signatures, DeclarationsHolder out, int[] iChild, boolean isGlobal, Identifier holderName, Identifier callerLibraryClass, String callerLibrary) { try { TypeRef valueType = v.getValueType(); for (Declarator vs : v.getDeclarators()) { if (vs.getDefaultValue() != null) { continue; } String name = vs.resolveName(); if (name == null || name.length() == 0) { name = "anonymous" + (nextAnonymousFieldId++); } TypeRef mutatedType = valueType; if (!(vs instanceof DirectDeclarator)) { mutatedType = (TypeRef) vs.mutateTypeKeepingParent(valueType); vs = new DirectDeclarator(vs.resolveName()); } //Declarator d = v.getDeclarators().get(0); List<Declaration> vds = convertVariablesDeclarationToBridJ(name, mutatedType, iChild, vs.getBits(), isGlobal, holderName, callerLibraryClass, callerLibrary, v, vs); if (vs.getBits() > 0) { for (Declaration vd : vds) { vd.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), expr(vs.getBits()))); } } for (Declaration vd : vds) { if (vd instanceof Function) { if (!signatures.addMethod((Function) vd)) { continue; } } vd.importDetails(mutatedType, true); vd.moveAllCommentsBefore(); if (!(mutatedType instanceof Primitive) && !result.config.noComments) { vd.addToCommentBefore("C type : " + mutatedType); } out.addDeclaration(vd); } //} } return true; } catch (Throwable e) { if (!(e instanceof UnsupportedConversionException)) { e.printStackTrace(); } // if (!result.config.limitComments) out.addDeclaration(new EmptyDeclaration(e.toString())); return false; } finally { iChild[0]++; } } int nextAnonymousFieldId; @Override protected void configureCallbackStruct(Struct callbackStruct) { callbackStruct.setType(Struct.Type.JavaClass); callbackStruct.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Abstract); } @Override protected Struct createFakePointerClass(Identifier fakePointer) { Struct ptClass = result.declarationsConverter.publicStaticClass(fakePointer, ident(TypedPointer.class), Struct.Type.JavaClass, null); String addressVarName = "address"; ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(long.class))).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName)))))); ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(org.bridj.Pointer.class))).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName)))))); return ptClass; } @Override protected void fillLibraryMapping(Result result, SourceFiles sourceFiles, DeclarationsHolder declarations, DeclarationsHolder implementations, String library, Identifier javaPackage, Expression nativeLibFieldExpr) throws IOException { super.fillLibraryMapping(result, sourceFiles, declarations, implementations, library, javaPackage, nativeLibFieldExpr); if (implementations instanceof ModifiableElement) { ModifiableElement minterf = (ModifiableElement) implementations; minterf.addAnnotation(new Annotation(org.bridj.ann.Library.class, expr(library))); minterf.addAnnotation(new Annotation(org.bridj.ann.Runtime.class, classLiteral(result.hasCPlusPlus ? CPPRuntime.class : CRuntime.class))); } } @Override public void generateLibraryFiles(SourceFiles sourceFiles, Result result, JNAeratorConfig config) throws IOException { for (String library : result.libraries) { if (library == null) { continue; // to handle code defined in macro-expanded expressions } Identifier javaPackage = result.javaPackageByLibrary.get(library); Identifier implementationsSimpleClassName = result.getLibraryClassSimpleName(library); Identifier declarationsSimpleClassName = result.getLibraryDeclarationsClassSimpleName(library); Identifier implementationsFullClassName = result.getLibraryClassFullName(library);//ident(javaPackage, libraryClassName); Identifier declarationsFullClassName = result.getLibraryDeclarationsClassFullName(library); //if (!result.objCClasses.isEmpty()) // out.println("import org.rococoa.ID;"); Struct implementations = new Struct(); implementations.setType(Struct.Type.JavaClass); implementations.addToCommentBefore("Wrapper for library <b>" + library + "</b>", result.declarationsConverter.getFileCommentContent(result.config.libraryProjectSources.get(library), null)); implementations.addModifiers(ModifierType.Public); implementations.setTag(implementationsSimpleClassName); implementations.addParent(ident(config.runtime.libraryClass, expr(typeRef(implementationsSimpleClassName)))); if (declarationsFullClassName != null) { implementations.addProtocol(declarationsFullClassName.clone()); } if (!config.noStaticInit) implementations.addDeclaration(newStaticInit()); implementations.setResolvedJavaIdentifier(implementationsFullClassName); Struct declarations; if (declarationsFullClassName != null) { declarations = new Struct(); declarations.setType(Struct.Type.JavaInterface); declarations.addToCommentBefore("Interface for library <b>" + library + "</b>", result.declarationsConverter.getFileCommentContent(result.config.libraryProjectSources.get(library), null)); declarations.addModifiers(ModifierType.Public); declarations.setTag(declarationsSimpleClassName.clone()); declarations.setResolvedJavaIdentifier(declarationsFullClassName); } else { declarations = implementations; } // String libFileOrDirArgName = "libraryFileOrDirectory"; // Function constr = new Function(Function.Type.JavaMethod, fullLibraryClassName.resolveLastSimpleIdentifier().clone(), null, new Arg(libFileOrDirArgName, typeRef(File.class))); // constr.addModifiers(ModifierType.Public); // constr.setBody(block(stat(methodCall("super", varRef(libFileOrDirArgName))))); // interf.addDeclaration(constr); // // constr = new Function(Function.Type.JavaMethod, fullLibraryClassName.resolveLastSimpleIdentifier().clone(), null); // constr.addModifiers(ModifierType.Public); // constr.addThrown(typeRef(FileNotFoundException.class)); // constr.setBody(block(stat(methodCall("super", classLiteral(typeRef(fullLibraryClassName.clone())))))); // interf.addDeclaration(constr); fillLibraryMapping(result, sourceFiles, declarations, implementations, library, javaPackage, varRef("this")); writeLibraryInterface(result, sourceFiles, declarations, library, javaPackage); if (declarations != implementations) { writeLibraryInterface(result, sourceFiles, implementations, library, javaPackage); } } } private Function newStaticInit() { Function f = new Function(Function.Type.StaticInit, null, null).setBody(block( stat(methodCall( expr(typeRef(BridJ.class)), Expression.MemberRefStyle.Dot, "register")))).addModifiers(ModifierType.Static); return f; } private void addParentNamespaceAnnotation(ModifiableElement dest, Identifier parentNamespace) { if (parentNamespace != null) { dest.addAnnotation(new Annotation(typeRef(org.bridj.ann.Namespace.class), expr(parentNamespace.toString()))); } } }
false
true
public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { if (e.isForwardDeclaration()) { return; } Identifier rawEnumName = getActualTaggedTypeName(e); Map<String, EnumItemResult> results = result.typeConverter.getEnumValuesAndCommentsByName(e, libraryClassName); boolean hasEnumClass = false; if (rawEnumName != null && rawEnumName.resolveLastSimpleIdentifier().getName() != null) { hasEnumClass = true; Identifier enumName = result.typeConverter.getValidJavaIdentifier(rawEnumName); if (!signatures.addClass(enumName)) { return; } signatures = new Signatures(); Enum en = new Enum(); if (result.config.forceNames || !rawEnumName.equals(enumName)) annotateActualName(en, rawEnumName); addParentNamespaceAnnotation(en, e.getParentNamespace()); if (!result.config.noComments) { en.importComments(e, "enum values", getFileCommentContent(e)); } en.setType(Enum.Type.Java); en.setTag(enumName.clone()); en.addModifiers(ModifierType.Public); out.addDeclaration(new TaggedTypeRefDeclaration(en)); Struct body = new Struct(); en.setBody(body); boolean hasValidItem = false; for (EnumItemResult er : results.values()) { if (er.errorElement != null) { out.addDeclaration(er.errorElement); continue; } String itemName = result.typeConverter.getValidJavaIdentifierString(ident(er.originalItem.getName())); Enum.EnumItem item = new Enum.EnumItem(itemName, er.convertedValue); en.addItem(item); hasValidItem = true; if (!result.config.noComments) { if (item != null) {// && hasEnumClass) { item.importComments(er.originalItem); } } } if (hasValidItem) { en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); String valueArgName = "value"; body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName)))))); body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)))).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( new Statement.Return( methodCall( methodCall( expr(typeRef(Collections.class)), MemberRefStyle.Dot, "singleton", thisRef()), MemberRefStyle.Dot, "iterator")))).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( new Statement.Return( methodCall( expr(typeRef(FlagSet.class)), MemberRefStyle.Dot, "fromValue", varRef(valueArgName), methodCall( "values"))))).addModifiers(ModifierType.Public, ModifierType.Static)); } } else { outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); } } void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { Convention.Style cc = null; if (originalFunction.hasModifier(ModifierType.__stdcall)) { cc = Convention.Style.StdCall; } else if (originalFunction.hasModifier(ModifierType.__fastcall)) { cc = Convention.Style.FastCall; } else if (originalFunction.hasModifier(ModifierType.__thiscall)) { cc = Convention.Style.ThisCall; } else if (originalFunction.hasModifier(ModifierType.__pascal)) { cc = Convention.Style.Pascal; } if (cc != null) { target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); } } @Override public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder declarations, DeclarationsHolder implementations, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { assert implementations != null; boolean extractingDeclarations = declarations != null && implementations != declarations; Element parent = function.getParentElement(); MemberVisibility visibility = function.getVisibility(); boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); boolean isInStruct = parent instanceof Struct; if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) { return; } boolean isStatic = function.hasModifier(ModifierType.Static); boolean isConstructor = iConstructor != -1; Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); if (result.config.synchronizedMethods && !isCallback) { nativeMethod.addModifiers(ModifierType.Synchronized); } addCallingConventionAnnotation(function, nativeMethod); if (function.getName() != null && !functionName.toString().equals(function.getName().toString()) && !isCallback) { TypeRef mgc = result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name); if (mgc != null) { nativeMethod.addAnnotation(new Annotation(mgc, "(\"" + function.getName() + "\")")); } } Function rawMethod = nativeMethod.clone(); //Map<String, NL4JConversion> argTypes = new LinkedHashMap<String, NL4JConversion>(); boolean isObjectiveC = function.getType() == Type.ObjCMethod; int iArg = 1; Set<String> argNames = new TreeSet<String>(); List<Expression> superConstructorArgs = null; if (isConstructor) { superConstructorArgs = new ArrayList<Expression>(); superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); superConstructorArgs.add(expr(iConstructor)); } Identifier varArgType = null; String varArgName = null; NL4JConversion returnType = null; List<NL4JConversion> paramTypes = new ArrayList<NL4JConversion>(); List<String> paramNames = new ArrayList<String>(); if (!isConstructor) { returnType = ((BridJTypeConversion) result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); } for (Arg arg : function.getArgs()) { String paramName; if (arg.isVarArg()) { assert arg.getValueType() == null; paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); varArgType = ident(isObjectiveC ? NSObject.class : Object.class); } else { paramName = chooseJavaArgName(arg.getName(), iArg, argNames); paramTypes.add(((BridJTypeConversion) result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); } paramNames.add(paramName); if (isConstructor) { superConstructorArgs.add(varRef(paramName)); } iArg++; } fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); List<Declaration> extractibleDecls = new ArrayList<Declaration>(); Block convertedBody = null; if (isConstructor) { convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); } else if (result.config.convertBodies && function.getBody() != null) { try { Pair<Element, List<Declaration>> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); convertedBody = (Block) bodyAndExtraDeclarations.getFirst(); for (Declaration d : bodyAndExtraDeclarations.getSecond()) { implementations.addDeclaration(d); // extractibleDecls.add(d); } } catch (Exception ex) { ex.printStackTrace(System.out); nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); } } if (!result.config.noComments) { nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); } boolean generateStaticMethod = (isStatic || !isCallback && !isInStruct) && (declarations == null || implementations == declarations); nativeMethod.addModifiers( isProtected && !extractingDeclarations && !result.config.publicRawBindings ? ModifierType.Protected : ModifierType.Public, generateStaticMethod ? ModifierType.Static : null); boolean isOptional = isOptionalFunction(function.getName() + ""); implementations.addDeclaration(nativeMethod); boolean forwardedToRaw = false; if (convertedBody == null) { if (result.config.genRawBindings) {// && !isCallback) { // Function rawMethod = nativeMethod.clone(); rawMethod.setArgs(Collections.EMPTY_LIST); fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); rawMethod.addModifiers( extractingDeclarations || isCallback || result.config.publicRawBindings ? ModifierType.Public : ModifierType.Protected, isCallback ? ModifierType.Abstract : ModifierType.Native); if (generateStaticMethod) { rawMethod.addModifiers(ModifierType.Static); } if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { implementations.addDeclaration(rawMethod); extractibleDecls.add(rawMethod); if (isOptional && !isCallback) { rawMethod.addAnnotation(new Annotation(typeRef(Optional.class))); } List<Expression> followedArgs = new ArrayList<Expression>(); for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); Expression followedArg; switch (paramType.type) { case Pointer: followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); break; case Enum: followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); break; // case NativeSize: // case NativeLong: // followedArg = methodCall(varRef(paramName), "longValue"); // break; default: followedArg = varRef(paramName); break; } followedArgs.add(followedArg); } if (varArgType != null) { followedArgs.add(varRef(varArgName)); } Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); if (isVoid) { nativeMethod.setBody(block(stat(followedCall))); } else { switch (returnType.type) { case Pointer: if (returnType.isTypedPointer) { followedCall = new New(nativeMethod.getValueType(), followedCall); } else { Expression ptrExpr = expr(typeRef(org.bridj.Pointer.class)); Expression targetTypeExpr = result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType())); if (targetTypeExpr == null || (returnType.targetTypeConversion != null && returnType.targetTypeConversion.type == ConvType.Void)) { followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall); } else { followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, targetTypeExpr); } } break; case Enum: followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); break; case NativeLong: case NativeSize: if (!rawMethod.getValueType().toString().equals("long")) { followedCall = new New(nativeMethod.getValueType().clone(), followedCall); } default: break; } nativeMethod.setBody(block(new Statement.Return(followedCall))); } forwardedToRaw = true; } } if (!forwardedToRaw) { nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); if (isOptional && !isCallback) { nativeMethod.addAnnotation(new Annotation(typeRef(Optional.class))); } } else if (isCallback) { nativeMethod.addModifiers(ModifierType.Final); } } else { nativeMethod.setBody(convertedBody); } if (!forwardedToRaw && convertedBody == null) { extractibleDecls.add(nativeMethod); } for (Declaration d : extractibleDecls) { if (extractingDeclarations) { if (d instanceof Function) { Function m = (Function)d.clone(); m.setBody(null); m.removeModifiers(ModifierType.Abstract, ModifierType.Final, ModifierType.Static, ModifierType.Native, ModifierType.Public, ModifierType.Protected); declarations.addDeclaration(m); // d.addAnnotation(new Annotation(typeRef(Override.class))); } } } } private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List<NL4JConversion> paramTypes, List<String> paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); } if (varArgType != null) { nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); } if (returnType != null) { returnType.annotateTypedType(nativeMethod, useRawTypes); nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); } String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); if (!javaMethodName.equals(functionName)) { nativeMethod.setName(javaMethodName); } if (!isCallback && !javaMethodName.equals(functionName) || returnType != null && result.config.forceNames) { annotateActualName(nativeMethod, functionName); } } @Override public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { Identifier structName = getActualTaggedTypeName(struct); if (structName == null) { return null; } //if (structName.toString().contains("MonoObject")) // structName.toString(); if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) { return null; } if (!signatures.addClass(structName)) { return null; } boolean isUnion = struct.getType() == Struct.Type.CUnion; boolean inheritsFromStruct = false; Identifier baseClass = null; int parentFieldsCount = 0; List<String> preComments = new ArrayList<String>(); for (SimpleTypeRef parentName : struct.getParents()) { Struct parent = result.structsByName.get(parentName.getName()); if (parent == null) { // TODO report error continue; } try { parentFieldsCount += countFieldsInStruct(parent); } catch (UnsupportedConversionException ex) { preComments.add("Error: " + ex); } baseClass = result.typeConverter.getTaggedTypeIdentifierInJava(parent); if (baseClass != null) { inheritsFromStruct = true; break; // TODO handle multiple and virtual inheritage } } boolean hasMemberFunctions = false; for (Declaration d : struct.getDeclarations()) { if (d instanceof Function) { hasMemberFunctions = true; break; } } Constant uuid = (Constant) struct.getModifierValue(ModifierType.UUID); if (baseClass == null) { switch (struct.getType()) { case CStruct: case CUnion: if (!hasMemberFunctions) { baseClass = ident(StructObject.class); break; } case CPPClass: baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); result.hasCPlusPlus = true; break; default: throw new UnsupportedOperationException(); } } Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); if (!result.config.noStaticInit) structJavaClass.addDeclaration(newStaticInit()); //if (result.config.microsoftCOM) { if (uuid != null) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); } if (result.config.forceNames) annotateActualName(structJavaClass, structName); addParentNamespaceAnnotation(structJavaClass, struct.getParentNamespace()); structJavaClass.addToCommentBefore(preComments); //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); final int iChild[] = new int[]{parentFieldsCount}; //cl.addDeclaration(new EmptyDeclaration()) Signatures childSignatures = new Signatures(); /*if (isVirtual(struct) && !onlyFields) { String vptrName = DEFAULT_VPTR_NAME; VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); vptr.addModifiers(ModifierType.Public); structJavaClass.addDeclaration(vptr); childSignatures.variablesSignatures.add(vptrName); // TODO add vptr grabber to constructor ! }*/ // private static StructIO<MyStruct> io = StructIO.getInstance(MyStruct.class); if (isUnion) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); } int iVirtual = 0, iConstructor = 0; //List<Declaration> children = new ArrayList<Declaration>(); boolean succeeded = true; for (Declaration d : struct.getDeclarations()) { //if (isUnion) // iChild[0] = 0; if (d instanceof VariablesDeclaration) { succeeded = convertVariablesDeclaration((VariablesDeclaration) d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary) && succeeded; } else if (!onlyFields) { if (d instanceof TaggedTypeRefDeclaration) { TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); if (tr instanceof Struct) { outputConvertedStruct((Struct) tr, childSignatures, structJavaClass, callerLibrary, false); } else if (tr instanceof Enum) { convertEnum((Enum) tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (d instanceof TypeDef) { TypeDef td = (TypeDef) d; TypeRef tr = td.getValueType(); if (tr instanceof Struct) { outputConvertedStruct((Struct) tr, childSignatures, structJavaClass, callerLibrary, false); } else { FunctionSignature fs = null; if (tr instanceof FunctionSignature) { fs = (FunctionSignature) tr; } else if (tr instanceof TypeRef.Pointer) { TypeRef target = ((TypeRef.Pointer) tr).getTarget(); if (target instanceof FunctionSignature) { fs = (FunctionSignature) target; } } if (fs != null) { convertCallback(fs, childSignatures, structJavaClass); } } } else if (result.config.genCPlusPlus && d instanceof Function) { Function f = (Function) d; boolean isVirtual = f.hasModifier(ModifierType.Virtual); boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); if (isConstructor && f.getArgs().isEmpty()) { continue; // default constructor was already generated } String library = result.getLibrary(struct); if (library == null) { continue; } List<Declaration> decls = new ArrayList<Declaration>(); DeclarationsHolder out = new ListWrapper(decls); convertFunction(f, childSignatures, false, out, out, callerLibraryClass, isConstructor ? iConstructor : -1); for (Declaration md : decls) { if (!(md instanceof Function)) { continue; } Function method = (Function) md; boolean commentOut = false; if (isVirtual) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); } else if (method.getValueType() == null) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); isConstructor = true; } if (method.getName().toString().equals("operator")) { commentOut = true; } if (commentOut) { structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); } else { structJavaClass.addDeclaration(method); } } if (isVirtual) { iVirtual++; } if (isConstructor) { iConstructor++; } } } } if (succeeded) { Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(defaultConstructor)) { structJavaClass.addDeclaration(defaultConstructor); } String ptrName = "pointer"; Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(castConstructor)) { structJavaClass.addDeclaration(castConstructor); } } else { structJavaClass.addModifiers(ModifierType.Abstract); } return structJavaClass; } Map<Identifier, Boolean> structsVirtuality = new HashMap<Identifier, Boolean>(); public boolean isVirtual(Struct struct) { Identifier name = getActualTaggedTypeName(struct); Boolean bVirtual = structsVirtuality.get(name); if (bVirtual == null) { boolean hasVirtualParent = false, hasVirtualMembers = false; for (SimpleTypeRef parentName : struct.getParents()) { Struct parentStruct = result.structsByName.get(parentName.getName()); if (parentStruct == null) { if (result.config.verbose) { System.out.println("Failed to resolve parent '" + parentName + "' for struct '" + name + "'"); } continue; } if (isVirtual(parentStruct)) { hasVirtualParent = true; break; } } for (Declaration mb : struct.getDeclarations()) { if (mb.hasModifier(ModifierType.Virtual)) { hasVirtualMembers = true; break; } } bVirtual = hasVirtualMembers && !hasVirtualParent; structsVirtuality.put(name, bVirtual); } return bVirtual; } protected String ioVarName = "io", ioStaticVarName = "IO"; public List<Declaration> convertVariablesDeclarationToBridJ(String name, TypeRef mutatedType, int[] iChild, int bits, boolean isGlobal, Identifier holderName, Identifier callerLibraryName, String callerLibrary, Element... toImportDetailsFrom) throws UnsupportedConversionException { name = result.typeConverter.getValidJavaArgumentName(ident(name)).toString(); //convertVariablesDeclaration(name, mutatedType, out, iChild, callerLibraryName); final boolean useRawTypes = false; //Expression initVal = null; int fieldIndex = iChild[0]; //convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structPeerExpr, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { NL4JConversion conv = ((BridJTypeConversion) result.typeConverter).convertTypeToNL4J( mutatedType, callerLibraryName, thisField("io"), varRef(name), fieldIndex, bits); if (conv == null) { throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java"); } else if (conv.isUndefined) { throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java (undefined type)"); } else if ("void".equals(String.valueOf(conv.getTypeRef(useRawTypes)))) { throw new UnsupportedConversionException(mutatedType, "void type !"); //out.add(new EmptyDeclaration("SKIPPED:", v.formatComments("", true, true, false), v.toString())); } Function convDecl = new Function(); conv.annotateTypedType(convDecl, useRawTypes); convDecl.setType(Type.JavaMethod); convDecl.addModifiers(ModifierType.Public); if (conv.arrayLengths != null) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Length), "({" + StringUtils.implode(conv.arrayLengths, ", ") + "})")); } if (conv.bits != null) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), conv.bits)); } if (conv.byValue) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ByValue))); } for (Element e : toImportDetailsFrom) { convDecl.importDetails(e, false); } convDecl.importDetails(mutatedType, true); //convDecl.importDetails(javaType, true); // convDecl.importDetails(v, false); // convDecl.importDetails(vs, false); // convDecl.importDetails(valueType, false); // valueType.stripDetails(); convDecl.moveAllCommentsBefore(); convDecl.setName(ident(name)); if (!isGlobal) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Field), expr(fieldIndex))); } convDecl.setValueType(conv.getTypeRef(useRawTypes)); TypeRef javaType = convDecl.getValueType(); String pointerGetSetMethodSuffix = StringUtils.capitalize(javaType.toString()); Expression getGlobalPointerExpr = null; if (isGlobal) { getGlobalPointerExpr = methodCall(methodCall(methodCall(expr(typeRef(BridJ.class)), "getNativeLibrary", expr(callerLibrary)), "getSymbolPointer", expr(name)), "as", result.typeConverter.typeLiteral(javaType.clone())); } List<Declaration> out = new ArrayList<Declaration>(); boolean addedGetterOrSetter = false; if (conv.getExpr != null) { Function getter = convDecl.clone(); if (isGlobal) { getter.setBody(block( tryRethrow(new Statement.Return(cast(javaType.clone(), methodCall(getGlobalPointerExpr, "get")))))); } else { getter.setBody(block( new Statement.Return(conv.getExpr))); } out.add(getter); addedGetterOrSetter = true; } if (!conv.readOnly && conv.setExpr != null) { Function setter = convDecl.clone(); setter.setValueType(typeRef(holderName.clone()));//Void.TYPE)); setter.addArg(new Arg(name, javaType)); //setter.addModifiers(ModifierType.Native); if (isGlobal) { setter.setBody(block( tryRethrow(block( stat(methodCall(getGlobalPointerExpr, "set", varRef(name))), new Statement.Return(thisRef()))))); } else { setter.setBody(block( stat(conv.setExpr), new Statement.Return(thisRef()))); } out.add(setter); addedGetterOrSetter = true; if (result.config.scalaStructSetters) { setter = new Function(); setter.setType(Type.JavaMethod); setter.setName(ident(name + "_$eq")); setter.setValueType(javaType.clone()); setter.addArg(new Arg(name, javaType.clone())); setter.addModifiers(ModifierType.Public, ModifierType.Final); setter.setBody(block( stat(methodCall(name, varRef(name))), new Statement.Return(varRef(name)))); out.add(setter); } } if (!addedGetterOrSetter) { out.add(new EmptyDeclaration("Failed to convert value " + name + " of type " + mutatedType)); } return out; } @Override public boolean convertVariablesDeclaration(VariablesDeclaration v, Signatures signatures, DeclarationsHolder out, int[] iChild, boolean isGlobal, Identifier holderName, Identifier callerLibraryClass, String callerLibrary) { try { TypeRef valueType = v.getValueType(); for (Declarator vs : v.getDeclarators()) { if (vs.getDefaultValue() != null) { continue; } String name = vs.resolveName(); if (name == null || name.length() == 0) { name = "anonymous" + (nextAnonymousFieldId++); } TypeRef mutatedType = valueType; if (!(vs instanceof DirectDeclarator)) { mutatedType = (TypeRef) vs.mutateTypeKeepingParent(valueType); vs = new DirectDeclarator(vs.resolveName()); } //Declarator d = v.getDeclarators().get(0); List<Declaration> vds = convertVariablesDeclarationToBridJ(name, mutatedType, iChild, vs.getBits(), isGlobal, holderName, callerLibraryClass, callerLibrary, v, vs); if (vs.getBits() > 0) { for (Declaration vd : vds) { vd.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), expr(vs.getBits()))); } } for (Declaration vd : vds) { if (vd instanceof Function) { if (!signatures.addMethod((Function) vd)) { continue; } } vd.importDetails(mutatedType, true); vd.moveAllCommentsBefore(); if (!(mutatedType instanceof Primitive) && !result.config.noComments) { vd.addToCommentBefore("C type : " + mutatedType); } out.addDeclaration(vd); } //} } return true; } catch (Throwable e) { if (!(e instanceof UnsupportedConversionException)) { e.printStackTrace(); } // if (!result.config.limitComments) out.addDeclaration(new EmptyDeclaration(e.toString())); return false; } finally { iChild[0]++; } } int nextAnonymousFieldId; @Override protected void configureCallbackStruct(Struct callbackStruct) { callbackStruct.setType(Struct.Type.JavaClass); callbackStruct.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Abstract); } @Override protected Struct createFakePointerClass(Identifier fakePointer) { Struct ptClass = result.declarationsConverter.publicStaticClass(fakePointer, ident(TypedPointer.class), Struct.Type.JavaClass, null); String addressVarName = "address"; ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(long.class))).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName)))))); ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(org.bridj.Pointer.class))).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName)))))); return ptClass; } @Override protected void fillLibraryMapping(Result result, SourceFiles sourceFiles, DeclarationsHolder declarations, DeclarationsHolder implementations, String library, Identifier javaPackage, Expression nativeLibFieldExpr) throws IOException { super.fillLibraryMapping(result, sourceFiles, declarations, implementations, library, javaPackage, nativeLibFieldExpr); if (implementations instanceof ModifiableElement) { ModifiableElement minterf = (ModifiableElement) implementations; minterf.addAnnotation(new Annotation(org.bridj.ann.Library.class, expr(library))); minterf.addAnnotation(new Annotation(org.bridj.ann.Runtime.class, classLiteral(result.hasCPlusPlus ? CPPRuntime.class : CRuntime.class))); } } @Override public void generateLibraryFiles(SourceFiles sourceFiles, Result result, JNAeratorConfig config) throws IOException { for (String library : result.libraries) { if (library == null) { continue; // to handle code defined in macro-expanded expressions } Identifier javaPackage = result.javaPackageByLibrary.get(library); Identifier implementationsSimpleClassName = result.getLibraryClassSimpleName(library); Identifier declarationsSimpleClassName = result.getLibraryDeclarationsClassSimpleName(library); Identifier implementationsFullClassName = result.getLibraryClassFullName(library);//ident(javaPackage, libraryClassName); Identifier declarationsFullClassName = result.getLibraryDeclarationsClassFullName(library); //if (!result.objCClasses.isEmpty()) // out.println("import org.rococoa.ID;"); Struct implementations = new Struct(); implementations.setType(Struct.Type.JavaClass); implementations.addToCommentBefore("Wrapper for library <b>" + library + "</b>", result.declarationsConverter.getFileCommentContent(result.config.libraryProjectSources.get(library), null)); implementations.addModifiers(ModifierType.Public); implementations.setTag(implementationsSimpleClassName); implementations.addParent(ident(config.runtime.libraryClass, expr(typeRef(implementationsSimpleClassName)))); if (declarationsFullClassName != null) { implementations.addProtocol(declarationsFullClassName.clone()); } if (!config.noStaticInit) implementations.addDeclaration(newStaticInit()); implementations.setResolvedJavaIdentifier(implementationsFullClassName); Struct declarations; if (declarationsFullClassName != null) { declarations = new Struct(); declarations.setType(Struct.Type.JavaInterface); declarations.addToCommentBefore("Interface for library <b>" + library + "</b>", result.declarationsConverter.getFileCommentContent(result.config.libraryProjectSources.get(library), null)); declarations.addModifiers(ModifierType.Public); declarations.setTag(declarationsSimpleClassName.clone()); declarations.setResolvedJavaIdentifier(declarationsFullClassName); } else { declarations = implementations; } // String libFileOrDirArgName = "libraryFileOrDirectory"; // Function constr = new Function(Function.Type.JavaMethod, fullLibraryClassName.resolveLastSimpleIdentifier().clone(), null, new Arg(libFileOrDirArgName, typeRef(File.class))); // constr.addModifiers(ModifierType.Public); // constr.setBody(block(stat(methodCall("super", varRef(libFileOrDirArgName))))); // interf.addDeclaration(constr); // // constr = new Function(Function.Type.JavaMethod, fullLibraryClassName.resolveLastSimpleIdentifier().clone(), null); // constr.addModifiers(ModifierType.Public); // constr.addThrown(typeRef(FileNotFoundException.class)); // constr.setBody(block(stat(methodCall("super", classLiteral(typeRef(fullLibraryClassName.clone())))))); // interf.addDeclaration(constr); fillLibraryMapping(result, sourceFiles, declarations, implementations, library, javaPackage, varRef("this")); writeLibraryInterface(result, sourceFiles, declarations, library, javaPackage); if (declarations != implementations) { writeLibraryInterface(result, sourceFiles, implementations, library, javaPackage); } } } private Function newStaticInit() { Function f = new Function(Function.Type.StaticInit, null, null).setBody(block( stat(methodCall( expr(typeRef(BridJ.class)), Expression.MemberRefStyle.Dot, "register")))).addModifiers(ModifierType.Static); return f; } private void addParentNamespaceAnnotation(ModifiableElement dest, Identifier parentNamespace) { if (parentNamespace != null) { dest.addAnnotation(new Annotation(typeRef(org.bridj.ann.Namespace.class), expr(parentNamespace.toString()))); } } }
public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { if (e.isForwardDeclaration()) { return; } Identifier rawEnumName = getActualTaggedTypeName(e); Map<String, EnumItemResult> results = result.typeConverter.getEnumValuesAndCommentsByName(e, libraryClassName); boolean hasEnumClass = false; if (rawEnumName != null && rawEnumName.resolveLastSimpleIdentifier().getName() != null) { hasEnumClass = true; Identifier enumName = result.typeConverter.getValidJavaIdentifier(rawEnumName); if (!signatures.addClass(enumName)) { return; } signatures = new Signatures(); Enum en = new Enum(); if (result.config.forceNames || !rawEnumName.equals(enumName)) annotateActualName(en, rawEnumName); addParentNamespaceAnnotation(en, e.getParentNamespace()); if (!result.config.noComments) { en.importComments(e, "enum values", getFileCommentContent(e)); } en.setType(Enum.Type.Java); en.setTag(enumName.clone()); en.addModifiers(ModifierType.Public); out.addDeclaration(new TaggedTypeRefDeclaration(en)); Struct body = new Struct(); en.setBody(body); boolean hasValidItem = false; for (EnumItemResult er : results.values()) { if (er.errorElement != null) { out.addDeclaration(er.errorElement); continue; } String itemName = result.typeConverter.getValidJavaIdentifierString(ident(er.originalItem.getName())); Enum.EnumItem item = new Enum.EnumItem(itemName, er.convertedValue); en.addItem(item); hasValidItem = true; if (!result.config.noComments) { if (item != null) {// && hasEnumClass) { item.importComments(er.originalItem); } } } if (hasValidItem) { en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); String valueArgName = "value"; body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName)))))); body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)))).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( new Statement.Return( methodCall( methodCall( expr(typeRef(Collections.class)), MemberRefStyle.Dot, "singleton", thisRef()), MemberRefStyle.Dot, "iterator")))).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( new Statement.Return( methodCall( expr(typeRef(FlagSet.class)), MemberRefStyle.Dot, "fromValue", varRef(valueArgName), methodCall( "values"))))).addModifiers(ModifierType.Public, ModifierType.Static)); } } else { outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); } } void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { Convention.Style cc = null; if (originalFunction.hasModifier(ModifierType.__stdcall)) { cc = Convention.Style.StdCall; } else if (originalFunction.hasModifier(ModifierType.__fastcall)) { cc = Convention.Style.FastCall; } else if (originalFunction.hasModifier(ModifierType.__thiscall)) { cc = Convention.Style.ThisCall; } else if (originalFunction.hasModifier(ModifierType.__pascal)) { cc = Convention.Style.Pascal; } if (cc != null) { target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); } } @Override public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder declarations, DeclarationsHolder implementations, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { assert implementations != null; boolean extractingDeclarations = declarations != null && implementations != declarations; Element parent = function.getParentElement(); MemberVisibility visibility = function.getVisibility(); boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); boolean isInStruct = parent instanceof Struct; if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) { return; } boolean isStatic = function.hasModifier(ModifierType.Static); boolean isConstructor = iConstructor != -1; Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); if (result.config.synchronizedMethods && !isCallback) { nativeMethod.addModifiers(ModifierType.Synchronized); } addCallingConventionAnnotation(function, nativeMethod); if (function.getName() != null && !isCallback && (!functionName.toString().equals(function.getName().toString()) || result.config.forceNames)) { annotateActualName(nativeMethod, function.getName()); } Function rawMethod = nativeMethod.clone(); //Map<String, NL4JConversion> argTypes = new LinkedHashMap<String, NL4JConversion>(); boolean isObjectiveC = function.getType() == Type.ObjCMethod; int iArg = 1; Set<String> argNames = new TreeSet<String>(); List<Expression> superConstructorArgs = null; if (isConstructor) { superConstructorArgs = new ArrayList<Expression>(); superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); superConstructorArgs.add(expr(iConstructor)); } Identifier varArgType = null; String varArgName = null; NL4JConversion returnType = null; List<NL4JConversion> paramTypes = new ArrayList<NL4JConversion>(); List<String> paramNames = new ArrayList<String>(); if (!isConstructor) { returnType = ((BridJTypeConversion) result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); } for (Arg arg : function.getArgs()) { String paramName; if (arg.isVarArg()) { assert arg.getValueType() == null; paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); varArgType = ident(isObjectiveC ? NSObject.class : Object.class); } else { paramName = chooseJavaArgName(arg.getName(), iArg, argNames); paramTypes.add(((BridJTypeConversion) result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); } paramNames.add(paramName); if (isConstructor) { superConstructorArgs.add(varRef(paramName)); } iArg++; } fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); List<Declaration> extractibleDecls = new ArrayList<Declaration>(); Block convertedBody = null; if (isConstructor) { convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); } else if (result.config.convertBodies && function.getBody() != null) { try { Pair<Element, List<Declaration>> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); convertedBody = (Block) bodyAndExtraDeclarations.getFirst(); for (Declaration d : bodyAndExtraDeclarations.getSecond()) { implementations.addDeclaration(d); // extractibleDecls.add(d); } } catch (Exception ex) { ex.printStackTrace(System.out); nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); } } if (!result.config.noComments) { nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); } boolean generateStaticMethod = (isStatic || !isCallback && !isInStruct) && (declarations == null || implementations == declarations); nativeMethod.addModifiers( isProtected && !extractingDeclarations && !result.config.publicRawBindings ? ModifierType.Protected : ModifierType.Public, generateStaticMethod ? ModifierType.Static : null); boolean isOptional = isOptionalFunction(function.getName() + ""); implementations.addDeclaration(nativeMethod); boolean forwardedToRaw = false; if (convertedBody == null) { if (result.config.genRawBindings) {// && !isCallback) { // Function rawMethod = nativeMethod.clone(); rawMethod.setArgs(Collections.EMPTY_LIST); fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); rawMethod.addModifiers( extractingDeclarations || isCallback || result.config.publicRawBindings ? ModifierType.Public : ModifierType.Protected, isCallback ? ModifierType.Abstract : ModifierType.Native); if (generateStaticMethod) { rawMethod.addModifiers(ModifierType.Static); } if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { implementations.addDeclaration(rawMethod); extractibleDecls.add(rawMethod); if (isOptional && !isCallback) { rawMethod.addAnnotation(new Annotation(typeRef(Optional.class))); } List<Expression> followedArgs = new ArrayList<Expression>(); for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); Expression followedArg; switch (paramType.type) { case Pointer: followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); break; case Enum: followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); break; // case NativeSize: // case NativeLong: // followedArg = methodCall(varRef(paramName), "longValue"); // break; default: followedArg = varRef(paramName); break; } followedArgs.add(followedArg); } if (varArgType != null) { followedArgs.add(varRef(varArgName)); } Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); if (isVoid) { nativeMethod.setBody(block(stat(followedCall))); } else { switch (returnType.type) { case Pointer: if (returnType.isTypedPointer) { followedCall = new New(nativeMethod.getValueType(), followedCall); } else { Expression ptrExpr = expr(typeRef(org.bridj.Pointer.class)); Expression targetTypeExpr = result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType())); if (targetTypeExpr == null || (returnType.targetTypeConversion != null && returnType.targetTypeConversion.type == ConvType.Void)) { followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall); } else { followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, targetTypeExpr); } } break; case Enum: followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); break; case NativeLong: case NativeSize: if (!rawMethod.getValueType().toString().equals("long")) { followedCall = new New(nativeMethod.getValueType().clone(), followedCall); } default: break; } nativeMethod.setBody(block(new Statement.Return(followedCall))); } forwardedToRaw = true; } } if (!forwardedToRaw) { nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); if (isOptional && !isCallback) { nativeMethod.addAnnotation(new Annotation(typeRef(Optional.class))); } } else if (isCallback) { nativeMethod.addModifiers(ModifierType.Final); } } else { nativeMethod.setBody(convertedBody); } if (!forwardedToRaw && convertedBody == null) { extractibleDecls.add(nativeMethod); } for (Declaration d : extractibleDecls) { if (extractingDeclarations) { if (d instanceof Function) { Function m = (Function)d.clone(); m.setBody(null); m.removeModifiers(ModifierType.Abstract, ModifierType.Final, ModifierType.Static, ModifierType.Native, ModifierType.Public, ModifierType.Protected); declarations.addDeclaration(m); // d.addAnnotation(new Annotation(typeRef(Override.class))); } } } } private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List<NL4JConversion> paramTypes, List<String> paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); } if (varArgType != null) { nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); } if (returnType != null) { returnType.annotateTypedType(nativeMethod, useRawTypes); nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); } String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); if (!javaMethodName.equals(functionName)) { nativeMethod.setName(javaMethodName); } } @Override public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { Identifier structName = getActualTaggedTypeName(struct); if (structName == null) { return null; } //if (structName.toString().contains("MonoObject")) // structName.toString(); if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) { return null; } if (!signatures.addClass(structName)) { return null; } boolean isUnion = struct.getType() == Struct.Type.CUnion; boolean inheritsFromStruct = false; Identifier baseClass = null; int parentFieldsCount = 0; List<String> preComments = new ArrayList<String>(); for (SimpleTypeRef parentName : struct.getParents()) { Struct parent = result.structsByName.get(parentName.getName()); if (parent == null) { // TODO report error continue; } try { parentFieldsCount += countFieldsInStruct(parent); } catch (UnsupportedConversionException ex) { preComments.add("Error: " + ex); } baseClass = result.typeConverter.getTaggedTypeIdentifierInJava(parent); if (baseClass != null) { inheritsFromStruct = true; break; // TODO handle multiple and virtual inheritage } } boolean hasMemberFunctions = false; for (Declaration d : struct.getDeclarations()) { if (d instanceof Function) { hasMemberFunctions = true; break; } } Constant uuid = (Constant) struct.getModifierValue(ModifierType.UUID); if (baseClass == null) { switch (struct.getType()) { case CStruct: case CUnion: if (!hasMemberFunctions) { baseClass = ident(StructObject.class); break; } case CPPClass: baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); result.hasCPlusPlus = true; break; default: throw new UnsupportedOperationException(); } } Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); if (!result.config.noStaticInit) structJavaClass.addDeclaration(newStaticInit()); //if (result.config.microsoftCOM) { if (uuid != null) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); } if (result.config.forceNames) annotateActualName(structJavaClass, structName); addParentNamespaceAnnotation(structJavaClass, struct.getParentNamespace()); structJavaClass.addToCommentBefore(preComments); //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); final int iChild[] = new int[]{parentFieldsCount}; //cl.addDeclaration(new EmptyDeclaration()) Signatures childSignatures = new Signatures(); /*if (isVirtual(struct) && !onlyFields) { String vptrName = DEFAULT_VPTR_NAME; VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); vptr.addModifiers(ModifierType.Public); structJavaClass.addDeclaration(vptr); childSignatures.variablesSignatures.add(vptrName); // TODO add vptr grabber to constructor ! }*/ // private static StructIO<MyStruct> io = StructIO.getInstance(MyStruct.class); if (isUnion) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); } int iVirtual = 0, iConstructor = 0; //List<Declaration> children = new ArrayList<Declaration>(); boolean succeeded = true; for (Declaration d : struct.getDeclarations()) { //if (isUnion) // iChild[0] = 0; if (d instanceof VariablesDeclaration) { succeeded = convertVariablesDeclaration((VariablesDeclaration) d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary) && succeeded; } else if (!onlyFields) { if (d instanceof TaggedTypeRefDeclaration) { TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); if (tr instanceof Struct) { outputConvertedStruct((Struct) tr, childSignatures, structJavaClass, callerLibrary, false); } else if (tr instanceof Enum) { convertEnum((Enum) tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (d instanceof TypeDef) { TypeDef td = (TypeDef) d; TypeRef tr = td.getValueType(); if (tr instanceof Struct) { outputConvertedStruct((Struct) tr, childSignatures, structJavaClass, callerLibrary, false); } else { FunctionSignature fs = null; if (tr instanceof FunctionSignature) { fs = (FunctionSignature) tr; } else if (tr instanceof TypeRef.Pointer) { TypeRef target = ((TypeRef.Pointer) tr).getTarget(); if (target instanceof FunctionSignature) { fs = (FunctionSignature) target; } } if (fs != null) { convertCallback(fs, childSignatures, structJavaClass); } } } else if (result.config.genCPlusPlus && d instanceof Function) { Function f = (Function) d; boolean isVirtual = f.hasModifier(ModifierType.Virtual); boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); if (isConstructor && f.getArgs().isEmpty()) { continue; // default constructor was already generated } String library = result.getLibrary(struct); if (library == null) { continue; } List<Declaration> decls = new ArrayList<Declaration>(); DeclarationsHolder out = new ListWrapper(decls); convertFunction(f, childSignatures, false, out, out, callerLibraryClass, isConstructor ? iConstructor : -1); for (Declaration md : decls) { if (!(md instanceof Function)) { continue; } Function method = (Function) md; boolean commentOut = false; if (isVirtual) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); } else if (method.getValueType() == null) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); isConstructor = true; } if (method.getName().toString().equals("operator")) { commentOut = true; } if (commentOut) { structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); } else { structJavaClass.addDeclaration(method); } } if (isVirtual) { iVirtual++; } if (isConstructor) { iConstructor++; } } } } if (succeeded) { Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(defaultConstructor)) { structJavaClass.addDeclaration(defaultConstructor); } String ptrName = "pointer"; Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(castConstructor)) { structJavaClass.addDeclaration(castConstructor); } } else { structJavaClass.addModifiers(ModifierType.Abstract); } return structJavaClass; } Map<Identifier, Boolean> structsVirtuality = new HashMap<Identifier, Boolean>(); public boolean isVirtual(Struct struct) { Identifier name = getActualTaggedTypeName(struct); Boolean bVirtual = structsVirtuality.get(name); if (bVirtual == null) { boolean hasVirtualParent = false, hasVirtualMembers = false; for (SimpleTypeRef parentName : struct.getParents()) { Struct parentStruct = result.structsByName.get(parentName.getName()); if (parentStruct == null) { if (result.config.verbose) { System.out.println("Failed to resolve parent '" + parentName + "' for struct '" + name + "'"); } continue; } if (isVirtual(parentStruct)) { hasVirtualParent = true; break; } } for (Declaration mb : struct.getDeclarations()) { if (mb.hasModifier(ModifierType.Virtual)) { hasVirtualMembers = true; break; } } bVirtual = hasVirtualMembers && !hasVirtualParent; structsVirtuality.put(name, bVirtual); } return bVirtual; } protected String ioVarName = "io", ioStaticVarName = "IO"; public List<Declaration> convertVariablesDeclarationToBridJ(String name, TypeRef mutatedType, int[] iChild, int bits, boolean isGlobal, Identifier holderName, Identifier callerLibraryName, String callerLibrary, Element... toImportDetailsFrom) throws UnsupportedConversionException { name = result.typeConverter.getValidJavaArgumentName(ident(name)).toString(); //convertVariablesDeclaration(name, mutatedType, out, iChild, callerLibraryName); final boolean useRawTypes = false; //Expression initVal = null; int fieldIndex = iChild[0]; //convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structPeerExpr, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { NL4JConversion conv = ((BridJTypeConversion) result.typeConverter).convertTypeToNL4J( mutatedType, callerLibraryName, thisField("io"), varRef(name), fieldIndex, bits); if (conv == null) { throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java"); } else if (conv.isUndefined) { throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java (undefined type)"); } else if ("void".equals(String.valueOf(conv.getTypeRef(useRawTypes)))) { throw new UnsupportedConversionException(mutatedType, "void type !"); //out.add(new EmptyDeclaration("SKIPPED:", v.formatComments("", true, true, false), v.toString())); } Function convDecl = new Function(); conv.annotateTypedType(convDecl, useRawTypes); convDecl.setType(Type.JavaMethod); convDecl.addModifiers(ModifierType.Public); if (conv.arrayLengths != null) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Length), "({" + StringUtils.implode(conv.arrayLengths, ", ") + "})")); } if (conv.bits != null) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), conv.bits)); } if (conv.byValue) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ByValue))); } for (Element e : toImportDetailsFrom) { convDecl.importDetails(e, false); } convDecl.importDetails(mutatedType, true); //convDecl.importDetails(javaType, true); // convDecl.importDetails(v, false); // convDecl.importDetails(vs, false); // convDecl.importDetails(valueType, false); // valueType.stripDetails(); convDecl.moveAllCommentsBefore(); convDecl.setName(ident(name)); if (!isGlobal) { convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Field), expr(fieldIndex))); } convDecl.setValueType(conv.getTypeRef(useRawTypes)); TypeRef javaType = convDecl.getValueType(); String pointerGetSetMethodSuffix = StringUtils.capitalize(javaType.toString()); Expression getGlobalPointerExpr = null; if (isGlobal) { getGlobalPointerExpr = methodCall(methodCall(methodCall(expr(typeRef(BridJ.class)), "getNativeLibrary", expr(callerLibrary)), "getSymbolPointer", expr(name)), "as", result.typeConverter.typeLiteral(javaType.clone())); } List<Declaration> out = new ArrayList<Declaration>(); boolean addedGetterOrSetter = false; if (conv.getExpr != null) { Function getter = convDecl.clone(); if (isGlobal) { getter.setBody(block( tryRethrow(new Statement.Return(cast(javaType.clone(), methodCall(getGlobalPointerExpr, "get")))))); } else { getter.setBody(block( new Statement.Return(conv.getExpr))); } out.add(getter); addedGetterOrSetter = true; } if (!conv.readOnly && conv.setExpr != null) { Function setter = convDecl.clone(); setter.setValueType(typeRef(holderName.clone()));//Void.TYPE)); setter.addArg(new Arg(name, javaType)); //setter.addModifiers(ModifierType.Native); if (isGlobal) { setter.setBody(block( tryRethrow(block( stat(methodCall(getGlobalPointerExpr, "set", varRef(name))), new Statement.Return(thisRef()))))); } else { setter.setBody(block( stat(conv.setExpr), new Statement.Return(thisRef()))); } out.add(setter); addedGetterOrSetter = true; if (result.config.scalaStructSetters) { setter = new Function(); setter.setType(Type.JavaMethod); setter.setName(ident(name + "_$eq")); setter.setValueType(javaType.clone()); setter.addArg(new Arg(name, javaType.clone())); setter.addModifiers(ModifierType.Public, ModifierType.Final); setter.setBody(block( stat(methodCall(name, varRef(name))), new Statement.Return(varRef(name)))); out.add(setter); } } if (!addedGetterOrSetter) { out.add(new EmptyDeclaration("Failed to convert value " + name + " of type " + mutatedType)); } return out; } @Override public boolean convertVariablesDeclaration(VariablesDeclaration v, Signatures signatures, DeclarationsHolder out, int[] iChild, boolean isGlobal, Identifier holderName, Identifier callerLibraryClass, String callerLibrary) { try { TypeRef valueType = v.getValueType(); for (Declarator vs : v.getDeclarators()) { if (vs.getDefaultValue() != null) { continue; } String name = vs.resolveName(); if (name == null || name.length() == 0) { name = "anonymous" + (nextAnonymousFieldId++); } TypeRef mutatedType = valueType; if (!(vs instanceof DirectDeclarator)) { mutatedType = (TypeRef) vs.mutateTypeKeepingParent(valueType); vs = new DirectDeclarator(vs.resolveName()); } //Declarator d = v.getDeclarators().get(0); List<Declaration> vds = convertVariablesDeclarationToBridJ(name, mutatedType, iChild, vs.getBits(), isGlobal, holderName, callerLibraryClass, callerLibrary, v, vs); if (vs.getBits() > 0) { for (Declaration vd : vds) { vd.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), expr(vs.getBits()))); } } for (Declaration vd : vds) { if (vd instanceof Function) { if (!signatures.addMethod((Function) vd)) { continue; } } vd.importDetails(mutatedType, true); vd.moveAllCommentsBefore(); if (!(mutatedType instanceof Primitive) && !result.config.noComments) { vd.addToCommentBefore("C type : " + mutatedType); } out.addDeclaration(vd); } //} } return true; } catch (Throwable e) { if (!(e instanceof UnsupportedConversionException)) { e.printStackTrace(); } // if (!result.config.limitComments) out.addDeclaration(new EmptyDeclaration(e.toString())); return false; } finally { iChild[0]++; } } int nextAnonymousFieldId; @Override protected void configureCallbackStruct(Struct callbackStruct) { callbackStruct.setType(Struct.Type.JavaClass); callbackStruct.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Abstract); } @Override protected Struct createFakePointerClass(Identifier fakePointer) { Struct ptClass = result.declarationsConverter.publicStaticClass(fakePointer, ident(TypedPointer.class), Struct.Type.JavaClass, null); String addressVarName = "address"; ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(long.class))).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName)))))); ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(org.bridj.Pointer.class))).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName)))))); return ptClass; } @Override protected void fillLibraryMapping(Result result, SourceFiles sourceFiles, DeclarationsHolder declarations, DeclarationsHolder implementations, String library, Identifier javaPackage, Expression nativeLibFieldExpr) throws IOException { super.fillLibraryMapping(result, sourceFiles, declarations, implementations, library, javaPackage, nativeLibFieldExpr); if (implementations instanceof ModifiableElement) { ModifiableElement minterf = (ModifiableElement) implementations; minterf.addAnnotation(new Annotation(org.bridj.ann.Library.class, expr(library))); minterf.addAnnotation(new Annotation(org.bridj.ann.Runtime.class, classLiteral(result.hasCPlusPlus ? CPPRuntime.class : CRuntime.class))); } } @Override public void generateLibraryFiles(SourceFiles sourceFiles, Result result, JNAeratorConfig config) throws IOException { for (String library : result.libraries) { if (library == null) { continue; // to handle code defined in macro-expanded expressions } Identifier javaPackage = result.javaPackageByLibrary.get(library); Identifier implementationsSimpleClassName = result.getLibraryClassSimpleName(library); Identifier declarationsSimpleClassName = result.getLibraryDeclarationsClassSimpleName(library); Identifier implementationsFullClassName = result.getLibraryClassFullName(library);//ident(javaPackage, libraryClassName); Identifier declarationsFullClassName = result.getLibraryDeclarationsClassFullName(library); //if (!result.objCClasses.isEmpty()) // out.println("import org.rococoa.ID;"); Struct implementations = new Struct(); implementations.setType(Struct.Type.JavaClass); implementations.addToCommentBefore("Wrapper for library <b>" + library + "</b>", result.declarationsConverter.getFileCommentContent(result.config.libraryProjectSources.get(library), null)); implementations.addModifiers(ModifierType.Public); implementations.setTag(implementationsSimpleClassName); implementations.addParent(ident(config.runtime.libraryClass, expr(typeRef(implementationsSimpleClassName)))); if (declarationsFullClassName != null) { implementations.addProtocol(declarationsFullClassName.clone()); } if (!config.noStaticInit) implementations.addDeclaration(newStaticInit()); implementations.setResolvedJavaIdentifier(implementationsFullClassName); Struct declarations; if (declarationsFullClassName != null) { declarations = new Struct(); declarations.setType(Struct.Type.JavaInterface); declarations.addToCommentBefore("Interface for library <b>" + library + "</b>", result.declarationsConverter.getFileCommentContent(result.config.libraryProjectSources.get(library), null)); declarations.addModifiers(ModifierType.Public); declarations.setTag(declarationsSimpleClassName.clone()); declarations.setResolvedJavaIdentifier(declarationsFullClassName); } else { declarations = implementations; } // String libFileOrDirArgName = "libraryFileOrDirectory"; // Function constr = new Function(Function.Type.JavaMethod, fullLibraryClassName.resolveLastSimpleIdentifier().clone(), null, new Arg(libFileOrDirArgName, typeRef(File.class))); // constr.addModifiers(ModifierType.Public); // constr.setBody(block(stat(methodCall("super", varRef(libFileOrDirArgName))))); // interf.addDeclaration(constr); // // constr = new Function(Function.Type.JavaMethod, fullLibraryClassName.resolveLastSimpleIdentifier().clone(), null); // constr.addModifiers(ModifierType.Public); // constr.addThrown(typeRef(FileNotFoundException.class)); // constr.setBody(block(stat(methodCall("super", classLiteral(typeRef(fullLibraryClassName.clone())))))); // interf.addDeclaration(constr); fillLibraryMapping(result, sourceFiles, declarations, implementations, library, javaPackage, varRef("this")); writeLibraryInterface(result, sourceFiles, declarations, library, javaPackage); if (declarations != implementations) { writeLibraryInterface(result, sourceFiles, implementations, library, javaPackage); } } } private Function newStaticInit() { Function f = new Function(Function.Type.StaticInit, null, null).setBody(block( stat(methodCall( expr(typeRef(BridJ.class)), Expression.MemberRefStyle.Dot, "register")))).addModifiers(ModifierType.Static); return f; } private void addParentNamespaceAnnotation(ModifiableElement dest, Identifier parentNamespace) { if (parentNamespace != null) { dest.addAnnotation(new Annotation(typeRef(org.bridj.ann.Namespace.class), expr(parentNamespace.toString()))); } } }
diff --git a/app/controllers/Login.java b/app/controllers/Login.java index b09bf9d..4670b01 100644 --- a/app/controllers/Login.java +++ b/app/controllers/Login.java @@ -1,170 +1,170 @@ package controllers; import java.lang.Exception; import java.util.*; //import play.api.libs.concurrent.Promise; import play.libs.F.Promise; import play.libs.Json; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.node.ObjectNode; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.JsonParser; import play.*; import play.mvc.*; import play.data.*; import views.html.*; import models.*; import play.mvc.Http.Request; import play.mvc.Http.Cookie; import play.libs.OpenID; import play.libs.OpenID.UserInfo; public class Login extends Controller { public static int sessionDuration = 3600*24*30; @SuppressWarnings("serial") public static final Map<String, String> identifiers = new HashMap<String, String>() { { put("google", "https://www.google.com/accounts/o8/id"); } }; public static Result auth() { String providerId = "google"; String providerUrl = identifiers.get(providerId); //String returnToUrl = "http://localhost:9000/login/verify"; String returnToUrl = Application.domain + "/login/verify"; if (providerUrl == null) return badRequest(index.render(getCustSession(), InfoDisplay.ERROR, "Provider could not be found.")); // set the information to get Map<String, String> attributes = new HashMap<String, String>(); attributes.put("Email", "http://schema.openid.net/contact/email"); attributes.put("FirstName", "http://schema.openid.net/namePerson/first"); attributes.put("LastName", "http://schema.openid.net/namePerson/last"); // ask to openid the information Promise<String> redirectUrl = OpenID.redirectURL(providerUrl, returnToUrl, attributes); return redirect(redirectUrl.get()); } // return the session of the logged customer public static CustomerSession getCustSession() { MonDataBase db = MonDataBase.getInstance(); Http.Cookie cookie = request().cookies().get("connected"); try { if (cookie != null) { String custId = cookie.value(); return new CustomerSession(custId, db.getLogin(custId)); } return null; } catch (Exception e) { return null; } } public boolean isConnected() { return (getCustSession() != null); } // get the result of openid public static Result verify() { Promise<UserInfo> userInfoPromise = OpenID.verifiedId(); UserInfo userInfo = userInfoPromise.get(); JsonNode json = Json.toJson(userInfo); // parse the data from openId String email = json.findPath("Email").getTextValue(); String firstName = json.findPath("FirstName").getTextValue(); String lastName = json.findPath("LastName").getTextValue(); MonDataBase db = MonDataBase.getInstance(); try { String customerId = db.connection(email); response().setCookie("connected", customerId, sessionDuration); CustomerSession custSession = new CustomerSession(customerId, MonDataBase.getInstance().getLogin(customerId)); return ok(index.render(custSession, InfoDisplay.SUCCESS, "You are now connected.")); } catch (CustomerException e) { try { - String customerId = db.addCustomer(email, firstName, lastName); + String customerId = db.addCustomer(email, lastName, firstName); response().setCookie("connected", customerId, sessionDuration); CustomerSession custSession = new CustomerSession(customerId, firstName + " " + lastName); return ok(index.render(custSession, InfoDisplay.SUCCESS, "You are now connected")); } catch (Exception f) { return badRequest(index.render(getCustSession(), InfoDisplay.ERROR, "Error when logging in. " + f)); } } catch (Exception e) { return badRequest(index.render(getCustSession(), InfoDisplay.ERROR, "Error when logging in. " + e)); } } /*public static String connection(String login, String password) throws Exception { MonDataBase db = MonDataBase.getInstance(); String customerId = db.connection(login, password); response().setCookie("connected", customerId, sessionDuration); return customerId; }*/ public static String getConnected() throws Exception { CustomerSession custSession = getCustSession(); if (custSession == null) throw new CustomerException("You must be connected."); return custSession.getId(); } public static Result logout() { response().discardCookies("connected"); return ok(index.render(null, InfoDisplay.INFO, "You are now logged out.")); } /*public static Result submit() { Form<Client> filledForm = loginForm.bindFromRequest(); //Check in the database if login exist and if it matches with the password if(!filledForm.hasErrors()) { try { String checker = connection(filledForm.field("login").value(), filledForm.field("password").value()); CustomerSession custSession = new CustomerSession(checker, filledForm.field("login").value()); Client created = filledForm.get(); return ok(index.render(custSession, filledForm, InfoDisplay.SUCCESS, "You are now connected.")); } catch (LoginException e) { filledForm.reject("login", "This login does not exist"); return badRequest(index.render(getCustSession(), filledForm, InfoDisplay.ERROR, "Error when logging in. This login does not exist.")); } catch (PasswordException e) { filledForm.reject("password", "The password does not match"); return badRequest(index.render(getCustSession(), filledForm, InfoDisplay.ERROR, "Error when logging in. The password does not match.")); } catch(Exception e) { return badRequest(index.render(getCustSession(), filledForm, InfoDisplay.ERROR, "Error when logging in. " + e)); } } return badRequest(index.render(getCustSession(), filledForm, InfoDisplay.ERROR, "Error when logging in. Please fill correctly all the fields.")); }*/ }
true
true
public static Result verify() { Promise<UserInfo> userInfoPromise = OpenID.verifiedId(); UserInfo userInfo = userInfoPromise.get(); JsonNode json = Json.toJson(userInfo); // parse the data from openId String email = json.findPath("Email").getTextValue(); String firstName = json.findPath("FirstName").getTextValue(); String lastName = json.findPath("LastName").getTextValue(); MonDataBase db = MonDataBase.getInstance(); try { String customerId = db.connection(email); response().setCookie("connected", customerId, sessionDuration); CustomerSession custSession = new CustomerSession(customerId, MonDataBase.getInstance().getLogin(customerId)); return ok(index.render(custSession, InfoDisplay.SUCCESS, "You are now connected.")); } catch (CustomerException e) { try { String customerId = db.addCustomer(email, firstName, lastName); response().setCookie("connected", customerId, sessionDuration); CustomerSession custSession = new CustomerSession(customerId, firstName + " " + lastName); return ok(index.render(custSession, InfoDisplay.SUCCESS, "You are now connected")); } catch (Exception f) { return badRequest(index.render(getCustSession(), InfoDisplay.ERROR, "Error when logging in. " + f)); } } catch (Exception e) { return badRequest(index.render(getCustSession(), InfoDisplay.ERROR, "Error when logging in. " + e)); } }
public static Result verify() { Promise<UserInfo> userInfoPromise = OpenID.verifiedId(); UserInfo userInfo = userInfoPromise.get(); JsonNode json = Json.toJson(userInfo); // parse the data from openId String email = json.findPath("Email").getTextValue(); String firstName = json.findPath("FirstName").getTextValue(); String lastName = json.findPath("LastName").getTextValue(); MonDataBase db = MonDataBase.getInstance(); try { String customerId = db.connection(email); response().setCookie("connected", customerId, sessionDuration); CustomerSession custSession = new CustomerSession(customerId, MonDataBase.getInstance().getLogin(customerId)); return ok(index.render(custSession, InfoDisplay.SUCCESS, "You are now connected.")); } catch (CustomerException e) { try { String customerId = db.addCustomer(email, lastName, firstName); response().setCookie("connected", customerId, sessionDuration); CustomerSession custSession = new CustomerSession(customerId, firstName + " " + lastName); return ok(index.render(custSession, InfoDisplay.SUCCESS, "You are now connected")); } catch (Exception f) { return badRequest(index.render(getCustSession(), InfoDisplay.ERROR, "Error when logging in. " + f)); } } catch (Exception e) { return badRequest(index.render(getCustSession(), InfoDisplay.ERROR, "Error when logging in. " + e)); } }
diff --git a/src/org/intellij/erlang/formatter/ErlangBlock.java b/src/org/intellij/erlang/formatter/ErlangBlock.java index 8302e106..ea3a38fd 100644 --- a/src/org/intellij/erlang/formatter/ErlangBlock.java +++ b/src/org/intellij/erlang/formatter/ErlangBlock.java @@ -1,235 +1,235 @@ /* * Copyright 2012 Sergey Ignatov * * 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.intellij.erlang.formatter; import com.intellij.formatting.*; import com.intellij.formatting.templateLanguages.BlockWithParent; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.TokenType; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.util.containers.ContainerUtil; import org.intellij.erlang.formatter.settings.ErlangCodeStyleSettings; import org.intellij.erlang.psi.ErlangFakeBinaryExpression; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.intellij.erlang.ErlangTypes.*; /** * @author ignatov */ public class ErlangBlock implements ASTBlock, BlockWithParent { public static final TokenSet BLOCKS_TOKEN_SET = TokenSet.create( ERL_CLAUSE_BODY, ERL_MACROS_BODY, // ERL_TYPED_RECORD_FIELDS, ERL_ARGUMENT_LIST, ERL_TUPLE_EXPRESSION, ERL_LIST_EXPRESSION, ERL_CR_CLAUSES, ERL_IF_CLAUSES, ERL_TRY_CLAUSES, ERL_CATCH_EXPRESSION, ERL_BEGIN_END_BODY, ERL_TOP_TYPE_CLAUSE, ERL_FUN_CLAUSES, ERL_TRY_EXPRESSIONS_CLAUSE, ERL_TYPE_SIG_GUARD ); private ASTNode myNode; private Alignment myAlignment; private Indent myIndent; private Wrap myWrap; private CommonCodeStyleSettings mySettings; private ErlangCodeStyleSettings myErlangSettings; private final SpacingBuilder mySpacingBuilder; private List<Block> mySubBlocks; private BlockWithParent myParent; public ErlangBlock(@Nullable BlockWithParent parent, // todo[ignatov]: remove parent, use AlignmentStrategy instead of @NotNull ASTNode node, @Nullable Alignment alignment, @Nullable Wrap wrap, @NotNull CommonCodeStyleSettings settings, @NotNull ErlangCodeStyleSettings erlangSettings, @NotNull SpacingBuilder spacingBuilder) { myParent = parent; myNode = node; myAlignment = alignment; myWrap = wrap; mySettings = settings; myErlangSettings = erlangSettings; mySpacingBuilder = spacingBuilder; myIndent = new ErlangIndentProcessor(mySettings).getChildIndent(node); } @Override public ASTNode getNode() { return myNode; } @NotNull @Override public TextRange getTextRange() { return myNode.getTextRange(); } @Override public Wrap getWrap() { return myWrap; } @Override public Indent getIndent() { return myIndent; } @Override public Alignment getAlignment() { return myAlignment; } @NotNull @Override public List<Block> getSubBlocks() { if (mySubBlocks == null) { mySubBlocks = buildSubBlocks(); } return new ArrayList<Block>(mySubBlocks); } private List<Block> buildSubBlocks() { List<Block> blocks = new ArrayList<Block>(); Alignment alignment = null; Alignment baseAlignment = Alignment.createAlignment(); IElementType parentType = getNode().getElementType(); PsiElement psi = getNode().getPsi(); for (ASTNode child = myNode.getFirstChildNode(); child != null; child = child.getTreeNext()) { IElementType childType = child.getElementType(); if (child.getTextRange().getLength() == 0 || childType == TokenType.WHITE_SPACE) continue; if (myErlangSettings.ALIGN_MULTILINE_BLOCK) { if (parentType == ERL_PARENTHESIZED_EXPRESSION || parentType == ERL_ARGUMENT_LIST || parentType == ERL_ARGUMENT_DEFINITION_LIST || parentType == ERL_FUN_TYPE) { if (childType != ERL_PAR_LEFT && childType != ERL_PAR_RIGHT) { alignment = baseAlignment; } } - if (parentType == ERL_TUPLE_EXPRESSION || parentType == ERL_RECORD_TUPLE || parentType == ERL_TYPED_RECORD_FIELDS) { + if (parentType == ERL_TUPLE_EXPRESSION || parentType == ERL_RECORD_TUPLE || parentType == ERL_TYPED_RECORD_FIELDS || parentType == ERL_RECORD_FIELDS) { if (childType != ERL_CURLY_LEFT && childType != ERL_CURLY_RIGHT) { alignment = baseAlignment; } } if (parentType == ERL_LIST_EXPRESSION || parentType == ERL_LIST_COMPREHENSION || parentType == ERL_EXPORT_FUNCTIONS) { if (childType != ERL_BRACKET_LEFT && childType != ERL_BRACKET_RIGHT && childType != ERL_BIN_START && childType != ERL_BIN_END && childType != ERL_LC_EXPRS) { alignment = baseAlignment; } } if (psi instanceof ErlangFakeBinaryExpression) { alignment = baseAlignment; } } boolean isEmacsStyleFunctionAlignment = false; //noinspection ConstantConditions if (isEmacsStyleFunctionAlignment && parentType == ERL_FUNCTION_CLAUSE && childType == ERL_CLAUSE_BODY) { // Emacs style alignment for function clauses @Nullable BlockWithParent clause = getParent(); List<Block> subBlocks = clause instanceof ASTBlock ? ((ASTBlock) clause).getSubBlocks() : Collections.<Block>emptyList(); List<Block> functionsBlock = ContainerUtil.filter(subBlocks, new Condition<Block>() { @Override public boolean value(Block block) { return ((ASTBlock) block).getNode().getElementType() == ERL_FUNCTION_CLAUSE; } }); Block first = ContainerUtil.getFirstItem(functionsBlock); if (this.equals(first)) { alignment = Alignment.createAlignment(true); } else if (first != null) { List<Block> list = first.getSubBlocks(); Block filter = ContainerUtil.getFirstItem(ContainerUtil.filter(list, new Condition<Block>() { @Override public boolean value(Block block) { return ((ASTBlock) block).getNode().getElementType() == ERL_CLAUSE_BODY; } })); alignment = filter == null ? null : filter.getAlignment(); } } blocks.add(buildSubBlock(child, alignment)); alignment = null; } return Collections.unmodifiableList(blocks); } private Block buildSubBlock(@NotNull ASTNode child, @Nullable Alignment alignment) { return new ErlangBlock(this, child, alignment, null, mySettings, myErlangSettings, mySpacingBuilder); } @Override public Spacing getSpacing(Block child1, Block child2) { return mySpacingBuilder.getSpacing(this, child1, child2); } @NotNull @Override public ChildAttributes getChildAttributes(int newChildIndex) { Indent childIndent = Indent.getNoneIndent(); IElementType type = myNode.getElementType(); ASTNode sibling = FormatterUtil.getNextNonWhitespaceSibling(myNode); if (BLOCKS_TOKEN_SET.contains(type) || type == ERL_IF_EXPRESSION) { childIndent = Indent.getNormalIndent(true); } return new ChildAttributes(childIndent, null); } @Override public boolean isIncomplete() { return false; } @Override public boolean isLeaf() { return myNode.getFirstChildNode() == null; } @Override public BlockWithParent getParent() { return myParent; } @Override public void setParent(BlockWithParent blockWithParent) { myParent = blockWithParent; } }
true
true
private List<Block> buildSubBlocks() { List<Block> blocks = new ArrayList<Block>(); Alignment alignment = null; Alignment baseAlignment = Alignment.createAlignment(); IElementType parentType = getNode().getElementType(); PsiElement psi = getNode().getPsi(); for (ASTNode child = myNode.getFirstChildNode(); child != null; child = child.getTreeNext()) { IElementType childType = child.getElementType(); if (child.getTextRange().getLength() == 0 || childType == TokenType.WHITE_SPACE) continue; if (myErlangSettings.ALIGN_MULTILINE_BLOCK) { if (parentType == ERL_PARENTHESIZED_EXPRESSION || parentType == ERL_ARGUMENT_LIST || parentType == ERL_ARGUMENT_DEFINITION_LIST || parentType == ERL_FUN_TYPE) { if (childType != ERL_PAR_LEFT && childType != ERL_PAR_RIGHT) { alignment = baseAlignment; } } if (parentType == ERL_TUPLE_EXPRESSION || parentType == ERL_RECORD_TUPLE || parentType == ERL_TYPED_RECORD_FIELDS) { if (childType != ERL_CURLY_LEFT && childType != ERL_CURLY_RIGHT) { alignment = baseAlignment; } } if (parentType == ERL_LIST_EXPRESSION || parentType == ERL_LIST_COMPREHENSION || parentType == ERL_EXPORT_FUNCTIONS) { if (childType != ERL_BRACKET_LEFT && childType != ERL_BRACKET_RIGHT && childType != ERL_BIN_START && childType != ERL_BIN_END && childType != ERL_LC_EXPRS) { alignment = baseAlignment; } } if (psi instanceof ErlangFakeBinaryExpression) { alignment = baseAlignment; } } boolean isEmacsStyleFunctionAlignment = false; //noinspection ConstantConditions if (isEmacsStyleFunctionAlignment && parentType == ERL_FUNCTION_CLAUSE && childType == ERL_CLAUSE_BODY) { // Emacs style alignment for function clauses @Nullable BlockWithParent clause = getParent(); List<Block> subBlocks = clause instanceof ASTBlock ? ((ASTBlock) clause).getSubBlocks() : Collections.<Block>emptyList(); List<Block> functionsBlock = ContainerUtil.filter(subBlocks, new Condition<Block>() { @Override public boolean value(Block block) { return ((ASTBlock) block).getNode().getElementType() == ERL_FUNCTION_CLAUSE; } }); Block first = ContainerUtil.getFirstItem(functionsBlock); if (this.equals(first)) { alignment = Alignment.createAlignment(true); } else if (first != null) { List<Block> list = first.getSubBlocks(); Block filter = ContainerUtil.getFirstItem(ContainerUtil.filter(list, new Condition<Block>() { @Override public boolean value(Block block) { return ((ASTBlock) block).getNode().getElementType() == ERL_CLAUSE_BODY; } })); alignment = filter == null ? null : filter.getAlignment(); } } blocks.add(buildSubBlock(child, alignment)); alignment = null; } return Collections.unmodifiableList(blocks); }
private List<Block> buildSubBlocks() { List<Block> blocks = new ArrayList<Block>(); Alignment alignment = null; Alignment baseAlignment = Alignment.createAlignment(); IElementType parentType = getNode().getElementType(); PsiElement psi = getNode().getPsi(); for (ASTNode child = myNode.getFirstChildNode(); child != null; child = child.getTreeNext()) { IElementType childType = child.getElementType(); if (child.getTextRange().getLength() == 0 || childType == TokenType.WHITE_SPACE) continue; if (myErlangSettings.ALIGN_MULTILINE_BLOCK) { if (parentType == ERL_PARENTHESIZED_EXPRESSION || parentType == ERL_ARGUMENT_LIST || parentType == ERL_ARGUMENT_DEFINITION_LIST || parentType == ERL_FUN_TYPE) { if (childType != ERL_PAR_LEFT && childType != ERL_PAR_RIGHT) { alignment = baseAlignment; } } if (parentType == ERL_TUPLE_EXPRESSION || parentType == ERL_RECORD_TUPLE || parentType == ERL_TYPED_RECORD_FIELDS || parentType == ERL_RECORD_FIELDS) { if (childType != ERL_CURLY_LEFT && childType != ERL_CURLY_RIGHT) { alignment = baseAlignment; } } if (parentType == ERL_LIST_EXPRESSION || parentType == ERL_LIST_COMPREHENSION || parentType == ERL_EXPORT_FUNCTIONS) { if (childType != ERL_BRACKET_LEFT && childType != ERL_BRACKET_RIGHT && childType != ERL_BIN_START && childType != ERL_BIN_END && childType != ERL_LC_EXPRS) { alignment = baseAlignment; } } if (psi instanceof ErlangFakeBinaryExpression) { alignment = baseAlignment; } } boolean isEmacsStyleFunctionAlignment = false; //noinspection ConstantConditions if (isEmacsStyleFunctionAlignment && parentType == ERL_FUNCTION_CLAUSE && childType == ERL_CLAUSE_BODY) { // Emacs style alignment for function clauses @Nullable BlockWithParent clause = getParent(); List<Block> subBlocks = clause instanceof ASTBlock ? ((ASTBlock) clause).getSubBlocks() : Collections.<Block>emptyList(); List<Block> functionsBlock = ContainerUtil.filter(subBlocks, new Condition<Block>() { @Override public boolean value(Block block) { return ((ASTBlock) block).getNode().getElementType() == ERL_FUNCTION_CLAUSE; } }); Block first = ContainerUtil.getFirstItem(functionsBlock); if (this.equals(first)) { alignment = Alignment.createAlignment(true); } else if (first != null) { List<Block> list = first.getSubBlocks(); Block filter = ContainerUtil.getFirstItem(ContainerUtil.filter(list, new Condition<Block>() { @Override public boolean value(Block block) { return ((ASTBlock) block).getNode().getElementType() == ERL_CLAUSE_BODY; } })); alignment = filter == null ? null : filter.getAlignment(); } } blocks.add(buildSubBlock(child, alignment)); alignment = null; } return Collections.unmodifiableList(blocks); }
diff --git a/src/game/gui/MazeEditorPanel.java b/src/game/gui/MazeEditorPanel.java index 96f9721..ef225d8 100644 --- a/src/game/gui/MazeEditorPanel.java +++ b/src/game/gui/MazeEditorPanel.java @@ -1,511 +1,511 @@ package game.gui; import game.logic.Game; import game.ui.GameOptions; import game.ui.GameOutput; import game.ui.MazePictures; import general_utilities.MazeInput; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Iterator; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JToolBar; import maze_objects.Dragon; import maze_objects.Hero; import maze_objects.Maze; import maze_objects.Movable; import maze_objects.Sword; import maze_objects.Tile; public class MazeEditorPanel extends JDialog { private static final long serialVersionUID = -981182364507201188L; public MazeObjectToDraw currentObject = new MazeObjectToDraw(); public Game game; public GameOptions options = new GameOptions(false); public MazePictures pictures; //This boolean indicates if the user clicked on a new dragon or is repeating the same public boolean newDragon; public int numberOfExits = 0; public boolean createdHero; public boolean createdSword; private int maze_rows; private int maze_columns; private int dragonType; public MazeEditorPanel(Frame parent, final Game game, MazePictures pictures) { super(parent, "Maze Editor", true); setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); this.game = game; this.pictures = pictures; createMenuBar(); createToolBar(); if(askNewGameOptions() == 1) return; initializeNewGame(); MazePainterPanel mazePainter = new MazePainterPanel(this); Dimension mazeEditorDimension = new Dimension(options.columns * GUInterface.SPRITESIZE, options.rows * GUInterface.SPRITESIZE); JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportView(mazePainter); Dimension scrollPaneDimension = new Dimension(mazeEditorDimension.width + GUInterface.SCROLLBAR_PIXELS, mazeEditorDimension.height + GUInterface.SCROLLBAR_PIXELS); scrollPane.setPreferredSize(GUInterface.getFormattedPreferredDimension(scrollPaneDimension, GUInterface.MAXIMUM_WINDOW_SIZE)); getContentPane().add(scrollPane); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setResizable(false); pack(); setLocationRelativeTo(null); setVisible(true); } private void initializeNewGame() { this.game = new Game(options); this.game.setMaze(new Maze(options.rows, options.columns, true)); this.game.getHero().print = false; this.game.getSword().print = false; } private int askNewGameOptions() { String rows; String columns; do { rows = JOptionPane.showInputDialog(this, "Number of rows? (Min. 6, Max. 500 but clipping will occur!)"); } while(!MazeInput.isInteger(rows) && rows != null); if(rows == null) return 1; do { columns = JOptionPane.showInputDialog(this, "Number of columns? (Min. 6, Max. 500 but clipping will occur!)"); } while(!MazeInput.isInteger(columns) && columns != null); if(columns == null) return 1; if(Integer.parseInt(rows) < 6 || Integer.parseInt(columns) < 6 || Integer.parseInt(columns) > 500 || Integer.parseInt(columns) > 500) { JOptionPane.showMessageDialog(this, "Invalid row and/or column number detected, using 10 for both!", "Invalid input error", JOptionPane.ERROR_MESSAGE); maze_rows = 10; maze_columns = 10; } else { maze_rows = Integer.parseInt(rows); maze_columns = Integer.parseInt(columns); } String[] possibilities = {"Randomly sleeping", "Always awake", "Static"}; String dragonOption = (String)JOptionPane.showInputDialog( this, "Dragon type:", "Dragon type", JOptionPane.QUESTION_MESSAGE, null, possibilities, possibilities[0]); if(dragonOption == null) return 1; if(dragonOption.equals( "Randomly sleeping" )) dragonType = Dragon.SLEEPING; else if(dragonOption.equals( "Always awake" )) dragonType = Dragon.NORMAL; else dragonType = Dragon.STATIC; updateOptions(); return 0; } private void createToolBar() { JToolBar toolBar = new JToolBar(); toolBar.setFloatable(false); getContentPane().add(toolBar); JButton btnFloor = new JButton(""); btnFloor.setIcon(new ImageIcon(InfoPanel.class.getResource("/images/empty.png"))); toolBar.add(btnFloor); btnFloor.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { currentObject.set(Tile.empty); } }); JButton btnWall = new JButton(""); btnWall.setIcon(new ImageIcon(InfoPanel.class.getResource("/images/wall.png"))); toolBar.add(btnWall); btnWall.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { currentObject.set(Tile.wall); } }); JButton btnExit = new JButton(""); btnExit.setIcon(new ImageIcon(InfoPanel.class.getResource("/images/exit.png"))); toolBar.add(btnExit); btnExit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { currentObject.set(Tile.exit); } }); JButton btnDragon = new JButton(""); btnDragon.setIcon(new ImageIcon(InfoPanel.class.getResource("/images/dragon.png"))); toolBar.add(btnDragon); btnDragon.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { currentObject.set(new Dragon(0, 0, options.dragonType)); newDragon = true; } }); JButton btnSword = new JButton(""); btnSword.setIcon(new ImageIcon(InfoPanel.class.getResource("/images/sword.png"))); toolBar.add(btnSword); btnSword.addActionListener(new SetSword()); JButton btnHero = new JButton(""); btnHero.setIcon(new ImageIcon(InfoPanel.class.getResource("/images/hero.png"))); toolBar.add(btnHero); btnHero.addActionListener(new SetHero()); } private void createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); fileMenu.getAccessibleContext().setAccessibleDescription( "File menu"); menuBar.add(fileMenu); - JMenuItem saveGameMenuItem = new JMenuItem("Save Maze", KeyEvent.VK_S); + JMenuItem saveGameMenuItem = new JMenuItem("Save maze", KeyEvent.VK_S); saveGameMenuItem.getAccessibleContext().setAccessibleDescription( "Saves the current maze to a file"); fileMenu.add(saveGameMenuItem); saveGameMenuItem.addActionListener(new SaveMaze()); - JMenuItem exitGameMenuItem = new JMenuItem("Exit game", + JMenuItem exitGameMenuItem = new JMenuItem("Exit editor", KeyEvent.VK_E); exitGameMenuItem.getAccessibleContext().setAccessibleDescription( - "Exits the game"); + "Exits the editor"); fileMenu.add(exitGameMenuItem); exitGameMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { int option = JOptionPane.showConfirmDialog( MazeEditorPanel.this, - "Do you really want to exit the game?", + "Do you really want to exit the editor?\nDon't forget to save!", "Confirm exit", JOptionPane.YES_NO_OPTION); if(option == JOptionPane.YES_OPTION) dispose(); } }); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic(KeyEvent.VK_H); helpMenu.getAccessibleContext().setAccessibleDescription( "Help menu"); menuBar.add(helpMenu); JMenuItem keysHelpMenuItem = new JMenuItem("Help", KeyEvent.VK_H); keysHelpMenuItem.getAccessibleContext().setAccessibleDescription( "Explains how to use the editor"); helpMenu.add(keysHelpMenuItem); keysHelpMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(MazeEditorPanel.this, "\nPlace the objects on the toolbar to create a custom game.\n" + "If you want to place multiple dragons, click the dragon icon again after placing one, and place the new one.\n" + "You cannot place anything on the corners, and only exits or walls on the map borders.\n" + "You can't create a game that doesn't have one hero and one sword and at least an exit.\n" + "You can, however, create an enemyless game, but, come on, where's the fun in that?\n\n", "Help", JOptionPane.PLAIN_MESSAGE); } }); setJMenuBar(menuBar); } private void updateOptions() { options.randomMaze = true; options.rows = maze_rows; options.columns = maze_columns; options.dragonType = dragonType; options.multipleDragons = true; options.randomSpawns = false; } class SetHero implements ActionListener { @Override public void actionPerformed(ActionEvent e) { currentObject.set(game.getHero()); } } class SetSword implements ActionListener { @Override public void actionPerformed(ActionEvent e) { currentObject.set(game.getSword()); } } class SaveMaze implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if(numberOfExits == 0) { JOptionPane.showMessageDialog(MazeEditorPanel.this, "You need at least one exit on your maze!", "No exits found", JOptionPane.ERROR_MESSAGE); return; } if(!createdHero) { JOptionPane.showMessageDialog(MazeEditorPanel.this, "You need to place your hero!", "No hero found", JOptionPane.ERROR_MESSAGE); return; } if(!createdSword) { JOptionPane.showMessageDialog(MazeEditorPanel.this, "You need to place a sword!", "No sword found", JOptionPane.ERROR_MESSAGE); return; } GameOutput.showSaveGameDialog(game); } } } class MazePainterPanel extends JPanel implements MouseListener { private static final long serialVersionUID = -5533602405577612408L; MazeEditorPanel parent; private ArrayList<Movable> movableObjects = new ArrayList<Movable>(); public MazePainterPanel(MazeEditorPanel parent) { this.parent = parent; setFocusable(true); addMouseListener(this); Dimension defaultPreferred = new Dimension(parent.options.columns * GUInterface.SPRITESIZE, parent.options.rows * GUInterface.SPRITESIZE); setMaximumSize(GUInterface.MAXIMUM_WINDOW_SIZE); setPreferredSize(defaultPreferred); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); GameOutput.printGame(parent.game, g, parent.pictures); } @Override public void mouseClicked(MouseEvent e) { return; } @Override public void mouseEntered(MouseEvent e) { return; } @Override public void mouseExited(MouseEvent e) { return; } @Override public void mousePressed(MouseEvent e) { int printRow = e.getY() / 32; int printColumn = e.getX() / 32; if( checkIfAtCorner(printRow, printColumn) || ( checkIfAtMargin(printRow, printColumn) && checkIfNotWallOrExitTile() ) ) return; if(parent.game.getMaze().getPositions()[printRow][printColumn] == Tile.exit) parent.numberOfExits--; deleteObjectOn(printRow, printColumn); if(parent.currentObject.isMovable) { movableObjects.remove(parent.currentObject.movable); if( (parent.currentObject.movable instanceof Dragon) && !parent.newDragon ) parent.game.removeDragon((Dragon) parent.currentObject.movable); parent.currentObject.movable.setRow(printRow); parent.currentObject.movable.setColumn(printColumn); parent.currentObject.movable.print = true; movableObjects.add(parent.currentObject.movable); if(parent.currentObject.movable instanceof Dragon) { parent.game.addDragon((Dragon) parent.currentObject.movable); parent.newDragon = false; } } else { parent.game.getMaze().getPositions()[printRow][printColumn] = parent.currentObject.tile; if(parent.currentObject.tile == Tile.exit) parent.numberOfExits++; } checkIfCreatedHeroAndSword(); repaint(); } private boolean checkIfNotWallOrExitTile() { return parent.currentObject.isMovable || ( parent.currentObject.tile != Tile.exit && parent.currentObject.tile != Tile.wall ); } @Override public void mouseReleased(MouseEvent e) { return; } private void deleteObjectOn(int row, int column) { parent.game.getMaze().getPositions()[row][column] = Tile.empty; Iterator<Movable> iter = movableObjects.iterator(); if(movableObjects != null) while(iter.hasNext()) { Movable movable = iter.next(); if(movable.getRow() == row && movable.getColumn() == column) { if(movable instanceof Dragon) { Iterator<Dragon> dragonIter = parent.game.getDragons().iterator(); while(dragonIter.hasNext()) { Dragon dragon = dragonIter.next(); if(dragon.getRow() == row && dragon.getColumn() == column) { boolean dragonWasDead; if(dragon.getState() == Dragon.DEAD) dragonWasDead = true; else dragonWasDead = false; dragonIter.remove(); parent.game.removeDragon(dragonWasDead); } } } movable.setRow(0); movable.setColumn(0); movable.print = false; iter.remove(); } } } private void checkIfCreatedHeroAndSword() { parent.createdHero = false; parent.createdSword = false; for(Movable movable : movableObjects) { if(movable instanceof Hero) parent.createdHero = true; else if(movable instanceof Sword) parent.createdSword = true; } } private boolean checkIfAtMargin(int printRow, int printColumn) { return printRow <= 0 || printRow >= (parent.options.rows - 1) || printColumn <= 0 || printColumn >= (parent.options.columns - 1); } private boolean checkIfAtCorner(int printRow, int printColumn) { if(printRow == 0) if(printColumn == 0 || printColumn == (parent.options.columns - 1)) return true; if(printRow == (parent.options.rows - 1)) if(printColumn == 0 || printColumn == (parent.options.columns - 1)) return true; return false; } }
false
true
private void createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); fileMenu.getAccessibleContext().setAccessibleDescription( "File menu"); menuBar.add(fileMenu); JMenuItem saveGameMenuItem = new JMenuItem("Save Maze", KeyEvent.VK_S); saveGameMenuItem.getAccessibleContext().setAccessibleDescription( "Saves the current maze to a file"); fileMenu.add(saveGameMenuItem); saveGameMenuItem.addActionListener(new SaveMaze()); JMenuItem exitGameMenuItem = new JMenuItem("Exit game", KeyEvent.VK_E); exitGameMenuItem.getAccessibleContext().setAccessibleDescription( "Exits the game"); fileMenu.add(exitGameMenuItem); exitGameMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { int option = JOptionPane.showConfirmDialog( MazeEditorPanel.this, "Do you really want to exit the game?", "Confirm exit", JOptionPane.YES_NO_OPTION); if(option == JOptionPane.YES_OPTION) dispose(); } }); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic(KeyEvent.VK_H); helpMenu.getAccessibleContext().setAccessibleDescription( "Help menu"); menuBar.add(helpMenu); JMenuItem keysHelpMenuItem = new JMenuItem("Help", KeyEvent.VK_H); keysHelpMenuItem.getAccessibleContext().setAccessibleDescription( "Explains how to use the editor"); helpMenu.add(keysHelpMenuItem); keysHelpMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(MazeEditorPanel.this, "\nPlace the objects on the toolbar to create a custom game.\n" + "If you want to place multiple dragons, click the dragon icon again after placing one, and place the new one.\n" + "You cannot place anything on the corners, and only exits or walls on the map borders.\n" + "You can't create a game that doesn't have one hero and one sword and at least an exit.\n" + "You can, however, create an enemyless game, but, come on, where's the fun in that?\n\n", "Help", JOptionPane.PLAIN_MESSAGE); } }); setJMenuBar(menuBar); }
private void createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); fileMenu.getAccessibleContext().setAccessibleDescription( "File menu"); menuBar.add(fileMenu); JMenuItem saveGameMenuItem = new JMenuItem("Save maze", KeyEvent.VK_S); saveGameMenuItem.getAccessibleContext().setAccessibleDescription( "Saves the current maze to a file"); fileMenu.add(saveGameMenuItem); saveGameMenuItem.addActionListener(new SaveMaze()); JMenuItem exitGameMenuItem = new JMenuItem("Exit editor", KeyEvent.VK_E); exitGameMenuItem.getAccessibleContext().setAccessibleDescription( "Exits the editor"); fileMenu.add(exitGameMenuItem); exitGameMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { int option = JOptionPane.showConfirmDialog( MazeEditorPanel.this, "Do you really want to exit the editor?\nDon't forget to save!", "Confirm exit", JOptionPane.YES_NO_OPTION); if(option == JOptionPane.YES_OPTION) dispose(); } }); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic(KeyEvent.VK_H); helpMenu.getAccessibleContext().setAccessibleDescription( "Help menu"); menuBar.add(helpMenu); JMenuItem keysHelpMenuItem = new JMenuItem("Help", KeyEvent.VK_H); keysHelpMenuItem.getAccessibleContext().setAccessibleDescription( "Explains how to use the editor"); helpMenu.add(keysHelpMenuItem); keysHelpMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(MazeEditorPanel.this, "\nPlace the objects on the toolbar to create a custom game.\n" + "If you want to place multiple dragons, click the dragon icon again after placing one, and place the new one.\n" + "You cannot place anything on the corners, and only exits or walls on the map borders.\n" + "You can't create a game that doesn't have one hero and one sword and at least an exit.\n" + "You can, however, create an enemyless game, but, come on, where's the fun in that?\n\n", "Help", JOptionPane.PLAIN_MESSAGE); } }); setJMenuBar(menuBar); }
diff --git a/sisu-inject/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/MapOrientedComponentConfigurator.java b/sisu-inject/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/MapOrientedComponentConfigurator.java index f622a528..33e784cf 100644 --- a/sisu-inject/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/MapOrientedComponentConfigurator.java +++ b/sisu-inject/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/component/configurator/MapOrientedComponentConfigurator.java @@ -1,53 +1,53 @@ package org.codehaus.plexus.component.configurator; import java.util.Map; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.MapOrientedComponent; import org.codehaus.plexus.component.configurator.converters.composite.MapConverter; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; /* * Copyright 2001-2005 The Apache Software Foundation. * * 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. */ public class MapOrientedComponentConfigurator extends AbstractComponentConfigurator { @Override public void configureComponent( final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm, final ConfigurationListener listener ) throws ComponentConfigurationException { if ( !( component instanceof MapOrientedComponent ) ) { throw new ComponentConfigurationException( "This configurator can only process implementations of " + MapOrientedComponent.class.getName() ); } final MapConverter converter = new MapConverter(); @SuppressWarnings( "rawtypes" ) final Map context = - (Map) converter.fromConfiguration( converterLookup, configuration, null, null, containerRealm, - expressionEvaluator, listener ); + (Map) converter.fromConfiguration( converterLookup, configuration, Map.class, component.getClass(), + containerRealm, expressionEvaluator, listener ); ( (MapOrientedComponent) component ).setComponentConfiguration( context ); } }
true
true
public void configureComponent( final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm, final ConfigurationListener listener ) throws ComponentConfigurationException { if ( !( component instanceof MapOrientedComponent ) ) { throw new ComponentConfigurationException( "This configurator can only process implementations of " + MapOrientedComponent.class.getName() ); } final MapConverter converter = new MapConverter(); @SuppressWarnings( "rawtypes" ) final Map context = (Map) converter.fromConfiguration( converterLookup, configuration, null, null, containerRealm, expressionEvaluator, listener ); ( (MapOrientedComponent) component ).setComponentConfiguration( context ); }
public void configureComponent( final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm, final ConfigurationListener listener ) throws ComponentConfigurationException { if ( !( component instanceof MapOrientedComponent ) ) { throw new ComponentConfigurationException( "This configurator can only process implementations of " + MapOrientedComponent.class.getName() ); } final MapConverter converter = new MapConverter(); @SuppressWarnings( "rawtypes" ) final Map context = (Map) converter.fromConfiguration( converterLookup, configuration, Map.class, component.getClass(), containerRealm, expressionEvaluator, listener ); ( (MapOrientedComponent) component ).setComponentConfiguration( context ); }
diff --git a/webmacro/src/org/webmacro/WM.java b/webmacro/src/org/webmacro/WM.java index 4f86cc03..80f267be 100755 --- a/webmacro/src/org/webmacro/WM.java +++ b/webmacro/src/org/webmacro/WM.java @@ -1,349 +1,351 @@ /* * Copyright (c) 1998, 1999 Semiotek Inc. All Rights Reserved. * * This software is the confidential intellectual property of * of Semiotek Inc.; it is copyrighted and licensed, not sold. * You may use it under the terms of the GNU General Public License, * version 2, as published by the Free Software Foundation. If you * do not want to use the GPL, you may still use the software after * purchasing a proprietary developers license from Semiotek Inc. * * This software is provided "as is", with NO WARRANTY, not even the * implied warranties of fitness to purpose, or merchantability. You * assume all risks and liabilities associated with its use. * * See the attached License.html file for details, or contact us * by e-mail at [email protected] to get a copy. */ package org.webmacro; import org.webmacro.engine.*; import org.webmacro.resource.*; import org.webmacro.util.*; import org.webmacro.profile.*; import java.util.*; import org.webmacro.servlet.WebContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This class implements the WebMacro Manager interface. You can instantiate * this yourself if you want to use WebMacro in standalone mode, rather than * subclassing from org.webmacro.servlet.WMServlet. This is actually the * same class used by the servlet framework to manage access to the broker * there, so you really don't lose much of anything by choosing to go * standalone by using this object. All you have to do is come up with * your own context objects. */ public class WM implements WebMacro { final private static Map _brokers = new HashMap(); final private static BrokerOwner _default = new BrokerOwner(); final private Context _context; private WebContext _webContext = null; // INIT METHODS--MANAGE ACCESS TO THE BROKER final private Broker _broker; // cache for rapid access final private BrokerOwner _owner; // mgr that loads/unloads broker private boolean _alive = false; // so we don't unload twice final private Provider _tmplProvider; final private Provider _urlProvider; final private Log _log; final private ThreadLocal _contextCache; final private ThreadLocal _webContextCache; public WM() throws InitException { this(null, null); } public WM(ClassLoader cl) throws InitException { this(null, cl); } public WM(String config) throws InitException { this(config,null); } public WM(String config, ClassLoader cl) throws InitException { BrokerOwner owner = null; Broker broker = null; try { if (config == null) { owner = _default; } else { synchronized(_brokers) { owner = (BrokerOwner) _brokers.get(config); if (owner == null) { owner = new BrokerOwner(config, cl); _brokers.put(config,owner); } } } broker = owner.init(); } finally { _owner = owner; _broker = broker; if (_broker != null) { _alive = true; _log = _broker.getLog("wm", "WebMacro instance lifecycle"); _log.info("new " + this); _context = new Context(_broker); + // XXXX: check this is right - was missing & never initialized + _webContext = new WebContext(_broker); _contextCache = new ThreadLocal() { public Object initialValue() { return new ScalablePool(); } }; _webContextCache = new ThreadLocal() { public Object initialValue() { return new ScalablePool(); } }; } else { _alive = false; _log = LogSystem.getSystemLog("wm"); _log.error("Failed to initialized WebMacro from: " + config); _context = null; _contextCache = null; _webContextCache = null; } } try { _tmplProvider = _broker.getProvider("template"); _urlProvider = _broker.getProvider("url"); } catch (NotFoundException nfe) { _log.error("Could not load configuration", nfe); throw new InitException("Could not locate provider:\n " + nfe + "\nThis implies that WebMacro is badly misconfigured, you\n" + "should double check that all configuration files and\n" + "options are set up correctly. In a default install of\n" + "WebMacro this likely means your WebMacro.properties file\n" + "was not found on your CLASSPATH."); } } /** * Call this method when you are finished with WebMacro. If you don't call this * method, the Broker and all of WebMacro's caches may not be properly * shut down, potentially resulting in loss of data, and wasted memory. This * method is called in the finalizer, but it is best to call it as soon as you * know you are done with WebMacro. * <p> * After a call to destroy() attempts to use this object may yield unpredicatble * results. */ final public void destroy() { if (_alive) { _alive = false; _owner.done(); _log.info("shutdown " + this); } } public String toString() { return "WebMacro(" + _broker.getName() + ")"; } /** * This message returns false until you destroy() this object, subsequently it * returns true. Do not attempt to use this object after it has been destroyed. */ final public boolean isDestroyed() { return !_alive; } /** * You should never call this method, on any object. Leave it up to the garbage * collector. If you want to shut this object down, call destroy() instead. If * you subclass this message, be sure to call super.finalize() since this is one * of the cases where it matters. */ protected void finalize() throws Throwable { destroy(); super.finalize(); } /** * This object is used to access components that have been plugged * into WebMacro; it is shared between all instances of this class and * its subclasses. It is created when the first instance is initialized, * and deleted when the last instance is shut down. If you attempt to * access it after the last servlet has been shutdown, it will either * be in a shutdown state or else null. */ final public Broker getBroker() { // this method can be unsynch. because the broker manages its own // state, plus the only time the _broker will be shutdown or null // is after the last servlet has shutdown--so why would anyone be // accessing us then? if they do the _broker will throw exceptions // complaining that it has been shut down, or they'll get a null here. return _broker; } /** * Instantiate a new context from a pool. This method is more * efficient, in terms of object creation, than creating a * Context directly. The Context will return to the pool * when Context.recycle() is called. */ final public Context getContext() { Pool cpool = (Pool) _contextCache.get(); Context c = (Context) cpool.get(); if (c == null) { c = (Context) _context.clone(); } c.setPool(cpool); return c; } /** * Instantiate a new webcontext from a pool. This method is more * efficient, in terms of object creation, than creating a * WebContext object directly. The WebContext will return to * the pool when WebContext.recycle() is called. */ final public WebContext getWebContext(HttpServletRequest req, HttpServletResponse resp) { Pool cpool = (Pool) _webContextCache.get(); WebContext c = (WebContext) cpool.get(); if (c == null) { c = _webContext.newInstance(req,resp); } Context ctx = c; ctx.setPool(cpool); return c; } /** * Retrieve a template from the "template" provider. * @exception NotFoundException if the template was not found */ final public Template getTemplate(String key) throws NotFoundException { return (Template) _tmplProvider.get(key); } /** * Retrieve a URL from the "url" provider. Equivalent to * getBroker().getValue("url",url) * @exception NotFoundException if the template was not found */ final public String getURL(String url) throws NotFoundException { return (String) _urlProvider.get(url); } /** * Retrieve configuration information from the "config" provider. * Equivalent to getBroker().get("config",key) * @exception NotFoundException could not locate requested information */ final public String getConfig(String key) throws NotFoundException { return (String) _broker.get("config", key); } /** * Get a log to write information to. Log type names should be lower * case and short. They may be printed on every line of the log * file. The description is a longer explanation of the type of * log messages you intend to produce with this Log object. */ final public Log getLog(String type, String description) { return _broker.getLog(type, description); } /** * Get a log using the type as the description */ final public Log getLog(String type) { return _broker.getLog(type,type); } } final class BrokerOwner { /*final*/ String _config; private Broker _broker; private static int _brokerUsers = 0; final private ClassLoader _classloader; BrokerOwner() { this(null,null); } BrokerOwner(String config) { this(config,null); } BrokerOwner(String config, ClassLoader cl) { _classloader = cl; _config = config; _broker = null; _brokerUsers = 0; } synchronized Broker init() throws InitException { _brokerUsers++; if (_broker == null) { try { _broker = (_config == null) ? new Broker(_classloader) : new Broker(_config,_classloader); } catch (InitException e) { e.printStackTrace(); _broker = null; _brokerUsers = 0; throw e; // rethrow } catch (Throwable t) { _broker = null; _brokerUsers = 0; throw new InitException( "An unexpected exception was raised during initialization. This is bad,\n" + "there is either a bug in WebMacro, or your configuration is messed up:\n" + t + "\nHere are some clues: if you got a ClassNotFound exception, either\n" + "something is missing from your classpath (odd since this code ran)\n" + "or your JVM is failing some important classfile due to bytecode problems\n" + "and then claiming that, it does not exist... you might also see some kind\n" + "of VerifyException or error in that case. If you suspect something like\n" + "this is happening, recompile the WebMacro base classes with your own Java\n" + "compiler and libraries--usually that helps. It could also be that your\n" + "JVM is not new enough. Again you could try recompiling, but if it is\n" + "older than Java 1.1.7 you might be out of luck. If none of this helps,\n" + "please join the WebMacro mailing list and let us know about the problem,\n" + "because yet another possibility is WebMacro has a bug--and anyway, we \n" + "might know a workaround, or at least like to hear about the bug.\n"); } } return _broker; } synchronized void done() { _brokerUsers--; if ((_brokerUsers == 0) && (_broker != null)) { _broker.shutdown(); _broker = null; } } }
true
true
public WM(String config, ClassLoader cl) throws InitException { BrokerOwner owner = null; Broker broker = null; try { if (config == null) { owner = _default; } else { synchronized(_brokers) { owner = (BrokerOwner) _brokers.get(config); if (owner == null) { owner = new BrokerOwner(config, cl); _brokers.put(config,owner); } } } broker = owner.init(); } finally { _owner = owner; _broker = broker; if (_broker != null) { _alive = true; _log = _broker.getLog("wm", "WebMacro instance lifecycle"); _log.info("new " + this); _context = new Context(_broker); _contextCache = new ThreadLocal() { public Object initialValue() { return new ScalablePool(); } }; _webContextCache = new ThreadLocal() { public Object initialValue() { return new ScalablePool(); } }; } else { _alive = false; _log = LogSystem.getSystemLog("wm"); _log.error("Failed to initialized WebMacro from: " + config); _context = null; _contextCache = null; _webContextCache = null; } } try { _tmplProvider = _broker.getProvider("template"); _urlProvider = _broker.getProvider("url"); } catch (NotFoundException nfe) { _log.error("Could not load configuration", nfe); throw new InitException("Could not locate provider:\n " + nfe + "\nThis implies that WebMacro is badly misconfigured, you\n" + "should double check that all configuration files and\n" + "options are set up correctly. In a default install of\n" + "WebMacro this likely means your WebMacro.properties file\n" + "was not found on your CLASSPATH."); } }
public WM(String config, ClassLoader cl) throws InitException { BrokerOwner owner = null; Broker broker = null; try { if (config == null) { owner = _default; } else { synchronized(_brokers) { owner = (BrokerOwner) _brokers.get(config); if (owner == null) { owner = new BrokerOwner(config, cl); _brokers.put(config,owner); } } } broker = owner.init(); } finally { _owner = owner; _broker = broker; if (_broker != null) { _alive = true; _log = _broker.getLog("wm", "WebMacro instance lifecycle"); _log.info("new " + this); _context = new Context(_broker); // XXXX: check this is right - was missing & never initialized _webContext = new WebContext(_broker); _contextCache = new ThreadLocal() { public Object initialValue() { return new ScalablePool(); } }; _webContextCache = new ThreadLocal() { public Object initialValue() { return new ScalablePool(); } }; } else { _alive = false; _log = LogSystem.getSystemLog("wm"); _log.error("Failed to initialized WebMacro from: " + config); _context = null; _contextCache = null; _webContextCache = null; } } try { _tmplProvider = _broker.getProvider("template"); _urlProvider = _broker.getProvider("url"); } catch (NotFoundException nfe) { _log.error("Could not load configuration", nfe); throw new InitException("Could not locate provider:\n " + nfe + "\nThis implies that WebMacro is badly misconfigured, you\n" + "should double check that all configuration files and\n" + "options are set up correctly. In a default install of\n" + "WebMacro this likely means your WebMacro.properties file\n" + "was not found on your CLASSPATH."); } }
diff --git a/src/com/oresomecraft/maps/arcade/maps/Paintball_Charlie.java b/src/com/oresomecraft/maps/arcade/maps/Paintball_Charlie.java index 753e50e..2b9ef5b 100644 --- a/src/com/oresomecraft/maps/arcade/maps/Paintball_Charlie.java +++ b/src/com/oresomecraft/maps/arcade/maps/Paintball_Charlie.java @@ -1,91 +1,91 @@ package com.oresomecraft.maps.arcade.maps; import com.oresomecraft.OresomeBattles.api.BattlePlayer; import com.oresomecraft.OresomeBattles.api.Gamemode; import com.oresomecraft.OresomeBattles.api.Team; import com.oresomecraft.maps.MapConfig; import com.oresomecraft.maps.arcade.games.TeamPaintBallMap; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; @MapConfig public class Paintball_Charlie extends TeamPaintBallMap implements Listener { public Paintball_Charlie() { super.initiate(this, name, fullName, creators, modes); disableDrops(new Material[]{Material.COOKED_BEEF, Material.SNOW_BALL}); setAllowPhysicalDamage(false); setAllowBuild(false); } @Override public void readyFFASpawns() { // Nothing to see here. :-) } // Map details String name = "warehouse"; String fullName = "Paintball (Charlie)"; String creators = "meganlovesmusic, SuperDuckFace and _Husky_"; Gamemode[] modes = {Gamemode.LTS}; public void readyTDMSpawns() { World w = Bukkit.getServer().getWorld(name); redSpawns.add(new Location(w, -34, 74, 43)); blueSpawns.add(new Location(w, 71, 74, 43)); } public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack SNOW_BALL = new ItemStack(Material.SNOW_BALL, 200); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 10); i.setItem(0, SNOW_BALL); i.setItem(1, STEAK); Bukkit.getScheduler().runTask(plugin, new Runnable() { public void run() { p.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, 1000 * 20, 2)); } }); } @EventHandler public void onBlockClick(PlayerInteractEvent event) { Player p = event.getPlayer(); if (p.getLocation().getWorld().getName().equals(name)) { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { Block b = event.getClickedBlock(); World w = Bukkit.getWorld(name); Team team = BattlePlayer.getBattlePlayer(p).getTeam(); if (b.getType().equals(Material.PISTON_BASE)) { - if (team == Team.LTS_RED) { - p.teleport(new Location(w, -29, 74, 43)); - } else if (team == Team.LTS_BLUE) { - p.teleport(new Location(w, 66, 75, 43)); + if (b.getLocation().equals(new Location(w, -38, 75, 43))) { + p.teleport(new Location(w, -29, 74, 43)); // red + } else if (b.getLocation().equals(new Location(w, 74, 75, 43))) { + p.teleport(new Location(w, 66, 75, 43)); // blue } } } } } }
true
true
public void onBlockClick(PlayerInteractEvent event) { Player p = event.getPlayer(); if (p.getLocation().getWorld().getName().equals(name)) { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { Block b = event.getClickedBlock(); World w = Bukkit.getWorld(name); Team team = BattlePlayer.getBattlePlayer(p).getTeam(); if (b.getType().equals(Material.PISTON_BASE)) { if (team == Team.LTS_RED) { p.teleport(new Location(w, -29, 74, 43)); } else if (team == Team.LTS_BLUE) { p.teleport(new Location(w, 66, 75, 43)); } } } } }
public void onBlockClick(PlayerInteractEvent event) { Player p = event.getPlayer(); if (p.getLocation().getWorld().getName().equals(name)) { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { Block b = event.getClickedBlock(); World w = Bukkit.getWorld(name); Team team = BattlePlayer.getBattlePlayer(p).getTeam(); if (b.getType().equals(Material.PISTON_BASE)) { if (b.getLocation().equals(new Location(w, -38, 75, 43))) { p.teleport(new Location(w, -29, 74, 43)); // red } else if (b.getLocation().equals(new Location(w, 74, 75, 43))) { p.teleport(new Location(w, 66, 75, 43)); // blue } } } } }
diff --git a/src/com/android/settings/DateTimeSettingsSetupWizard.java b/src/com/android/settings/DateTimeSettingsSetupWizard.java index 4720e71e5..08204b69a 100644 --- a/src/com/android/settings/DateTimeSettingsSetupWizard.java +++ b/src/com/android/settings/DateTimeSettingsSetupWizard.java @@ -1,331 +1,328 @@ /* * 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.settings; import android.app.Activity; import android.app.AlarmManager; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.ListPopupWindow; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.TimePicker; import java.util.Calendar; import java.util.TimeZone; public class DateTimeSettingsSetupWizard extends Activity implements OnClickListener, OnItemClickListener, OnCheckedChangeListener, PreferenceFragment.OnPreferenceStartFragmentCallback { private static final String TAG = DateTimeSettingsSetupWizard.class.getSimpleName(); // force the first status of auto datetime flag. private static final String EXTRA_INITIAL_AUTO_DATETIME_VALUE = "extra_initial_auto_datetime_value"; // If we have enough screen real estate, we use a radically different layout with // big date and time pickers right on the screen, which requires very different handling. // Otherwise, we use the standard date time settings fragment. private boolean mUsingXLargeLayout; /* Available only in XL */ private CompoundButton mAutoDateTimeButton; // private CompoundButton mAutoTimeZoneButton; private Button mTimeZoneButton; private ListPopupWindow mTimeZonePopup; private SimpleAdapter mTimeZoneAdapter; private TimeZone mSelectedTimeZone; private TimePicker mTimePicker; private DatePicker mDatePicker; private InputMethodManager mInputMethodManager; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.date_time_settings_setupwizard); // we know we've loaded the special xlarge layout because it has controls // not present in the standard layout mUsingXLargeLayout = findViewById(R.id.time_zone_button) != null; if (mUsingXLargeLayout) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); initUiForXl(); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); findViewById(R.id.next_button).setOnClickListener(this); } mTimeZoneAdapter = ZonePicker.constructTimezoneAdapter(this, false, R.layout.date_time_setup_custom_list_item_2); final View layoutRoot = findViewById(R.id.layout_root); layoutRoot.setSystemUiVisibility(View.STATUS_BAR_DISABLE_BACK); } public void initUiForXl() { // Currently just comment out codes related to auto timezone. // TODO: Remove them when we are sure they are unnecessary. /* final boolean autoTimeZoneEnabled = isAutoTimeZoneEnabled(); mAutoTimeZoneButton = (CompoundButton)findViewById(R.id.time_zone_auto); mAutoTimeZoneButton.setChecked(autoTimeZoneEnabled); mAutoTimeZoneButton.setOnCheckedChangeListener(this); mAutoTimeZoneButton.setText(autoTimeZoneEnabled ? R.string.zone_auto_summaryOn : R.string.zone_auto_summaryOff);*/ final TimeZone tz = TimeZone.getDefault(); mSelectedTimeZone = tz; mTimeZoneButton = (Button)findViewById(R.id.time_zone_button); mTimeZoneButton.setText(tz.getDisplayName()); // mTimeZoneButton.setText(DateTimeSettings.getTimeZoneText(tz)); mTimeZoneButton.setOnClickListener(this); final boolean autoDateTimeEnabled; final Intent intent = getIntent(); if (intent.hasExtra(EXTRA_INITIAL_AUTO_DATETIME_VALUE)) { autoDateTimeEnabled = intent.getBooleanExtra(EXTRA_INITIAL_AUTO_DATETIME_VALUE, false); } else { autoDateTimeEnabled = isAutoDateTimeEnabled(); } mAutoDateTimeButton = (CompoundButton)findViewById(R.id.date_time_auto_button); mAutoDateTimeButton.setChecked(autoDateTimeEnabled); - ((TextView)findViewById(R.id.date_time_auto_text)) - .setText(autoDateTimeEnabled ? R.string.date_time_auto_summaryOn : - R.string.date_time_auto_summaryOff); mAutoDateTimeButton.setOnCheckedChangeListener(this); mTimePicker = (TimePicker)findViewById(R.id.time_picker); mTimePicker.setEnabled(!autoDateTimeEnabled); mDatePicker = (DatePicker)findViewById(R.id.date_picker); mDatePicker.setEnabled(!autoDateTimeEnabled); mDatePicker.setCalendarViewShown(false); mInputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); ((Button)findViewById(R.id.next_button)).setOnClickListener(this); final Button skipButton = (Button)findViewById(R.id.skip_button); if (skipButton != null) { skipButton.setOnClickListener(this); } } @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_TIME_TICK); filter.addAction(Intent.ACTION_TIME_CHANGED); filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); registerReceiver(mIntentReceiver, filter, null, null); } @Override public void onPause() { super.onPause(); unregisterReceiver(mIntentReceiver); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.time_zone_button: { showTimezonePicker(R.id.time_zone_button); break; } case R.id.next_button: { if (mSelectedTimeZone != null) { final TimeZone systemTimeZone = TimeZone.getDefault(); if (!systemTimeZone.equals(mSelectedTimeZone)) { Log.i(TAG, "Another TimeZone is selected by a user. Changing system TimeZone."); final AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarm.setTimeZone(mSelectedTimeZone.getID()); } } if (mAutoDateTimeButton != null) { Settings.System.putInt(getContentResolver(), Settings.System.AUTO_TIME, mAutoDateTimeButton.isChecked() ? 1 : 0); if (!mAutoDateTimeButton.isChecked()) { DateTimeSettings.setDate(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth()); DateTimeSettings.setTime( mTimePicker.getCurrentHour(), mTimePicker.getCurrentMinute()); } } } // $FALL-THROUGH$ case R.id.skip_button: { setResult(RESULT_OK); finish(); break; } } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final boolean autoEnabled = isChecked; // just for readibility. /*if (buttonView == mAutoTimeZoneButton) { // In XL screen, we save all the state only when the next button is pressed. if (!mUsingXLargeLayout) { Settings.System.putInt(getContentResolver(), Settings.System.AUTO_TIME_ZONE, isChecked ? 1 : 0); } mTimeZone.setEnabled(!autoEnabled); if (isChecked) { findViewById(R.id.current_time_zone).setVisibility(View.VISIBLE); findViewById(R.id.zone_picker).setVisibility(View.GONE); } } else */ if (buttonView == mAutoDateTimeButton) { Settings.System.putInt(getContentResolver(), Settings.System.AUTO_TIME, isChecked ? 1 : 0); mTimePicker.setEnabled(!autoEnabled); mDatePicker.setEnabled(!autoEnabled); } if (autoEnabled) { final View focusedView = getCurrentFocus(); if (focusedView != null) { mInputMethodManager.hideSoftInputFromWindow(focusedView.getWindowToken(), 0); focusedView.clearFocus(); } } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final TimeZone tz = ZonePicker.obtainTimeZoneFromItem(parent.getItemAtPosition(position)); if (mUsingXLargeLayout) { mSelectedTimeZone = tz; final Calendar now = Calendar.getInstance(tz); if (mTimeZoneButton != null) { mTimeZoneButton.setText(tz.getDisplayName()); } // mTimeZoneButton.setText(DateTimeSettings.getTimeZoneText(tz)); mDatePicker.updateDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)); mTimePicker.setCurrentHour(now.get(Calendar.HOUR_OF_DAY)); mTimePicker.setCurrentMinute(now.get(Calendar.MINUTE)); } else { // in prefs mode, we actually change the setting right now, as opposed to waiting // until Next is pressed in xLarge mode final AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarm.setTimeZone(tz.getID()); DateTimeSettings settingsFragment = (DateTimeSettings) getFragmentManager(). findFragmentById(R.id.date_time_settings_fragment); settingsFragment.updateTimeAndDateDisplay(this); } mTimeZonePopup.dismiss(); } /** * If this is called, that means we're in prefs style portrait mode for a large display * and the user has tapped on the time zone preference. If we were a PreferenceActivity, * we'd then launch the timezone fragment in a new activity, but we aren't, and here * on a tablet display, we really want more of a popup picker look' like the one we use * for the xlarge version of this activity. So we just take this opportunity to launch that. * * TODO: For phones, we might want to change this to do the "normal" opening * of the zonepicker fragment in its own activity. Or we might end up just * creating a separate DateTimeSettingsSetupWizardPhone activity that subclasses * PreferenceActivity in the first place to handle all that automatically. */ @Override public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) { showTimezonePicker(R.id.timezone_dropdown_anchor); return true; } private void showTimezonePicker(int anchorViewId) { View anchorView = findViewById(anchorViewId); if (anchorView == null) { Log.e(TAG, "Unable to find zone picker anchor view " + anchorViewId); return; } mTimeZonePopup = new ListPopupWindow(this, null); mTimeZonePopup.setWidth(anchorView.getWidth()); mTimeZonePopup.setAnchorView(anchorView); mTimeZonePopup.setAdapter(mTimeZoneAdapter); mTimeZonePopup.setOnItemClickListener(this); mTimeZonePopup.setModal(true); mTimeZonePopup.show(); } private boolean isAutoDateTimeEnabled() { try { return Settings.System.getInt(getContentResolver(), Settings.System.AUTO_TIME) > 0; } catch (SettingNotFoundException e) { return true; } } /* private boolean isAutoTimeZoneEnabled() { try { return Settings.System.getInt(getContentResolver(), Settings.System.AUTO_TIME_ZONE) > 0; } catch (SettingNotFoundException e) { return true; } }*/ private void updateTimeAndDateDisplay() { if (!mUsingXLargeLayout) { return; } final Calendar now = Calendar.getInstance(); mTimeZoneButton.setText(now.getTimeZone().getDisplayName()); mDatePicker.updateDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)); mTimePicker.setCurrentHour(now.get(Calendar.HOUR_OF_DAY)); mTimePicker.setCurrentMinute(now.get(Calendar.MINUTE)); } private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateTimeAndDateDisplay(); } }; }
true
true
public void initUiForXl() { // Currently just comment out codes related to auto timezone. // TODO: Remove them when we are sure they are unnecessary. /* final boolean autoTimeZoneEnabled = isAutoTimeZoneEnabled(); mAutoTimeZoneButton = (CompoundButton)findViewById(R.id.time_zone_auto); mAutoTimeZoneButton.setChecked(autoTimeZoneEnabled); mAutoTimeZoneButton.setOnCheckedChangeListener(this); mAutoTimeZoneButton.setText(autoTimeZoneEnabled ? R.string.zone_auto_summaryOn : R.string.zone_auto_summaryOff);*/ final TimeZone tz = TimeZone.getDefault(); mSelectedTimeZone = tz; mTimeZoneButton = (Button)findViewById(R.id.time_zone_button); mTimeZoneButton.setText(tz.getDisplayName()); // mTimeZoneButton.setText(DateTimeSettings.getTimeZoneText(tz)); mTimeZoneButton.setOnClickListener(this); final boolean autoDateTimeEnabled; final Intent intent = getIntent(); if (intent.hasExtra(EXTRA_INITIAL_AUTO_DATETIME_VALUE)) { autoDateTimeEnabled = intent.getBooleanExtra(EXTRA_INITIAL_AUTO_DATETIME_VALUE, false); } else { autoDateTimeEnabled = isAutoDateTimeEnabled(); } mAutoDateTimeButton = (CompoundButton)findViewById(R.id.date_time_auto_button); mAutoDateTimeButton.setChecked(autoDateTimeEnabled); ((TextView)findViewById(R.id.date_time_auto_text)) .setText(autoDateTimeEnabled ? R.string.date_time_auto_summaryOn : R.string.date_time_auto_summaryOff); mAutoDateTimeButton.setOnCheckedChangeListener(this); mTimePicker = (TimePicker)findViewById(R.id.time_picker); mTimePicker.setEnabled(!autoDateTimeEnabled); mDatePicker = (DatePicker)findViewById(R.id.date_picker); mDatePicker.setEnabled(!autoDateTimeEnabled); mDatePicker.setCalendarViewShown(false); mInputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); ((Button)findViewById(R.id.next_button)).setOnClickListener(this); final Button skipButton = (Button)findViewById(R.id.skip_button); if (skipButton != null) { skipButton.setOnClickListener(this); } }
public void initUiForXl() { // Currently just comment out codes related to auto timezone. // TODO: Remove them when we are sure they are unnecessary. /* final boolean autoTimeZoneEnabled = isAutoTimeZoneEnabled(); mAutoTimeZoneButton = (CompoundButton)findViewById(R.id.time_zone_auto); mAutoTimeZoneButton.setChecked(autoTimeZoneEnabled); mAutoTimeZoneButton.setOnCheckedChangeListener(this); mAutoTimeZoneButton.setText(autoTimeZoneEnabled ? R.string.zone_auto_summaryOn : R.string.zone_auto_summaryOff);*/ final TimeZone tz = TimeZone.getDefault(); mSelectedTimeZone = tz; mTimeZoneButton = (Button)findViewById(R.id.time_zone_button); mTimeZoneButton.setText(tz.getDisplayName()); // mTimeZoneButton.setText(DateTimeSettings.getTimeZoneText(tz)); mTimeZoneButton.setOnClickListener(this); final boolean autoDateTimeEnabled; final Intent intent = getIntent(); if (intent.hasExtra(EXTRA_INITIAL_AUTO_DATETIME_VALUE)) { autoDateTimeEnabled = intent.getBooleanExtra(EXTRA_INITIAL_AUTO_DATETIME_VALUE, false); } else { autoDateTimeEnabled = isAutoDateTimeEnabled(); } mAutoDateTimeButton = (CompoundButton)findViewById(R.id.date_time_auto_button); mAutoDateTimeButton.setChecked(autoDateTimeEnabled); mAutoDateTimeButton.setOnCheckedChangeListener(this); mTimePicker = (TimePicker)findViewById(R.id.time_picker); mTimePicker.setEnabled(!autoDateTimeEnabled); mDatePicker = (DatePicker)findViewById(R.id.date_picker); mDatePicker.setEnabled(!autoDateTimeEnabled); mDatePicker.setCalendarViewShown(false); mInputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); ((Button)findViewById(R.id.next_button)).setOnClickListener(this); final Button skipButton = (Button)findViewById(R.id.skip_button); if (skipButton != null) { skipButton.setOnClickListener(this); } }
diff --git a/org.jcryptool.core/src/org/jcryptool/core/Application.java b/org.jcryptool.core/src/org/jcryptool/core/Application.java index e0f28ab7..f2788b8b 100644 --- a/org.jcryptool.core/src/org/jcryptool/core/Application.java +++ b/org.jcryptool.core/src/org/jcryptool/core/Application.java @@ -1,71 +1,71 @@ // -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2008 JCrypTool Team and Contributors * * 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 *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.core; import java.util.Locale; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; /** * This class controls all aspects of the application's execution * * @author Dominik Schadow * @version 1.0.0 */ public class Application implements IApplication { /* * (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) */ public Object start(IApplicationContext context) throws Exception { try { - if (Locale.getDefault() != Locale.GERMAN && Locale.getDefault() != Locale.ENGLISH) { + if (!Locale.GERMAN.equals(Locale.getDefault()) && !Locale.ENGLISH.equals(Locale.getDefault())) { System.setProperty("osgi.nl", "en"); // fixes Platform.getNL() Locale.setDefault(Locale.ENGLISH); } } catch (Exception e) { e.printStackTrace(); } Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) return IApplication.EXIT_RESTART; else return IApplication.EXIT_OK; } finally { display.dispose(); } } /* * (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#stop() */ public void stop() { final IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench == null) return; final Display display = workbench.getDisplay(); display.syncExec(new Runnable() { public void run() { if (!display.isDisposed()) workbench.close(); } }); } }
true
true
public Object start(IApplicationContext context) throws Exception { try { if (Locale.getDefault() != Locale.GERMAN && Locale.getDefault() != Locale.ENGLISH) { System.setProperty("osgi.nl", "en"); // fixes Platform.getNL() Locale.setDefault(Locale.ENGLISH); } } catch (Exception e) { e.printStackTrace(); } Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) return IApplication.EXIT_RESTART; else return IApplication.EXIT_OK; } finally { display.dispose(); } }
public Object start(IApplicationContext context) throws Exception { try { if (!Locale.GERMAN.equals(Locale.getDefault()) && !Locale.ENGLISH.equals(Locale.getDefault())) { System.setProperty("osgi.nl", "en"); // fixes Platform.getNL() Locale.setDefault(Locale.ENGLISH); } } catch (Exception e) { e.printStackTrace(); } Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) return IApplication.EXIT_RESTART; else return IApplication.EXIT_OK; } finally { display.dispose(); } }
diff --git a/pact/pact-common/src/main/java/eu/stratosphere/pact/common/type/PactRecord.java b/pact/pact-common/src/main/java/eu/stratosphere/pact/common/type/PactRecord.java index d98812045..a5ef4c7b0 100644 --- a/pact/pact-common/src/main/java/eu/stratosphere/pact/common/type/PactRecord.java +++ b/pact/pact-common/src/main/java/eu/stratosphere/pact/common/type/PactRecord.java @@ -1,1642 +1,1642 @@ /*********************************************************************************************************************** * * Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **********************************************************************************************************************/ package eu.stratosphere.pact.common.type; import java.io.DataInput; import java.io.DataOutput; import java.io.EOFException; import java.io.IOException; import java.io.UTFDataFormatException; import java.util.Iterator; import java.util.List; import eu.stratosphere.nephele.services.memorymanager.DataOutputView; import eu.stratosphere.nephele.services.memorymanager.MemorySegment; import eu.stratosphere.pact.common.util.InstantiationUtil; /** * The Pact Record is the basic data record that flows between functions in a Pact program. The record is a tuple of * arbitrary values. * * <p> * The Pact Record implements a sparse tuple model, meaning that the record can contain many fields which are actually * null and not represented in the record. It has internally a bitmap marking which fields are set and which are not. * * This class is NOT thread-safe! * * @author Stephan Ewen ([email protected]) */ public final class PactRecord implements Value { private static final int NULL_INDICATOR_OFFSET = Integer.MIN_VALUE; // value marking a field as null private static final int MODIFIED_INDICATOR_OFFSET = Integer.MIN_VALUE + 1; // value marking field as modified // private static final int DEFAULT_FIELD_LEN = 8; // length estimate for bin array // -------------------------------------------------------------------------------------------- private final InternalDeSerializer serializer = new InternalDeSerializer(); // DataInput and DataOutput abstraction private byte[] binaryData; // the buffer containing the binary representation private byte[] switchBuffer; // the buffer containing the binary representation private int[] offsets; // the offsets to the binary representations of the fields private int[] lengths; // the lengths of the fields private Value[] readFields; // the cache for objects into which the binary representations are read private Value[] writeFields; // the cache for objects into which the binary representations are read private int binaryLen; // the length of the contents in the binary buffer that is valid private int numFields; // the number of fields in the record private int firstModifiedPos = Integer.MAX_VALUE; // position of the first modification (since (de)serialization) // -------------------------------------------------------------------------------------------- /** * Required nullary constructor for instantiation by serialization logic. */ public PactRecord() {} /** * Creates a new record containing only a single field, which is the given value. * * @param value The value for the single field of the record. */ public PactRecord(Value value) { setField(0, value); } /** * Creates a new record containing exactly to fields, which are the given values. * * @param val1 The value for the first field. * @param val2 The value for the second field. */ public PactRecord(Value val1, Value val2) { makeSpace(2); setField(0, val1); setField(1, val2); } /** * Creates a new pact record, containing the given number of fields. The fields are initially all nulls. * * @param numFields The number of fields for the record. */ public PactRecord(int numFields) { setNumFields(numFields); } // -------------------------------------------------------------------------------------------- // Basic Accessors // -------------------------------------------------------------------------------------------- /** * Gets the number of fields currently in the record. This also includes null fields. * * @return The number of fields in the record. */ public int getNumFields() { return this.numFields; } /** * Sets the number of fields in the record. If the new number of fields is longer than the current number of * fields, then null fields are appended. If the new number of fields is smaller than the current number of * fields, then the last fields are truncated. * * @param numFields The new number of fields. */ public void setNumFields(final int numFields) { final int oldNumFields = this.numFields; // check whether we increase or decrease the fields if (numFields > oldNumFields) { makeSpace(numFields); for (int i = oldNumFields; i < numFields; i++) { this.offsets[i] = NULL_INDICATOR_OFFSET; } markModified(oldNumFields); } else { // decrease the number of fields // we do not remove the values from the cache, as the objects (if they are there) will most likely // be reused when the record is re-filled markModified(numFields); } this.numFields = numFields; } /** * Reserves space for at least the given number of fields in the internal arrays. * * @param numFields The number of fields to reserve space for. */ public void makeSpace(int numFields) { final int oldNumFields = this.numFields; // increase the number of fields in the arrays if (this.offsets == null) { this.offsets = new int[numFields]; } else if (this.offsets.length < numFields) { int[] newOffs = new int[Math.max(numFields + 1, oldNumFields << 1)]; System.arraycopy(this.offsets, 0, newOffs, 0, oldNumFields); this.offsets = newOffs; } if (this.lengths == null) { this.lengths = new int[numFields]; } else if (this.lengths.length < numFields) { int[] newLens = new int[Math.max(numFields + 1, oldNumFields << 1)]; System.arraycopy(this.lengths, 0, newLens, 0, oldNumFields); this.lengths = newLens; } if (this.readFields == null) { this.readFields = new Value[numFields]; } else if (this.readFields.length < numFields) { Value[] newFields = new Value[Math.max(numFields + 1, oldNumFields << 1)]; System.arraycopy(this.readFields, 0, newFields, 0, oldNumFields); this.readFields = newFields; } if (this.writeFields == null) { this.writeFields = new Value[numFields]; } else if (this.writeFields.length < numFields) { Value[] newFields = new Value[Math.max(numFields + 1, oldNumFields << 1)]; System.arraycopy(this.writeFields, 0, newFields, 0, oldNumFields); this.writeFields = newFields; } } /** * Gets the field at the given position from the record. This method checks internally, if this instance of * the record has previously returned a value for this field. If so, it reuses the object, if not, it * creates one from the supplied class. * * @param <T> The type of the field. * * @param fieldNum The logical position of the field. * @param type The type of the field as a class. This class is used to instantiate a value object, if none had * previously been instantiated. * @return The field at the given position, or null, if the field was null. * @throws IndexOutOfBoundsException Thrown, if the field number is negative or larger or equal to the number of * fields in this record. */ @SuppressWarnings("unchecked") public <T extends Value> T getField(final int fieldNum, final Class<T> type) { // range check if (fieldNum < 0 || fieldNum >= this.numFields) { throw new IndexOutOfBoundsException(); } // get offset and check for null final int offset = this.offsets[fieldNum]; if (offset == NULL_INDICATOR_OFFSET) { return null; } else if (offset == MODIFIED_INDICATOR_OFFSET) { // value that has been set is new or modified return (T) this.writeFields[fieldNum]; } final int limit = offset + this.lengths[fieldNum]; // get an instance, either from the instance cache or create a new one final Value oldField = this.readFields[fieldNum]; final T field; if (oldField != null && oldField.getClass() == type) { field = (T) oldField; } else { field = InstantiationUtil.instantiate(type, Value.class); this.readFields[fieldNum] = field; } // deserialize deserialize(field, offset, limit, fieldNum); return field; } /** * Gets the field at the given position. The method tries to deserialize the fields into the given target value. * If the fields has been changed since the last (de)serialization, or is null, them the target value is left * unchanged and the changed value (or null) is returned. * <p> * In all cases, the returned value contains the correct data (or is correctly null). * * @param fieldNum The position of the field. * @param target The value to deserialize the field into. * * @return The value with the contents of the requested field, or null, if the field is null. */ @SuppressWarnings("unchecked") public <T extends Value> T getField(int fieldNum, T target) { // range check if (fieldNum < 0 || fieldNum >= this.numFields) throw new IndexOutOfBoundsException(); if (target == null) throw new NullPointerException("The target object may not be null"); // get offset and check for null int offset = this.offsets[fieldNum]; if (offset == NULL_INDICATOR_OFFSET) { return null; } else if (offset == MODIFIED_INDICATOR_OFFSET) { // value that has been set is new or modified // bring the binary in sync so that the deserialization gives the correct result return (T) this.writeFields[fieldNum]; } final int limit = offset + this.lengths[fieldNum]; deserialize(target, offset, limit, fieldNum); return target; } /** * Gets the field at the given position. If the field at that position is null, then this method leaves * the target field unchanged and returns false. * * @param fieldNum The position of the field. * @param target The value to deserialize the field into. * @return True, if the field was deserialized properly, false, if the field was null. */ public boolean getFieldInto(int fieldNum, Value target) { // range check if (fieldNum < 0 || fieldNum >= this.numFields) { throw new IndexOutOfBoundsException(); } // get offset and check for null int offset = this.offsets[fieldNum]; if (offset == NULL_INDICATOR_OFFSET) { return false; } else if (offset == MODIFIED_INDICATOR_OFFSET) { // value that has been set is new or modified // bring the binary in sync so that the deserialization gives the correct result updateBinaryRepresenation(); offset = this.offsets[fieldNum]; } final int limit = offset + this.lengths[fieldNum]; deserialize(target, offset, limit, fieldNum); return true; } /** * @param positions * @param targets * @return */ public boolean getFieldsInto(int[] positions, Value[] targets) { for (int i = 0; i < positions.length; i++) { if (!getFieldInto(positions[i], targets[i])) return false; } return true; } /** * @param positions * @param targets * @return */ public void getFieldsIntoCheckingNull(int[] positions, Value[] targets) { for (int i = 0; i < positions.length; i++) { if (!getFieldInto(positions[i], targets[i])) throw new NullKeyFieldException(i); } } /** * Deserializes the given object from the binary string, starting at the given position. * If the deserialization asks for more that <code>limit - offset</code> bytes, than * an exception is thrown. * * @param <T> The generic type of the value to be deserialized. * @param target The object to deserialize the data into. * @param offset The offset in the binary string. * @param limit The limit in the binary string. */ private final <T extends Value> void deserialize(T target, int offset, int limit, int fieldNumber) { final InternalDeSerializer serializer = this.serializer; serializer.memory = this.binaryData; serializer.position = offset; serializer.end = limit; try { target.read(serializer); } catch (Exception e) { throw new DeserializationException("Error reading field " + fieldNumber + " as " + target.getClass().getName(), e); } } /** * Sets the field at the given position to the given value. If the field position is larger or equal than * the current number of fields in the record, than the record is expanded to host as many columns. * <p> * The value is kept as a reference in the record until the binary representation is synchronized. Until that * point, all modifications to the value's object will change the value inside the record. * <p> * The binary representation is synchronized the latest when the record is emitted. It may be triggered * manually at an earlier point, but it is generally not necessary and advisable. Because the synchronization * triggers the serialization on all modified values, it may be an expensive operation. * * @param fieldNum The position of the field, starting at zero. * @param value The new value. */ public void setField(int fieldNum, Value value) { // range check if (fieldNum < 0) throw new IndexOutOfBoundsException(); // if the field number is beyond the size, the tuple is expanded if (fieldNum >= this.numFields) { setNumFields(fieldNum + 1); } internallySetField(fieldNum, value); } /** * @param value */ public void addField(Value value) { final int num = this.numFields; setNumFields(num + 1); internallySetField(num, value); } // /** // * Inserts a field into the record at the specified position. // * // * @param position Position of the new field in the record. // * @param value Value to be inserted. // * // * @throws IndexOutOfBoundsException Thrown, when the position is not between 0 (inclusive) and the // * number of fields (exclusive). // */ // public void insertField(int position, Value value) // { // // range check // if (position < 0 || position > this.numFields) { // throw new IndexOutOfBoundsException(); // } // final int oldNumFields = this.numFields; // setNumFields(oldNumFields + 1); // // // shift the offsets, lengths and fields in order to make space for the new field // final int len = oldNumFields - position; // System.arraycopy(this.offsets, position, this.offsets, position + 1, len); // System.arraycopy(this.lengths, position, this.lengths, position + 1, len); // System.arraycopy(this.fields, position, this.fields, position + 1, len); // // // Set the field at given position to given value and mark as modified // internallySetField(position, value); // } private final void internallySetField(int fieldNum, Value value) { // check if we modify an existing field this.offsets[fieldNum] = value != null ? MODIFIED_INDICATOR_OFFSET : NULL_INDICATOR_OFFSET; this.writeFields[fieldNum] = value; markModified(fieldNum); } private final void markModified(int field) { if (this.firstModifiedPos > field) { this.firstModifiedPos = field; } } // /** // * Removes the field at the given position. // * // * @param field The index number of the field to be removed. // * @throws IndexOutOfBoundsException Thrown, when the position is not between 0 (inclusive) and the // * number of fields (exclusive). // */ // public void removeField(int field) // { // // range check // if (field < 0 || field >= this.numFields) { // throw new IndexOutOfBoundsException(); // } // int lastIndex = this.numFields - 1; // // if (field < lastIndex) { // int len = lastIndex - field; // System.arraycopy(this.offsets, field + 1, this.offsets, field, len); // System.arraycopy(this.lengths, field + 1, this.lengths, field, len); // System.arraycopy(this.fields, field + 1, this.fields, field, len); // markModified(field); // } // this.offsets[lastIndex] = NULL_INDICATOR_OFFSET; // this.lengths[lastIndex] = 0; // this.fields[lastIndex] = null; // // setNumFields(lastIndex); // } // /** // * Projects (deletes) the record using the given bit mask. The bits correspond to the individual columns: // * <code>(1 == keep, 0 == delete)</code>. // * <p> // * <b>Only use when record has not more than 64 fields!</b> // * // * @param mask The bitmask used for the projection. The i-th bit corresponds to the i-th // * field in the record, starting with the least significant bit. // */ // public void project(long mask) // { // final int oldNumFields = this.numFields; // int index = 0; // // for (int i = 0; i < oldNumFields; i++) { // if ((mask & 0x1L) == 0) { // this.removeField(index); // } // else { // index++; // } // mask >>>= 1; // } // } // /** // * Projects (deletes) the record using the given bit mask. The bits correspond to the individual columns: // * <code>(1 == keep, 0 == delete)</code>. // * // * @param mask The bit masks used for the projection. The i-th bit in the n-th mask corresponds to the // * <code>(n * 64) + i</code>-th field in the record, starting with the least significant bit. // */ // public void project(long[] mask) // { // long curMask = 0; // int offset = 0; // long tmp = 0; // int len = 0; // int index = 0; // int oldNumFields = this.numFields; // // for (int k = 0; k < mask.length; k++) { // curMask = mask[k]; // offset = k * Long.SIZE; // len = ((offset + Long.SIZE) < oldNumFields) ? Long.SIZE : oldNumFields - offset; // // for (int l = 0; l < len; l++) { // tmp = (1L << l) & curMask; // // if (tmp == 0) { // this.removeField(index); // } // else { // index++; // } // } // } // } /** * Sets the field at the given position to <code>null</code>. * * @param field The field index. * @throws IndexOutOfBoundsException Thrown, when the position is not between 0 (inclusive) and the * number of fields (exclusive). */ public void setNull(int field) { // range check if (field < 0 || field >= this.numFields) { throw new IndexOutOfBoundsException(); } internallySetField(field, null); } /** * Sets the fields to <code>null</code> using the given bit mask. * The bits correspond to the individual columns: <code>(1 == nullify, 0 == keep)</code>. * * @param mask Bit mask, where the i-th least significant bit represents the i-th field in the record. */ public void setNull(long mask) { for (int i = 0; i < this.numFields; i++, mask >>>= 1) { if ((mask & 0x1) != 0) internallySetField(i, null); } } /** * Sets the fields to <code>null</code> using the given bit mask. * The bits correspond to the individual columns: <code>(1 == nullify, 0 == keep)</code>. * * @param mask Bit mask, where the i-th least significant bit in the n-th bit mask represents the * <code>(n*64) + i</code>-th field in the record. */ public void setNull(long[] mask) { for (int maskPos = 0, i = 0; i < this.numFields;) { long currMask = mask[maskPos]; for (int k = 64; i < this.numFields && k > 0; --k, i++, currMask >>>= 1) { if ((currMask & 0x1) != 0) internallySetField(i, null); } } } /** * Clears the record. After this operation, the record will have zero fields. */ public void clear() { if (this.numFields > 0) { this.numFields = 0; this.firstModifiedPos = -1; } } public void concatenate(PactRecord record) { throw new UnsupportedOperationException(); } /** * @param other */ public void unionFields(PactRecord other) { throw new UnsupportedOperationException(); } /** * @param target */ public void copyToIfModified(PactRecord target) { copyTo(target); } /** * @param target */ public void copyTo(PactRecord target) { updateBinaryRepresenation(); if (target.binaryData == null || target.binaryData.length < this.binaryLen) { target.binaryData = new byte[this.binaryLen]; } if (target.offsets == null || target.offsets.length < this.numFields) { target.offsets = new int[this.numFields]; } if (target.lengths == null || target.lengths.length < this.numFields) { target.lengths = new int[this.numFields]; } if (target.readFields == null || target.readFields.length < this.numFields) { target.readFields = new Value[this.numFields]; } if (target.writeFields == null || target.writeFields.length < this.numFields) { target.writeFields = new Value[this.numFields]; } System.arraycopy(this.binaryData, 0, target.binaryData, 0, this.binaryLen); System.arraycopy(this.offsets, 0, target.offsets, 0, this.numFields); System.arraycopy(this.lengths, 0, target.lengths, 0, this.numFields); target.binaryLen = this.binaryLen; target.numFields = this.numFields; target.firstModifiedPos = Integer.MAX_VALUE; } /** * Creates an exact copy of this record. * * @return An exact copy of this record. */ public PactRecord createCopy() { final PactRecord rec = new PactRecord(); copyTo(rec); return rec; } // -------------------------------------------------------------------------------------------- /** * @param positions * @param searchValues * @param deserializationHolders * @return */ public final boolean equalsFields(int[] positions, Value[] searchValues, Value[] deserializationHolders) { for (int i = 0; i < positions.length; i++) { final Value v = getField(positions[i], deserializationHolders[i]); if (v == null || (!v.equals(searchValues[i]))) { return false; } } return true; } // -------------------------------------------------------------------------------------------- /** * Updates the binary representation of the data, such that it reflects the state of the currently * stored fields. If the binary representation is already up to date, nothing happens. Otherwise, * this function triggers the modified fields to serialize themselves into the records buffer and * afterwards updates the offset table. */ public void updateBinaryRepresenation() { // check whether the binary state is in sync final int firstModified = this.firstModifiedPos < 0 ? 0 : this.firstModifiedPos; if (firstModified == Integer.MAX_VALUE) return; final InternalDeSerializer serializer = this.serializer; final int[] offsets = this.offsets; final int numFields = this.numFields; if (numFields > 0) { int offset = 0; if (firstModified > 0) { // search backwards to find the latest preceeding non-null field for (int i = firstModified - 1; i >= 0; i--) { if (this.offsets[i] != NULL_INDICATOR_OFFSET) { offset = this.offsets[i] + this.lengths[i]; break; } } } serializer.memory = this.switchBuffer != null ? this.switchBuffer : new byte[numFields * 8]; - serializer.position = offset; + serializer.position = 0; // we assume that changed and unchanged fields are interleaved and serialize into another array - if (offset > 0) { - // copy the first unchanged portion as one - System.arraycopy(this.binaryData, 0, serializer.memory, 0, offset); - } try { + if (offset > 0) { + // copy the first unchanged portion as one + serializer.write(this.binaryData, 0, offset); + } // copy field by field for (int i = firstModified; i < numFields; i++) { final int co = offsets[i]; /// skip null fields if (co == NULL_INDICATOR_OFFSET) continue; offsets[i] = offset; if (co == MODIFIED_INDICATOR_OFFSET) // serialize modified fields this.writeFields[i].write(serializer); else // bin-copy unmodified fields serializer.write(this.binaryData, co, this.lengths[i]); this.lengths[i] = serializer.position - offset; offset = serializer.position; } } catch (Exception e) { throw new RuntimeException("Error in data type serialization: " + e.getMessage(), e); } this.switchBuffer = this.binaryData; this.binaryData = serializer.memory; } try { int slp = serializer.position; // track the last position of the serializer // now, serialize the lengths, the sparsity mask and the number of fields if (numFields <= 8) { // efficient handling of common case with up to eight fields int mask = 0; for (int i = numFields - 1; i > 0; i--) { if (offsets[i] != NULL_INDICATOR_OFFSET) { slp = serializer.position; serializer.writeValLenIntBackwards(offsets[i]); mask |= 0x1; } mask <<= 1; } if (offsets[0] != NULL_INDICATOR_OFFSET) { mask |= 0x1; // add the non-null bit to the mask } else { // the first field is null, so some previous field was the first non-null field serializer.position = slp; } serializer.writeByte(mask); } else { // general case. offsets first (in backward order) for (int i = numFields - 1; i > 0; i--) { if (offsets[i] != NULL_INDICATOR_OFFSET) { slp = serializer.position; serializer.writeValLenIntBackwards(offsets[i]); } } if (offsets[0] == NULL_INDICATOR_OFFSET) { serializer.position = slp; } // now the mask. we write it in chucks of 8 bit. // the remainder %8 comes first int col = numFields - 1; int mask = 0; int i = numFields & 0x7; if (i > 0) { for (; i > 0; i--, col--) { mask <<= 1; mask |= (offsets[col] != NULL_INDICATOR_OFFSET) ? 0x1 : 0x0; } serializer.writeByte(mask); } // now the eight-bit chunks for (i = numFields >>> 3; i > 0; i--) { mask = 0; for (int k = 0; k < 8; k++, col--) { mask <<= 1; mask |= (offsets[col] != NULL_INDICATOR_OFFSET) ? 0x1 : 0x0; } serializer.writeByte(mask); } } serializer.writeValLenIntBackwards(numFields); } catch (Exception e) { throw new RuntimeException("Serialization into binary state failed: " + e.getMessage(), e); } // set the fields this.binaryData = serializer.memory; this.binaryLen = serializer.position; this.firstModifiedPos = Integer.MAX_VALUE; } // -------------------------------------------------------------------------------------------- // Serialization // -------------------------------------------------------------------------------------------- /* (non-Javadoc) * @see eu.stratosphere.nephele.io.IOReadableWritable#write(java.io.DataOutput) */ @Override public void write(DataOutput out) throws IOException { // make sure everything is in a valid binary representation updateBinaryRepresenation(); // write the length first, variably encoded, then the contents of the binary array writeVarLengthInt(out, this.binaryLen); out.write(this.binaryData, 0, this.binaryLen); } /* (non-Javadoc) * @see eu.stratosphere.nephele.io.IOReadableWritable#read(java.io.DataInput) */ @Override public void read(DataInput in) throws IOException { final int len = readVarLengthInt(in); this.binaryLen = len; // ensure out byte array is large enough byte[] data = this.binaryData; if (data == null || data.length < len) { data = new byte[len]; this.binaryData = data; } // read the binary data in.readFully(data, 0, len); initFields(data, 0, len); } private final void initFields(byte[] data, int begin, int len) { // read number of fields, variable length encoded reverse at the back int pos = begin + len - 2; int numFields = data[begin + len - 1] & 0xFF; if (numFields >= MAX_BIT) { int shift = 7; int curr; numFields = numFields & 0x7f; while ((curr = data[pos--]) >= MAX_BIT) { numFields |= (curr & 0x7f) << shift; shift += 7; } numFields |= curr << shift; } this.numFields = numFields; // ensure that all arrays are there and of sufficient size if (this.offsets == null || this.offsets.length < numFields) { this.offsets = new int[numFields]; } if (this.lengths == null || this.lengths.length < numFields) { this.lengths = new int[numFields]; } if (this.readFields == null || this.readFields.length < numFields) { this.readFields = new Value[numFields]; } if (this.writeFields == null || this.writeFields.length < numFields) { this.writeFields = new Value[numFields]; } final int beginMasks = pos; // beginning of bitmap for null fields final int fieldsBy8 = (numFields >>> 3) + ((numFields & 0x7) == 0 ? 0 : 1); pos = beginMasks - fieldsBy8; int lastNonNullField = -1; for (int field = 0, chunk = 0; chunk < fieldsBy8; chunk++) { int mask = data[beginMasks - chunk]; for (int i = 0; i < 8 && field < numFields; i++, field++) { if ((mask & 0x1) == 0x1) { // not null, so read the offset value, if we are not the first non-null fields if (lastNonNullField >= 0) { // offset value is variable length encoded int start = data[pos--] & 0xff; if (start >= MAX_BIT) { int shift = 7; int curr; start = start & 0x7f; while ((curr = data[pos--] & 0xff) >= MAX_BIT) { start |= (curr & 0x7f) << shift; shift += 7; } start |= curr << shift; } this.offsets[field] = start + begin; this.lengths[lastNonNullField] = start + begin - this.offsets[lastNonNullField]; } else { this.offsets[field] = begin; } lastNonNullField = field; } else { // field is null this.offsets[field] = NULL_INDICATOR_OFFSET; } mask >>= 1; } } if (lastNonNullField >= 0) { this.lengths[lastNonNullField] = pos - this.offsets[lastNonNullField] + 1; } this.firstModifiedPos = Integer.MAX_VALUE; } /** * @param fields * @param holders * @param binData * @param offset * @return */ public boolean readBinary(int[] fields, Value[] holders, byte[] binData, int offset) { // read the length int val = binData[offset++] & 0xff; if (val >= MAX_BIT) { int shift = 7; int curr; val = val & 0x7f; while ((curr = binData[offset++] & 0xff) >= MAX_BIT) { val |= (curr & 0x7f) << shift; shift += 7; } val |= curr << shift; } // initialize the fields this.binaryData = binData; initFields(binData, offset, val); // get the values return getFieldsInto(fields, holders); } /** * @param fields * @param holders * @param memory * @param firstSegment * @param offset * @return */ public boolean readBinary(int[] fields, Value[] holders, List<MemorySegment> memory, int firstSegment, int offset) { deserialize(memory, firstSegment, offset); return getFieldsInto(fields, holders); } /** * @param record * @param target * @param furtherBuffers * @param targetForUsedFurther * @return * @throws IOException */ public long serialize(PactRecord record, DataOutputView target, Iterator<MemorySegment> furtherBuffers, List<MemorySegment> targetForUsedFurther) throws IOException { updateBinaryRepresenation(); long bytesForLen = 1; if (target.getRemainingBytes() >= this.binaryLen + 5) { int len = this.binaryLen; while (len >= MAX_BIT) { target.write(len | MAX_BIT); len >>= 7; bytesForLen++; } target.write(len); target.write(this.binaryData, 0, this.binaryLen); } else { // need to span multiple buffers if (target.getRemainingBytes() < 6) { // span var-length-int int len = this.binaryLen; while (len >= MAX_BIT) { if (target.getRemainingBytes() == 0) { target = getNextBuffer(furtherBuffers, targetForUsedFurther); if (target == null) { return -1; } } target.write(len | MAX_BIT); len >>= 7; bytesForLen++; } if (target.getRemainingBytes() == 0) { target = getNextBuffer(furtherBuffers, targetForUsedFurther); if (target == null) { return -1; } } target.write(len); if (target.getRemainingBytes() == 0) { target = getNextBuffer(furtherBuffers, targetForUsedFurther); if (target == null) { return -1; } } } else { int len = this.binaryLen; while (len >= MAX_BIT) { target.write(len | MAX_BIT); len >>= 7; bytesForLen++; } target.write(len); } // now write the binary data int currOff = 0; while (true) { int toWrite = Math.min(this.binaryLen - currOff, target.getRemainingBytes()); target.write(this.binaryData, currOff, toWrite); currOff += toWrite; if (currOff < this.binaryLen) { target = getNextBuffer(furtherBuffers, targetForUsedFurther); if (target == null) { return -1; } } else { break; } } } return bytesForLen + this.binaryLen; } private final DataOutputView getNextBuffer(Iterator<MemorySegment> furtherBuffers, List<MemorySegment> targetForUsedFurther) { if (furtherBuffers.hasNext()) { MemorySegment seg = furtherBuffers.next(); targetForUsedFurther.add(seg); DataOutputView target = seg.outputView; return target; } else return null; } /** * @param sources * @param segmentNum * @param segmentOffset * @throws IOException */ public void deserialize(List<MemorySegment> sources, int segmentNum, int segmentOffset) { MemorySegment seg = sources.get(segmentNum); if (seg.size() - segmentOffset > 5) { int val = seg.get(segmentOffset++) & 0xff; if (val >= MAX_BIT) { int shift = 7; int curr; val = val & 0x7f; while ((curr = seg.get(segmentOffset++) & 0xff) >= MAX_BIT) { val |= (curr & 0x7f) << shift; shift += 7; } val |= curr << shift; } this.binaryLen = val; } else { int end = seg.size(); int val = seg.get(segmentOffset++) & 0xff; if (segmentOffset == end) { segmentOffset = 0; seg = sources.get(++segmentNum); } if (val >= MAX_BIT) { int shift = 7; int curr; val = val & 0x7f; while ((curr = seg.get(segmentOffset++) & 0xff) >= MAX_BIT) { val |= (curr & 0x7f) << shift; shift += 7; if (segmentOffset == end) { segmentOffset = 0; seg = sources.get(++segmentNum); } } val |= curr << shift; } this.binaryLen = val; if (segmentOffset == end) { segmentOffset = 0; seg = sources.get(++segmentNum); } } // read the binary representation if (this.binaryData == null || this.binaryData.length < this.binaryLen) { this.binaryData = new byte[this.binaryLen]; } int remaining = seg.size() - segmentOffset; if (remaining >= this.binaryLen) { seg.get(segmentOffset, this.binaryData, 0, this.binaryLen); } else { // read across segments int offset = 0; while (true) { int toRead = Math.min(seg.size() - segmentOffset, this.binaryLen - offset); seg.get(segmentOffset, this.binaryData, offset, toRead); offset += toRead; segmentOffset += toRead; if (offset < this.binaryLen) { segmentOffset = 0; seg = sources.get(++segmentNum); } else break; } } initFields(this.binaryData, 0, this.binaryLen); } // -------------------------------------------------------------------------------------------- // Utilities // -------------------------------------------------------------------------------------------- private static final void writeVarLengthInt(DataOutput out, int value) throws IOException { while (value >= MAX_BIT) { out.write(value | MAX_BIT); value >>= 7; } out.write(value); } private static final int readVarLengthInt(DataInput in) throws IOException { // read first byte int val = in.readUnsignedByte(); if (val >= MAX_BIT) { int shift = 7; int curr; val = val & 0x7f; while ((curr = in.readUnsignedByte()) >= MAX_BIT) { val |= (curr & 0x7f) << shift; shift += 7; } val |= curr << shift; } return val; } private static final int MAX_BIT = 0x1 << 7; // ------------------------------------------------------------------------ // Utility class for internal (de)serialization // ------------------------------------------------------------------------ /** * Internal interface class to provide serialization for the data types. * * @author Stephan Ewen */ private final class InternalDeSerializer implements DataInput, DataOutput { private byte[] memory; private int position; private int end; // ---------------------------------------------------------------------------------------- // Data Input // ---------------------------------------------------------------------------------------- @Override public boolean readBoolean() throws IOException { if (this.position < this.end) { return this.memory[this.position++] != 0; } else { throw new EOFException(); } } @Override public byte readByte() throws IOException { if (this.position < this.end) { return this.memory[this.position++]; } else { throw new EOFException(); } } @Override public char readChar() throws IOException { if (this.position < this.end - 1) { return (char) (((this.memory[this.position++] & 0xff) << 8) | ((this.memory[this.position++] & 0xff) << 0)); } else { throw new EOFException(); } } @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } @Override public void readFully(byte[] b) throws IOException { readFully(b, 0, b.length); } @Override public void readFully(byte[] b, int off, int len) throws IOException { if (this.position < this.end && this.position <= this.end - len && off <= b.length - len) { System.arraycopy(this.memory, position, b, off, len); position += len; } else { throw new EOFException(); } } @Override public int readInt() throws IOException { if (this.position >= 0 && this.position < this.end - 3) { return ((this.memory[position++] & 0xff) << 24) | ((this.memory[position++] & 0xff) << 16) | ((this.memory[position++] & 0xff) << 8) | ((this.memory[position++] & 0xff) << 0); } else { throw new EOFException(); } } @Override public String readLine() throws IOException { if (this.position < this.end) { // read until a newline is found StringBuilder bld = new StringBuilder(); char curr = readChar(); while (position < this.end && curr != '\n') { bld.append(curr); curr = readChar(); } // trim a trailing carriage return int len = bld.length(); if (len > 0 && bld.charAt(len - 1) == '\r') { bld.setLength(len - 1); } String s = bld.toString(); bld.setLength(0); return s; } else { return null; } } @Override public long readLong() throws IOException { if (position >= 0 && position < this.end - 7) { return (((long) this.memory[position++] & 0xff) << 56) | (((long) this.memory[position++] & 0xff) << 48) | (((long) this.memory[position++] & 0xff) << 40) | (((long) this.memory[position++] & 0xff) << 32) | (((long) this.memory[position++] & 0xff) << 24) | (((long) this.memory[position++] & 0xff) << 16) | (((long) this.memory[position++] & 0xff) << 8) | (((long) this.memory[position++] & 0xff) << 0); } else { throw new EOFException(); } } @Override public short readShort() throws IOException { if (position >= 0 && position < this.end - 1) { return (short) ((((this.memory[position++]) & 0xff) << 8) | (((this.memory[position++]) & 0xff) << 0)); } else { throw new EOFException(); } } @Override public String readUTF() throws IOException { int utflen = readUnsignedShort(); byte[] bytearr = new byte[utflen]; char[] chararr = new char[utflen]; int c, char2, char3; int count = 0; int chararr_count = 0; readFully(bytearr, 0, utflen); while (count < utflen) { c = (int) bytearr[count] & 0xff; if (c > 127) break; count++; chararr[chararr_count++] = (char) c; } while (count < utflen) { c = (int) bytearr[count] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: /* 0xxxxxxx */ count++; chararr[chararr_count++] = (char) c; break; case 12: case 13: /* 110x xxxx 10xx xxxx */ count += 2; if (count > utflen) throw new UTFDataFormatException("malformed input: partial character at end"); char2 = (int) bytearr[count - 1]; if ((char2 & 0xC0) != 0x80) throw new UTFDataFormatException("malformed input around byte " + count); chararr[chararr_count++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: /* 1110 xxxx 10xx xxxx 10xx xxxx */ count += 3; if (count > utflen) throw new UTFDataFormatException("malformed input: partial character at end"); char2 = (int) bytearr[count - 2]; char3 = (int) bytearr[count - 1]; if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) throw new UTFDataFormatException("malformed input around byte " + (count - 1)); chararr[chararr_count++] = (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; default: /* 10xx xxxx, 1111 xxxx */ throw new UTFDataFormatException("malformed input around byte " + count); } } // The number of chars produced may be less than utflen return new String(chararr, 0, chararr_count); } @Override public int readUnsignedByte() throws IOException { if (this.position < this.end) { return (this.memory[this.position++] & 0xff); } else { throw new EOFException(); } } @Override public int readUnsignedShort() throws IOException { if (this.position < this.end - 1) { return ((this.memory[this.position++] & 0xff) << 8) | ((this.memory[this.position++] & 0xff) << 0); } else { throw new EOFException(); } } @Override public int skipBytes(int n) throws IOException { if (this.position <= this.end - n) { this.position += n; return n; } else { n = this.end - this.position; this.position = this.end; return n; } } // ---------------------------------------------------------------------------------------- // Data Output // ---------------------------------------------------------------------------------------- @Override public void write(int b) throws IOException { if (this.position >= this.memory.length) { resize(1); } this.memory[this.position++] = (byte) (b & 0xff); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { if (len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } if (this.position > this.memory.length - len) { resize(len); } System.arraycopy(b, off, this.memory, this.position, len); this.position += len; } @Override public void writeBoolean(boolean v) throws IOException { write(v ? 1 : 0); } @Override public void writeByte(int v) throws IOException { write(v); } @Override public void writeBytes(String s) throws IOException { final int sLen = s.length(); if (this.position >= this.memory.length - sLen) { resize(sLen); } for (int i = 0; i < sLen; i++) { writeByte(s.charAt(i)); } this.position += sLen; } @Override public void writeChar(int v) throws IOException { if (this.position >= this.memory.length - 1) { resize(2); } this.memory[this.position++] = (byte) (v >> 8); this.memory[this.position++] = (byte) v; } @Override public void writeChars(String s) throws IOException { final int sLen = s.length(); if (this.position >= this.memory.length - 2*sLen) { resize(2*sLen); } for (int i = 0; i < sLen; i++) { writeChar(s.charAt(i)); } } @Override public void writeDouble(double v) throws IOException { writeLong(Double.doubleToLongBits(v)); } @Override public void writeFloat(float v) throws IOException { writeInt(Float.floatToIntBits(v)); } @Override public void writeInt(int v) throws IOException { if (this.position >= this.memory.length - 3) { resize(4); } this.memory[this.position++] = (byte) (v >> 24); this.memory[this.position++] = (byte) (v >> 16); this.memory[this.position++] = (byte) (v >> 8); this.memory[this.position++] = (byte) v; } @Override public void writeLong(long v) throws IOException { if (this.position >= this.memory.length - 7) { resize(8); } this.memory[this.position++] = (byte) (v >> 56); this.memory[this.position++] = (byte) (v >> 48); this.memory[this.position++] = (byte) (v >> 40); this.memory[this.position++] = (byte) (v >> 32); this.memory[this.position++] = (byte) (v >> 24); this.memory[this.position++] = (byte) (v >> 16); this.memory[this.position++] = (byte) (v >> 8); this.memory[this.position++] = (byte) v; } @Override public void writeShort(int v) throws IOException { if (this.position >= this.memory.length - 1) { resize(2); } this.memory[this.position++] = (byte) ((v >>> 8) & 0xff); this.memory[this.position++] = (byte) ((v >>> 0) & 0xff); } @Override public void writeUTF(String str) throws IOException { int strlen = str.length(); int utflen = 0; int c; /* use charAt instead of copying String to char array */ for (int i = 0; i < strlen; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { utflen++; } else if (c > 0x07FF) { utflen += 3; } else { utflen += 2; } } if (utflen > 65535) throw new UTFDataFormatException("Encoded string is too long: " + utflen); else if (this.position > this.memory.length - utflen - 2) { resize(utflen); } byte[] bytearr = this.memory; int count = this.position; bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF); bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF); int i = 0; for (i = 0; i < strlen; i++) { c = str.charAt(i); if (!((c >= 0x0001) && (c <= 0x007F))) break; bytearr[count++] = (byte) c; } for (; i < strlen; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { bytearr[count++] = (byte) c; } else if (c > 0x07FF) { bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F)); bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); } else { bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); } } this.position = count; } private final void writeValLenIntBackwards(int value) throws IOException { if (this.position > this.memory.length - 4) { resize(4); } if (value <= 0x7f) { this.memory[this.position++] = (byte) value; } else if (value <= 0x3fff) { this.memory[this.position++] = (byte) (value >>> 7); this.memory[this.position++] = (byte) (value | MAX_BIT); } else if (value <= 0x1fffff) { this.memory[this.position++] = (byte) (value >>> 14); this.memory[this.position++] = (byte) ((value >>> 7) | MAX_BIT); this.memory[this.position++] = (byte) (value | MAX_BIT); } else if (value <= 0xfffffff) { this.memory[this.position++] = (byte) ( value >>> 21); this.memory[this.position++] = (byte) ((value >>> 14) | MAX_BIT); this.memory[this.position++] = (byte) ((value >>> 7) | MAX_BIT); this.memory[this.position++] = (byte) (value | MAX_BIT); } else { this.memory[this.position++] = (byte) ( value >>> 28); this.memory[this.position++] = (byte) ((value >>> 21) | MAX_BIT); this.memory[this.position++] = (byte) ((value >>> 14) | MAX_BIT); this.memory[this.position++] = (byte) ((value >>> 7) | MAX_BIT); this.memory[this.position++] = (byte) (value | MAX_BIT); } } private final void resize(int minCapacityAdd) throws IOException { try { final int newLen = Math.max(this.memory.length * 2, this.memory.length + minCapacityAdd); final byte[] nb = new byte[newLen]; System.arraycopy(this.memory, 0, nb, 0, this.position); this.memory = nb; } catch (NegativeArraySizeException nasex) { throw new IOException("Serialization failed because the record length would exceed 2GB."); } } }; }
false
true
public void updateBinaryRepresenation() { // check whether the binary state is in sync final int firstModified = this.firstModifiedPos < 0 ? 0 : this.firstModifiedPos; if (firstModified == Integer.MAX_VALUE) return; final InternalDeSerializer serializer = this.serializer; final int[] offsets = this.offsets; final int numFields = this.numFields; if (numFields > 0) { int offset = 0; if (firstModified > 0) { // search backwards to find the latest preceeding non-null field for (int i = firstModified - 1; i >= 0; i--) { if (this.offsets[i] != NULL_INDICATOR_OFFSET) { offset = this.offsets[i] + this.lengths[i]; break; } } } serializer.memory = this.switchBuffer != null ? this.switchBuffer : new byte[numFields * 8]; serializer.position = offset; // we assume that changed and unchanged fields are interleaved and serialize into another array if (offset > 0) { // copy the first unchanged portion as one System.arraycopy(this.binaryData, 0, serializer.memory, 0, offset); } try { // copy field by field for (int i = firstModified; i < numFields; i++) { final int co = offsets[i]; /// skip null fields if (co == NULL_INDICATOR_OFFSET) continue; offsets[i] = offset; if (co == MODIFIED_INDICATOR_OFFSET) // serialize modified fields this.writeFields[i].write(serializer); else // bin-copy unmodified fields serializer.write(this.binaryData, co, this.lengths[i]); this.lengths[i] = serializer.position - offset; offset = serializer.position; } } catch (Exception e) { throw new RuntimeException("Error in data type serialization: " + e.getMessage(), e); } this.switchBuffer = this.binaryData; this.binaryData = serializer.memory; } try { int slp = serializer.position; // track the last position of the serializer // now, serialize the lengths, the sparsity mask and the number of fields if (numFields <= 8) { // efficient handling of common case with up to eight fields int mask = 0; for (int i = numFields - 1; i > 0; i--) { if (offsets[i] != NULL_INDICATOR_OFFSET) { slp = serializer.position; serializer.writeValLenIntBackwards(offsets[i]); mask |= 0x1; } mask <<= 1; } if (offsets[0] != NULL_INDICATOR_OFFSET) { mask |= 0x1; // add the non-null bit to the mask } else { // the first field is null, so some previous field was the first non-null field serializer.position = slp; } serializer.writeByte(mask); } else { // general case. offsets first (in backward order) for (int i = numFields - 1; i > 0; i--) { if (offsets[i] != NULL_INDICATOR_OFFSET) { slp = serializer.position; serializer.writeValLenIntBackwards(offsets[i]); } } if (offsets[0] == NULL_INDICATOR_OFFSET) { serializer.position = slp; } // now the mask. we write it in chucks of 8 bit. // the remainder %8 comes first int col = numFields - 1; int mask = 0; int i = numFields & 0x7; if (i > 0) { for (; i > 0; i--, col--) { mask <<= 1; mask |= (offsets[col] != NULL_INDICATOR_OFFSET) ? 0x1 : 0x0; } serializer.writeByte(mask); } // now the eight-bit chunks for (i = numFields >>> 3; i > 0; i--) { mask = 0; for (int k = 0; k < 8; k++, col--) { mask <<= 1; mask |= (offsets[col] != NULL_INDICATOR_OFFSET) ? 0x1 : 0x0; } serializer.writeByte(mask); } } serializer.writeValLenIntBackwards(numFields); } catch (Exception e) { throw new RuntimeException("Serialization into binary state failed: " + e.getMessage(), e); } // set the fields this.binaryData = serializer.memory; this.binaryLen = serializer.position; this.firstModifiedPos = Integer.MAX_VALUE; }
public void updateBinaryRepresenation() { // check whether the binary state is in sync final int firstModified = this.firstModifiedPos < 0 ? 0 : this.firstModifiedPos; if (firstModified == Integer.MAX_VALUE) return; final InternalDeSerializer serializer = this.serializer; final int[] offsets = this.offsets; final int numFields = this.numFields; if (numFields > 0) { int offset = 0; if (firstModified > 0) { // search backwards to find the latest preceeding non-null field for (int i = firstModified - 1; i >= 0; i--) { if (this.offsets[i] != NULL_INDICATOR_OFFSET) { offset = this.offsets[i] + this.lengths[i]; break; } } } serializer.memory = this.switchBuffer != null ? this.switchBuffer : new byte[numFields * 8]; serializer.position = 0; // we assume that changed and unchanged fields are interleaved and serialize into another array try { if (offset > 0) { // copy the first unchanged portion as one serializer.write(this.binaryData, 0, offset); } // copy field by field for (int i = firstModified; i < numFields; i++) { final int co = offsets[i]; /// skip null fields if (co == NULL_INDICATOR_OFFSET) continue; offsets[i] = offset; if (co == MODIFIED_INDICATOR_OFFSET) // serialize modified fields this.writeFields[i].write(serializer); else // bin-copy unmodified fields serializer.write(this.binaryData, co, this.lengths[i]); this.lengths[i] = serializer.position - offset; offset = serializer.position; } } catch (Exception e) { throw new RuntimeException("Error in data type serialization: " + e.getMessage(), e); } this.switchBuffer = this.binaryData; this.binaryData = serializer.memory; } try { int slp = serializer.position; // track the last position of the serializer // now, serialize the lengths, the sparsity mask and the number of fields if (numFields <= 8) { // efficient handling of common case with up to eight fields int mask = 0; for (int i = numFields - 1; i > 0; i--) { if (offsets[i] != NULL_INDICATOR_OFFSET) { slp = serializer.position; serializer.writeValLenIntBackwards(offsets[i]); mask |= 0x1; } mask <<= 1; } if (offsets[0] != NULL_INDICATOR_OFFSET) { mask |= 0x1; // add the non-null bit to the mask } else { // the first field is null, so some previous field was the first non-null field serializer.position = slp; } serializer.writeByte(mask); } else { // general case. offsets first (in backward order) for (int i = numFields - 1; i > 0; i--) { if (offsets[i] != NULL_INDICATOR_OFFSET) { slp = serializer.position; serializer.writeValLenIntBackwards(offsets[i]); } } if (offsets[0] == NULL_INDICATOR_OFFSET) { serializer.position = slp; } // now the mask. we write it in chucks of 8 bit. // the remainder %8 comes first int col = numFields - 1; int mask = 0; int i = numFields & 0x7; if (i > 0) { for (; i > 0; i--, col--) { mask <<= 1; mask |= (offsets[col] != NULL_INDICATOR_OFFSET) ? 0x1 : 0x0; } serializer.writeByte(mask); } // now the eight-bit chunks for (i = numFields >>> 3; i > 0; i--) { mask = 0; for (int k = 0; k < 8; k++, col--) { mask <<= 1; mask |= (offsets[col] != NULL_INDICATOR_OFFSET) ? 0x1 : 0x0; } serializer.writeByte(mask); } } serializer.writeValLenIntBackwards(numFields); } catch (Exception e) { throw new RuntimeException("Serialization into binary state failed: " + e.getMessage(), e); } // set the fields this.binaryData = serializer.memory; this.binaryLen = serializer.position; this.firstModifiedPos = Integer.MAX_VALUE; }
diff --git a/app/Sketch.java b/app/Sketch.java index bacb8aa0..19521bf7 100644 --- a/app/Sketch.java +++ b/app/Sketch.java @@ -1,2191 +1,2191 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Arduino project - http://arduino.berlios.de/ Copyright (c) 2004-05 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology 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$ */ package processing.app; import processing.app.preproc.*; //import processing.core.*; import java.awt.*; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.JOptionPane; import com.oroinc.text.regex.*; /** * Stores information about files in the current sketch */ public class Sketch { static File tempBuildFolder; Editor editor; /** * Name of sketch, which is the name of main file * (without .pde or .java extension) */ String name; /** * Name of 'main' file, used by load(), such as sketch_04040.pde */ String mainFilename; /** * true if any of the files have been modified. */ boolean modified; public File folder; public File dataFolder; public File codeFolder; static final int PDE = 0; static final int JAVA = 1; public SketchCode current; int codeCount; SketchCode code[]; int hiddenCount; SketchCode hidden[]; Hashtable zipFileContents; // all these set each time build() is called String mainClassName; String classPath; String libraryPath; boolean externalRuntime; Vector importedLibraries; // vec of File objects /** * path is location of the main .pde file, because this is also * simplest to use when opening the file from the finder/explorer. */ public Sketch(Editor editor, String path) throws IOException { this.editor = editor; File mainFile = new File(path); //System.out.println("main file is " + mainFile); mainFilename = mainFile.getName(); //System.out.println("main file is " + mainFilename); // get the name of the sketch by chopping .pde or .java // off of the main file name if (mainFilename.endsWith(".pde")) { name = mainFilename.substring(0, mainFilename.length() - 4); } else if (mainFilename.endsWith(".c")) { name = mainFilename.substring(0, mainFilename.length() - 2); } else if (mainFilename.endsWith(".cpp")) { name = mainFilename.substring(0, mainFilename.length() - 4); } // lib/build must exist when the application is started // it is added to the CLASSPATH by default, but if it doesn't // exist when the application is started, then java will remove // the entry from the CLASSPATH, causing Runner to fail. // /* tempBuildFolder = new File(TEMP_BUILD_PATH); if (!tempBuildFolder.exists()) { tempBuildFolder.mkdirs(); Base.showError("Required folder missing", "A required folder was missing from \n" + "from your installation of Processing.\n" + "It has now been replaced, please restart \n" + "the application to complete the repair.", null); } */ tempBuildFolder = Base.getBuildFolder(); //Base.addBuildFolderToClassPath(); folder = new File(new File(path).getParent()); //System.out.println("sketch dir is " + folder); load(); } /** * Build the list of files. * * Generally this is only done once, rather than * each time a change is made, because otherwise it gets to be * a nightmare to keep track of what files went where, because * not all the data will be saved to disk. * * This also gets called when the main sketch file is renamed, * because the sketch has to be reloaded from a different folder. * * Another exception is when an external editor is in use, * in which case the load happens each time "run" is hit. */ public void load() { codeFolder = new File(folder, "code"); dataFolder = new File(folder, "data"); // get list of files in the sketch folder String list[] = folder.list(); for (int i = 0; i < list.length; i++) { if (list[i].endsWith(".pde")) codeCount++; else if (list[i].endsWith(".c")) codeCount++; else if (list[i].endsWith(".cpp")) codeCount++; else if (list[i].endsWith(".pde.x")) hiddenCount++; else if (list[i].endsWith(".c.x")) hiddenCount++; else if (list[i].endsWith(".cpp.x")) hiddenCount++; } code = new SketchCode[codeCount]; hidden = new SketchCode[hiddenCount]; int codeCounter = 0; int hiddenCounter = 0; for (int i = 0; i < list.length; i++) { if (list[i].endsWith(".pde")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), PDE); } else if (list[i].endsWith(".c")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 2), new File(folder, list[i]), JAVA); } else if (list[i].endsWith(".cpp")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), JAVA); } else if (list[i].endsWith(".pde.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 6), new File(folder, list[i]), PDE); } else if (list[i].endsWith(".c.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), JAVA); } else if (list[i].endsWith(".cpp.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 6), new File(folder, list[i]), JAVA); } } // remove any entries that didn't load properly int index = 0; while (index < codeCount) { if ((code[index] == null) || (code[index].program == null)) { for (int i = index+1; i < codeCount; i++) { code[i-1] = code[i]; } codeCount--; } else { index++; } } // move the main class to the first tab // start at 1, if it's at zero, don't bother for (int i = 1; i < codeCount; i++) { if (code[i].file.getName().equals(mainFilename)) { SketchCode temp = code[0]; code[0] = code[i]; code[i] = temp; break; } } // sort the entries at the top sortCode(); // set the main file to be the current tab setCurrent(0); } protected void insertCode(SketchCode newCode) { // make sure the user didn't hide the sketch folder ensureExistence(); // add file to the code/codeCount list, resort the list if (codeCount == code.length) { SketchCode temp[] = new SketchCode[codeCount+1]; System.arraycopy(code, 0, temp, 0, codeCount); code = temp; } code[codeCount++] = newCode; } protected void sortCode() { // cheap-ass sort of the rest of the files // it's a dumb, slow sort, but there shouldn't be more than ~5 files for (int i = 1; i < codeCount; i++) { int who = i; for (int j = i + 1; j < codeCount; j++) { if (code[j].name.compareTo(code[who].name) < 0) { who = j; // this guy is earlier in the alphabet } } if (who != i) { // swap with someone if changes made SketchCode temp = code[who]; code[who] = code[i]; code[i] = temp; } } } boolean renamingCode; public void newCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } renamingCode = false; editor.status.edit("Name for new file:", ""); } public void renameCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // ask for new name of file (internal to window) // TODO maybe just popup a text area? renamingCode = true; String prompt = (current == code[0]) ? "New name for sketch:" : "New name for file:"; String oldName = (current.flavor == PDE) ? current.name : current.name + ".cpp"; editor.status.edit(prompt, oldName); } /** * This is called upon return from entering a new file name. * (that is, from either newCode or renameCode after the prompt) * This code is almost identical for both the newCode and renameCode * cases, so they're kept merged except for right in the middle * where they diverge. */ public void nameCode(String newName) { // make sure the user didn't hide the sketch folder ensureExistence(); // if renaming to the same thing as before, just ignore. // also ignoring case here, because i don't want to write // a bunch of special stuff for each platform // (osx is case insensitive but preserving, windows insensitive, // *nix is sensitive and preserving.. argh) if (renamingCode && newName.equalsIgnoreCase(current.name)) { // exit quietly for the 'rename' case. // if it's a 'new' then an error will occur down below return; } // don't allow blank names if (newName.trim().equals("")) { return; } if (newName.trim().equals(".c") || newName.trim().equals(".pde") || newName.trim().equals(".cpp")) { return; } String newFilename = null; int newFlavor = 0; // separate into newName (no extension) and newFilename (with ext) // add .pde to file if it has no extension if (newName.endsWith(".pde")) { newFilename = newName; newName = newName.substring(0, newName.length() - 4); newFlavor = PDE; } else if (newName.endsWith(".c") || newName.endsWith(".cpp")) { // don't show this error if creating a new tab if (renamingCode && (code[0] == current)) { Base.showWarning("Problem with rename", "The main .pde file cannot be .c or .cpp file.\n" + "(It may be time for your to graduate to a\n" + "\"real\" programming environment)", null); return; } newFilename = newName; if(newName.endsWith(".c")) newName = newName.substring(0, newName.length() - 2); else if(newName.endsWith(".cpp")) newName = newName.substring(0, newName.length() - 4); newFlavor = JAVA; } else { newFilename = newName + ".pde"; newFlavor = PDE; } // dots are allowed for the .pde and .java, but not in the name // make sure the user didn't name things poo.time.pde // or something like that (nothing against poo time) if (newName.indexOf('.') != -1) { newName = Sketchbook.sanitizedName(newName); newFilename = newName + ((newFlavor == PDE) ? ".pde" : ".cpp"); } // create the new file, new SketchCode object and load it File newFile = new File(folder, newFilename); if (newFile.exists()) { // yay! users will try anything Base.showMessage("Nope", "A file named \"" + newFile + "\" already exists\n" + "in \"" + folder.getAbsolutePath() + "\""); return; } File newFileHidden = new File(folder, newFilename + ".x"); if (newFileHidden.exists()) { // don't let them get away with it if they try to create something // with the same name as something hidden Base.showMessage("No Way", "A hidden tab with the same name already exists.\n" + "Use \"Unhide\" to bring it back."); return; } if (renamingCode) { if (current == code[0]) { // get the new folder name/location File newFolder = new File(folder.getParentFile(), newName); if (newFolder.exists()) { Base.showWarning("Cannot Rename", "Sorry, a sketch (or folder) named " + "\"" + newName + "\" already exists.", null); return; } // unfortunately this can't be a "save as" because that // only copies the sketch files and the data folder // however this *will* first save the sketch, then rename // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); try { // save this new SketchCode current.save(); } catch (Exception e) { Base.showWarning("Error", "Could not rename the sketch. (0)", e); return; } } if (!current.file.renameTo(newFile)) { Base.showWarning("Error", "Could not rename \"" + current.file.getName() + "\" to \"" + newFile.getName() + "\"", null); return; } // save each of the other tabs because this is gonna be re-opened try { for (int i = 1; i < codeCount; i++) { //if (code[i].modified) code[i].save(); code[i].save(); } } catch (Exception e) { Base.showWarning("Error", "Could not rename the sketch. (1)", e); return; } // now rename the sketch folder and re-open boolean success = folder.renameTo(newFolder); if (!success) { Base.showWarning("Error", "Could not rename the sketch. (2)", null); return; } // if successful, set base properties for the sketch File mainFile = new File(newFolder, newName + ".pde"); mainFilename = mainFile.getAbsolutePath(); // having saved everything and renamed the folder and the main .pde, // use the editor to re-open the sketch to re-init state // (unfortunately this will kill positions for carets etc) editor.handleOpenUnchecked(mainFilename); /* // backtrack and don't rename the sketch folder success = newFolder.renameTo(folder); if (!success) { String msg = "Started renaming sketch and then ran into\n" + "nasty trouble. Try to salvage with Copy & Paste\n" + "or attempt a \"Save As\" to see if that works."; Base.showWarning("Serious Error", msg, null); } return; } */ /* // set the sketch name... used by the pde and whatnot. // the name is only set in the sketch constructor, // so it's important here name = newName; code[0].name = newName; code[0].file = mainFile; code[0].program = editor.getText(); code[0].save(); folder = newFolder; // get the changes into the sketchbook menu editor.sketchbook.rebuildMenus(); // reload the sketch load(); */ } else { if (!current.file.renameTo(newFile)) { Base.showWarning("Error", "Could not rename \"" + current.file.getName() + "\" to \"" + newFile.getName() + "\"", null); return; } // just reopen the class itself current.name = newName; current.file = newFile; current.flavor = newFlavor; } } else { // creating a new file try { newFile.createNewFile(); // TODO returns a boolean } catch (IOException e) { Base.showWarning("Error", "Could not create the file \"" + newFile + "\"\n" + "in \"" + folder.getAbsolutePath() + "\"", e); return; } SketchCode newCode = new SketchCode(newName, newFile, newFlavor); insertCode(newCode); } // sort the entries sortCode(); // set the new guy as current setCurrent(newName); // update the tabs //editor.header.repaint(); editor.header.rebuild(); // force the update on the mac? Toolkit.getDefaultToolkit().sync(); //editor.header.getToolkit().sync(); } /** * Remove a piece of code from the sketch and from the disk. */ public void deleteCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // confirm deletion with user, yes/no Object[] options = { "OK", "Cancel" }; String prompt = (current == code[0]) ? "Are you sure you want to delete this sketch?" : "Are you sure you want to delete \"" + current.name + "\"?"; int result = JOptionPane.showOptionDialog(editor, prompt, "Delete", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { if (current == code[0]) { // need to unset all the modified flags, otherwise tries // to do a save on the handleNew() // delete the entire sketch Base.removeDir(folder); // get the changes into the sketchbook menu //sketchbook.rebuildMenus(); // make a new sketch, and i think this will rebuild the sketch menu editor.handleNewUnchecked(); } else { // delete the file if (!current.file.delete()) { Base.showMessage("Couldn't do it", "Could not delete \"" + current.name + "\"."); return; } // remove code from the list removeCode(current); // just set current tab to the main tab setCurrent(0); // update the tabs editor.header.repaint(); } } } protected void removeCode(SketchCode which) { // remove it from the internal list of files // resort internal list of files for (int i = 0; i < codeCount; i++) { if (code[i] == which) { for (int j = i; j < codeCount-1; j++) { code[j] = code[j+1]; } codeCount--; return; } } System.err.println("removeCode: internal error.. could not find code"); } public void hideCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // don't allow hide of the main code // TODO maybe gray out the menu on setCurrent(0) if (current == code[0]) { Base.showMessage("Can't do that", "You cannot hide the main " + ".pde file from a sketch\n"); return; } // rename the file File newFile = new File(current.file.getAbsolutePath() + ".x"); if (!current.file.renameTo(newFile)) { Base.showWarning("Error", "Could not hide " + "\"" + current.file.getName() + "\".", null); return; } current.file = newFile; // move it to the hidden list if (hiddenCount == hidden.length) { SketchCode temp[] = new SketchCode[hiddenCount+1]; System.arraycopy(hidden, 0, temp, 0, hiddenCount); hidden = temp; } hidden[hiddenCount++] = current; // remove it from the main list removeCode(current); // update the tabs setCurrent(0); editor.header.repaint(); } public void unhideCode(String what) { SketchCode unhideCode = null; for (int i = 0; i < hiddenCount; i++) { if (hidden[i].name.equals(what)) { //unhideIndex = i; unhideCode = hidden[i]; // remove from the 'hidden' list for (int j = i; j < hiddenCount-1; j++) { hidden[j] = hidden[j+1]; } hiddenCount--; break; } } //if (unhideIndex == -1) { if (unhideCode == null) { System.err.println("internal error: could find " + what + " to unhide."); return; } if (!unhideCode.file.exists()) { Base.showMessage("Can't unhide", "The file \"" + what + "\" no longer exists."); //System.out.println(unhideCode.file); return; } String unhidePath = unhideCode.file.getAbsolutePath(); File unhideFile = new File(unhidePath.substring(0, unhidePath.length() - 2)); if (!unhideCode.file.renameTo(unhideFile)) { Base.showMessage("Can't unhide", "The file \"" + what + "\" could not be" + "renamed and unhidden."); return; } unhideCode.file = unhideFile; insertCode(unhideCode); sortCode(); setCurrent(unhideCode.name); editor.header.repaint(); } /** * Sets the modified value for the code in the frontmost tab. */ public void setModified() { current.modified = true; calcModified(); } public void calcModified() { modified = false; for (int i = 0; i < codeCount; i++) { if (code[i].modified) { modified = true; break; } } editor.header.repaint(); } /** * Save all code in the current sketch. */ public boolean save() throws IOException { // make sure the user didn't hide the sketch folder ensureExistence(); // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); } // don't do anything if not actually modified //if (!modified) return false; if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is read-only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save this sketch to another location."); // if the user cancels, give up on the save() if (!saveAs()) return false; } for (int i = 0; i < codeCount; i++) { if (code[i].modified) code[i].save(); } calcModified(); return true; } /** * Handles 'Save As' for a sketch. * <P> * This basically just duplicates the current sketch folder to * a new location, and then calls 'Save'. (needs to take the current * state of the open files and save them to the new folder.. * but not save over the old versions for the old sketch..) * <P> * Also removes the previously-generated .class and .jar files, * because they can cause trouble. */ public boolean saveAs() throws IOException { // get new name for folder FileDialog fd = new FileDialog(editor, "Save sketch folder as...", FileDialog.SAVE); if (isReadOnly()) { // default to the sketchbook folder fd.setDirectory(Preferences.get("sketchbook.path")); } else { // default to the parent folder of where this was fd.setDirectory(folder.getParent()); } fd.setFile(folder.getName()); fd.show(); String newParentDir = fd.getDirectory(); String newName = fd.getFile(); // user cancelled selection if (newName == null) return false; newName = Sketchbook.sanitizeName(newName); // make sure there doesn't exist a tab with that name already // (but allow it if it's just the main tab resaving itself.. oops) File codeAlready = new File(folder, newName + ".pde"); if (codeAlready.exists() && (!newName.equals(name))) { Base.showMessage("Nope", "You can't save the sketch as \"" + newName + "\"\n" + "because the sketch already has a tab with that name."); return false; } // make sure there doesn't exist a tab with that name already File hiddenAlready = new File(folder, newName + ".pde.x"); if (hiddenAlready.exists()) { Base.showMessage("Nope", "You can't save the sketch as \"" + newName + "\"\n" + "because the sketch already has a " + "hidden tab with that name."); return false; } // new sketch folder File newFolder = new File(newParentDir, newName); // make sure the paths aren't the same if (newFolder.equals(folder)) { Base.showWarning("You can't fool me", "The new sketch name and location are the same as\n" + "the old. I ain't not doin nuthin' not now.", null); return false; } // check to see if the user is trying to save this sketch // inside the same sketch try { String newPath = newFolder.getCanonicalPath() + File.separator; String oldPath = folder.getCanonicalPath() + File.separator; if (newPath.indexOf(oldPath) == 0) { Base.showWarning("How very Borges of you", "You cannot save the sketch into a folder\n" + "inside itself. This would go on forever.", null); return false; } } catch (IOException e) { } // if the new folder already exists, then need to remove // its contents before copying everything over // (user will have already been warned) if (newFolder.exists()) { Base.removeDir(newFolder); } // in fact, you can't do this on windows because the file dialog // will instead put you inside the folder, but it happens on osx a lot. // now make a fresh copy of the folder newFolder.mkdirs(); // grab the contents of the current tab before saving // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); } // save the other tabs to their new location for (int i = 1; i < codeCount; i++) { File newFile = new File(newFolder, code[i].file.getName()); code[i].saveAs(newFile); } // save the hidden code to its new location for (int i = 0; i < hiddenCount; i++) { File newFile = new File(newFolder, hidden[i].file.getName()); hidden[i].saveAs(newFile); } // re-copy the data folder (this may take a while.. add progress bar?) if (dataFolder.exists()) { File newDataFolder = new File(newFolder, "data"); Base.copyDir(dataFolder, newDataFolder); } // re-copy the code folder if (codeFolder.exists()) { File newCodeFolder = new File(newFolder, "code"); Base.copyDir(codeFolder, newCodeFolder); } // save the main tab with its new name File newFile = new File(newFolder, newName + ".pde"); code[0].saveAs(newFile); editor.handleOpenUnchecked(newFile.getPath()); /* // copy the entire contents of the sketch folder Base.copyDir(folder, newFolder); // change the references to the dir location in SketchCode files for (int i = 0; i < codeCount; i++) { code[i].file = new File(newFolder, code[i].file.getName()); } for (int i = 0; i < hiddenCount; i++) { hidden[i].file = new File(newFolder, hidden[i].file.getName()); } // remove the old sketch file from the new dir code[0].file.delete(); // name for the new main .pde file code[0].file = new File(newFolder, newName + ".pde"); code[0].name = newName; // write the contents to the renamed file // (this may be resaved if the code is modified) code[0].modified = true; //code[0].save(); //System.out.println("modified is " + modified); // change the other paths String oldName = name; name = newName; File oldFolder = folder; folder = newFolder; dataFolder = new File(folder, "data"); codeFolder = new File(folder, "code"); // remove the 'applet', 'application', 'library' folders // from the copied version. // otherwise their .class and .jar files can cause conflicts. Base.removeDir(new File(folder, "applet")); Base.removeDir(new File(folder, "application")); //Base.removeDir(new File(folder, "library")); // do a "save" // this will take care of the unsaved changes in each of the tabs save(); // get the changes into the sketchbook menu //sketchbook.rebuildMenu(); // done inside Editor instead // update the tabs for the name change editor.header.repaint(); */ // let Editor know that the save was successful return true; } /** * Prompt the user for a new file to the sketch. * This could be .class or .jar files for the code folder, * .pde or .java files for the project, * or .dll, .jnilib, or .so files for the code folder */ public void addFile() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // get a dialog, select a file to add to the sketch String prompt = "Select an image or other data file to copy to your sketch"; //FileDialog fd = new FileDialog(new Frame(), prompt, FileDialog.LOAD); FileDialog fd = new FileDialog(editor, prompt, FileDialog.LOAD); fd.show(); String directory = fd.getDirectory(); String filename = fd.getFile(); if (filename == null) return; // copy the file into the folder. if people would rather // it move instead of copy, they can do it by hand File sourceFile = new File(directory, filename); File destFile = null; boolean addingCode = false; // if the file appears to be code related, drop it // into the code folder, instead of the data folder if (filename.toLowerCase().endsWith(".o") /*|| filename.toLowerCase().endsWith(".jar") || filename.toLowerCase().endsWith(".dll") || filename.toLowerCase().endsWith(".jnilib") || filename.toLowerCase().endsWith(".so") */ ) { //File codeFolder = new File(this.folder, "code"); if (!codeFolder.exists()) codeFolder.mkdirs(); destFile = new File(codeFolder, filename); } else if (filename.toLowerCase().endsWith(".pde") || filename.toLowerCase().endsWith(".c") || filename.toLowerCase().endsWith(".cpp")) { destFile = new File(this.folder, filename); addingCode = true; } else { //File dataFolder = new File(this.folder, "data"); if (!dataFolder.exists()) dataFolder.mkdirs(); destFile = new File(dataFolder, filename); } // make sure they aren't the same file if (!addingCode && sourceFile.equals(destFile)) { Base.showWarning("You can't fool me", "This file has already been copied to the\n" + "location where you're trying to add it.\n" + "I ain't not doin nuthin'.", null); return; } // in case the user is "adding" the code in an attempt // to update the sketch's tabs if (!sourceFile.equals(destFile)) { try { Base.copyFile(sourceFile, destFile); } catch (IOException e) { Base.showWarning("Error adding file", "Could not add '" + filename + "' to the sketch.", e); } } // make the tabs update after this guy is added if (addingCode) { String newName = destFile.getName(); int newFlavor = -1; if (newName.toLowerCase().endsWith(".pde")) { newName = newName.substring(0, newName.length() - 4); newFlavor = PDE; } else { newName = newName.substring(0, newName.length() - 2); newFlavor = JAVA; } // see also "nameCode" for identical situation SketchCode newCode = new SketchCode(newName, destFile, newFlavor); insertCode(newCode); sortCode(); setCurrent(newName); editor.header.repaint(); } } public void importLibrary(String jarPath) { System.out.println(jarPath); /* // make sure the user didn't hide the sketch folder ensureExistence(); String list[] = Compiler.packageListFromClassPath(jarPath); // import statements into the main sketch file (code[0]) // if the current code is a .java file, insert into current if (current.flavor == PDE) { setCurrent(0); } // could also scan the text in the file to see if each import // statement is already in there, but if the user has the import // commented out, then this will be a problem. StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { buffer.append("import "); buffer.append(list[i]); buffer.append(".*;\n"); } buffer.append('\n'); buffer.append(editor.getText()); editor.setText(buffer.toString(), 0, 0); // scroll to start setModified(); */ } /** * Change what file is currently being edited. * <OL> * <LI> store the String for the text of the current file. * <LI> retrieve the String for the text of the new file. * <LI> change the text that's visible in the text area * </OL> */ public void setCurrent(int which) { if (current == code[which]) { //System.out.println("already current, ignoring"); return; } // get the text currently being edited if (current != null) { current.program = editor.getText(); current.selectionStart = editor.textarea.getSelectionStart(); current.selectionStop = editor.textarea.getSelectionEnd(); current.scrollPosition = editor.textarea.getScrollPosition(); } current = code[which]; editor.setCode(current); //editor.setDocument(current.document, // current.selectionStart, current.selectionStop, // current.scrollPosition, current.undo); // set to the text for this file // 'true' means to wipe out the undo buffer // (so they don't undo back to the other file.. whups!) /* editor.setText(current.program, current.selectionStart, current.selectionStop, current.undo); */ // set stored caret and scroll positions //editor.textarea.setScrollPosition(current.scrollPosition); //editor.textarea.select(current.selectionStart, current.selectionStop); //editor.textarea.setSelectionStart(current.selectionStart); //editor.textarea.setSelectionEnd(current.selectionStop); editor.header.rebuild(); } /** * Internal helper function to set the current tab * based on a name (used by codeNew and codeRename). */ protected void setCurrent(String findName) { for (int i = 0; i < codeCount; i++) { if (findName.equals(code[i].name)) { setCurrent(i); return; } } } /** * Cleanup temporary files used during a build/run. */ protected void cleanup() { // if the java runtime is holding onto any files in the build dir, we // won't be able to delete them, so we need to force a gc here System.gc(); // note that we can't remove the builddir itself, otherwise // the next time we start up, internal runs using Runner won't // work because the build dir won't exist at startup, so the classloader // will ignore the fact that that dir is in the CLASSPATH in run.sh Base.removeDescendants(tempBuildFolder); } /** * Preprocess, Compile, and Run the current code. * <P> * There are three main parts to this process: * <PRE> * (0. if not java, then use another 'engine'.. i.e. python) * * 1. do the p5 language preprocessing * this creates a working .java file in a specific location * better yet, just takes a chunk of java code and returns a * new/better string editor can take care of saving this to a * file location * * 2. compile the code from that location * catching errors along the way * placing it in a ready classpath, or .. ? * * 3. run the code * needs to communicate location for window * and maybe setup presentation space as well * run externally if a code folder exists, * or if more than one file is in the project * * X. afterwards, some of these steps need a cleanup function * </PRE> */ public boolean handleRun(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); current.program = editor.getText(); // TODO record history here //current.history.record(program, SketchHistory.RUN); // if an external editor is being used, need to grab the // latest version of the code from the file. if (Preferences.getBoolean("editor.external")) { // history gets screwed by the open.. //String historySaved = history.lastRecorded; //handleOpen(sketch); //history.lastRecorded = historySaved; // nuke previous files and settings, just get things loaded load(); } // in case there were any boogers left behind // do this here instead of after exiting, since the exit // can happen so many different ways.. and this will be // better connected to the dataFolder stuff below. cleanup(); // make up a temporary class name to suggest. // name will only be used if the code is not in ADVANCED mode. String suggestedClassName = ("Temporary_" + String.valueOf((int) (Math.random() * 10000)) + "_" + String.valueOf((int) (Math.random() * 10000))); // handle preprocessing the main file's code //mainClassName = build(TEMP_BUILD_PATH, suggestedClassName); mainClassName = build(target, tempBuildFolder.getAbsolutePath(), suggestedClassName); // externalPaths is magically set by build() if (!externalRuntime) { // only if not running externally already // copy contents of data dir into lib/build if (dataFolder.exists()) { // just drop the files in the build folder (pre-68) //Base.copyDir(dataDir, buildDir); // drop the files into a 'data' subfolder of the build dir try { Base.copyDir(dataFolder, new File(tempBuildFolder, "data")); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem copying files from data folder"); } } } return (mainClassName != null); } /** * Build all the code for this sketch. * * In an advanced program, the returned classname could be different, * which is why the className is set based on the return value. * A compilation error will burp up a RunnerException. * * @return null if compilation failed, main class name if not */ protected String build(Target target, String buildPath, String suggestedClassName) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); String codeFolderPackages[] = null; String javaClassPath = System.getProperty("java.class.path"); // remove quotes if any.. this is an annoying thing on windows if (javaClassPath.startsWith("\"") && javaClassPath.endsWith("\"")) { javaClassPath = javaClassPath.substring(1, javaClassPath.length() - 1); } classPath = buildPath + File.pathSeparator + Sketchbook.librariesClassPath + File.pathSeparator + javaClassPath; //System.out.println("cp = " + classPath); // figure out the contents of the code folder to see if there // are files that need to be added to the imports //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { externalRuntime = true; //classPath += File.pathSeparator + //Compiler.contentsToClassPath(codeFolder); classPath = Compiler.contentsToClassPath(codeFolder) + File.pathSeparator + classPath; //codeFolderPackages = Compiler.packageListFromClassPath(classPath); //codeFolderPackages = Compiler.packageListFromClassPath(codeFolder); libraryPath = codeFolder.getAbsolutePath(); // get a list of .jar files in the "code" folder // (class files in subfolders should also be picked up) String codeFolderClassPath = Compiler.contentsToClassPath(codeFolder); // get list of packages found in those jars // codeFolderPackages = // Compiler.packageListFromClassPath(codeFolderClassPath); //PApplet.println(libraryPath); //PApplet.println("packages:"); //PApplet.printarr(codeFolderPackages); } else { // since using the special classloader, // run externally whenever there are extra classes defined //externalRuntime = (codeCount > 1); // this no longer appears to be true.. so scrapping for 0088 // check to see if multiple files that include a .java file externalRuntime = false; for (int i = 0; i < codeCount; i++) { if (code[i].flavor == JAVA) { externalRuntime = true; break; } } //codeFolderPackages = null; libraryPath = ""; } // if 'data' folder is large, set to external runtime if (dataFolder.exists() && Base.calcFolderSize(dataFolder) > 768 * 1024) { // if > 768k externalRuntime = true; } // 1. concatenate all .pde files to the 'main' pde // store line number for starting point of each code bit StringBuffer bigCode = new StringBuffer(code[0].program); int bigCount = countLines(code[0].program); for (int i = 1; i < codeCount; i++) { if (code[i].flavor == PDE) { code[i].preprocOffset = ++bigCount; bigCode.append('\n'); bigCode.append(code[i].program); bigCount += countLines(code[i].program); code[i].preprocName = null; // don't compile me } } // since using the special classloader, // run externally whenever there are extra classes defined /* if ((bigCode.indexOf(" class ") != -1) || (bigCode.indexOf("\nclass ") != -1)) { externalRuntime = true; } */ // if running in opengl mode, this is gonna be external //if (Preferences.get("renderer").equals("opengl")) { //externalRuntime = true; //} // 2. run preproc on that code using the sugg class name // to create a single .java file and write to buildpath String primaryClassName = null; PdePreprocessor preprocessor = new PdePreprocessor(); try { // if (i != 0) preproc will fail if a pde file is not // java mode, since that's required String className = preprocessor.write(bigCode.toString(), buildPath, suggestedClassName, codeFolderPackages); if (className == null) { throw new RunnerException("Could not find main class"); // this situation might be perfectly fine, // (i.e. if the file is empty) //System.out.println("No class found in " + code[i].name); //System.out.println("(any code in that file will be ignored)"); //System.out.println(); } else { //code[0].preprocName = className + "." + Preferences.get("build.extension"); code[0].preprocName = className + ".cpp"; } // store this for the compiler and the runtime primaryClassName = className; //System.out.println("primary class " + primaryClassName); // check if the 'main' file is in java mode if ((PdePreprocessor.programType == PdePreprocessor.JAVA) || (preprocessor.extraImports.length != 0)) { externalRuntime = true; // we in advanced mode now, boy } } catch (antlr.RecognitionException re) { // this even returns a column int errorFile = 0; int errorLine = re.getLine() - 1; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; - //errorLine -= preprocessor.prototypeCount; + errorLine -= preprocessor.prototypeCount; throw new RunnerException(re.getMessage(), errorFile, errorLine, re.getColumn()); } catch (antlr.TokenStreamRecognitionException tsre) { // while this seems to store line and column internally, // there doesn't seem to be a method to grab it.. // so instead it's done using a regexp PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // line 3:1: unexpected char: 0xA0 String mess = "^line (\\d+):(\\d+):\\s"; Pattern pattern = null; try { pattern = compiler.compile(mess); } catch (MalformedPatternException e) { Base.showWarning("Internal Problem", "An internal error occurred while trying\n" + "to compile the sketch. Please report\n" + "this online at " + "https://developer.berlios.de/bugs/?group_id=3590", e); } PatternMatcherInput input = new PatternMatcherInput(tsre.toString()); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); int errorLine = Integer.parseInt(result.group(1).toString()) - 1; int errorColumn = Integer.parseInt(result.group(2).toString()); int errorFile = 0; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; - //errorLine -= preprocessor.prototypeCount; + errorLine -= preprocessor.prototypeCount; throw new RunnerException(tsre.getMessage(), errorFile, errorLine, errorColumn); } else { // this is bad, defaults to the main class.. hrm. throw new RunnerException(tsre.toString(), 0, -1, -1); } } catch (RunnerException pe) { // RunnerExceptions are caught here and re-thrown, so that they don't // get lost in the more general "Exception" handler below. throw pe; } catch (Exception ex) { // TODO better method for handling this? System.err.println("Uncaught exception type:" + ex.getClass()); ex.printStackTrace(); throw new RunnerException(ex.toString()); } // grab the imports from the code just preproc'd importedLibraries = new Vector(); String imports[] = preprocessor.extraImports; for (int i = 0; i < imports.length; i++) { // remove things up to the last dot String entry = imports[i].substring(0, imports[i].lastIndexOf('.')); //System.out.println("found package " + entry); File libFolder = (File) Sketchbook.importToLibraryTable.get(entry); if (libFolder == null) { //throw new RunnerException("Could not find library for " + entry); continue; } importedLibraries.add(libFolder); libraryPath += File.pathSeparator + libFolder.getAbsolutePath(); /* String list[] = libFolder.list(); if (list != null) { for (int j = 0; j < list.length; j++) { // this might have a dll/jnilib/so packed, // so add it to the library path if (list[j].toLowerCase().endsWith(".jar")) { libraryPath += File.pathSeparator + libFolder.getAbsolutePath() + File.separator + list[j]; } } } */ } // 3. then loop over the code[] and save each .java file for (int i = 0; i < codeCount; i++) { if (code[i].flavor == JAVA) { // no pre-processing services necessary for java files // just write the the contents of 'program' to a .java file // into the build directory. uses byte stream and reader/writer // shtuff so that unicode bunk is properly handled //String filename = code[i].name + "." + Preferences.get("build.extension"); String filename = code[i].name + ".cpp"; try { Base.saveFile(code[i].program, new File(buildPath, filename)); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem moving " + filename + " to the build folder"); } code[i].preprocName = filename; } } // compile the program. errors will happen as a RunnerException // that will bubble up to whomever called build(). // // note: this has been changed to catch build exceptions, adjust // line number for number of included prototypes, and rethrow Compiler compiler = new Compiler(); boolean success; try { success = compiler.compile(this, buildPath, target); } catch (RunnerException re) { throw new RunnerException(re.getMessage(), re.file, - re.line,// - preprocessor.prototypeCount, + re.line - preprocessor.prototypeCount, re.column); } catch (Exception ex) { // TODO better method for handling this? throw new RunnerException(ex.toString()); } //System.out.println("success = " + success + " ... " + primaryClassName); return success ? primaryClassName : null; } protected void size(String buildPath, String suggestedClassName) throws RunnerException { long size = 0; Sizer sizer = new Sizer(buildPath, suggestedClassName); try { size = sizer.computeSize(); System.out.println("Binary sketch size: " + size + " bytes (of a " + Preferences.get("upload.maximum_size") + " byte maximum)"); } catch (RunnerException e) { System.err.println("Couldn't determine program size: " + e.getMessage()); } if (size > Preferences.getInteger("upload.maximum_size")) throw new RunnerException( "Sketch too big; try deleting code, removing floats, or see " + "http://www.arduino.cc/en/Main/FAQ for more advice."); } protected String upload(String buildPath, String suggestedClassName) throws RunnerException { // download the program // Uploader downloader = new Uploader(buildPath, suggestedClassName, this); // macos9 now officially broken.. see PdeCompilerJavac //PdeCompiler compiler = // ((PdeBase.platform == PdeBase.MACOS9) ? // new PdeCompilerJavac(buildPath, className, this) : // new PdeCompiler(buildPath, className, this)); // run the compiler, and funnel errors to the leechErr // which is a wrapped around // (this will catch and parse errors during compilation // the messageStream will call message() for 'compiler') MessageStream messageStream = new MessageStream(downloader); //PrintStream leechErr = new PrintStream(messageStream); //boolean result = compiler.compileJava(leechErr); //return compiler.compileJava(leechErr); boolean success = downloader.downloadJava(new PrintStream(messageStream)); return success ? suggestedClassName : null; } protected int countLines(String what) { char c[] = what.toCharArray(); int count = 0; for (int i = 0; i < c.length; i++) { if (c[i] == '\n') count++; } return count; } /** * Initiate export to applet. * <PRE> * +-------------------------------------------------------+ * + + * + Export to: [ Applet (for the web) + ] [ OK ] + * + + * + > Advanced + * + + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.1 + ] + * + + * + Recommended version of Java when exporting applets. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.3 + ] + * + + * + Java 1.3 is not recommended for applets, + * + unless you are using features that require it. + * + Using a version of Java other than 1.1 will require + * + your Windows users to install the Java Plug-In, + * + and your Macintosh users to be running OS X. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.4 + ] + * + + * + identical message as 1.3 above... + * + + * +-------------------------------------------------------+ * </PRE> */ public boolean exportApplet(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); zipFileContents = new Hashtable(); // nuke the old applet folder because it can cause trouble File appletFolder = new File(folder, "applet"); Base.removeDir(appletFolder); appletFolder.mkdirs(); // build the sketch String foundName = build(target, appletFolder.getPath(), name); size(appletFolder.getPath(), name); foundName = upload(appletFolder.getPath(), name); // (already reported) error during export, exit this function if (foundName == null) return false; // if name != exportSketchName, then that's weirdness // BUG unfortunately, that can also be a bug in the preproc :( if (!name.equals(foundName)) { Base.showWarning("Error during export", "Sketch name is " + name + " but the sketch\n" + "name in the code was " + foundName, null); return false; } /* int wide = PApplet.DEFAULT_WIDTH; int high = PApplet.DEFAULT_HEIGHT; PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // this matches against any uses of the size() function, // whether they contain numbers of variables or whatever. // this way, no warning is shown if size() isn't actually // used in the applet, which is the case especially for // beginners that are cutting/pasting from the reference. // modified for 83 to match size(XXX, ddd so that it'll // properly handle size(200, 200) and size(200, 200, P3D) String sizing = "[\\s\\;]size\\s*\\(\\s*(\\S+)\\s*,\\s*(\\d+)"; Pattern pattern = compiler.compile(sizing); // adds a space at the beginning, in case size() is the very // first thing in the program (very common), since the regexp // needs to check for things in front of it. PatternMatcherInput input = new PatternMatcherInput(" " + code[0].program); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); try { wide = Integer.parseInt(result.group(1).toString()); high = Integer.parseInt(result.group(2).toString()); } catch (NumberFormatException e) { // found a reference to size, but it didn't // seem to contain numbers final String message = "The size of this applet could not automatically be\n" + "determined from your code. You'll have to edit the\n" + "HTML file to set the size of the applet."; Base.showWarning("Could not find applet size", message, null); } } // else no size() command found // originally tried to grab this with a regexp matcher, // but it wouldn't span over multiple lines for the match. // this could prolly be forced, but since that's the case // better just to parse by hand. StringBuffer dbuffer = new StringBuffer(); String lines[] = PApplet.split(code[0].program, '\n'); for (int i = 0; i < lines.length; i++) { if (lines[i].trim().startsWith("/**")) { // this is our comment */ // some smartass put the whole thing on the same line //if (lines[j].indexOf("*/") != -1) break; // for (int j = i+1; j < lines.length; j++) { // if (lines[j].trim().endsWith("*/")) { // remove the */ from the end, and any extra *s // in case there's also content on this line // nah, don't bother.. make them use the three lines // break; // } /* int offset = 0; while ((offset < lines[j].length()) && ((lines[j].charAt(offset) == '*') || (lines[j].charAt(offset) == ' '))) { offset++; } // insert the return into the html to help w/ line breaks dbuffer.append(lines[j].substring(offset) + "\n"); } } } String description = dbuffer.toString(); StringBuffer sources = new StringBuffer(); for (int i = 0; i < codeCount; i++) { sources.append("<a href=\"" + code[i].file.getName() + "\">" + code[i].name + "</a> "); } File htmlOutputFile = new File(appletFolder, "index.html"); FileOutputStream fos = new FileOutputStream(htmlOutputFile); PrintStream ps = new PrintStream(fos); // @@sketch@@, @@width@@, @@height@@, @@archive@@, @@source@@ // and now @@description@@ InputStream is = null; // if there is an applet.html file in the sketch folder, use that File customHtml = new File(folder, "applet.html"); if (customHtml.exists()) { is = new FileInputStream(customHtml); } if (is == null) { is = Base.getStream("applet.html"); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = reader.readLine()) != null) { if (line.indexOf("@@") != -1) { StringBuffer sb = new StringBuffer(line); int index = 0; while ((index = sb.indexOf("@@sketch@@")) != -1) { sb.replace(index, index + "@@sketch@@".length(), name); } while ((index = sb.indexOf("@@source@@")) != -1) { sb.replace(index, index + "@@source@@".length(), sources.toString()); } while ((index = sb.indexOf("@@archive@@")) != -1) { sb.replace(index, index + "@@archive@@".length(), name + ".jar"); } while ((index = sb.indexOf("@@width@@")) != -1) { sb.replace(index, index + "@@width@@".length(), String.valueOf(wide)); } while ((index = sb.indexOf("@@height@@")) != -1) { sb.replace(index, index + "@@height@@".length(), String.valueOf(high)); } while ((index = sb.indexOf("@@description@@")) != -1) { sb.replace(index, index + "@@description@@".length(), description); } line = sb.toString(); } ps.println(line); } reader.close(); ps.flush(); ps.close(); // copy the loading gif to the applet String LOADING_IMAGE = "loading.gif"; File loadingImage = new File(folder, LOADING_IMAGE); if (!loadingImage.exists()) { loadingImage = new File("lib", LOADING_IMAGE); } Base.copyFile(loadingImage, new File(appletFolder, LOADING_IMAGE)); */ // copy the source files to the target, since we like // to encourage people to share their code for (int i = 0; i < codeCount; i++) { try { Base.copyFile(code[i].file, new File(appletFolder, code[i].file.getName())); } catch (IOException e) { e.printStackTrace(); } } /* // create new .jar file FileOutputStream zipOutputFile = new FileOutputStream(new File(appletFolder, name + ".jar")); ZipOutputStream zos = new ZipOutputStream(zipOutputFile); ZipEntry entry; // add the manifest file addManifest(zos); // add the contents of the code folder to the jar // unpacks all jar files //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { String includes = Compiler.contentsToClassPath(codeFolder); packClassPathIntoZipFile(includes, zos); } // add contents of 'library' folders to the jar file // if a file called 'export.txt' is in there, it contains // a list of the files that should be exported. // otherwise, all files are exported. Enumeration en = importedLibraries.elements(); while (en.hasMoreElements()) { // in the list is a File object that points the // library sketch's "library" folder File libraryFolder = (File)en.nextElement(); File exportSettings = new File(libraryFolder, "export.txt"); String exportList[] = null; if (exportSettings.exists()) { String info[] = Base.loadStrings(exportSettings); for (int i = 0; i < info.length; i++) { if (info[i].startsWith("applet")) { int idx = info[i].indexOf('='); // get applet= or applet = String commas = info[i].substring(idx+1).trim(); exportList = PApplet.split(commas, ", "); } } } else { exportList = libraryFolder.list(); } for (int i = 0; i < exportList.length; i++) { if (exportList[i].equals(".") || exportList[i].equals("..")) continue; exportList[i] = PApplet.trim(exportList[i]); if (exportList[i].equals("")) continue; File exportFile = new File(libraryFolder, exportList[i]); if (!exportFile.exists()) { System.err.println("File " + exportList[i] + " does not exist"); } else if (exportFile.isDirectory()) { System.err.println("Ignoring sub-folder \"" + exportList[i] + "\""); } else if (exportFile.getName().toLowerCase().endsWith(".zip") || exportFile.getName().toLowerCase().endsWith(".jar")) { packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos); } else { // just copy the file over.. prolly a .dll or something Base.copyFile(exportFile, new File(appletFolder, exportFile.getName())); } } } */ /* String bagelJar = "lib/core.jar"; packClassPathIntoZipFile(bagelJar, zos); // files to include from data directory // TODO this needs to be recursive if (dataFolder.exists()) { String dataFiles[] = dataFolder.list(); for (int i = 0; i < dataFiles.length; i++) { // don't export hidden files // skipping dot prefix removes all: . .. .DS_Store if (dataFiles[i].charAt(0) == '.') continue; entry = new ZipEntry(dataFiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(dataFolder, dataFiles[i]))); zos.closeEntry(); } } // add the project's .class files to the jar // just grabs everything from the build directory // since there may be some inner classes // (add any .class files from the applet dir, then delete them) // TODO this needs to be recursive (for packages) String classfiles[] = appletFolder.list(); for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { entry = new ZipEntry(classfiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(appletFolder, classfiles[i]))); zos.closeEntry(); } } */ String classfiles[] = appletFolder.list(); // remove the .class files from the applet folder. if they're not // removed, the msjvm will complain about an illegal access error, // since the classes are outside the jar file. for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { File deadguy = new File(appletFolder, classfiles[i]); if (!deadguy.delete()) { Base.showWarning("Could not delete", classfiles[i] + " could not \n" + "be deleted from the applet folder. \n" + "You'll need to remove it by hand.", null); } } } // close up the jar file /* zos.flush(); zos.close(); */ if(Preferences.getBoolean("uploader.open_folder")) Base.openFolder(appletFolder); return true; } /** * Export to application. * <PRE> * +-------------------------------------------------------+ * + + * + Export to: [ Application + ] [ OK ] + * + + * + > Advanced + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.1 + ] + * + + * + Not much point to using Java 1.1 for applications. + * + To run applications, all users will have to + * + install Java, in which case they'll most likely + * + have version 1.3 or later. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.3 + ] + * + + * + Java 1.3 is the recommended setting for exporting + * + applications. Applications will run on any Windows + * + or Unix machine with Java installed. Mac OS X has + * + Java installed with the operation system, so there + * + is no additional installation will be required. + * + + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + + * + Platform: [ Mac OS X + ] <-- defaults to current platform * + + * + Exports the application as a double-clickable + * + .app package, compatible with Mac OS X. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Platform: [ Windows + ] + * + + * + Exports the application as a double-clickable + * + .exe and a handful of supporting files. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Platform: [ jar file + ] + * + + * + A jar file can be used on any platform that has + * + Java installed. Simply doube-click the jar (or type + * + "java -jar sketch.jar" at a command prompt) to run + * + the application. It is the least fancy method for + * + exporting. + * + + * +-------------------------------------------------------+ * </PRE> */ public boolean exportApplication() { return true; } /* public void addManifest(ZipOutputStream zos) throws IOException { ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF"); zos.putNextEntry(entry); String contents = "Manifest-Version: 1.0\n" + "Created-By: Processing " + Base.VERSION_NAME + "\n" + "Main-Class: " + name + "\n"; // TODO not package friendly zos.write(contents.getBytes()); zos.closeEntry(); */ /* for (int i = 0; i < bagelClasses.length; i++) { if (!bagelClasses[i].endsWith(".class")) continue; entry = new ZipEntry(bagelClasses[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(exportDir + bagelClasses[i]))); zos.closeEntry(); } */ /* } */ /** * Slurps up .class files from a colon (or semicolon on windows) * separated list of paths and adds them to a ZipOutputStream. */ /* public void packClassPathIntoZipFile(String path, ZipOutputStream zos) throws IOException { String pieces[] = PApplet.split(path, File.pathSeparatorChar); for (int i = 0; i < pieces.length; i++) { if (pieces[i].length() == 0) continue; //System.out.println("checking piece " + pieces[i]); // is it a jar file or directory? if (pieces[i].toLowerCase().endsWith(".jar") || pieces[i].toLowerCase().endsWith(".zip")) { try { ZipFile file = new ZipFile(pieces[i]); Enumeration entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { // actually 'continue's for all dir entries } else { String entryName = entry.getName(); // ignore contents of the META-INF folders if (entryName.indexOf("META-INF") == 0) continue; // don't allow duplicate entries if (zipFileContents.get(entryName) != null) continue; zipFileContents.put(entryName, new Object()); ZipEntry entree = new ZipEntry(entryName); zos.putNextEntry(entree); byte buffer[] = new byte[(int) entry.getSize()]; InputStream is = file.getInputStream(entry); int offset = 0; int remaining = buffer.length; while (remaining > 0) { int count = is.read(buffer, offset, remaining); offset += count; remaining -= count; } zos.write(buffer); zos.flush(); zos.closeEntry(); } } } catch (IOException e) { System.err.println("Error in file " + pieces[i]); e.printStackTrace(); } } else { // not a .jar or .zip, prolly a directory File dir = new File(pieces[i]); // but must be a dir, since it's one of several paths // just need to check if it exists if (dir.exists()) { packClassPathIntoZipFileRecursive(dir, null, zos); } } } } */ /** * Continue the process of magical exporting. This function * can be called recursively to walk through folders looking * for more goodies that will be added to the ZipOutputStream. */ /* static public void packClassPathIntoZipFileRecursive(File dir, String sofar, ZipOutputStream zos) throws IOException { String files[] = dir.list(); for (int i = 0; i < files.length; i++) { // ignore . .. and .DS_Store if (files[i].charAt(0) == '.') continue; File sub = new File(dir, files[i]); String nowfar = (sofar == null) ? files[i] : (sofar + "/" + files[i]); if (sub.isDirectory()) { packClassPathIntoZipFileRecursive(sub, nowfar, zos); } else { // don't add .jar and .zip files, since they only work // inside the root, and they're unpacked if (!files[i].toLowerCase().endsWith(".jar") && !files[i].toLowerCase().endsWith(".zip") && files[i].charAt(0) != '.') { ZipEntry entry = new ZipEntry(nowfar); zos.putNextEntry(entry); zos.write(Base.grabFile(sub)); zos.closeEntry(); } } } } */ /** * Make sure the sketch hasn't been moved or deleted by some * nefarious user. If they did, try to re-create it and save. * Only checks to see if the main folder is still around, * but not its contents. */ protected void ensureExistence() { if (folder.exists()) return; Base.showWarning("Sketch Disappeared", "The sketch folder has disappeared.\n " + "Will attempt to re-save in the same location,\n" + "but anything besides the code will be lost.", null); try { folder.mkdirs(); modified = true; for (int i = 0; i < codeCount; i++) { code[i].save(); // this will force a save } for (int i = 0; i < hiddenCount; i++) { hidden[i].save(); // this will force a save } calcModified(); } catch (Exception e) { Base.showWarning("Could not re-save sketch", "Could not properly re-save the sketch. " + "You may be in trouble at this point,\n" + "and it might be time to copy and paste " + "your code to another text editor.", e); } } /** * Returns true if this is a read-only sketch. Used for the * examples directory, or when sketches are loaded from read-only * volumes or folders without appropriate permissions. */ public boolean isReadOnly() { String apath = folder.getAbsolutePath(); if (apath.startsWith(Sketchbook.examplesPath) || apath.startsWith(Sketchbook.librariesPath)) { return true; // canWrite() doesn't work on directories //} else if (!folder.canWrite()) { } else { // check to see if each modified code file can be written to for (int i = 0; i < codeCount; i++) { if (code[i].modified && !code[i].file.canWrite() && code[i].file.exists()) { //System.err.println("found a read-only file " + code[i].file); return true; } } //return true; } return false; } /** * Returns path to the main .pde file for this sketch. */ public String getMainFilePath() { return code[0].file.getAbsolutePath(); } }
false
true
public void importLibrary(String jarPath) { System.out.println(jarPath); /* // make sure the user didn't hide the sketch folder ensureExistence(); String list[] = Compiler.packageListFromClassPath(jarPath); // import statements into the main sketch file (code[0]) // if the current code is a .java file, insert into current if (current.flavor == PDE) { setCurrent(0); } // could also scan the text in the file to see if each import // statement is already in there, but if the user has the import // commented out, then this will be a problem. StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { buffer.append("import "); buffer.append(list[i]); buffer.append(".*;\n"); } buffer.append('\n'); buffer.append(editor.getText()); editor.setText(buffer.toString(), 0, 0); // scroll to start setModified(); */ } /** * Change what file is currently being edited. * <OL> * <LI> store the String for the text of the current file. * <LI> retrieve the String for the text of the new file. * <LI> change the text that's visible in the text area * </OL> */ public void setCurrent(int which) { if (current == code[which]) { //System.out.println("already current, ignoring"); return; } // get the text currently being edited if (current != null) { current.program = editor.getText(); current.selectionStart = editor.textarea.getSelectionStart(); current.selectionStop = editor.textarea.getSelectionEnd(); current.scrollPosition = editor.textarea.getScrollPosition(); } current = code[which]; editor.setCode(current); //editor.setDocument(current.document, // current.selectionStart, current.selectionStop, // current.scrollPosition, current.undo); // set to the text for this file // 'true' means to wipe out the undo buffer // (so they don't undo back to the other file.. whups!) /* editor.setText(current.program, current.selectionStart, current.selectionStop, current.undo); */ // set stored caret and scroll positions //editor.textarea.setScrollPosition(current.scrollPosition); //editor.textarea.select(current.selectionStart, current.selectionStop); //editor.textarea.setSelectionStart(current.selectionStart); //editor.textarea.setSelectionEnd(current.selectionStop); editor.header.rebuild(); } /** * Internal helper function to set the current tab * based on a name (used by codeNew and codeRename). */ protected void setCurrent(String findName) { for (int i = 0; i < codeCount; i++) { if (findName.equals(code[i].name)) { setCurrent(i); return; } } } /** * Cleanup temporary files used during a build/run. */ protected void cleanup() { // if the java runtime is holding onto any files in the build dir, we // won't be able to delete them, so we need to force a gc here System.gc(); // note that we can't remove the builddir itself, otherwise // the next time we start up, internal runs using Runner won't // work because the build dir won't exist at startup, so the classloader // will ignore the fact that that dir is in the CLASSPATH in run.sh Base.removeDescendants(tempBuildFolder); } /** * Preprocess, Compile, and Run the current code. * <P> * There are three main parts to this process: * <PRE> * (0. if not java, then use another 'engine'.. i.e. python) * * 1. do the p5 language preprocessing * this creates a working .java file in a specific location * better yet, just takes a chunk of java code and returns a * new/better string editor can take care of saving this to a * file location * * 2. compile the code from that location * catching errors along the way * placing it in a ready classpath, or .. ? * * 3. run the code * needs to communicate location for window * and maybe setup presentation space as well * run externally if a code folder exists, * or if more than one file is in the project * * X. afterwards, some of these steps need a cleanup function * </PRE> */ public boolean handleRun(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); current.program = editor.getText(); // TODO record history here //current.history.record(program, SketchHistory.RUN); // if an external editor is being used, need to grab the // latest version of the code from the file. if (Preferences.getBoolean("editor.external")) { // history gets screwed by the open.. //String historySaved = history.lastRecorded; //handleOpen(sketch); //history.lastRecorded = historySaved; // nuke previous files and settings, just get things loaded load(); } // in case there were any boogers left behind // do this here instead of after exiting, since the exit // can happen so many different ways.. and this will be // better connected to the dataFolder stuff below. cleanup(); // make up a temporary class name to suggest. // name will only be used if the code is not in ADVANCED mode. String suggestedClassName = ("Temporary_" + String.valueOf((int) (Math.random() * 10000)) + "_" + String.valueOf((int) (Math.random() * 10000))); // handle preprocessing the main file's code //mainClassName = build(TEMP_BUILD_PATH, suggestedClassName); mainClassName = build(target, tempBuildFolder.getAbsolutePath(), suggestedClassName); // externalPaths is magically set by build() if (!externalRuntime) { // only if not running externally already // copy contents of data dir into lib/build if (dataFolder.exists()) { // just drop the files in the build folder (pre-68) //Base.copyDir(dataDir, buildDir); // drop the files into a 'data' subfolder of the build dir try { Base.copyDir(dataFolder, new File(tempBuildFolder, "data")); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem copying files from data folder"); } } } return (mainClassName != null); } /** * Build all the code for this sketch. * * In an advanced program, the returned classname could be different, * which is why the className is set based on the return value. * A compilation error will burp up a RunnerException. * * @return null if compilation failed, main class name if not */ protected String build(Target target, String buildPath, String suggestedClassName) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); String codeFolderPackages[] = null; String javaClassPath = System.getProperty("java.class.path"); // remove quotes if any.. this is an annoying thing on windows if (javaClassPath.startsWith("\"") && javaClassPath.endsWith("\"")) { javaClassPath = javaClassPath.substring(1, javaClassPath.length() - 1); } classPath = buildPath + File.pathSeparator + Sketchbook.librariesClassPath + File.pathSeparator + javaClassPath; //System.out.println("cp = " + classPath); // figure out the contents of the code folder to see if there // are files that need to be added to the imports //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { externalRuntime = true; //classPath += File.pathSeparator + //Compiler.contentsToClassPath(codeFolder); classPath = Compiler.contentsToClassPath(codeFolder) + File.pathSeparator + classPath; //codeFolderPackages = Compiler.packageListFromClassPath(classPath); //codeFolderPackages = Compiler.packageListFromClassPath(codeFolder); libraryPath = codeFolder.getAbsolutePath(); // get a list of .jar files in the "code" folder // (class files in subfolders should also be picked up) String codeFolderClassPath = Compiler.contentsToClassPath(codeFolder); // get list of packages found in those jars // codeFolderPackages = // Compiler.packageListFromClassPath(codeFolderClassPath); //PApplet.println(libraryPath); //PApplet.println("packages:"); //PApplet.printarr(codeFolderPackages); } else { // since using the special classloader, // run externally whenever there are extra classes defined //externalRuntime = (codeCount > 1); // this no longer appears to be true.. so scrapping for 0088 // check to see if multiple files that include a .java file externalRuntime = false; for (int i = 0; i < codeCount; i++) { if (code[i].flavor == JAVA) { externalRuntime = true; break; } } //codeFolderPackages = null; libraryPath = ""; } // if 'data' folder is large, set to external runtime if (dataFolder.exists() && Base.calcFolderSize(dataFolder) > 768 * 1024) { // if > 768k externalRuntime = true; } // 1. concatenate all .pde files to the 'main' pde // store line number for starting point of each code bit StringBuffer bigCode = new StringBuffer(code[0].program); int bigCount = countLines(code[0].program); for (int i = 1; i < codeCount; i++) { if (code[i].flavor == PDE) { code[i].preprocOffset = ++bigCount; bigCode.append('\n'); bigCode.append(code[i].program); bigCount += countLines(code[i].program); code[i].preprocName = null; // don't compile me } } // since using the special classloader, // run externally whenever there are extra classes defined /* if ((bigCode.indexOf(" class ") != -1) || (bigCode.indexOf("\nclass ") != -1)) { externalRuntime = true; } */ // if running in opengl mode, this is gonna be external //if (Preferences.get("renderer").equals("opengl")) { //externalRuntime = true; //} // 2. run preproc on that code using the sugg class name // to create a single .java file and write to buildpath String primaryClassName = null; PdePreprocessor preprocessor = new PdePreprocessor(); try { // if (i != 0) preproc will fail if a pde file is not // java mode, since that's required String className = preprocessor.write(bigCode.toString(), buildPath, suggestedClassName, codeFolderPackages); if (className == null) { throw new RunnerException("Could not find main class"); // this situation might be perfectly fine, // (i.e. if the file is empty) //System.out.println("No class found in " + code[i].name); //System.out.println("(any code in that file will be ignored)"); //System.out.println(); } else { //code[0].preprocName = className + "." + Preferences.get("build.extension"); code[0].preprocName = className + ".cpp"; } // store this for the compiler and the runtime primaryClassName = className; //System.out.println("primary class " + primaryClassName); // check if the 'main' file is in java mode if ((PdePreprocessor.programType == PdePreprocessor.JAVA) || (preprocessor.extraImports.length != 0)) { externalRuntime = true; // we in advanced mode now, boy } } catch (antlr.RecognitionException re) { // this even returns a column int errorFile = 0; int errorLine = re.getLine() - 1; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; //errorLine -= preprocessor.prototypeCount; throw new RunnerException(re.getMessage(), errorFile, errorLine, re.getColumn()); } catch (antlr.TokenStreamRecognitionException tsre) { // while this seems to store line and column internally, // there doesn't seem to be a method to grab it.. // so instead it's done using a regexp PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // line 3:1: unexpected char: 0xA0 String mess = "^line (\\d+):(\\d+):\\s"; Pattern pattern = null; try { pattern = compiler.compile(mess); } catch (MalformedPatternException e) { Base.showWarning("Internal Problem", "An internal error occurred while trying\n" + "to compile the sketch. Please report\n" + "this online at " + "https://developer.berlios.de/bugs/?group_id=3590", e); } PatternMatcherInput input = new PatternMatcherInput(tsre.toString()); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); int errorLine = Integer.parseInt(result.group(1).toString()) - 1; int errorColumn = Integer.parseInt(result.group(2).toString()); int errorFile = 0; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; //errorLine -= preprocessor.prototypeCount; throw new RunnerException(tsre.getMessage(), errorFile, errorLine, errorColumn); } else { // this is bad, defaults to the main class.. hrm. throw new RunnerException(tsre.toString(), 0, -1, -1); } } catch (RunnerException pe) { // RunnerExceptions are caught here and re-thrown, so that they don't // get lost in the more general "Exception" handler below. throw pe; } catch (Exception ex) { // TODO better method for handling this? System.err.println("Uncaught exception type:" + ex.getClass()); ex.printStackTrace(); throw new RunnerException(ex.toString()); } // grab the imports from the code just preproc'd importedLibraries = new Vector(); String imports[] = preprocessor.extraImports; for (int i = 0; i < imports.length; i++) { // remove things up to the last dot String entry = imports[i].substring(0, imports[i].lastIndexOf('.')); //System.out.println("found package " + entry); File libFolder = (File) Sketchbook.importToLibraryTable.get(entry); if (libFolder == null) { //throw new RunnerException("Could not find library for " + entry); continue; } importedLibraries.add(libFolder); libraryPath += File.pathSeparator + libFolder.getAbsolutePath(); /* String list[] = libFolder.list(); if (list != null) { for (int j = 0; j < list.length; j++) { // this might have a dll/jnilib/so packed, // so add it to the library path if (list[j].toLowerCase().endsWith(".jar")) { libraryPath += File.pathSeparator + libFolder.getAbsolutePath() + File.separator + list[j]; } } } */ } // 3. then loop over the code[] and save each .java file for (int i = 0; i < codeCount; i++) { if (code[i].flavor == JAVA) { // no pre-processing services necessary for java files // just write the the contents of 'program' to a .java file // into the build directory. uses byte stream and reader/writer // shtuff so that unicode bunk is properly handled //String filename = code[i].name + "." + Preferences.get("build.extension"); String filename = code[i].name + ".cpp"; try { Base.saveFile(code[i].program, new File(buildPath, filename)); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem moving " + filename + " to the build folder"); } code[i].preprocName = filename; } } // compile the program. errors will happen as a RunnerException // that will bubble up to whomever called build(). // // note: this has been changed to catch build exceptions, adjust // line number for number of included prototypes, and rethrow Compiler compiler = new Compiler(); boolean success; try { success = compiler.compile(this, buildPath, target); } catch (RunnerException re) { throw new RunnerException(re.getMessage(), re.file, re.line,// - preprocessor.prototypeCount, re.column); } catch (Exception ex) { // TODO better method for handling this? throw new RunnerException(ex.toString()); } //System.out.println("success = " + success + " ... " + primaryClassName); return success ? primaryClassName : null; } protected void size(String buildPath, String suggestedClassName) throws RunnerException { long size = 0; Sizer sizer = new Sizer(buildPath, suggestedClassName); try { size = sizer.computeSize(); System.out.println("Binary sketch size: " + size + " bytes (of a " + Preferences.get("upload.maximum_size") + " byte maximum)"); } catch (RunnerException e) { System.err.println("Couldn't determine program size: " + e.getMessage()); } if (size > Preferences.getInteger("upload.maximum_size")) throw new RunnerException( "Sketch too big; try deleting code, removing floats, or see " + "http://www.arduino.cc/en/Main/FAQ for more advice."); } protected String upload(String buildPath, String suggestedClassName) throws RunnerException { // download the program // Uploader downloader = new Uploader(buildPath, suggestedClassName, this); // macos9 now officially broken.. see PdeCompilerJavac //PdeCompiler compiler = // ((PdeBase.platform == PdeBase.MACOS9) ? // new PdeCompilerJavac(buildPath, className, this) : // new PdeCompiler(buildPath, className, this)); // run the compiler, and funnel errors to the leechErr // which is a wrapped around // (this will catch and parse errors during compilation // the messageStream will call message() for 'compiler') MessageStream messageStream = new MessageStream(downloader); //PrintStream leechErr = new PrintStream(messageStream); //boolean result = compiler.compileJava(leechErr); //return compiler.compileJava(leechErr); boolean success = downloader.downloadJava(new PrintStream(messageStream)); return success ? suggestedClassName : null; } protected int countLines(String what) { char c[] = what.toCharArray(); int count = 0; for (int i = 0; i < c.length; i++) { if (c[i] == '\n') count++; } return count; } /** * Initiate export to applet. * <PRE> * +-------------------------------------------------------+ * + + * + Export to: [ Applet (for the web) + ] [ OK ] + * + + * + > Advanced + * + + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.1 + ] + * + + * + Recommended version of Java when exporting applets. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.3 + ] + * + + * + Java 1.3 is not recommended for applets, + * + unless you are using features that require it. + * + Using a version of Java other than 1.1 will require + * + your Windows users to install the Java Plug-In, + * + and your Macintosh users to be running OS X. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.4 + ] + * + + * + identical message as 1.3 above... + * + + * +-------------------------------------------------------+ * </PRE> */ public boolean exportApplet(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); zipFileContents = new Hashtable(); // nuke the old applet folder because it can cause trouble File appletFolder = new File(folder, "applet"); Base.removeDir(appletFolder); appletFolder.mkdirs(); // build the sketch String foundName = build(target, appletFolder.getPath(), name); size(appletFolder.getPath(), name); foundName = upload(appletFolder.getPath(), name); // (already reported) error during export, exit this function if (foundName == null) return false; // if name != exportSketchName, then that's weirdness // BUG unfortunately, that can also be a bug in the preproc :( if (!name.equals(foundName)) { Base.showWarning("Error during export", "Sketch name is " + name + " but the sketch\n" + "name in the code was " + foundName, null); return false; } /* int wide = PApplet.DEFAULT_WIDTH; int high = PApplet.DEFAULT_HEIGHT; PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // this matches against any uses of the size() function, // whether they contain numbers of variables or whatever. // this way, no warning is shown if size() isn't actually // used in the applet, which is the case especially for // beginners that are cutting/pasting from the reference. // modified for 83 to match size(XXX, ddd so that it'll // properly handle size(200, 200) and size(200, 200, P3D) String sizing = "[\\s\\;]size\\s*\\(\\s*(\\S+)\\s*,\\s*(\\d+)"; Pattern pattern = compiler.compile(sizing); // adds a space at the beginning, in case size() is the very // first thing in the program (very common), since the regexp // needs to check for things in front of it. PatternMatcherInput input = new PatternMatcherInput(" " + code[0].program); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); try { wide = Integer.parseInt(result.group(1).toString()); high = Integer.parseInt(result.group(2).toString()); } catch (NumberFormatException e) { // found a reference to size, but it didn't // seem to contain numbers final String message = "The size of this applet could not automatically be\n" + "determined from your code. You'll have to edit the\n" + "HTML file to set the size of the applet."; Base.showWarning("Could not find applet size", message, null); } } // else no size() command found // originally tried to grab this with a regexp matcher, // but it wouldn't span over multiple lines for the match. // this could prolly be forced, but since that's the case // better just to parse by hand. StringBuffer dbuffer = new StringBuffer(); String lines[] = PApplet.split(code[0].program, '\n'); for (int i = 0; i < lines.length; i++) { if (lines[i].trim().startsWith("/**")) { // this is our comment */ // some smartass put the whole thing on the same line //if (lines[j].indexOf("*/") != -1) break; // for (int j = i+1; j < lines.length; j++) { // if (lines[j].trim().endsWith("*/")) { // remove the */ from the end, and any extra *s // in case there's also content on this line // nah, don't bother.. make them use the three lines // break; // } /* int offset = 0; while ((offset < lines[j].length()) && ((lines[j].charAt(offset) == '*') || (lines[j].charAt(offset) == ' '))) { offset++; } // insert the return into the html to help w/ line breaks dbuffer.append(lines[j].substring(offset) + "\n"); } } } String description = dbuffer.toString(); StringBuffer sources = new StringBuffer(); for (int i = 0; i < codeCount; i++) { sources.append("<a href=\"" + code[i].file.getName() + "\">" + code[i].name + "</a> "); } File htmlOutputFile = new File(appletFolder, "index.html"); FileOutputStream fos = new FileOutputStream(htmlOutputFile); PrintStream ps = new PrintStream(fos); // @@sketch@@, @@width@@, @@height@@, @@archive@@, @@source@@ // and now @@description@@ InputStream is = null; // if there is an applet.html file in the sketch folder, use that File customHtml = new File(folder, "applet.html"); if (customHtml.exists()) { is = new FileInputStream(customHtml); } if (is == null) { is = Base.getStream("applet.html"); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = reader.readLine()) != null) { if (line.indexOf("@@") != -1) { StringBuffer sb = new StringBuffer(line); int index = 0; while ((index = sb.indexOf("@@sketch@@")) != -1) { sb.replace(index, index + "@@sketch@@".length(), name); } while ((index = sb.indexOf("@@source@@")) != -1) { sb.replace(index, index + "@@source@@".length(), sources.toString()); } while ((index = sb.indexOf("@@archive@@")) != -1) { sb.replace(index, index + "@@archive@@".length(), name + ".jar"); } while ((index = sb.indexOf("@@width@@")) != -1) { sb.replace(index, index + "@@width@@".length(), String.valueOf(wide)); } while ((index = sb.indexOf("@@height@@")) != -1) { sb.replace(index, index + "@@height@@".length(), String.valueOf(high)); } while ((index = sb.indexOf("@@description@@")) != -1) { sb.replace(index, index + "@@description@@".length(), description); } line = sb.toString(); } ps.println(line); } reader.close(); ps.flush(); ps.close(); // copy the loading gif to the applet String LOADING_IMAGE = "loading.gif"; File loadingImage = new File(folder, LOADING_IMAGE); if (!loadingImage.exists()) { loadingImage = new File("lib", LOADING_IMAGE); } Base.copyFile(loadingImage, new File(appletFolder, LOADING_IMAGE)); */ // copy the source files to the target, since we like // to encourage people to share their code for (int i = 0; i < codeCount; i++) { try { Base.copyFile(code[i].file, new File(appletFolder, code[i].file.getName())); } catch (IOException e) { e.printStackTrace(); } } /* // create new .jar file FileOutputStream zipOutputFile = new FileOutputStream(new File(appletFolder, name + ".jar")); ZipOutputStream zos = new ZipOutputStream(zipOutputFile); ZipEntry entry; // add the manifest file addManifest(zos); // add the contents of the code folder to the jar // unpacks all jar files //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { String includes = Compiler.contentsToClassPath(codeFolder); packClassPathIntoZipFile(includes, zos); } // add contents of 'library' folders to the jar file // if a file called 'export.txt' is in there, it contains // a list of the files that should be exported. // otherwise, all files are exported. Enumeration en = importedLibraries.elements(); while (en.hasMoreElements()) { // in the list is a File object that points the // library sketch's "library" folder File libraryFolder = (File)en.nextElement(); File exportSettings = new File(libraryFolder, "export.txt"); String exportList[] = null; if (exportSettings.exists()) { String info[] = Base.loadStrings(exportSettings); for (int i = 0; i < info.length; i++) { if (info[i].startsWith("applet")) { int idx = info[i].indexOf('='); // get applet= or applet = String commas = info[i].substring(idx+1).trim(); exportList = PApplet.split(commas, ", "); } } } else { exportList = libraryFolder.list(); } for (int i = 0; i < exportList.length; i++) { if (exportList[i].equals(".") || exportList[i].equals("..")) continue; exportList[i] = PApplet.trim(exportList[i]); if (exportList[i].equals("")) continue; File exportFile = new File(libraryFolder, exportList[i]); if (!exportFile.exists()) { System.err.println("File " + exportList[i] + " does not exist"); } else if (exportFile.isDirectory()) { System.err.println("Ignoring sub-folder \"" + exportList[i] + "\""); } else if (exportFile.getName().toLowerCase().endsWith(".zip") || exportFile.getName().toLowerCase().endsWith(".jar")) { packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos); } else { // just copy the file over.. prolly a .dll or something Base.copyFile(exportFile, new File(appletFolder, exportFile.getName())); } } } */ /* String bagelJar = "lib/core.jar"; packClassPathIntoZipFile(bagelJar, zos); // files to include from data directory // TODO this needs to be recursive if (dataFolder.exists()) { String dataFiles[] = dataFolder.list(); for (int i = 0; i < dataFiles.length; i++) { // don't export hidden files // skipping dot prefix removes all: . .. .DS_Store if (dataFiles[i].charAt(0) == '.') continue; entry = new ZipEntry(dataFiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(dataFolder, dataFiles[i]))); zos.closeEntry(); } } // add the project's .class files to the jar // just grabs everything from the build directory // since there may be some inner classes // (add any .class files from the applet dir, then delete them) // TODO this needs to be recursive (for packages) String classfiles[] = appletFolder.list(); for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { entry = new ZipEntry(classfiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(appletFolder, classfiles[i]))); zos.closeEntry(); } } */ String classfiles[] = appletFolder.list(); // remove the .class files from the applet folder. if they're not // removed, the msjvm will complain about an illegal access error, // since the classes are outside the jar file. for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { File deadguy = new File(appletFolder, classfiles[i]); if (!deadguy.delete()) { Base.showWarning("Could not delete", classfiles[i] + " could not \n" + "be deleted from the applet folder. \n" + "You'll need to remove it by hand.", null); } } } // close up the jar file /* zos.flush(); zos.close(); */ if(Preferences.getBoolean("uploader.open_folder")) Base.openFolder(appletFolder); return true; }
public void importLibrary(String jarPath) { System.out.println(jarPath); /* // make sure the user didn't hide the sketch folder ensureExistence(); String list[] = Compiler.packageListFromClassPath(jarPath); // import statements into the main sketch file (code[0]) // if the current code is a .java file, insert into current if (current.flavor == PDE) { setCurrent(0); } // could also scan the text in the file to see if each import // statement is already in there, but if the user has the import // commented out, then this will be a problem. StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { buffer.append("import "); buffer.append(list[i]); buffer.append(".*;\n"); } buffer.append('\n'); buffer.append(editor.getText()); editor.setText(buffer.toString(), 0, 0); // scroll to start setModified(); */ } /** * Change what file is currently being edited. * <OL> * <LI> store the String for the text of the current file. * <LI> retrieve the String for the text of the new file. * <LI> change the text that's visible in the text area * </OL> */ public void setCurrent(int which) { if (current == code[which]) { //System.out.println("already current, ignoring"); return; } // get the text currently being edited if (current != null) { current.program = editor.getText(); current.selectionStart = editor.textarea.getSelectionStart(); current.selectionStop = editor.textarea.getSelectionEnd(); current.scrollPosition = editor.textarea.getScrollPosition(); } current = code[which]; editor.setCode(current); //editor.setDocument(current.document, // current.selectionStart, current.selectionStop, // current.scrollPosition, current.undo); // set to the text for this file // 'true' means to wipe out the undo buffer // (so they don't undo back to the other file.. whups!) /* editor.setText(current.program, current.selectionStart, current.selectionStop, current.undo); */ // set stored caret and scroll positions //editor.textarea.setScrollPosition(current.scrollPosition); //editor.textarea.select(current.selectionStart, current.selectionStop); //editor.textarea.setSelectionStart(current.selectionStart); //editor.textarea.setSelectionEnd(current.selectionStop); editor.header.rebuild(); } /** * Internal helper function to set the current tab * based on a name (used by codeNew and codeRename). */ protected void setCurrent(String findName) { for (int i = 0; i < codeCount; i++) { if (findName.equals(code[i].name)) { setCurrent(i); return; } } } /** * Cleanup temporary files used during a build/run. */ protected void cleanup() { // if the java runtime is holding onto any files in the build dir, we // won't be able to delete them, so we need to force a gc here System.gc(); // note that we can't remove the builddir itself, otherwise // the next time we start up, internal runs using Runner won't // work because the build dir won't exist at startup, so the classloader // will ignore the fact that that dir is in the CLASSPATH in run.sh Base.removeDescendants(tempBuildFolder); } /** * Preprocess, Compile, and Run the current code. * <P> * There are three main parts to this process: * <PRE> * (0. if not java, then use another 'engine'.. i.e. python) * * 1. do the p5 language preprocessing * this creates a working .java file in a specific location * better yet, just takes a chunk of java code and returns a * new/better string editor can take care of saving this to a * file location * * 2. compile the code from that location * catching errors along the way * placing it in a ready classpath, or .. ? * * 3. run the code * needs to communicate location for window * and maybe setup presentation space as well * run externally if a code folder exists, * or if more than one file is in the project * * X. afterwards, some of these steps need a cleanup function * </PRE> */ public boolean handleRun(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); current.program = editor.getText(); // TODO record history here //current.history.record(program, SketchHistory.RUN); // if an external editor is being used, need to grab the // latest version of the code from the file. if (Preferences.getBoolean("editor.external")) { // history gets screwed by the open.. //String historySaved = history.lastRecorded; //handleOpen(sketch); //history.lastRecorded = historySaved; // nuke previous files and settings, just get things loaded load(); } // in case there were any boogers left behind // do this here instead of after exiting, since the exit // can happen so many different ways.. and this will be // better connected to the dataFolder stuff below. cleanup(); // make up a temporary class name to suggest. // name will only be used if the code is not in ADVANCED mode. String suggestedClassName = ("Temporary_" + String.valueOf((int) (Math.random() * 10000)) + "_" + String.valueOf((int) (Math.random() * 10000))); // handle preprocessing the main file's code //mainClassName = build(TEMP_BUILD_PATH, suggestedClassName); mainClassName = build(target, tempBuildFolder.getAbsolutePath(), suggestedClassName); // externalPaths is magically set by build() if (!externalRuntime) { // only if not running externally already // copy contents of data dir into lib/build if (dataFolder.exists()) { // just drop the files in the build folder (pre-68) //Base.copyDir(dataDir, buildDir); // drop the files into a 'data' subfolder of the build dir try { Base.copyDir(dataFolder, new File(tempBuildFolder, "data")); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem copying files from data folder"); } } } return (mainClassName != null); } /** * Build all the code for this sketch. * * In an advanced program, the returned classname could be different, * which is why the className is set based on the return value. * A compilation error will burp up a RunnerException. * * @return null if compilation failed, main class name if not */ protected String build(Target target, String buildPath, String suggestedClassName) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); String codeFolderPackages[] = null; String javaClassPath = System.getProperty("java.class.path"); // remove quotes if any.. this is an annoying thing on windows if (javaClassPath.startsWith("\"") && javaClassPath.endsWith("\"")) { javaClassPath = javaClassPath.substring(1, javaClassPath.length() - 1); } classPath = buildPath + File.pathSeparator + Sketchbook.librariesClassPath + File.pathSeparator + javaClassPath; //System.out.println("cp = " + classPath); // figure out the contents of the code folder to see if there // are files that need to be added to the imports //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { externalRuntime = true; //classPath += File.pathSeparator + //Compiler.contentsToClassPath(codeFolder); classPath = Compiler.contentsToClassPath(codeFolder) + File.pathSeparator + classPath; //codeFolderPackages = Compiler.packageListFromClassPath(classPath); //codeFolderPackages = Compiler.packageListFromClassPath(codeFolder); libraryPath = codeFolder.getAbsolutePath(); // get a list of .jar files in the "code" folder // (class files in subfolders should also be picked up) String codeFolderClassPath = Compiler.contentsToClassPath(codeFolder); // get list of packages found in those jars // codeFolderPackages = // Compiler.packageListFromClassPath(codeFolderClassPath); //PApplet.println(libraryPath); //PApplet.println("packages:"); //PApplet.printarr(codeFolderPackages); } else { // since using the special classloader, // run externally whenever there are extra classes defined //externalRuntime = (codeCount > 1); // this no longer appears to be true.. so scrapping for 0088 // check to see if multiple files that include a .java file externalRuntime = false; for (int i = 0; i < codeCount; i++) { if (code[i].flavor == JAVA) { externalRuntime = true; break; } } //codeFolderPackages = null; libraryPath = ""; } // if 'data' folder is large, set to external runtime if (dataFolder.exists() && Base.calcFolderSize(dataFolder) > 768 * 1024) { // if > 768k externalRuntime = true; } // 1. concatenate all .pde files to the 'main' pde // store line number for starting point of each code bit StringBuffer bigCode = new StringBuffer(code[0].program); int bigCount = countLines(code[0].program); for (int i = 1; i < codeCount; i++) { if (code[i].flavor == PDE) { code[i].preprocOffset = ++bigCount; bigCode.append('\n'); bigCode.append(code[i].program); bigCount += countLines(code[i].program); code[i].preprocName = null; // don't compile me } } // since using the special classloader, // run externally whenever there are extra classes defined /* if ((bigCode.indexOf(" class ") != -1) || (bigCode.indexOf("\nclass ") != -1)) { externalRuntime = true; } */ // if running in opengl mode, this is gonna be external //if (Preferences.get("renderer").equals("opengl")) { //externalRuntime = true; //} // 2. run preproc on that code using the sugg class name // to create a single .java file and write to buildpath String primaryClassName = null; PdePreprocessor preprocessor = new PdePreprocessor(); try { // if (i != 0) preproc will fail if a pde file is not // java mode, since that's required String className = preprocessor.write(bigCode.toString(), buildPath, suggestedClassName, codeFolderPackages); if (className == null) { throw new RunnerException("Could not find main class"); // this situation might be perfectly fine, // (i.e. if the file is empty) //System.out.println("No class found in " + code[i].name); //System.out.println("(any code in that file will be ignored)"); //System.out.println(); } else { //code[0].preprocName = className + "." + Preferences.get("build.extension"); code[0].preprocName = className + ".cpp"; } // store this for the compiler and the runtime primaryClassName = className; //System.out.println("primary class " + primaryClassName); // check if the 'main' file is in java mode if ((PdePreprocessor.programType == PdePreprocessor.JAVA) || (preprocessor.extraImports.length != 0)) { externalRuntime = true; // we in advanced mode now, boy } } catch (antlr.RecognitionException re) { // this even returns a column int errorFile = 0; int errorLine = re.getLine() - 1; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; errorLine -= preprocessor.prototypeCount; throw new RunnerException(re.getMessage(), errorFile, errorLine, re.getColumn()); } catch (antlr.TokenStreamRecognitionException tsre) { // while this seems to store line and column internally, // there doesn't seem to be a method to grab it.. // so instead it's done using a regexp PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // line 3:1: unexpected char: 0xA0 String mess = "^line (\\d+):(\\d+):\\s"; Pattern pattern = null; try { pattern = compiler.compile(mess); } catch (MalformedPatternException e) { Base.showWarning("Internal Problem", "An internal error occurred while trying\n" + "to compile the sketch. Please report\n" + "this online at " + "https://developer.berlios.de/bugs/?group_id=3590", e); } PatternMatcherInput input = new PatternMatcherInput(tsre.toString()); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); int errorLine = Integer.parseInt(result.group(1).toString()) - 1; int errorColumn = Integer.parseInt(result.group(2).toString()); int errorFile = 0; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; errorLine -= preprocessor.prototypeCount; throw new RunnerException(tsre.getMessage(), errorFile, errorLine, errorColumn); } else { // this is bad, defaults to the main class.. hrm. throw new RunnerException(tsre.toString(), 0, -1, -1); } } catch (RunnerException pe) { // RunnerExceptions are caught here and re-thrown, so that they don't // get lost in the more general "Exception" handler below. throw pe; } catch (Exception ex) { // TODO better method for handling this? System.err.println("Uncaught exception type:" + ex.getClass()); ex.printStackTrace(); throw new RunnerException(ex.toString()); } // grab the imports from the code just preproc'd importedLibraries = new Vector(); String imports[] = preprocessor.extraImports; for (int i = 0; i < imports.length; i++) { // remove things up to the last dot String entry = imports[i].substring(0, imports[i].lastIndexOf('.')); //System.out.println("found package " + entry); File libFolder = (File) Sketchbook.importToLibraryTable.get(entry); if (libFolder == null) { //throw new RunnerException("Could not find library for " + entry); continue; } importedLibraries.add(libFolder); libraryPath += File.pathSeparator + libFolder.getAbsolutePath(); /* String list[] = libFolder.list(); if (list != null) { for (int j = 0; j < list.length; j++) { // this might have a dll/jnilib/so packed, // so add it to the library path if (list[j].toLowerCase().endsWith(".jar")) { libraryPath += File.pathSeparator + libFolder.getAbsolutePath() + File.separator + list[j]; } } } */ } // 3. then loop over the code[] and save each .java file for (int i = 0; i < codeCount; i++) { if (code[i].flavor == JAVA) { // no pre-processing services necessary for java files // just write the the contents of 'program' to a .java file // into the build directory. uses byte stream and reader/writer // shtuff so that unicode bunk is properly handled //String filename = code[i].name + "." + Preferences.get("build.extension"); String filename = code[i].name + ".cpp"; try { Base.saveFile(code[i].program, new File(buildPath, filename)); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem moving " + filename + " to the build folder"); } code[i].preprocName = filename; } } // compile the program. errors will happen as a RunnerException // that will bubble up to whomever called build(). // // note: this has been changed to catch build exceptions, adjust // line number for number of included prototypes, and rethrow Compiler compiler = new Compiler(); boolean success; try { success = compiler.compile(this, buildPath, target); } catch (RunnerException re) { throw new RunnerException(re.getMessage(), re.file, re.line - preprocessor.prototypeCount, re.column); } catch (Exception ex) { // TODO better method for handling this? throw new RunnerException(ex.toString()); } //System.out.println("success = " + success + " ... " + primaryClassName); return success ? primaryClassName : null; } protected void size(String buildPath, String suggestedClassName) throws RunnerException { long size = 0; Sizer sizer = new Sizer(buildPath, suggestedClassName); try { size = sizer.computeSize(); System.out.println("Binary sketch size: " + size + " bytes (of a " + Preferences.get("upload.maximum_size") + " byte maximum)"); } catch (RunnerException e) { System.err.println("Couldn't determine program size: " + e.getMessage()); } if (size > Preferences.getInteger("upload.maximum_size")) throw new RunnerException( "Sketch too big; try deleting code, removing floats, or see " + "http://www.arduino.cc/en/Main/FAQ for more advice."); } protected String upload(String buildPath, String suggestedClassName) throws RunnerException { // download the program // Uploader downloader = new Uploader(buildPath, suggestedClassName, this); // macos9 now officially broken.. see PdeCompilerJavac //PdeCompiler compiler = // ((PdeBase.platform == PdeBase.MACOS9) ? // new PdeCompilerJavac(buildPath, className, this) : // new PdeCompiler(buildPath, className, this)); // run the compiler, and funnel errors to the leechErr // which is a wrapped around // (this will catch and parse errors during compilation // the messageStream will call message() for 'compiler') MessageStream messageStream = new MessageStream(downloader); //PrintStream leechErr = new PrintStream(messageStream); //boolean result = compiler.compileJava(leechErr); //return compiler.compileJava(leechErr); boolean success = downloader.downloadJava(new PrintStream(messageStream)); return success ? suggestedClassName : null; } protected int countLines(String what) { char c[] = what.toCharArray(); int count = 0; for (int i = 0; i < c.length; i++) { if (c[i] == '\n') count++; } return count; } /** * Initiate export to applet. * <PRE> * +-------------------------------------------------------+ * + + * + Export to: [ Applet (for the web) + ] [ OK ] + * + + * + > Advanced + * + + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.1 + ] + * + + * + Recommended version of Java when exporting applets. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.3 + ] + * + + * + Java 1.3 is not recommended for applets, + * + unless you are using features that require it. + * + Using a version of Java other than 1.1 will require + * + your Windows users to install the Java Plug-In, + * + and your Macintosh users to be running OS X. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.4 + ] + * + + * + identical message as 1.3 above... + * + + * +-------------------------------------------------------+ * </PRE> */ public boolean exportApplet(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); zipFileContents = new Hashtable(); // nuke the old applet folder because it can cause trouble File appletFolder = new File(folder, "applet"); Base.removeDir(appletFolder); appletFolder.mkdirs(); // build the sketch String foundName = build(target, appletFolder.getPath(), name); size(appletFolder.getPath(), name); foundName = upload(appletFolder.getPath(), name); // (already reported) error during export, exit this function if (foundName == null) return false; // if name != exportSketchName, then that's weirdness // BUG unfortunately, that can also be a bug in the preproc :( if (!name.equals(foundName)) { Base.showWarning("Error during export", "Sketch name is " + name + " but the sketch\n" + "name in the code was " + foundName, null); return false; } /* int wide = PApplet.DEFAULT_WIDTH; int high = PApplet.DEFAULT_HEIGHT; PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // this matches against any uses of the size() function, // whether they contain numbers of variables or whatever. // this way, no warning is shown if size() isn't actually // used in the applet, which is the case especially for // beginners that are cutting/pasting from the reference. // modified for 83 to match size(XXX, ddd so that it'll // properly handle size(200, 200) and size(200, 200, P3D) String sizing = "[\\s\\;]size\\s*\\(\\s*(\\S+)\\s*,\\s*(\\d+)"; Pattern pattern = compiler.compile(sizing); // adds a space at the beginning, in case size() is the very // first thing in the program (very common), since the regexp // needs to check for things in front of it. PatternMatcherInput input = new PatternMatcherInput(" " + code[0].program); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); try { wide = Integer.parseInt(result.group(1).toString()); high = Integer.parseInt(result.group(2).toString()); } catch (NumberFormatException e) { // found a reference to size, but it didn't // seem to contain numbers final String message = "The size of this applet could not automatically be\n" + "determined from your code. You'll have to edit the\n" + "HTML file to set the size of the applet."; Base.showWarning("Could not find applet size", message, null); } } // else no size() command found // originally tried to grab this with a regexp matcher, // but it wouldn't span over multiple lines for the match. // this could prolly be forced, but since that's the case // better just to parse by hand. StringBuffer dbuffer = new StringBuffer(); String lines[] = PApplet.split(code[0].program, '\n'); for (int i = 0; i < lines.length; i++) { if (lines[i].trim().startsWith("/**")) { // this is our comment */ // some smartass put the whole thing on the same line //if (lines[j].indexOf("*/") != -1) break; // for (int j = i+1; j < lines.length; j++) { // if (lines[j].trim().endsWith("*/")) { // remove the */ from the end, and any extra *s // in case there's also content on this line // nah, don't bother.. make them use the three lines // break; // } /* int offset = 0; while ((offset < lines[j].length()) && ((lines[j].charAt(offset) == '*') || (lines[j].charAt(offset) == ' '))) { offset++; } // insert the return into the html to help w/ line breaks dbuffer.append(lines[j].substring(offset) + "\n"); } } } String description = dbuffer.toString(); StringBuffer sources = new StringBuffer(); for (int i = 0; i < codeCount; i++) { sources.append("<a href=\"" + code[i].file.getName() + "\">" + code[i].name + "</a> "); } File htmlOutputFile = new File(appletFolder, "index.html"); FileOutputStream fos = new FileOutputStream(htmlOutputFile); PrintStream ps = new PrintStream(fos); // @@sketch@@, @@width@@, @@height@@, @@archive@@, @@source@@ // and now @@description@@ InputStream is = null; // if there is an applet.html file in the sketch folder, use that File customHtml = new File(folder, "applet.html"); if (customHtml.exists()) { is = new FileInputStream(customHtml); } if (is == null) { is = Base.getStream("applet.html"); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = reader.readLine()) != null) { if (line.indexOf("@@") != -1) { StringBuffer sb = new StringBuffer(line); int index = 0; while ((index = sb.indexOf("@@sketch@@")) != -1) { sb.replace(index, index + "@@sketch@@".length(), name); } while ((index = sb.indexOf("@@source@@")) != -1) { sb.replace(index, index + "@@source@@".length(), sources.toString()); } while ((index = sb.indexOf("@@archive@@")) != -1) { sb.replace(index, index + "@@archive@@".length(), name + ".jar"); } while ((index = sb.indexOf("@@width@@")) != -1) { sb.replace(index, index + "@@width@@".length(), String.valueOf(wide)); } while ((index = sb.indexOf("@@height@@")) != -1) { sb.replace(index, index + "@@height@@".length(), String.valueOf(high)); } while ((index = sb.indexOf("@@description@@")) != -1) { sb.replace(index, index + "@@description@@".length(), description); } line = sb.toString(); } ps.println(line); } reader.close(); ps.flush(); ps.close(); // copy the loading gif to the applet String LOADING_IMAGE = "loading.gif"; File loadingImage = new File(folder, LOADING_IMAGE); if (!loadingImage.exists()) { loadingImage = new File("lib", LOADING_IMAGE); } Base.copyFile(loadingImage, new File(appletFolder, LOADING_IMAGE)); */ // copy the source files to the target, since we like // to encourage people to share their code for (int i = 0; i < codeCount; i++) { try { Base.copyFile(code[i].file, new File(appletFolder, code[i].file.getName())); } catch (IOException e) { e.printStackTrace(); } } /* // create new .jar file FileOutputStream zipOutputFile = new FileOutputStream(new File(appletFolder, name + ".jar")); ZipOutputStream zos = new ZipOutputStream(zipOutputFile); ZipEntry entry; // add the manifest file addManifest(zos); // add the contents of the code folder to the jar // unpacks all jar files //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { String includes = Compiler.contentsToClassPath(codeFolder); packClassPathIntoZipFile(includes, zos); } // add contents of 'library' folders to the jar file // if a file called 'export.txt' is in there, it contains // a list of the files that should be exported. // otherwise, all files are exported. Enumeration en = importedLibraries.elements(); while (en.hasMoreElements()) { // in the list is a File object that points the // library sketch's "library" folder File libraryFolder = (File)en.nextElement(); File exportSettings = new File(libraryFolder, "export.txt"); String exportList[] = null; if (exportSettings.exists()) { String info[] = Base.loadStrings(exportSettings); for (int i = 0; i < info.length; i++) { if (info[i].startsWith("applet")) { int idx = info[i].indexOf('='); // get applet= or applet = String commas = info[i].substring(idx+1).trim(); exportList = PApplet.split(commas, ", "); } } } else { exportList = libraryFolder.list(); } for (int i = 0; i < exportList.length; i++) { if (exportList[i].equals(".") || exportList[i].equals("..")) continue; exportList[i] = PApplet.trim(exportList[i]); if (exportList[i].equals("")) continue; File exportFile = new File(libraryFolder, exportList[i]); if (!exportFile.exists()) { System.err.println("File " + exportList[i] + " does not exist"); } else if (exportFile.isDirectory()) { System.err.println("Ignoring sub-folder \"" + exportList[i] + "\""); } else if (exportFile.getName().toLowerCase().endsWith(".zip") || exportFile.getName().toLowerCase().endsWith(".jar")) { packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos); } else { // just copy the file over.. prolly a .dll or something Base.copyFile(exportFile, new File(appletFolder, exportFile.getName())); } } } */ /* String bagelJar = "lib/core.jar"; packClassPathIntoZipFile(bagelJar, zos); // files to include from data directory // TODO this needs to be recursive if (dataFolder.exists()) { String dataFiles[] = dataFolder.list(); for (int i = 0; i < dataFiles.length; i++) { // don't export hidden files // skipping dot prefix removes all: . .. .DS_Store if (dataFiles[i].charAt(0) == '.') continue; entry = new ZipEntry(dataFiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(dataFolder, dataFiles[i]))); zos.closeEntry(); } } // add the project's .class files to the jar // just grabs everything from the build directory // since there may be some inner classes // (add any .class files from the applet dir, then delete them) // TODO this needs to be recursive (for packages) String classfiles[] = appletFolder.list(); for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { entry = new ZipEntry(classfiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(appletFolder, classfiles[i]))); zos.closeEntry(); } } */ String classfiles[] = appletFolder.list(); // remove the .class files from the applet folder. if they're not // removed, the msjvm will complain about an illegal access error, // since the classes are outside the jar file. for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { File deadguy = new File(appletFolder, classfiles[i]); if (!deadguy.delete()) { Base.showWarning("Could not delete", classfiles[i] + " could not \n" + "be deleted from the applet folder. \n" + "You'll need to remove it by hand.", null); } } } // close up the jar file /* zos.flush(); zos.close(); */ if(Preferences.getBoolean("uploader.open_folder")) Base.openFolder(appletFolder); return true; }
diff --git a/src/de/aidger/view/forms/CourseEditorForm.java b/src/de/aidger/view/forms/CourseEditorForm.java index 1a8494c1..d0b62920 100644 --- a/src/de/aidger/view/forms/CourseEditorForm.java +++ b/src/de/aidger/view/forms/CourseEditorForm.java @@ -1,485 +1,485 @@ package de.aidger.view.forms; import static de.aidger.utils.Translation._; import java.text.ParseException; import java.util.List; import javax.swing.JPanel; import de.aidger.model.models.Course; import de.aidger.model.models.FinancialCategory; import de.aidger.utils.Logger; import de.aidger.view.models.ComboBoxModel; import de.aidger.view.models.GenericListModel; import de.aidger.view.models.UIFinancialCategory; import de.aidger.view.tabs.ViewerTab.DataType; import de.aidger.view.utils.InputPatternFilter; import de.aidger.view.utils.NumberFormat; import de.unistuttgart.iste.se.adohive.exceptions.AdoHiveException; import de.unistuttgart.iste.se.adohive.model.IFinancialCategory; /** * A form used for editing / creating new courses. * * @author aidGer Team */ @SuppressWarnings("serial") public class CourseEditorForm extends JPanel { /** * Constructs a course editor form. * * @param course * The course that will be edited */ @SuppressWarnings("unchecked") public CourseEditorForm(Course course, List<GenericListModel> listModels) { initComponents(); // add input filters InputPatternFilter.addDoubleFilter(txtAWHperGroup); InputPatternFilter.addFilter(txtPart, ".?"); InputPatternFilter.addFilter(txtSemester, "([0-9]{0,4})|(WS?|WS[0-9]{0,4})|(SS?|SS[0-9]{0,2})"); // help info for user hlpAWHperGroup.setToolTipText(_("Only a decimal number is allowed.")); hlpPart.setToolTipText(_("Only one character is allowed.")); hlpSemester .setToolTipText(_("Only the format SS[XX], WS[XXXX] and year in 4 digits is allowed.")); List<IFinancialCategory> fcs = null; try { fcs = (new FinancialCategory()).getAll(); } catch (AdoHiveException e) { Logger.error(e.getMessage()); } ComboBoxModel cmbFinancialCategoryModel = new ComboBoxModel( DataType.FinancialCategory); for (IFinancialCategory fc : fcs) { cmbFinancialCategoryModel.addElement(new UIFinancialCategory(fc)); } cmbFinancialCategory.setModel(cmbFinancialCategoryModel); listModels.add(cmbFinancialCategoryModel); if (course != null) { txtDescription.setText(course.getDescription()); txtSemester.setText(course.getSemester()); txtLecturer.setText(course.getLecturer()); txtAdvisor.setText(course.getAdvisor()); txtTargetAudience.setText(course.getTargetAudience()); spNumberOfGroups.setValue(course.getNumberOfGroups()); txtAWHperGroup.setText(NumberFormat.getInstance().format( course.getUnqualifiedWorkingHours())); cmbScope.setSelectedItem(course.getScope()); txtPart.setText(String.valueOf(course.getPart())); txtGroup.setText(course.getGroup()); txtRemark.setText(course.getRemark()); try { IFinancialCategory fc = (new FinancialCategory()) .getById(course.getFinancialCategoryId()); cmbFinancialCategory.setSelectedItem(new FinancialCategory(fc)); } catch (AdoHiveException e) { Logger.error(e.getMessage()); } } } /** * Get the description of the course * * @return The description of the course */ public String getDescription() { return txtDescription.getText(); } /** * Get the id referencing the category. * * @return The id of the category */ public int getFinancialCategoryId() { if (cmbFinancialCategory.getSelectedItem() == null) { return 0; } return ((FinancialCategory) cmbFinancialCategory.getSelectedItem()) .getId(); } /** * Get the group of the course. * * @return The group of the course */ public String getGroup() { return txtGroup.getText(); } /** * Get the lecturer of the course. * * @return The lecturer of the course */ public String getLecturer() { return txtLecturer.getText(); } /** * Get the advisor of the course. * * @return The advisor of the course */ public String getAdvisor() { return txtAdvisor.getText(); } /** * Get the number of groups in the course. * * @return The number of groups */ public int getNumberOfGroups() { return (Integer) spNumberOfGroups.getValue(); } /** * Get the part of the course. * * @return The part of the course * @throws StringIndexOutOfBoundsException */ public char getPart() throws StringIndexOutOfBoundsException { return txtPart.getText().charAt(0); } /** * Get remarks regarding the course. * * @return The remarks */ public String getRemark() { return txtRemark.getText(); } /** * Get the scope of the course. * * @return The scope of the course */ public String getScope() { return (String) cmbScope.getSelectedItem(); } /** * Get the semester of the course. * * @return The semester */ public String getSemester() { return txtSemester.getText(); } /** * Get the target audience of the course. * * @return The target audience */ public String getTargetAudience() { return txtTargetAudience.getText(); } /** * Get the amount of unqualified working hours granted. * * @return The amount of UWHs * @throws NumberFormatException */ public double getUnqualifiedWorkingHours() throws ParseException { return NumberFormat.getInstance().parse(txtAWHperGroup.getText()) .doubleValue(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; lblDescription = new javax.swing.JLabel(); lblSemester = new javax.swing.JLabel(); lblLecturer = new javax.swing.JLabel(); lblAdvisor = new javax.swing.JLabel(); lblNumberOfGroups = new javax.swing.JLabel(); lblTargetAudience = new javax.swing.JLabel(); txtDescription = new javax.swing.JTextField(); txtSemester = new javax.swing.JTextField(); txtLecturer = new javax.swing.JTextField(); txtAdvisor = new javax.swing.JTextField(); spNumberOfGroups = new javax.swing.JSpinner(); txtTargetAudience = new javax.swing.JTextField(); lblAWHperGroup = new javax.swing.JLabel(); lblScope = new javax.swing.JLabel(); lblPart = new javax.swing.JLabel(); lblGroup = new javax.swing.JLabel(); lblRemark = new javax.swing.JLabel(); lblFinancialCategory = new javax.swing.JLabel(); txtAWHperGroup = new javax.swing.JTextField(); cmbScope = new javax.swing.JComboBox(); txtPart = new javax.swing.JTextField(); txtGroup = new javax.swing.JTextField(); txtRemark = new javax.swing.JTextField(); cmbFinancialCategory = new javax.swing.JComboBox(); hlpAWHperGroup = new de.aidger.view.utils.HelpLabel(); hlpPart = new de.aidger.view.utils.HelpLabel(); hlpSemester = new de.aidger.view.utils.HelpLabel(); setLayout(new java.awt.GridBagLayout()); lblDescription.setText(_("Description")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblDescription, gridBagConstraints); lblSemester.setText(_("Semester")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblSemester, gridBagConstraints); lblLecturer.setText(_("Lecturer")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblLecturer, gridBagConstraints); lblAdvisor.setText(_("Advisor")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblAdvisor, gridBagConstraints); lblNumberOfGroups.setText(_("Number of Groups")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblNumberOfGroups, gridBagConstraints); lblTargetAudience.setText(_("Target Audience")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblTargetAudience, gridBagConstraints); txtDescription.setMinimumSize(new java.awt.Dimension(200, 25)); txtDescription.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtDescription, gridBagConstraints); txtSemester.setMinimumSize(new java.awt.Dimension(200, 25)); txtSemester.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtSemester, gridBagConstraints); txtLecturer.setMinimumSize(new java.awt.Dimension(200, 25)); txtLecturer.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtLecturer, gridBagConstraints); txtAdvisor.setMinimumSize(new java.awt.Dimension(200, 25)); txtAdvisor.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtAdvisor, gridBagConstraints); spNumberOfGroups.setModel(new javax.swing.SpinnerNumberModel(Integer .valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(spNumberOfGroups, gridBagConstraints); txtTargetAudience.setMinimumSize(new java.awt.Dimension(200, 25)); txtTargetAudience.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtTargetAudience, gridBagConstraints); lblAWHperGroup.setText(_("AWH per group")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblAWHperGroup, gridBagConstraints); lblScope.setText(_("Scope")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblScope, gridBagConstraints); lblPart.setText(_("Part")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblPart, gridBagConstraints); lblGroup.setText(_("Group")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblGroup, gridBagConstraints); lblRemark.setText(_("Remark")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblRemark, gridBagConstraints); lblFinancialCategory.setText(_("Financial Category")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblFinancialCategory, gridBagConstraints); txtAWHperGroup.setMinimumSize(new java.awt.Dimension(200, 25)); txtAWHperGroup.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtAWHperGroup, gridBagConstraints); cmbScope.setModel(new javax.swing.DefaultComboBoxModel(new String[] { - "", "1Ü", "2Ü", "1P", "2P", "4P", "6P" })); + "", "1\u00dc", "2\u00dc", "1P", "2P", "4P", "6P" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(cmbScope, gridBagConstraints); txtPart.setMinimumSize(new java.awt.Dimension(200, 25)); txtPart.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtPart, gridBagConstraints); txtGroup.setMinimumSize(new java.awt.Dimension(200, 25)); txtGroup.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtGroup, gridBagConstraints); txtRemark.setMinimumSize(new java.awt.Dimension(200, 25)); txtRemark.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtRemark, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(cmbFinancialCategory, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(hlpAWHperGroup, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(hlpPart, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(hlpSemester, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox cmbFinancialCategory; private javax.swing.JComboBox cmbScope; private de.aidger.view.utils.HelpLabel hlpAWHperGroup; private de.aidger.view.utils.HelpLabel hlpPart; private de.aidger.view.utils.HelpLabel hlpSemester; private javax.swing.JLabel lblAWHperGroup; private javax.swing.JLabel lblAdvisor; private javax.swing.JLabel lblDescription; private javax.swing.JLabel lblFinancialCategory; private javax.swing.JLabel lblGroup; private javax.swing.JLabel lblLecturer; private javax.swing.JLabel lblNumberOfGroups; private javax.swing.JLabel lblPart; private javax.swing.JLabel lblRemark; private javax.swing.JLabel lblScope; private javax.swing.JLabel lblSemester; private javax.swing.JLabel lblTargetAudience; private javax.swing.JSpinner spNumberOfGroups; private javax.swing.JTextField txtAWHperGroup; private javax.swing.JTextField txtAdvisor; private javax.swing.JTextField txtDescription; private javax.swing.JTextField txtGroup; private javax.swing.JTextField txtLecturer; private javax.swing.JTextField txtPart; private javax.swing.JTextField txtRemark; private javax.swing.JTextField txtSemester; private javax.swing.JTextField txtTargetAudience; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; lblDescription = new javax.swing.JLabel(); lblSemester = new javax.swing.JLabel(); lblLecturer = new javax.swing.JLabel(); lblAdvisor = new javax.swing.JLabel(); lblNumberOfGroups = new javax.swing.JLabel(); lblTargetAudience = new javax.swing.JLabel(); txtDescription = new javax.swing.JTextField(); txtSemester = new javax.swing.JTextField(); txtLecturer = new javax.swing.JTextField(); txtAdvisor = new javax.swing.JTextField(); spNumberOfGroups = new javax.swing.JSpinner(); txtTargetAudience = new javax.swing.JTextField(); lblAWHperGroup = new javax.swing.JLabel(); lblScope = new javax.swing.JLabel(); lblPart = new javax.swing.JLabel(); lblGroup = new javax.swing.JLabel(); lblRemark = new javax.swing.JLabel(); lblFinancialCategory = new javax.swing.JLabel(); txtAWHperGroup = new javax.swing.JTextField(); cmbScope = new javax.swing.JComboBox(); txtPart = new javax.swing.JTextField(); txtGroup = new javax.swing.JTextField(); txtRemark = new javax.swing.JTextField(); cmbFinancialCategory = new javax.swing.JComboBox(); hlpAWHperGroup = new de.aidger.view.utils.HelpLabel(); hlpPart = new de.aidger.view.utils.HelpLabel(); hlpSemester = new de.aidger.view.utils.HelpLabel(); setLayout(new java.awt.GridBagLayout()); lblDescription.setText(_("Description")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblDescription, gridBagConstraints); lblSemester.setText(_("Semester")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblSemester, gridBagConstraints); lblLecturer.setText(_("Lecturer")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblLecturer, gridBagConstraints); lblAdvisor.setText(_("Advisor")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblAdvisor, gridBagConstraints); lblNumberOfGroups.setText(_("Number of Groups")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblNumberOfGroups, gridBagConstraints); lblTargetAudience.setText(_("Target Audience")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblTargetAudience, gridBagConstraints); txtDescription.setMinimumSize(new java.awt.Dimension(200, 25)); txtDescription.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtDescription, gridBagConstraints); txtSemester.setMinimumSize(new java.awt.Dimension(200, 25)); txtSemester.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtSemester, gridBagConstraints); txtLecturer.setMinimumSize(new java.awt.Dimension(200, 25)); txtLecturer.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtLecturer, gridBagConstraints); txtAdvisor.setMinimumSize(new java.awt.Dimension(200, 25)); txtAdvisor.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtAdvisor, gridBagConstraints); spNumberOfGroups.setModel(new javax.swing.SpinnerNumberModel(Integer .valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(spNumberOfGroups, gridBagConstraints); txtTargetAudience.setMinimumSize(new java.awt.Dimension(200, 25)); txtTargetAudience.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtTargetAudience, gridBagConstraints); lblAWHperGroup.setText(_("AWH per group")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblAWHperGroup, gridBagConstraints); lblScope.setText(_("Scope")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblScope, gridBagConstraints); lblPart.setText(_("Part")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblPart, gridBagConstraints); lblGroup.setText(_("Group")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblGroup, gridBagConstraints); lblRemark.setText(_("Remark")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblRemark, gridBagConstraints); lblFinancialCategory.setText(_("Financial Category")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblFinancialCategory, gridBagConstraints); txtAWHperGroup.setMinimumSize(new java.awt.Dimension(200, 25)); txtAWHperGroup.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtAWHperGroup, gridBagConstraints); cmbScope.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "1Ü", "2Ü", "1P", "2P", "4P", "6P" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(cmbScope, gridBagConstraints); txtPart.setMinimumSize(new java.awt.Dimension(200, 25)); txtPart.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtPart, gridBagConstraints); txtGroup.setMinimumSize(new java.awt.Dimension(200, 25)); txtGroup.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtGroup, gridBagConstraints); txtRemark.setMinimumSize(new java.awt.Dimension(200, 25)); txtRemark.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtRemark, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(cmbFinancialCategory, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(hlpAWHperGroup, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(hlpPart, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(hlpSemester, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; lblDescription = new javax.swing.JLabel(); lblSemester = new javax.swing.JLabel(); lblLecturer = new javax.swing.JLabel(); lblAdvisor = new javax.swing.JLabel(); lblNumberOfGroups = new javax.swing.JLabel(); lblTargetAudience = new javax.swing.JLabel(); txtDescription = new javax.swing.JTextField(); txtSemester = new javax.swing.JTextField(); txtLecturer = new javax.swing.JTextField(); txtAdvisor = new javax.swing.JTextField(); spNumberOfGroups = new javax.swing.JSpinner(); txtTargetAudience = new javax.swing.JTextField(); lblAWHperGroup = new javax.swing.JLabel(); lblScope = new javax.swing.JLabel(); lblPart = new javax.swing.JLabel(); lblGroup = new javax.swing.JLabel(); lblRemark = new javax.swing.JLabel(); lblFinancialCategory = new javax.swing.JLabel(); txtAWHperGroup = new javax.swing.JTextField(); cmbScope = new javax.swing.JComboBox(); txtPart = new javax.swing.JTextField(); txtGroup = new javax.swing.JTextField(); txtRemark = new javax.swing.JTextField(); cmbFinancialCategory = new javax.swing.JComboBox(); hlpAWHperGroup = new de.aidger.view.utils.HelpLabel(); hlpPart = new de.aidger.view.utils.HelpLabel(); hlpSemester = new de.aidger.view.utils.HelpLabel(); setLayout(new java.awt.GridBagLayout()); lblDescription.setText(_("Description")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblDescription, gridBagConstraints); lblSemester.setText(_("Semester")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblSemester, gridBagConstraints); lblLecturer.setText(_("Lecturer")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblLecturer, gridBagConstraints); lblAdvisor.setText(_("Advisor")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblAdvisor, gridBagConstraints); lblNumberOfGroups.setText(_("Number of Groups")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblNumberOfGroups, gridBagConstraints); lblTargetAudience.setText(_("Target Audience")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(lblTargetAudience, gridBagConstraints); txtDescription.setMinimumSize(new java.awt.Dimension(200, 25)); txtDescription.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtDescription, gridBagConstraints); txtSemester.setMinimumSize(new java.awt.Dimension(200, 25)); txtSemester.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtSemester, gridBagConstraints); txtLecturer.setMinimumSize(new java.awt.Dimension(200, 25)); txtLecturer.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtLecturer, gridBagConstraints); txtAdvisor.setMinimumSize(new java.awt.Dimension(200, 25)); txtAdvisor.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtAdvisor, gridBagConstraints); spNumberOfGroups.setModel(new javax.swing.SpinnerNumberModel(Integer .valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(spNumberOfGroups, gridBagConstraints); txtTargetAudience.setMinimumSize(new java.awt.Dimension(200, 25)); txtTargetAudience.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtTargetAudience, gridBagConstraints); lblAWHperGroup.setText(_("AWH per group")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblAWHperGroup, gridBagConstraints); lblScope.setText(_("Scope")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblScope, gridBagConstraints); lblPart.setText(_("Part")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblPart, gridBagConstraints); lblGroup.setText(_("Group")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblGroup, gridBagConstraints); lblRemark.setText(_("Remark")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblRemark, gridBagConstraints); lblFinancialCategory.setText(_("Financial Category")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 50, 10, 10); add(lblFinancialCategory, gridBagConstraints); txtAWHperGroup.setMinimumSize(new java.awt.Dimension(200, 25)); txtAWHperGroup.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtAWHperGroup, gridBagConstraints); cmbScope.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "1\u00dc", "2\u00dc", "1P", "2P", "4P", "6P" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(cmbScope, gridBagConstraints); txtPart.setMinimumSize(new java.awt.Dimension(200, 25)); txtPart.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtPart, gridBagConstraints); txtGroup.setMinimumSize(new java.awt.Dimension(200, 25)); txtGroup.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtGroup, gridBagConstraints); txtRemark.setMinimumSize(new java.awt.Dimension(200, 25)); txtRemark.setPreferredSize(new java.awt.Dimension(200, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(txtRemark, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); add(cmbFinancialCategory, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(hlpAWHperGroup, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(hlpPart, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(hlpSemester, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/com/appnexus/opensdk/AdWebView.java b/src/com/appnexus/opensdk/AdWebView.java index bf8b1602..c94352bf 100644 --- a/src/com/appnexus/opensdk/AdWebView.java +++ b/src/com/appnexus/opensdk/AdWebView.java @@ -1,96 +1,96 @@ /** * */ package com.appnexus.opensdk; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; /** * @author [email protected] * */ public class AdWebView extends WebView implements Displayable{ /** * @param context */ protected AdWebView(Context context) { super(context); setup(); // TODO Auto-generated constructor stub } /** * @param context * @param attrs */ protected AdWebView(Context context, AttributeSet attrs) { super(context, attrs); setup(); // TODO Auto-generated constructor stub } /** * @param context The context for the AdWebView. Should be in an AdView * @param attrs * @param defStyle */ protected AdWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(); // TODO Auto-generated constructor stub } @SuppressLint("SetJavaScriptEnabled") private void setup(){ Settings.getSettings().ua=this.getSettings().getUserAgentString(); this.getSettings().setJavaScriptEnabled(true); this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); this.getSettings().setPluginState(WebSettings.PluginState.ON); this.getSettings().setBuiltInZoomControls(false); this.getSettings().setLightTouchEnabled(false); this.getSettings().setLoadsImagesAutomatically(true); this.getSettings().setSupportZoom(false); this.getSettings().setUseWideViewPort(true); this.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); setHorizontalScrollbarOverlay(false); setHorizontalScrollBarEnabled(false); setVerticalScrollbarOverlay(false); setVerticalScrollBarEnabled(false); setBackgroundColor(Color.TRANSPARENT); setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY); setOnTouchListener(new OnTouchListener() { + //Disables all dragging in the webview. Might interfere with interactive creatives @Override public boolean onTouch(View v, MotionEvent event) { - // TODO click the url in the ad. - return true; - } - });//Disables scrolling... also disables clicking. + return (event.getAction() == MotionEvent.ACTION_MOVE); + } + }); } protected void loadAd(AdResponse ad){ String body = "<html><head /><body style='margin:0;padding:0;'>" + ad.getBody() + "</body></html>"; this.loadData(body, "text/html", "UTF-8"); } @Override public View getView() { return this; } }
false
true
private void setup(){ Settings.getSettings().ua=this.getSettings().getUserAgentString(); this.getSettings().setJavaScriptEnabled(true); this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); this.getSettings().setPluginState(WebSettings.PluginState.ON); this.getSettings().setBuiltInZoomControls(false); this.getSettings().setLightTouchEnabled(false); this.getSettings().setLoadsImagesAutomatically(true); this.getSettings().setSupportZoom(false); this.getSettings().setUseWideViewPort(true); this.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); setHorizontalScrollbarOverlay(false); setHorizontalScrollBarEnabled(false); setVerticalScrollbarOverlay(false); setVerticalScrollBarEnabled(false); setBackgroundColor(Color.TRANSPARENT); setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO click the url in the ad. return true; } });//Disables scrolling... also disables clicking. }
private void setup(){ Settings.getSettings().ua=this.getSettings().getUserAgentString(); this.getSettings().setJavaScriptEnabled(true); this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); this.getSettings().setPluginState(WebSettings.PluginState.ON); this.getSettings().setBuiltInZoomControls(false); this.getSettings().setLightTouchEnabled(false); this.getSettings().setLoadsImagesAutomatically(true); this.getSettings().setSupportZoom(false); this.getSettings().setUseWideViewPort(true); this.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); setHorizontalScrollbarOverlay(false); setHorizontalScrollBarEnabled(false); setVerticalScrollbarOverlay(false); setVerticalScrollBarEnabled(false); setBackgroundColor(Color.TRANSPARENT); setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY); setOnTouchListener(new OnTouchListener() { //Disables all dragging in the webview. Might interfere with interactive creatives @Override public boolean onTouch(View v, MotionEvent event) { return (event.getAction() == MotionEvent.ACTION_MOVE); } }); }
diff --git a/swag-webapp/src/main/java/at/ac/tuwien/swag/webapp/in/messages/Notifications.java b/swag-webapp/src/main/java/at/ac/tuwien/swag/webapp/in/messages/Notifications.java index 5b48ff2..f9457da 100644 --- a/swag-webapp/src/main/java/at/ac/tuwien/swag/webapp/in/messages/Notifications.java +++ b/swag-webapp/src/main/java/at/ac/tuwien/swag/webapp/in/messages/Notifications.java @@ -1,59 +1,59 @@ package at.ac.tuwien.swag.webapp.in.messages; import java.text.Format; import java.text.SimpleDateFormat; import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.navigation.paging.PagingNavigator; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.request.mapper.parameter.PageParameters; import at.ac.tuwien.swag.model.dto.MessageDTO; import at.ac.tuwien.swag.webapp.SwagWebSession; import at.ac.tuwien.swag.webapp.in.provider.MessageSortableDataProvider; import at.ac.tuwien.swag.webapp.service.MessageService; import com.google.inject.Inject; public class Notifications extends Panel { private static final long serialVersionUID = -4045913776508864182L; @Inject private MessageService messages; public Notifications(String id) { super(id); String username = ((SwagWebSession) getSession()).getUsername(); List<MessageDTO> notificationList = messages.getNotifications(username); final Format formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); DataView<MessageDTO> dataView = - new DataView<MessageDTO>("notificationList", new MessageSortableDataProvider(notificationList)) { + new DataView<MessageDTO>("notificationsList", new MessageSortableDataProvider(notificationList)) { private static final long serialVersionUID = -7500357470052232668L; @Override protected void populateItem(Item<MessageDTO> item) { MessageDTO message = item.getModelObject(); PageParameters param = new PageParameters(); param.add("id", message.getId()); item.add(new Label("subject", message.getSubject())); item.add(new Label("date", formatter.format(message.getTimestamp()))); item.add(new BookmarkablePageLink<String>("view", MessageDetail.class, param)); } }; dataView.setItemsPerPage(15); add(dataView); add(new PagingNavigator("navigator", dataView)); } }
true
true
public Notifications(String id) { super(id); String username = ((SwagWebSession) getSession()).getUsername(); List<MessageDTO> notificationList = messages.getNotifications(username); final Format formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); DataView<MessageDTO> dataView = new DataView<MessageDTO>("notificationList", new MessageSortableDataProvider(notificationList)) { private static final long serialVersionUID = -7500357470052232668L; @Override protected void populateItem(Item<MessageDTO> item) { MessageDTO message = item.getModelObject(); PageParameters param = new PageParameters(); param.add("id", message.getId()); item.add(new Label("subject", message.getSubject())); item.add(new Label("date", formatter.format(message.getTimestamp()))); item.add(new BookmarkablePageLink<String>("view", MessageDetail.class, param)); } }; dataView.setItemsPerPage(15); add(dataView); add(new PagingNavigator("navigator", dataView)); }
public Notifications(String id) { super(id); String username = ((SwagWebSession) getSession()).getUsername(); List<MessageDTO> notificationList = messages.getNotifications(username); final Format formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); DataView<MessageDTO> dataView = new DataView<MessageDTO>("notificationsList", new MessageSortableDataProvider(notificationList)) { private static final long serialVersionUID = -7500357470052232668L; @Override protected void populateItem(Item<MessageDTO> item) { MessageDTO message = item.getModelObject(); PageParameters param = new PageParameters(); param.add("id", message.getId()); item.add(new Label("subject", message.getSubject())); item.add(new Label("date", formatter.format(message.getTimestamp()))); item.add(new BookmarkablePageLink<String>("view", MessageDetail.class, param)); } }; dataView.setItemsPerPage(15); add(dataView); add(new PagingNavigator("navigator", dataView)); }
diff --git a/client/src/edu/rit/se/sse/rapdevx/api/SessionApi.java b/client/src/edu/rit/se/sse/rapdevx/api/SessionApi.java index a929c17..ab60ad0 100644 --- a/client/src/edu/rit/se/sse/rapdevx/api/SessionApi.java +++ b/client/src/edu/rit/se/sse/rapdevx/api/SessionApi.java @@ -1,218 +1,218 @@ package edu.rit.se.sse.rapdevx.api; // TODO: add Exceptions for unexpected situations, like the session being not found. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import edu.rit.se.sse.rapdevx.api.dataclasses.Session; /** * API access to the Session object on the server side * * Approximates the ActiveRecord pattern * * @author Ben Nicholas */ public class SessionApi { public static String SERVER_URL = "localhost"; private static HttpClient HTTP_CLIENT = new DefaultHttpClient(); private static ResponseHandler<String> HANDLER = new BasicResponseHandler(); private static ObjectMapper MAPPER = new ObjectMapper( new JsonFactory()); private static TypeReference<Map<String, String>> STRING_MAP_TYPE = new TypeReference<Map<String, String>>() { }; /** * Create a new session, optionally specifying a game to join. If no game is * provided, the session will be registered into the matchmaking pool on the * server side and be assigned to a game. * * @param gameID * The game that the user would like to join. If there is no * preference, pass in null. * * @return The initial session object, potentially populated with game_id. * If no game_id is provided, periodically check for updates until * the session has been given a game. * @throws Exception * Talk to cody about this. */ public static Session createSession(String nickname, String gameID) throws Exception { String incomingJson = ""; try { // contents of the POST String data = URLEncoder.encode("nickname", "UTF-8") + "=" + URLEncoder.encode(nickname, "UTF-8"); // if there is a gameID if (gameID != null) data += "&" + URLEncoder.encode("game_id", "UTF-8") + "=" + URLEncoder.encode(gameID, "UTF-8"); // url... URL url = new URL("http", SERVER_URL, 8080, "/sessions"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.connect(); OutputStreamWriter wr = new OutputStreamWriter( conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { incomingJson += line; } wr.close(); rd.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (incomingJson.equals("")) { - throw new Exception("Something is REALLY FUCKED UP."); + throw new Exception("No JSON recieved from server"); } else { // need to pull the change for the below method. return Session.fromJSON(incomingJson); } } /** * Check for updates to the given session, primarily used while waiting for * a game assignment. * * @param sessionToCheck * The session to check for updates(session_id is the only * important part) * * @return A newly allocated session object, with the server's current view * of the provided session. */ public static Session updateSession(Session sessionToCheck) { String json = getResponse("/session/" + sessionToCheck.getsession_id()); Session session = Session.fromJSON(json); return session; } /** * "Log out" of your current game session. * * @param sessionToDestroy * The session to be destroyed(session_id is the only important * part) * * @return A boolean representing whether or not the destroy operation was * successful. */ public static boolean destroySession(Session sessionToDestroy) { try { URL url = new URL("http", SERVER_URL, 8080, "/session/" + sessionToDestroy.getsession_id()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("DELETE"); conn.connect(); return conn.getResponseCode() == 200; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } /** * Helper method. * * Gets body for request. * * @param args * Part after domain (like /game or /session/1) * @return */ private static String getResponse(String args) { try { URL url = new URL("http", SERVER_URL, 8080, args); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("GET"); conn.connect(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; String incomingJson = ""; while ((line = rd.readLine()) != null) { incomingJson += line; } rd.close(); return incomingJson; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
true
true
public static Session createSession(String nickname, String gameID) throws Exception { String incomingJson = ""; try { // contents of the POST String data = URLEncoder.encode("nickname", "UTF-8") + "=" + URLEncoder.encode(nickname, "UTF-8"); // if there is a gameID if (gameID != null) data += "&" + URLEncoder.encode("game_id", "UTF-8") + "=" + URLEncoder.encode(gameID, "UTF-8"); // url... URL url = new URL("http", SERVER_URL, 8080, "/sessions"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.connect(); OutputStreamWriter wr = new OutputStreamWriter( conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { incomingJson += line; } wr.close(); rd.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (incomingJson.equals("")) { throw new Exception("Something is REALLY FUCKED UP."); } else { // need to pull the change for the below method. return Session.fromJSON(incomingJson); } }
public static Session createSession(String nickname, String gameID) throws Exception { String incomingJson = ""; try { // contents of the POST String data = URLEncoder.encode("nickname", "UTF-8") + "=" + URLEncoder.encode(nickname, "UTF-8"); // if there is a gameID if (gameID != null) data += "&" + URLEncoder.encode("game_id", "UTF-8") + "=" + URLEncoder.encode(gameID, "UTF-8"); // url... URL url = new URL("http", SERVER_URL, 8080, "/sessions"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.connect(); OutputStreamWriter wr = new OutputStreamWriter( conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { incomingJson += line; } wr.close(); rd.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (incomingJson.equals("")) { throw new Exception("No JSON recieved from server"); } else { // need to pull the change for the below method. return Session.fromJSON(incomingJson); } }
diff --git a/jython/org/python/modules/cPickle.java b/jython/org/python/modules/cPickle.java index 145dcf72..0fe1273c 100644 --- a/jython/org/python/modules/cPickle.java +++ b/jython/org/python/modules/cPickle.java @@ -1,2075 +1,2075 @@ /* * Copyright 1998 Finn Bock. * * This program contains material copyrighted by: * Copyright � 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, * The Netherlands. */ /* note about impl: instanceof vs. CPython type(.) is . */ package org.python.modules; import java.util.*; import org.python.core.*; import org.python.core.imp; /** * * From the python documentation: * <p> * The <tt>cPickle.java</tt> module implements a basic but powerful algorithm * for ``pickling'' (a.k.a. serializing, marshalling or flattening) nearly * arbitrary Python objects. This is the act of converting objects to a * stream of bytes (and back: ``unpickling''). * This is a more primitive notion than * persistency -- although <tt>cPickle.java</tt> reads and writes file * objects, it does not handle the issue of naming persistent objects, nor * the (even more complicated) area of concurrent access to persistent * objects. The <tt>cPickle.java</tt> module can transform a complex object * into a byte stream and it can transform the byte stream into an object * with the same internal structure. The most obvious thing to do with these * byte streams is to write them onto a file, but it is also conceivable * to send them across a network or store them in a database. The module * <tt>shelve</tt> provides a simple interface to pickle and unpickle * objects on ``dbm''-style database files. * <P> * <b>Note:</b> The <tt>cPickle.java</tt> have the same interface as the * standard module <tt>pickle</tt>except that <tt>Pickler</tt> and * <tt>Unpickler</tt> are factory functions, not classes (so they cannot be * used as base classes for inheritance). * This limitation is similar for the original cPickle.c version. * * <P> * Unlike the built-in module <tt>marshal</tt>, <tt>cPickle.java</tt> handles * the following correctly: * <P> * * <UL><LI>recursive objects (objects containing references to themselves) * * <P> * * <LI>object sharing (references to the same object in different places) * * <P> * * <LI>user-defined classes and their instances * * <P> * * </UL> * * <P> * The data format used by <tt>cPickle.java</tt> is Python-specific. This has * the advantage that there are no restrictions imposed by external * standards such as XDR (which can't represent pointer sharing); however * it means that non-Python programs may not be able to reconstruct * pickled Python objects. * * <P> * By default, the <tt>cPickle.java</tt> data format uses a printable ASCII * representation. This is slightly more voluminous than a binary * representation. The big advantage of using printable ASCII (and of * some other characteristics of <tt>cPickle.java</tt>'s representation) is * that for debugging or recovery purposes it is possible for a human to read * the pickled file with a standard text editor. * * <P> * A binary format, which is slightly more efficient, can be chosen by * specifying a nonzero (true) value for the <i>bin</i> argument to the * <tt>Pickler</tt> constructor or the <tt>dump()</tt> and <tt>dumps()</tt> * functions. The binary format is not the default because of backwards * compatibility with the Python 1.4 pickle module. In a future version, * the default may change to binary. * * <P> * The <tt>cPickle.java</tt> module doesn't handle code objects. * <P> * For the benefit of persistency modules written using <tt>cPickle.java</tt>, * it supports the notion of a reference to an object outside the pickled * data stream. Such objects are referenced by a name, which is an * arbitrary string of printable ASCII characters. The resolution of * such names is not defined by the <tt>cPickle.java</tt> module -- the * persistent object module will have to implement a method * <tt>persistent_load()</tt>. To write references to persistent objects, * the persistent module must define a method <tt>persistent_id()</tt> which * returns either <tt>None</tt> or the persistent ID of the object. * * <P> * There are some restrictions on the pickling of class instances. * * <P> * First of all, the class must be defined at the top level in a module. * Furthermore, all its instance variables must be picklable. * * <P> * * <P> * When a pickled class instance is unpickled, its <tt>__init__()</tt> method * is normally <i>not</i> invoked. <b>Note:</b> This is a deviation * from previous versions of this module; the change was introduced in * Python 1.5b2. The reason for the change is that in many cases it is * desirable to have a constructor that requires arguments; it is a * (minor) nuisance to have to provide a <tt>__getinitargs__()</tt> method. * * <P> * If it is desirable that the <tt>__init__()</tt> method be called on * unpickling, a class can define a method <tt>__getinitargs__()</tt>, * which should return a <i>tuple</i> containing the arguments to be * passed to the class constructor (<tt>__init__()</tt>). This method is * called at pickle time; the tuple it returns is incorporated in the * pickle for the instance. * <P> * Classes can further influence how their instances are pickled -- if the * class defines the method <tt>__getstate__()</tt>, it is called and the * return state is pickled as the contents for the instance, and if the class * defines the method <tt>__setstate__()</tt>, it is called with the * unpickled state. (Note that these methods can also be used to * implement copying class instances.) If there is no * <tt>__getstate__()</tt> method, the instance's <tt>__dict__</tt> is * pickled. If there is no <tt>__setstate__()</tt> method, the pickled * object must be a dictionary and its items are assigned to the new * instance's dictionary. (If a class defines both <tt>__getstate__()</tt> * and <tt>__setstate__()</tt>, the state object needn't be a dictionary * -- these methods can do what they want.) This protocol is also used * by the shallow and deep copying operations defined in the <tt>copy</tt> * module. * <P> * Note that when class instances are pickled, their class's code and * data are not pickled along with them. Only the instance data are * pickled. This is done on purpose, so you can fix bugs in a class or * add methods and still load objects that were created with an earlier * version of the class. If you plan to have long-lived objects that * will see many versions of a class, it may be worthwhile to put a version * number in the objects so that suitable conversions can be made by the * class's <tt>__setstate__()</tt> method. * * <P> * When a class itself is pickled, only its name is pickled -- the class * definition is not pickled, but re-imported by the unpickling process. * Therefore, the restriction that the class must be defined at the top * level in a module applies to pickled classes as well. * * <P> * * <P> * The interface can be summarized as follows. * * <P> * To pickle an object <tt>x</tt> onto a file <tt>f</tt>, open for writing: * * <P> * <dl><dd><pre> * p = pickle.Pickler(f) * p.dump(x) * </pre></dl> * * <P> * A shorthand for this is: * * <P> * <dl><dd><pre> * pickle.dump(x, f) * </pre></dl> * * <P> * To unpickle an object <tt>x</tt> from a file <tt>f</tt>, open for reading: * * <P> * <dl><dd><pre> * u = pickle.Unpickler(f) * x = u.load() * </pre></dl> * * <P> * A shorthand is: * * <P> * <dl><dd><pre> * x = pickle.load(f) * </pre></dl> * * <P> * The <tt>Pickler</tt> class only calls the method <tt>f.write()</tt> with a * string argument. The <tt>Unpickler</tt> calls the methods * <tt>f.read()</tt> (with an integer argument) and <tt>f.readline()</tt> * (without argument), both returning a string. It is explicitly allowed to * pass non-file objects here, as long as they have the right methods. * * <P> * The constructor for the <tt>Pickler</tt> class has an optional second * argument, <i>bin</i>. If this is present and nonzero, the binary * pickle format is used; if it is zero or absent, the (less efficient, * but backwards compatible) text pickle format is used. The * <tt>Unpickler</tt> class does not have an argument to distinguish * between binary and text pickle formats; it accepts either format. * * <P> * The following types can be pickled: * * <UL><LI><tt>None</tt> * * <P> * * <LI>integers, long integers, floating point numbers * * <P> * * <LI>strings * * <P> * * <LI>tuples, lists and dictionaries containing only picklable objects * * <P> * * <LI>classes that are defined at the top level in a module * * <P> * * <LI>instances of such classes whose <tt>__dict__</tt> or * <tt>__setstate__()</tt> is picklable * * <P> * * </UL> * * <P> * Attempts to pickle unpicklable objects will raise the * <tt>PicklingError</tt> exception; when this happens, an unspecified * number of bytes may have been written to the file. * * <P> * It is possible to make multiple calls to the <tt>dump()</tt> method of * the same <tt>Pickler</tt> instance. These must then be matched to the * same number of calls to the <tt>load()</tt> method of the * corresponding <tt>Unpickler</tt> instance. If the same object is * pickled by multiple <tt>dump()</tt> calls, the <tt>load()</tt> will all * yield references to the same object. <i>Warning</i>: this is intended * for pickling multiple objects without intervening modifications to the * objects or their parts. If you modify an object and then pickle it * again using the same <tt>Pickler</tt> instance, the object is not * pickled again -- a reference to it is pickled and the * <tt>Unpickler</tt> will return the old value, not the modified one. * (There are two problems here: (a) detecting changes, and (b) * marshalling a minimal set of changes. I have no answers. Garbage * Collection may also become a problem here.) * * <P> * Apart from the <tt>Pickler</tt> and <tt>Unpickler</tt> classes, the * module defines the following functions, and an exception: * * <P> * <dl><dt><b><tt>dump</tt></a></b> (<var>object, file</var><big>[</big><var>, * bin</var><big>]</big>) * <dd> * Write a pickled representation of <i>obect</i> to the open file object * <i>file</i>. This is equivalent to * "<tt>Pickler(<i>file</i>, <i>bin</i>).dump(<i>object</i>)</tt>". * If the optional <i>bin</i> argument is present and nonzero, the binary * pickle format is used; if it is zero or absent, the (less efficient) * text pickle format is used. * </dl> * * <P> * <dl><dt><b><tt>load</tt></a></b> (<var>file</var>) * <dd> * Read a pickled object from the open file object <i>file</i>. This is * equivalent to "<tt>Unpickler(<i>file</i>).load()</tt>". * </dl> * * <P> * <dl><dt><b><tt>dumps</tt></a></b> (<var>object</var><big>[</big><var>, * bin</var><big>]</big>) * <dd> * Return the pickled representation of the object as a string, instead * of writing it to a file. If the optional <i>bin</i> argument is * present and nonzero, the binary pickle format is used; if it is zero * or absent, the (less efficient) text pickle format is used. * </dl> * * <P> * <dl><dt><b><tt>loads</tt></a></b> (<var>string</var>) * <dd> * Read a pickled object from a string instead of a file. Characters in * the string past the pickled object's representation are ignored. * </dl> * * <P> * <dl><dt><b><a name="l2h-3763"><tt>PicklingError</tt></a></b> * <dd> * This exception is raised when an unpicklable object is passed to * <tt>Pickler.dump()</tt>. * </dl> * * * <p> * For the complete documentation on the pickle module, please see the * "Python Library Reference" * <p><hr><p> * * The module is based on both original pickle.py and the cPickle.c * version, except that all mistakes and errors are my own. * <p> * @author Finn Bock, [email protected] * @version cPickle.java,v 1.30 1999/05/15 17:40:12 fb Exp */ public class cPickle implements ClassDictInit { /** * The doc string */ public static String __doc__ = "Java implementation and optimization of the Python pickle module\n" + "\n" + "$Id$\n"; /** * The program version. */ public static String __version__ = "1.30"; /** * File format version we write. */ public static final String format_version = "1.3"; /** * Old format versions we can read. */ public static final String[] compatible_formats = new String[] { "1.0", "1.1", "1.2" }; public static String[] __depends__ = new String[] { "copy_reg", }; public static PyObject PickleError; public static PyObject PicklingError; public static PyObject UnpickleableError; public static PyObject UnpicklingError; public static final PyString BadPickleGet = new PyString("cPickle.BadPickleGet"); final static char MARK = '('; final static char STOP = '.'; final static char POP = '0'; final static char POP_MARK = '1'; final static char DUP = '2'; final static char FLOAT = 'F'; final static char INT = 'I'; final static char BININT = 'J'; final static char BININT1 = 'K'; final static char LONG = 'L'; final static char BININT2 = 'M'; final static char NONE = 'N'; final static char PERSID = 'P'; final static char BINPERSID = 'Q'; final static char REDUCE = 'R'; final static char STRING = 'S'; final static char BINSTRING = 'T'; final static char SHORT_BINSTRING = 'U'; final static char UNICODE = 'V'; final static char BINUNICODE = 'X'; final static char APPEND = 'a'; final static char BUILD = 'b'; final static char GLOBAL = 'c'; final static char DICT = 'd'; final static char EMPTY_DICT = '}'; final static char APPENDS = 'e'; final static char GET = 'g'; final static char BINGET = 'h'; final static char INST = 'i'; final static char LONG_BINGET = 'j'; final static char LIST = 'l'; final static char EMPTY_LIST = ']'; final static char OBJ = 'o'; final static char PUT = 'p'; final static char BINPUT = 'q'; final static char LONG_BINPUT = 'r'; final static char SETITEM = 's'; final static char TUPLE = 't'; final static char EMPTY_TUPLE = ')'; final static char SETITEMS = 'u'; final static char BINFLOAT = 'G'; private static PyDictionary dispatch_table = null; private static PyDictionary safe_constructors = null; private static PyClass BuiltinFunctionType = PyJavaClass.lookup(PyReflectedFunction.class); private static PyClass BuiltinMethodType = PyJavaClass.lookup(PyMethod.class); private static PyClass ClassType = PyJavaClass.lookup(PyClass.class); private static PyClass DictionaryType = PyJavaClass.lookup(PyDictionary.class); private static PyClass StringMapType = PyJavaClass.lookup(PyStringMap.class); private static PyClass FloatType = PyJavaClass.lookup(PyFloat.class); private static PyClass FunctionType = PyJavaClass.lookup(PyFunction.class); private static PyClass InstanceType = PyJavaClass.lookup(PyInstance.class); private static PyClass IntType = PyJavaClass.lookup(PyInteger.class); private static PyClass ListType = PyJavaClass.lookup(PyList.class); private static PyClass LongType = PyJavaClass.lookup(PyLong.class); private static PyClass NoneType = PyJavaClass.lookup(PyNone.class); private static PyClass StringType = PyJavaClass.lookup(PyString.class); private static PyClass TupleType = PyJavaClass.lookup(PyTuple.class); private static PyClass FileType = PyJavaClass.lookup(PyFile.class); private static PyObject dict; /** * Initialization when module is imported. */ public static void classDictInit(PyObject dict) { cPickle.dict = dict; // XXX: Hack for JPython 1.0.1. By default __builtin__ is not in // sys.modules. imp.importName("__builtin__", true); PyModule copyreg = (PyModule)importModule("copy_reg"); dispatch_table = (PyDictionary)copyreg.__getattr__("dispatch_table"); safe_constructors = (PyDictionary) copyreg.__getattr__("safe_constructors"); PickleError = buildClass("PickleError", Py.Exception, "_PickleError", ""); PicklingError = buildClass("PicklingError", PickleError, "_empty__init__", ""); UnpickleableError = buildClass("UnpickleableError", PicklingError, "_UnpickleableError", ""); UnpicklingError = buildClass("UnpicklingError", PickleError, "_empty__init__", ""); } // An empty __init__ method public static PyObject _empty__init__(PyObject[] arg, String[] kws) { PyObject dict = new PyStringMap(); dict.__setitem__("__module__", new PyString("cPickle")); return dict; } public static PyObject _PickleError(PyObject[] arg, String[] kws) { PyObject dict = _empty__init__(arg, kws); dict.__setitem__("__init__", getJavaFunc("_PickleError__init__")); dict.__setitem__("__str__", getJavaFunc("_PickleError__str__")); return dict; } public static void _PickleError__init__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args"); PyObject self = ap.getPyObject(0); PyObject args = ap.getList(1); self.__setattr__("args", args); } public static PyString _PickleError__str__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__str__", arg, kws, "self"); PyObject self = ap.getPyObject(0); PyObject args = self.__getattr__("args"); if (args.__len__() > 0 && args.__getitem__(0).__len__() > 0) return args.__getitem__(0).__str__(); else return new PyString("(what)"); } public static PyObject _UnpickleableError(PyObject[] arg, String[] kws) { PyObject dict = _empty__init__(arg, kws); dict.__setitem__("__init__", getJavaFunc("_UnpickleableError__init__")); dict.__setitem__("__str__", getJavaFunc("_UnpickleableError__str__")); return dict; } public static void _UnpickleableError__init__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args"); PyObject self = ap.getPyObject(0); PyObject args = ap.getList(1); self.__setattr__("args", args); } public static PyString _UnpickleableError__str__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__str__", arg, kws, "self"); PyObject self = ap.getPyObject(0); PyObject args = self.__getattr__("args"); PyObject a = args.__len__() > 0 ? args.__getitem__(0) : new PyString("(what)"); return new PyString("Cannot pickle %s objects").__mod__(a).__str__(); } public cPickle() { } /** * Returns a pickler instance. * @param file a file-like object, can be a cStringIO.StringIO, * a PyFile or any python object which implements a * <i>write</i> method. The data will be written as text. * @returns a new Pickler instance. */ public static Pickler Pickler(PyObject file) { return new Pickler(file, false); } /** * Returns a pickler instance. * @param file a file-like object, can be a cStringIO.StringIO, * a PyFile or any python object which implements a * <i>write</i> method. * @param bin when true, the output will be written as binary data. * @returns a new Pickler instance. */ public static Pickler Pickler(PyObject file, boolean bin) { return new Pickler(file, bin); } /** * Returns a unpickler instance. * @param file a file-like object, can be a cStringIO.StringIO, * a PyFile or any python object which implements a * <i>read</i> and <i>readline</i> method. * @returns a new Unpickler instance. */ public static Unpickler Unpickler(PyObject file) { return new Unpickler(file); } /** * Shorthand function which pickles the object on the file. * @param object a data object which should be pickled. * @param file a file-like object, can be a cStringIO.StringIO, * a PyFile or any python object which implements a * <i>write</i> method. The data will be written as * text. * @returns a new Unpickler instance. */ public static void dump(PyObject object, PyObject file) { dump(object, file, false); } /** * Shorthand function which pickles the object on the file. * @param object a data object which should be pickled. * @param file a file-like object, can be a cStringIO.StringIO, * a PyFile or any python object which implements a * <i>write</i> method. * @param bin when true, the output will be written as binary data. * @returns a new Unpickler instance. */ public static void dump(PyObject object, PyObject file, boolean bin) { new Pickler(file, bin).dump(object); } /** * Shorthand function which pickles and returns the string representation. * @param object a data object which should be pickled. * @returns a string representing the pickled object. */ public static String dumps(PyObject object) { return dumps(object, false); } /** * Shorthand function which pickles and returns the string representation. * @param object a data object which should be pickled. * @param bin when true, the output will be written as binary data. * @returns a string representing the pickled object. */ public static String dumps(PyObject object, boolean bin) { cStringIO.StringIO file = cStringIO.StringIO(); dump(object, file, bin); return file.getvalue(); } /** * Shorthand function which unpickles a object from the file and returns * the new object. * @param file a file-like object, can be a cStringIO.StringIO, * a PyFile or any python object which implements a * <i>read</i> and <i>readline</i> method. * @returns a new object. */ public static Object load(PyObject file) { return new Unpickler(file).load(); } /** * Shorthand function which unpickles a object from the string and * returns the new object. * @param str a strings which must contain a pickled object * representation. * @returns a new object. */ public static Object loads(PyObject str) { cStringIO.StringIO file = cStringIO.StringIO(str.toString()); return new Unpickler(file).load(); } // Factory for creating IOFile representation. private static IOFile createIOFile(PyObject file) { Object f = file.__tojava__(cStringIO.StringIO.class); if (f != Py.NoConversion) return new cStringIOFile((cStringIO.StringIO)file); else if (__builtin__.isinstance(file, FileType)) return new FileIOFile(file); else return new ObjectIOFile(file); } // IOFiles encapsulates and optimise access to the different file // representation. interface IOFile { public abstract void write(String str); // Usefull optimization since most data written are chars. public abstract void write(char str); public abstract void flush(); public abstract String read(int len); // Usefull optimization since all readlines removes the // trainling newline. public abstract String readlineNoNl(); } // Use a cStringIO as a file. static class cStringIOFile implements IOFile { cStringIO.StringIO file; cStringIOFile(PyObject file) { this.file = (cStringIO.StringIO)file.__tojava__(Object.class); } public void write(String str) { file.write(str); } public void write(char ch) { file.writeChar(ch); } public void flush() {} public String read(int len) { return file.read(len); } public String readlineNoNl() { return file.readlineNoNl(); } } // Use a PyFile as a file. static class FileIOFile implements IOFile { PyFile file; FileIOFile(PyObject file) { this.file = (PyFile)file.__tojava__(PyFile.class); if (this.file.closed) throw Py.ValueError("I/O operation on closed file"); } public void write(String str) { file.write(str); } public void write(char ch) { file.write(cStringIO.getString(ch)); } public void flush() {} public String read(int len) { return file.read(len).toString(); } public String readlineNoNl() { String line = file.readline().toString(); return line.substring(0, line.length()-1); } } // Use any python object as a file. static class ObjectIOFile implements IOFile { char[] charr = new char[1]; StringBuffer buff = new StringBuffer(); PyObject write; PyObject read; PyObject readline; final int BUF_SIZE = 256; ObjectIOFile(PyObject file) { // this.file = file; write = file.__findattr__("write"); read = file.__findattr__("read"); readline = file.__findattr__("readline"); } public void write(String str) { buff.append(str); if (buff.length() > BUF_SIZE) flush(); } public void write(char ch) { buff.append(ch); if (buff.length() > BUF_SIZE) flush(); } public void flush() { write.__call__(new PyString(buff.toString())); buff.setLength(0); } public String read(int len) { return read.__call__(new PyInteger(len)).toString(); } public String readlineNoNl() { String line = readline.__call__().toString(); return line.substring(0, line.length()-1); } } /** * The Pickler object * @see cPickle#Pickler(PyObject) * @see cPickle#Pickler(PyObject,boolean) */ static public class Pickler { private IOFile file; private boolean bin; /** * Hmm, not documented, perhaps it shouldn't be public? XXX: fixme. */ private PickleMemo memo = new PickleMemo(); /** * To write references to persistent objects, the persistent module * must assign a method to persistent_id which returns either None * or the persistent ID of the object. * For the benefit of persistency modules written using pickle, * it supports the notion of a reference to an object outside * the pickled data stream. * Such objects are referenced by a name, which is an arbitrary * string of printable ASCII characters. */ public PyObject persistent_id = null; /** * Hmm, not documented, perhaps it shouldn't be public? XXX: fixme. */ public PyObject inst_persistent_id = null; public Pickler(PyObject file, boolean bin) { this.file = createIOFile(file); this.bin = bin; } /** * Write a pickled representation of the object. * @param object The object which will be pickled. */ public void dump(PyObject object) { save(object); file.write(STOP); file.flush(); } // Save name as in pickle.py but semantics are slightly changed. private void put(int i) { if (bin) { if (i < 256) { file.write(BINPUT); file.write((char)i); return; } file.write(LONG_BINPUT); file.write((char)( i & 0xFF)); file.write((char)((i >>> 8) & 0xFF)); file.write((char)((i >>> 16) & 0xFF)); file.write((char)((i >>> 24) & 0xFF)); return; } file.write(PUT); file.write(String.valueOf(i)); file.write("\n"); } // Same name as in pickle.py but semantics are slightly changed. private void get(int i) { if (bin) { if (i < 256) { file.write(BINGET); file.write((char)i); return; } file.write(LONG_BINGET); file.write((char)( i & 0xFF)); file.write((char)((i >>> 8) & 0xFF)); file.write((char)((i >>> 16) & 0xFF)); file.write((char)((i >>> 24) & 0xFF)); return; } file.write(GET); file.write(String.valueOf(i)); file.write("\n"); } private void save(PyObject object) { save(object, false); } private void save(PyObject object, boolean pers_save) { if (!pers_save) { if (persistent_id != null) { PyObject pid = persistent_id.__call__(object); if (pid != Py.None) { save_pers(pid); return; } } } int d = Py.id(object); PyClass t = __builtin__.type(object); if (t == TupleType && object.__len__() == 0) { if (bin) save_empty_tuple(object); else save_tuple(object); return; } int m = getMemoPosition(d, object); if (m >= 0) { get(m); return; } if (save_type(object, t)) return; if (inst_persistent_id != null) { PyObject pid = inst_persistent_id.__call__(object); if (pid != Py.None) { save_pers(pid); return; } } PyObject tup = null; PyObject reduce = dispatch_table.__finditem__(t); if (reduce == null) { reduce = object.__findattr__("__reduce__"); if (reduce == null) throw new PyException(UnpickleableError, object); tup = reduce.__call__(); } else { tup = reduce.__call__(object); } - if (tup instanceof PyString) { + if (tup instanceof PyString) { save_global(object, tup); return; } if (!(tup instanceof PyTuple)) { throw new PyException(PicklingError, "Value returned by " + reduce.__repr__() + " must be a tuple"); } int l = tup.__len__(); if (l != 2 && l != 3) { throw new PyException(PicklingError, "tuple returned by " + reduce.__repr__() + " must contain only two or three elements"); } PyObject callable = tup.__finditem__(0); PyObject arg_tup = tup.__finditem__(1); PyObject state = (l > 2) ? tup.__finditem__(2) : Py.None; if (!(arg_tup instanceof PyTuple) && arg_tup != Py.None) { throw new PyException(PicklingError, "Second element of tupe returned by " + reduce.__repr__() + " must be a tuple"); } save_reduce(callable, arg_tup, state); put(putMemo(d, object)); } final private void save_pers(PyObject pid) { if (!bin) { file.write(PERSID); file.write(pid.toString()); file.write("\n"); } else { save(pid, true); file.write(BINPERSID); } } final private void save_reduce(PyObject callable, PyObject arg_tup, PyObject state) { save(callable); save(arg_tup); file.write(REDUCE); if (state != Py.None) { save(state); file.write(BUILD); } } final private boolean save_type(PyObject object, PyClass cls) { //System.out.println("save_type " + object + " " + cls); if (cls == NoneType) save_none(object); else if (cls == StringType) save_string(object); else if (cls == IntType) save_int(object); else if (cls == LongType) save_long(object); else if (cls == FloatType) save_float(object); else if (cls == TupleType) save_tuple(object); else if (cls == ListType) save_list(object); else if (cls == DictionaryType || cls == StringMapType) save_dict(object); else if (cls == InstanceType) save_inst((PyInstance)object); else if (cls == ClassType) save_global(object); else if (cls == FunctionType) save_global(object); else if (cls == BuiltinFunctionType) save_global(object); else return false; return true; } final private void save_none(PyObject object) { file.write(NONE); } final private void save_int(PyObject object) { if (bin) { int l = ((PyInteger)object).getValue(); char i1 = (char)( l & 0xFF); char i2 = (char)((l >>> 8 ) & 0xFF); char i3 = (char)((l >>> 16) & 0xFF); char i4 = (char)((l >>> 24) & 0xFF); if (i3 == '\0' && i4 == '\0') { if (i2 == '\0') { file.write(BININT1); file.write(i1); return; } file.write(BININT2); file.write(i1); file.write(i2); return; } file.write(BININT); file.write(i1); file.write(i2); file.write(i3); file.write(i4); } else { file.write(INT); file.write(object.toString()); file.write("\n"); } } final private void save_long(PyObject object) { file.write(LONG); file.write(object.toString()); file.write("\n"); } final private void save_float(PyObject object) { if (bin) { file.write(BINFLOAT); double value= ((PyFloat) object).getValue(); // It seems that struct.pack('>d', ..) and doubleToLongBits // are the same. Good for me :-) long bits = Double.doubleToLongBits(value); file.write((char)((bits >>> 56) & 0xFF)); file.write((char)((bits >>> 48) & 0xFF)); file.write((char)((bits >>> 40) & 0xFF)); file.write((char)((bits >>> 32) & 0xFF)); file.write((char)((bits >>> 24) & 0xFF)); file.write((char)((bits >>> 16) & 0xFF)); file.write((char)((bits >>> 8) & 0xFF)); file.write((char)((bits >>> 0) & 0xFF)); } else { file.write(FLOAT); file.write(object.toString()); file.write("\n"); } } final private void save_string(PyObject object) { boolean unicode = ((PyString) object).isunicode(); String str = object.toString(); if (bin) { if (unicode) str = codecs.PyUnicode_EncodeUTF8(str, "struct"); int l = str.length(); if (l < 256 && !unicode) { file.write(SHORT_BINSTRING); file.write((char)l); } else { if (unicode) file.write(BINUNICODE); else file.write(BINSTRING); file.write((char)( l & 0xFF)); file.write((char)((l >>> 8 ) & 0xFF)); file.write((char)((l >>> 16) & 0xFF)); file.write((char)((l >>> 24) & 0xFF)); } file.write(str); } else { if (unicode) { file.write(UNICODE); file.write(codecs.PyUnicode_EncodeRawUnicodeEscape(str, "strict", true)); } else { file.write(STRING); file.write(object.__repr__().toString()); } file.write("\n"); } put(putMemo(Py.id(object), object)); } final private void save_tuple(PyObject object) { int d = Py.id(object); file.write(MARK); int len = object.__len__(); for (int i = 0; i < len; i++) save(object.__finditem__(i)); if (len > 0) { int m = getMemoPosition(d, object); if (m >= 0) { if (bin) { file.write(POP_MARK); get(m); return; } for (int i = 0; i < len+1; i++) file.write(POP); get(m); return; } } file.write(TUPLE); put(putMemo(d, object)); } final private void save_empty_tuple(PyObject object) { file.write(EMPTY_TUPLE); } final private void save_list(PyObject object) { if (bin) file.write(EMPTY_LIST); else { file.write(MARK); file.write(LIST); } put(putMemo(Py.id(object), object)); int len = object.__len__(); boolean using_appends = bin && len > 1; if (using_appends) file.write(MARK); for (int i = 0; i < len; i++) { save(object.__finditem__(i)); if (!using_appends) file.write(APPEND); } if (using_appends) file.write(APPENDS); } final private void save_dict(PyObject object) { if (bin) file.write(EMPTY_DICT); else { file.write(MARK); file.write(DICT); } put(putMemo(Py.id(object), object)); PyObject list = object.invoke("keys"); int len = list.__len__(); boolean using_setitems = (bin && len > 1); if (using_setitems) file.write(MARK); for (int i = 0; i < len; i++) { PyObject key = list.__finditem__(i); PyObject value = object.__finditem__(key); save(key); save(value); if (!using_setitems) file.write(SETITEM); } if (using_setitems) file.write(SETITEMS); } final private void save_inst(PyInstance object) { if (object instanceof PyJavaInstance) throw new PyException(PicklingError, "Unable to pickle java objects."); PyClass cls = object.__class__; PySequence args = null; PyObject getinitargs = object.__findattr__("__getinitargs__"); if (getinitargs != null) { args = (PySequence)getinitargs.__call__(); // XXX Assert it's a sequence keep_alive(args); } file.write(MARK); if (bin) save(cls); if (args != null) { int len = args.__len__(); for (int i = 0; i < len; i++) save(args.__finditem__(i)); } int mid = putMemo(Py.id(object), object); if (bin) { file.write(OBJ); put(mid); } else { file.write(INST); file.write(cls.__findattr__("__module__").toString()); file.write("\n"); file.write(cls.__name__); file.write("\n"); put(mid); } PyObject stuff = null; PyObject getstate = object.__findattr__("__getstate__"); if (getstate == null) { stuff = object.__dict__; } else { stuff = getstate.__call__(); keep_alive(stuff); } save(stuff); file.write(BUILD); } final private void save_global(PyObject object) { save_global(object, null); } final private void save_global(PyObject object, PyObject name) { if (name == null) name = object.__findattr__("__name__"); PyObject module = object.__findattr__("__module__"); if (module == null || module == Py.None) module = whichmodule(object, name); file.write(GLOBAL); file.write(module.toString()); file.write("\n"); file.write(name.toString()); file.write("\n"); put(putMemo(Py.id(object), object)); } final private int getMemoPosition(int id, Object o) { return memo.findPosition(id, o); } final private int putMemo(int id, PyObject object) { int memo_len = memo.size(); memo.put(id, memo_len, object); return memo_len; } /** * Keeps a reference to the object x in the memo. * * Because we remember objects by their id, we have * to assure that possibly temporary objects are kept * alive by referencing them. * We store a reference at the id of the memo, which should * normally not be used unless someone tries to deepcopy * the memo itself... */ final private void keep_alive(PyObject obj) { int id = System.identityHashCode(memo); PyList list = (PyList) memo.findValue(id, memo); if (list == null) { list = new PyList(); memo.put(id, -1, list); } list.append(obj); } } private static Hashtable classmap = new Hashtable(); final private static PyObject whichmodule(PyObject cls, PyObject clsname) { PyObject name = (PyObject)classmap.get(cls); if (name != null) return name; name = new PyString("__main__"); // For use with JPython1.0.x //PyObject modules = sys.modules; // For use with JPython1.1.x //PyObject modules = Py.getSystemState().modules; PyObject sys = imp.importName("sys", true); PyObject modules = sys.__findattr__("modules"); PyObject keylist = modules.invoke("keys"); int len = keylist.__len__(); for (int i = 0; i < len; i++) { PyObject key = keylist.__finditem__(i); PyObject value = modules.__finditem__(key); if (!key.equals("__main__") && value.__findattr__(clsname.toString().intern()) == cls) { name = key; break; } } classmap.put(cls, name); //System.out.println(name); return name; } /* * A very specialized and simplified version of PyStringMap. It can * only use integers as keys and stores both an integer and an object * as value. It is very private! */ static private class PickleMemo { //Table of primes to cycle through private final int[] primes = { 13, 61, 251, 1021, 4093, 5987, 9551, 15683, 19609, 31397, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789,}; private transient int[] keys; private transient int[] position; private transient Object[] values; private int size; private transient int filled; private transient int prime; // Not actually used, since there is no delete methods. private String DELETEDKEY = "<deleted key>"; public PickleMemo(int capacity) { prime = 0; keys = null; values = null; resize(capacity); } public PickleMemo() { this(4); } public synchronized int size() { return size; } private int findIndex(int key, Object value) { int[] table = keys; int maxindex = table.length; int index = (key & 0x7fffffff) % maxindex; // Fairly aribtrary choice for stepsize... int stepsize = maxindex / 5; // Cycle through possible positions for the key; //int collisions = 0; while (true) { int tkey = table[index]; if (tkey == key && value == values[index]) { return index; } if (values[index] == null) return -1; index = (index+stepsize) % maxindex; } } public int findPosition(int key, Object value) { int idx = findIndex(key, value); if (idx < 0) return -1; return position[idx]; } public Object findValue(int key, Object value) { int idx = findIndex(key, value); if (idx < 0) return null; return values[idx]; } private final void insertkey(int key, int pos, Object value) { int[] table = keys; int maxindex = table.length; int index = (key & 0x7fffffff) % maxindex; // Fairly aribtrary choice for stepsize... int stepsize = maxindex / 5; // Cycle through possible positions for the key; while (true) { int tkey = table[index]; if (values[index] == null) { table[index] = key; position[index] = pos; values[index] = value; filled++; size++; break; } else if (tkey == key && values[index] == value) { position[index] = pos; break; } else if (values[index] == DELETEDKEY) { table[index] = key; position[index] = pos; values[index] = value; size++; break; } index = (index+stepsize) % maxindex; } } private synchronized final void resize(int capacity) { int p = prime; for(; p<primes.length; p++) { if (primes[p] >= capacity) break; } if (primes[p] < capacity) { throw Py.ValueError("can't make hashtable of size: " + capacity); } capacity = primes[p]; prime = p; int[] oldKeys = keys; int[] oldPositions = position; Object[] oldValues = values; keys = new int[capacity]; position = new int[capacity]; values = new Object[capacity]; size = 0; filled = 0; if (oldValues != null) { int n = oldValues.length; for(int i=0; i<n; i++) { Object value = oldValues[i]; if (value == null || value == DELETEDKEY) continue; insertkey(oldKeys[i], oldPositions[i], value); } } } public void put(int key, int pos, Object value) { if (2*filled > keys.length) resize(keys.length+1); insertkey(key, pos, value); } } /** * The Unpickler object. Unpickler instances are create by the factory * methods Unpickler. * @see cPickle#Unpickler(PyObject) */ static public class Unpickler { private IOFile file; public Hashtable memo = new Hashtable(); /** * For the benefit of persistency modules written using pickle, * it supports the notion of a reference to an object outside * the pickled data stream. * Such objects are referenced by a name, which is an arbitrary * string of printable ASCII characters. * The resolution of such names is not defined by the pickle module * -- the persistent object module will have to add a method * persistent_load(). */ public PyObject persistent_load = null; private PyObject mark = new PyString("spam"); private int stackTop; private PyObject[] stack; Unpickler(PyObject file) { this.file = createIOFile(file); } /** * Unpickle and return an instance of the object represented by * the file. */ public PyObject load() { stackTop = 0; stack = new PyObject[10]; while (true) { String s = file.read(1); // System.out.println("load:" + s); // for (int i = 0; i < stackTop; i++) // System.out.println(" " + stack[i]); if (s.length() < 1) load_eof(); char key = s.charAt(0); switch (key) { case PERSID: load_persid(); break; case BINPERSID: load_binpersid(); break; case NONE: load_none(); break; case INT: load_int(); break; case BININT: load_binint(); break; case BININT1: load_binint1(); break; case BININT2: load_binint2(); break; case LONG: load_long(); break; case FLOAT: load_float(); break; case BINFLOAT: load_binfloat(); break; case STRING: load_string(); break; case BINSTRING: load_binstring(); break; case SHORT_BINSTRING: load_short_binstring(); break; case UNICODE: load_unicode(); break; case BINUNICODE: load_binunicode(); break; case TUPLE: load_tuple(); break; case EMPTY_TUPLE: load_empty_tuple(); break; case EMPTY_LIST: load_empty_list(); break; case EMPTY_DICT: load_empty_dictionary(); break; case LIST: load_list(); break; case DICT: load_dict(); break; case INST: load_inst(); break; case OBJ: load_obj(); break; case GLOBAL: load_global(); break; case REDUCE: load_reduce(); break; case POP: load_pop(); break; case POP_MARK: load_pop_mark(); break; case DUP: load_dup(); break; case GET: load_get(); break; case BINGET: load_binget(); break; case LONG_BINGET: load_long_binget(); break; case PUT: load_put(); break; case BINPUT: load_binput(); break; case LONG_BINPUT: load_long_binput(); break; case APPEND: load_append(); break; case APPENDS: load_appends(); break; case SETITEM: load_setitem(); break; case SETITEMS: load_setitems(); break; case BUILD: load_build(); break; case MARK: load_mark(); break; case STOP: return load_stop(); } } } final private int marker() { for (int k = stackTop-1; k >= 0; k--) if (stack[k] == mark) return stackTop-k-1; throw new PyException(UnpicklingError, "Inputstream corrupt, marker not found"); } final private void load_eof() { throw new PyException(Py.EOFError); } final private void load_persid() { String pid = file.readlineNoNl(); push(persistent_load.__call__(new PyString(pid))); } final private void load_binpersid() { PyObject pid = pop(); push(persistent_load.__call__(pid)); } final private void load_none() { push(Py.None); } final private void load_int() { String line = file.readlineNoNl(); // XXX: use strop instead? push(new PyInteger(Integer.parseInt(line))); } final private void load_binint() { String s = file.read(4); int x = s.charAt(0) | (s.charAt(1)<<8) | (s.charAt(2)<<16) | (s.charAt(3)<<24); push(new PyInteger(x)); } final private void load_binint1() { int val = (int)file.read(1).charAt(0); push(new PyInteger(val)); } final private void load_binint2() { String s = file.read(2); int val = ((int)s.charAt(1)) << 8 | ((int)s.charAt(0)); push(new PyInteger(val)); } final private void load_long() { String line = file.readlineNoNl(); push(new PyLong(line.substring(0, line.length()-1))); } final private void load_float() { String line = file.readlineNoNl(); push(new PyFloat(Double.valueOf(line).doubleValue())); } final private void load_binfloat() { String s = file.read(8); long bits = (long)s.charAt(7) | ((long)s.charAt(6) << 8) | ((long)s.charAt(5) << 16) | ((long)s.charAt(4) << 24) | ((long)s.charAt(3) << 32) | ((long)s.charAt(2) << 40) | ((long)s.charAt(1) << 48) | ((long)s.charAt(0) << 56); push(new PyFloat(Double.longBitsToDouble(bits))); } final private void load_string() { String line = file.readlineNoNl(); String value; char quote = line.charAt(0); if (quote != '"' && quote != '\'') throw Py.ValueError("insecure string pickle"); int nslash = 0; int i; char ch = '\0'; int n = line.length(); for (i = 1; i < n; i++) { ch = line.charAt(i); if (ch == quote && nslash % 2 == 0) break; if (ch == '\\') nslash++; else nslash = 0; } if (ch != quote) throw Py.ValueError("insecure string pickle"); for (i++ ; i < line.length(); i++) { if (line.charAt(i) > ' ') throw Py.ValueError("insecure string pickle " + i); } value = PyString.decode_UnicodeEscape(line, 1, n-1, "strict", false); push(new PyString(value)); } final private void load_binstring() { String d = file.read(4); int len = d.charAt(0) | (d.charAt(1)<<8) | (d.charAt(2)<<16) | (d.charAt(3)<<24); push(new PyString(file.read(len))); } final private void load_short_binstring() { int len = (int)file.read(1).charAt(0); push(new PyString(file.read(len))); } final private void load_unicode() { String line = file.readlineNoNl(); int n = line.length(); String value = codecs.PyUnicode_DecodeRawUnicodeEscape(line, "strict"); push(new PyString(value)); } final private void load_binunicode() { String d = file.read(4); int len = d.charAt(0) | (d.charAt(1)<<8) | (d.charAt(2)<<16) | (d.charAt(3)<<24); String line = file.read(len); push(new PyString(codecs.PyUnicode_DecodeUTF8(line, "strict"))); } final private void load_tuple() { PyObject[] arr = new PyObject[marker()]; pop(arr); pop(); push(new PyTuple(arr)); } final private void load_empty_tuple() { push(new PyTuple(Py.EmptyObjects)); } final private void load_empty_list() { push(new PyList(Py.EmptyObjects)); } final private void load_empty_dictionary() { push(new PyDictionary()); } final private void load_list() { PyObject[] arr = new PyObject[marker()]; pop(arr); pop(); push(new PyList(arr)); } final private void load_dict() { int k = marker(); PyDictionary d = new PyDictionary(); for (int i = 0; i < k; i += 2) { PyObject value = pop(); PyObject key = pop(); d.__setitem__(key, value); } pop(); push(d); } final private void load_inst() { PyObject[] args = new PyObject[marker()]; pop(args); pop(); String module = file.readlineNoNl(); String name = file.readlineNoNl(); PyObject klass = find_class(module, name); PyObject value = null; if (args.length == 0 && klass instanceof PyClass && klass.__findattr__("__getinitargs__") == null) { value = new PyInstance((PyClass)klass); } else { value = klass.__call__(args); } push(value); } final private void load_obj() { PyObject[] args = new PyObject[marker()-1]; pop(args); PyObject klass = pop(); pop(); PyObject value = null; if (args.length == 0 && klass instanceof PyClass && klass.__findattr__("__getinitargs__") == null) { value = new PyInstance((PyClass)klass); } else { value = klass.__call__(args); } push(value); } final private void load_global() { String module = file.readlineNoNl(); String name = file.readlineNoNl(); PyObject klass = find_class(module, name); push(klass); } final private PyObject find_class(String module, String name) { PyObject fc = dict.__finditem__("find_global"); if (fc != null) { if (fc == Py.None) throw new PyException(UnpicklingError, "Global and instance pickles are not supported."); return fc.__call__(new PyString(module), new PyString(name)); } PyObject modules = Py.getSystemState().modules; PyObject mod = modules.__finditem__(module.intern()); if (mod == null) { mod = importModule(module); } PyObject global = mod.__findattr__(name.intern()); if (global == null) { throw new PyException(Py.SystemError, "Failed to import class " + name + " from module " + module); } return global; } final private void load_reduce() { PyObject arg_tup = pop(); PyObject callable = pop(); if (!(callable instanceof PyClass)) { if (safe_constructors.__finditem__(callable) == null) { if (callable.__findattr__("__safe_for_unpickling__") == null) throw new PyException(UnpicklingError, callable + " is not safe for unpickling"); } } PyObject value = null; if (arg_tup == Py.None) { // XXX __basicnew__ ? value = callable.__findattr__("__basicnew__").__call__(); } else { value = callable.__call__(make_array(arg_tup)); } push(value); } final private PyObject[] make_array(PyObject seq) { int n = seq.__len__(); PyObject[] objs= new PyObject[n]; for(int i=0; i<n; i++) objs[i] = seq.__finditem__(i); return objs; } final private void load_pop() { pop(); } final private void load_pop_mark() { pop(marker()); } final private void load_dup() { push(peek()); } final private void load_get() { String py_str = file.readlineNoNl(); PyObject value = (PyObject)memo.get(py_str); if (value == null) throw new PyException(BadPickleGet, py_str); push(value); } final private void load_binget() { String py_key = String.valueOf((int)file.read(1).charAt(0)); PyObject value = (PyObject)memo.get(py_key); if (value == null) throw new PyException(BadPickleGet, py_key); push(value); } final private void load_long_binget() { String d = file.read(4); int i = d.charAt(0) | (d.charAt(1)<<8) | (d.charAt(2)<<16) | (d.charAt(3)<<24); String py_key = String.valueOf(i); PyObject value = (PyObject)memo.get(py_key); if (value == null) throw new PyException(BadPickleGet, py_key); push(value); } final private void load_put() { memo.put(file.readlineNoNl(), peek()); } final private void load_binput() { int i = (int)file.read(1).charAt(0); memo.put(String.valueOf(i), peek()); } final private void load_long_binput() { String d = file.read(4); int i = d.charAt(0) | (d.charAt(1)<<8) | (d.charAt(2)<<16) | (d.charAt(3)<<24); memo.put(String.valueOf(i), peek()); } final private void load_append() { PyObject value = pop(); PyList list = (PyList)peek(); list.append(value); } final private void load_appends() { int mark = marker(); PyList list = (PyList)peek(mark+1); for (int i = mark-1; i >= 0; i--) list.append(peek(i)); pop(mark+1); } final private void load_setitem() { PyObject value = pop(); PyObject key = pop(); PyDictionary dict = (PyDictionary)peek(); dict.__setitem__(key, value); } final private void load_setitems() { int mark = marker(); PyDictionary dict = (PyDictionary)peek(mark+1); for (int i = 0; i < mark; i += 2) { PyObject key = peek(i+1); PyObject value = peek(i); dict.__setitem__(key, value); } pop(mark+1); } final private void load_build() { PyObject value = pop(); PyInstance inst = (PyInstance)peek(); PyObject setstate = inst.__findattr__("__setstate__"); if (setstate == null) { inst.__dict__.__findattr__("update").__call__(value); } else { setstate.__call__(value); } } final private void load_mark() { push(mark); } final private PyObject load_stop() { return pop(); } final private PyObject peek() { return stack[stackTop-1]; } final private PyObject peek(int count) { return stack[stackTop-count-1]; } final private PyObject pop() { PyObject val = stack[--stackTop]; stack[stackTop] = null; return val; } final private void pop(int count) { for (int i = 0; i < count; i++) stack[--stackTop] = null; } final private void pop(PyObject[] arr) { int len = arr.length; System.arraycopy(stack, stackTop - len, arr, 0, len); stackTop -= len; } final private void push(PyObject val) { if (stackTop >= stack.length) { PyObject[] newStack = new PyObject[(stackTop+1) * 2]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } stack[stackTop++] = val; } } private static PyObject importModule(String name) { PyObject silly_list = new PyTuple(new PyString[] { Py.newString("__doc__"), }); return __builtin__.__import__(name, null, null, silly_list); } private static PyObject getJavaFunc(String name) { return Py.newJavaFunc(cPickle.class, name); } private static PyObject buildClass(String classname, PyObject superclass, String classCodeName, String doc) { PyObject[] sclass = Py.EmptyObjects; if (superclass != null) sclass = new PyObject[] { superclass }; PyObject cls = Py.makeClass( classname, sclass, Py.newJavaCode(cPickle.class, classCodeName), new PyString(doc)); return cls; } }
true
true
private void save(PyObject object, boolean pers_save) { if (!pers_save) { if (persistent_id != null) { PyObject pid = persistent_id.__call__(object); if (pid != Py.None) { save_pers(pid); return; } } } int d = Py.id(object); PyClass t = __builtin__.type(object); if (t == TupleType && object.__len__() == 0) { if (bin) save_empty_tuple(object); else save_tuple(object); return; } int m = getMemoPosition(d, object); if (m >= 0) { get(m); return; } if (save_type(object, t)) return; if (inst_persistent_id != null) { PyObject pid = inst_persistent_id.__call__(object); if (pid != Py.None) { save_pers(pid); return; } } PyObject tup = null; PyObject reduce = dispatch_table.__finditem__(t); if (reduce == null) { reduce = object.__findattr__("__reduce__"); if (reduce == null) throw new PyException(UnpickleableError, object); tup = reduce.__call__(); } else { tup = reduce.__call__(object); } if (tup instanceof PyString) { save_global(object, tup); return; } if (!(tup instanceof PyTuple)) { throw new PyException(PicklingError, "Value returned by " + reduce.__repr__() + " must be a tuple"); } int l = tup.__len__(); if (l != 2 && l != 3) { throw new PyException(PicklingError, "tuple returned by " + reduce.__repr__() + " must contain only two or three elements"); } PyObject callable = tup.__finditem__(0); PyObject arg_tup = tup.__finditem__(1); PyObject state = (l > 2) ? tup.__finditem__(2) : Py.None; if (!(arg_tup instanceof PyTuple) && arg_tup != Py.None) { throw new PyException(PicklingError, "Second element of tupe returned by " + reduce.__repr__() + " must be a tuple"); } save_reduce(callable, arg_tup, state); put(putMemo(d, object)); }
private void save(PyObject object, boolean pers_save) { if (!pers_save) { if (persistent_id != null) { PyObject pid = persistent_id.__call__(object); if (pid != Py.None) { save_pers(pid); return; } } } int d = Py.id(object); PyClass t = __builtin__.type(object); if (t == TupleType && object.__len__() == 0) { if (bin) save_empty_tuple(object); else save_tuple(object); return; } int m = getMemoPosition(d, object); if (m >= 0) { get(m); return; } if (save_type(object, t)) return; if (inst_persistent_id != null) { PyObject pid = inst_persistent_id.__call__(object); if (pid != Py.None) { save_pers(pid); return; } } PyObject tup = null; PyObject reduce = dispatch_table.__finditem__(t); if (reduce == null) { reduce = object.__findattr__("__reduce__"); if (reduce == null) throw new PyException(UnpickleableError, object); tup = reduce.__call__(); } else { tup = reduce.__call__(object); } if (tup instanceof PyString) { save_global(object, tup); return; } if (!(tup instanceof PyTuple)) { throw new PyException(PicklingError, "Value returned by " + reduce.__repr__() + " must be a tuple"); } int l = tup.__len__(); if (l != 2 && l != 3) { throw new PyException(PicklingError, "tuple returned by " + reduce.__repr__() + " must contain only two or three elements"); } PyObject callable = tup.__finditem__(0); PyObject arg_tup = tup.__finditem__(1); PyObject state = (l > 2) ? tup.__finditem__(2) : Py.None; if (!(arg_tup instanceof PyTuple) && arg_tup != Py.None) { throw new PyException(PicklingError, "Second element of tupe returned by " + reduce.__repr__() + " must be a tuple"); } save_reduce(callable, arg_tup, state); put(putMemo(d, object)); }
diff --git a/waterken/remote/src/org/waterken/remote/http/Callee.java b/waterken/remote/src/org/waterken/remote/http/Callee.java index 162e2eaf..3752c312 100644 --- a/waterken/remote/src/org/waterken/remote/http/Callee.java +++ b/waterken/remote/src/org/waterken/remote/http/Callee.java @@ -1,305 +1,306 @@ // Copyright 2007 Waterken Inc. under the terms of the MIT X license // found at http://www.opensource.org/licenses/mit-license.html package org.waterken.remote.http; import static org.joe_e.array.PowerlessArray.builder; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import org.joe_e.Struct; import org.joe_e.array.ArrayBuilder; import org.joe_e.array.ByteArray; import org.joe_e.array.ConstArray; import org.joe_e.array.PowerlessArray; import org.joe_e.charset.URLEncoding; import org.joe_e.reflect.Reflection; import org.ref_send.promise.Fulfilled; import org.ref_send.promise.Rejected; import org.ref_send.promise.Volatile; import org.ref_send.promise.eventual.Do; import org.ref_send.promise.eventual.Eventual; import org.ref_send.scope.Layout; import org.ref_send.scope.Scope; import org.ref_send.var.Factory; import org.waterken.http.MediaType; import org.waterken.http.Request; import org.waterken.http.Response; import org.waterken.http.Server; import org.waterken.http.TokenList; import org.waterken.io.snapshot.Snapshot; import org.waterken.remote.Exports; import org.waterken.syntax.json.JSONDeserializer; import org.waterken.syntax.json.JSONSerializer; import org.waterken.uri.Header; import org.waterken.uri.Path; import org.waterken.uri.Query; import org.waterken.uri.URI; import org.waterken.vat.Root; import org.web_send.Entity; /** * Server-side of the HTTP web-amp protocol. */ final class Callee extends Struct implements Server, Serializable { static private final long serialVersionUID = 1L; private final Server bootstrap; private final ClassLoader code; private final Exports exports; Callee(final Server bootstrap, final Root local) { this.bootstrap = bootstrap; code = local.fetch(null, Root.code); exports = new Exports(local); } // org.waterken.http.Server interface public void serve(final String resource, final Volatile<Request> requestor, final Do<Response,?> respond) throws Exception { // check for web browser bootstrap request final String query = URI.query(null, resource); if (null == query) { final String project = exports.getProject(); bootstrap.serve("file:///site/" + URLEncoding.encode(project) + "/"+ URLEncoding.encode(Path.name(URI.path(resource))), requestor, respond); return; } // determine the request final Request request; try { request = requestor.cast(); } catch (final Exception e) { respond.reject(e); return; } // made it to the final processor, so bounce a TRACE if ("TRACE".equals(request.method)) { respond.fulfill(request.trace()); return; } // check that there is no path name if (!"".equals(Path.name(URI.path(resource)))) { respond.fulfill(never(request.method)); return; } // determine the request subject Volatile<?> subject; try { subject = Eventual.promised(exports.use(Query.arg("", query, "s"))); } catch (final Exception e) { subject = new Rejected<Object>(e); } // determine the request type final String p = Query.arg(null, query, "p"); if (null == p || "*".equals(p)) { // when block or introspection Object value; try { // AUDIT: call to untrusted application code value = subject.cast(); } catch (final NullPointerException e) { respond.fulfill(serialize(request.method, "404", "not yet", ephemeral, new Rejected<Object>(e))); return; } catch (final Exception e) { value = new Rejected<Object>(e); } if ("GET".equals(request.method) || "HEAD".equals(request.method)) { if ("*".equals(p)) { final Class<?> t = null!=value?value.getClass():Void.class; if (!Exports.isPBC(t)) { value = describe(t); } } respond.fulfill(serialize(request.method, "200", "OK", forever, value)); } else { final String[] allow = { "TRACE", "OPTIONS", "GET", "HEAD" }; if ("OPTIONS".equals(request.method)) { respond.fulfill(Request.options(allow)); } else { respond.fulfill(Request.notAllowed(allow)); } } return; } // member access // to preserve message order, force settling of a promise if (!(subject instanceof Fulfilled)) { respond.fulfill(never(request.method)); return; } // AUDIT: call to untrusted application code final Object target = ((Fulfilled<?>)subject).cast(); // prevent access to local implementation details final Class<?> type = null != target ? target.getClass() : Void.class; if (Exports.isPBC(type)) { respond.fulfill(never(request.method)); return; } // process the request final Method lambda = Exports.dispatch(type, p); if ("GET".equals(request.method) || "HEAD".equals(request.method)) { Object value; try { if (null == Exports.property(lambda)) { throw new ClassCastException(); } // AUDIT: call to untrusted application code value = Reflection.invoke(Exports.bubble(lambda), target); } catch (final Exception e) { value = new Rejected<Object>(e); } - final boolean constant = "getClass".equals(lambda.getName()); + final boolean constant = + null == lambda || "getClass".equals(lambda.getName()); final int maxAge = constant ? forever : ephemeral; final String etag = constant ? null : exports.getTransactionTag(); Response r = request.hasVersion(etag) ? new Response("HTTP/1.1", "304", "Not Modified", PowerlessArray.array( new Header("Cache-Control", "max-age=" + maxAge) ), null) : serialize(request.method, "200", "OK", maxAge, value); if (null != etag) { r = r.with("ETag", etag); } respond.fulfill(r); } else if ("POST".equals(request.method)) { final String contentType = request.getContentType(); final MediaType mime = null != contentType ? MediaType.decode(contentType) : AMP.mime; final Entity raw; if (AMP.mime.contains(mime) || MediaType.text.contains(mime)) { if (!TokenList.equivalent("UTF-8", mime.get("charset", "UTF-8"))) { throw new Exception("charset MUST be UTF-8"); } raw = null; } else { raw = new Entity(contentType, ((Snapshot)request.body).content); } final String m = Query.arg(null, query, "m"); final Object value = exports.once(m, lambda, new Factory<Object>() { @Override public Object run() { try { if (null != Exports.property(lambda)) { throw new ClassCastException(); } final ConstArray<?> argv = null != raw ? ConstArray.array(raw) : deserialize(request, ConstArray.array( lambda.getGenericParameterTypes())); // AUDIT: call to untrusted application code return Reflection.invoke(Exports.bubble(lambda), target, argv.toArray(new Object[argv.length()])); } catch (final Exception e) { return new Rejected<Object>(e); } } }); respond.fulfill(serialize(request.method, "200", "OK", ephemeral, value)); } else { final String[] allow = null != lambda ? (null == Exports.property(lambda) ? new String[] { "TRACE", "OPTIONS", "POST" } : new String[] { "TRACE", "OPTIONS", "GET", "HEAD" }) : new String[] { "TRACE", "OPTIONS" }; if ("OPTIONS".equals(request.method)) { respond.fulfill(Request.options(allow)); } else { respond.fulfill(Request.notAllowed(allow)); } } } /** * Constructs a 404 response. */ private Response never(final String method) throws Exception { return serialize(method, "404", "never", forever, new Rejected<Object>(new NullPointerException())); } private Response serialize(final String method, final String status, final String phrase, final int maxAge, final Object value) throws Exception { if (value instanceof Entity) { final ByteArray content = ((Entity)value).content; return new Response("HTTP/1.1", status, phrase, PowerlessArray.array( new Header("Cache-Control", "max-age=" + maxAge), new Header("Content-Type", ((Entity)value).type), new Header("Content-Length", "" + content.length()) ), "HEAD".equals(method) ? null : new Snapshot(content)); } final ByteArray.BuilderOutputStream out = ByteArray.builder(1024).asOutputStream(); new JSONSerializer().run(exports.reply(), ConstArray.array(value), out); final Snapshot body = new Snapshot(out.snapshot()); return new Response("HTTP/1.1", status, phrase, PowerlessArray.array( new Header("Cache-Control", "max-age=" + maxAge), new Header("Content-Type", AMP.mime.toString()), new Header("Content-Length", "" + body.content.length()) ), "HEAD".equals(method) ? null : body); } private ConstArray<?> deserialize(final Request request, final ConstArray<Type> parameters) throws Exception { final String base = request.base(exports.getHere()); return new JSONDeserializer().run(base, exports.connect(), parameters, code, ((Snapshot)request.body).content.asInputStream()); } static private Scope describe(final Class<?> type) { final Object ts = types(type); return new Scope(new Layout(PowerlessArray.array("$")), ConstArray.array(ts)); } /** * Enumerate all types implemented by a class. */ static private PowerlessArray<String> types(final Class<?> actual) { final Class<?> end = Struct.class.isAssignableFrom(actual) ? Struct.class : Object.class; final PowerlessArray.Builder<String> r = builder(4); for (Class<?> i=actual; end!=i; i=i.getSuperclass()) { ifaces(i, r); } return r.snapshot(); } /** * List all the interfaces implemented by a class. */ static private void ifaces(final Class<?> type, final ArrayBuilder<String> r) { if (type == Serializable.class) { return; } if (Modifier.isPublic(type.getModifiers())) { try { r.append(Reflection.getName(type).replace('$', '-')); } catch (final Exception e) {} } for (final Class<?> i : type.getInterfaces()) { ifaces(i, r); } } }
true
true
public void serve(final String resource, final Volatile<Request> requestor, final Do<Response,?> respond) throws Exception { // check for web browser bootstrap request final String query = URI.query(null, resource); if (null == query) { final String project = exports.getProject(); bootstrap.serve("file:///site/" + URLEncoding.encode(project) + "/"+ URLEncoding.encode(Path.name(URI.path(resource))), requestor, respond); return; } // determine the request final Request request; try { request = requestor.cast(); } catch (final Exception e) { respond.reject(e); return; } // made it to the final processor, so bounce a TRACE if ("TRACE".equals(request.method)) { respond.fulfill(request.trace()); return; } // check that there is no path name if (!"".equals(Path.name(URI.path(resource)))) { respond.fulfill(never(request.method)); return; } // determine the request subject Volatile<?> subject; try { subject = Eventual.promised(exports.use(Query.arg("", query, "s"))); } catch (final Exception e) { subject = new Rejected<Object>(e); } // determine the request type final String p = Query.arg(null, query, "p"); if (null == p || "*".equals(p)) { // when block or introspection Object value; try { // AUDIT: call to untrusted application code value = subject.cast(); } catch (final NullPointerException e) { respond.fulfill(serialize(request.method, "404", "not yet", ephemeral, new Rejected<Object>(e))); return; } catch (final Exception e) { value = new Rejected<Object>(e); } if ("GET".equals(request.method) || "HEAD".equals(request.method)) { if ("*".equals(p)) { final Class<?> t = null!=value?value.getClass():Void.class; if (!Exports.isPBC(t)) { value = describe(t); } } respond.fulfill(serialize(request.method, "200", "OK", forever, value)); } else { final String[] allow = { "TRACE", "OPTIONS", "GET", "HEAD" }; if ("OPTIONS".equals(request.method)) { respond.fulfill(Request.options(allow)); } else { respond.fulfill(Request.notAllowed(allow)); } } return; } // member access // to preserve message order, force settling of a promise if (!(subject instanceof Fulfilled)) { respond.fulfill(never(request.method)); return; } // AUDIT: call to untrusted application code final Object target = ((Fulfilled<?>)subject).cast(); // prevent access to local implementation details final Class<?> type = null != target ? target.getClass() : Void.class; if (Exports.isPBC(type)) { respond.fulfill(never(request.method)); return; } // process the request final Method lambda = Exports.dispatch(type, p); if ("GET".equals(request.method) || "HEAD".equals(request.method)) { Object value; try { if (null == Exports.property(lambda)) { throw new ClassCastException(); } // AUDIT: call to untrusted application code value = Reflection.invoke(Exports.bubble(lambda), target); } catch (final Exception e) { value = new Rejected<Object>(e); } final boolean constant = "getClass".equals(lambda.getName()); final int maxAge = constant ? forever : ephemeral; final String etag = constant ? null : exports.getTransactionTag(); Response r = request.hasVersion(etag) ? new Response("HTTP/1.1", "304", "Not Modified", PowerlessArray.array( new Header("Cache-Control", "max-age=" + maxAge) ), null) : serialize(request.method, "200", "OK", maxAge, value); if (null != etag) { r = r.with("ETag", etag); } respond.fulfill(r); } else if ("POST".equals(request.method)) { final String contentType = request.getContentType(); final MediaType mime = null != contentType ? MediaType.decode(contentType) : AMP.mime; final Entity raw; if (AMP.mime.contains(mime) || MediaType.text.contains(mime)) { if (!TokenList.equivalent("UTF-8", mime.get("charset", "UTF-8"))) { throw new Exception("charset MUST be UTF-8"); } raw = null; } else { raw = new Entity(contentType, ((Snapshot)request.body).content); } final String m = Query.arg(null, query, "m"); final Object value = exports.once(m, lambda, new Factory<Object>() { @Override public Object run() { try { if (null != Exports.property(lambda)) { throw new ClassCastException(); } final ConstArray<?> argv = null != raw ? ConstArray.array(raw) : deserialize(request, ConstArray.array( lambda.getGenericParameterTypes())); // AUDIT: call to untrusted application code return Reflection.invoke(Exports.bubble(lambda), target, argv.toArray(new Object[argv.length()])); } catch (final Exception e) { return new Rejected<Object>(e); } } }); respond.fulfill(serialize(request.method, "200", "OK", ephemeral, value)); } else { final String[] allow = null != lambda ? (null == Exports.property(lambda) ? new String[] { "TRACE", "OPTIONS", "POST" } : new String[] { "TRACE", "OPTIONS", "GET", "HEAD" }) : new String[] { "TRACE", "OPTIONS" }; if ("OPTIONS".equals(request.method)) { respond.fulfill(Request.options(allow)); } else { respond.fulfill(Request.notAllowed(allow)); } } }
public void serve(final String resource, final Volatile<Request> requestor, final Do<Response,?> respond) throws Exception { // check for web browser bootstrap request final String query = URI.query(null, resource); if (null == query) { final String project = exports.getProject(); bootstrap.serve("file:///site/" + URLEncoding.encode(project) + "/"+ URLEncoding.encode(Path.name(URI.path(resource))), requestor, respond); return; } // determine the request final Request request; try { request = requestor.cast(); } catch (final Exception e) { respond.reject(e); return; } // made it to the final processor, so bounce a TRACE if ("TRACE".equals(request.method)) { respond.fulfill(request.trace()); return; } // check that there is no path name if (!"".equals(Path.name(URI.path(resource)))) { respond.fulfill(never(request.method)); return; } // determine the request subject Volatile<?> subject; try { subject = Eventual.promised(exports.use(Query.arg("", query, "s"))); } catch (final Exception e) { subject = new Rejected<Object>(e); } // determine the request type final String p = Query.arg(null, query, "p"); if (null == p || "*".equals(p)) { // when block or introspection Object value; try { // AUDIT: call to untrusted application code value = subject.cast(); } catch (final NullPointerException e) { respond.fulfill(serialize(request.method, "404", "not yet", ephemeral, new Rejected<Object>(e))); return; } catch (final Exception e) { value = new Rejected<Object>(e); } if ("GET".equals(request.method) || "HEAD".equals(request.method)) { if ("*".equals(p)) { final Class<?> t = null!=value?value.getClass():Void.class; if (!Exports.isPBC(t)) { value = describe(t); } } respond.fulfill(serialize(request.method, "200", "OK", forever, value)); } else { final String[] allow = { "TRACE", "OPTIONS", "GET", "HEAD" }; if ("OPTIONS".equals(request.method)) { respond.fulfill(Request.options(allow)); } else { respond.fulfill(Request.notAllowed(allow)); } } return; } // member access // to preserve message order, force settling of a promise if (!(subject instanceof Fulfilled)) { respond.fulfill(never(request.method)); return; } // AUDIT: call to untrusted application code final Object target = ((Fulfilled<?>)subject).cast(); // prevent access to local implementation details final Class<?> type = null != target ? target.getClass() : Void.class; if (Exports.isPBC(type)) { respond.fulfill(never(request.method)); return; } // process the request final Method lambda = Exports.dispatch(type, p); if ("GET".equals(request.method) || "HEAD".equals(request.method)) { Object value; try { if (null == Exports.property(lambda)) { throw new ClassCastException(); } // AUDIT: call to untrusted application code value = Reflection.invoke(Exports.bubble(lambda), target); } catch (final Exception e) { value = new Rejected<Object>(e); } final boolean constant = null == lambda || "getClass".equals(lambda.getName()); final int maxAge = constant ? forever : ephemeral; final String etag = constant ? null : exports.getTransactionTag(); Response r = request.hasVersion(etag) ? new Response("HTTP/1.1", "304", "Not Modified", PowerlessArray.array( new Header("Cache-Control", "max-age=" + maxAge) ), null) : serialize(request.method, "200", "OK", maxAge, value); if (null != etag) { r = r.with("ETag", etag); } respond.fulfill(r); } else if ("POST".equals(request.method)) { final String contentType = request.getContentType(); final MediaType mime = null != contentType ? MediaType.decode(contentType) : AMP.mime; final Entity raw; if (AMP.mime.contains(mime) || MediaType.text.contains(mime)) { if (!TokenList.equivalent("UTF-8", mime.get("charset", "UTF-8"))) { throw new Exception("charset MUST be UTF-8"); } raw = null; } else { raw = new Entity(contentType, ((Snapshot)request.body).content); } final String m = Query.arg(null, query, "m"); final Object value = exports.once(m, lambda, new Factory<Object>() { @Override public Object run() { try { if (null != Exports.property(lambda)) { throw new ClassCastException(); } final ConstArray<?> argv = null != raw ? ConstArray.array(raw) : deserialize(request, ConstArray.array( lambda.getGenericParameterTypes())); // AUDIT: call to untrusted application code return Reflection.invoke(Exports.bubble(lambda), target, argv.toArray(new Object[argv.length()])); } catch (final Exception e) { return new Rejected<Object>(e); } } }); respond.fulfill(serialize(request.method, "200", "OK", ephemeral, value)); } else { final String[] allow = null != lambda ? (null == Exports.property(lambda) ? new String[] { "TRACE", "OPTIONS", "POST" } : new String[] { "TRACE", "OPTIONS", "GET", "HEAD" }) : new String[] { "TRACE", "OPTIONS" }; if ("OPTIONS".equals(request.method)) { respond.fulfill(Request.options(allow)); } else { respond.fulfill(Request.notAllowed(allow)); } } }
diff --git a/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/dsb/impl/DvnNewJavaFieldCutter.java b/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/dsb/impl/DvnNewJavaFieldCutter.java index 61020b50a..511a0e44a 100644 --- a/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/dsb/impl/DvnNewJavaFieldCutter.java +++ b/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/dsb/impl/DvnNewJavaFieldCutter.java @@ -1,354 +1,353 @@ /** * */ package edu.harvard.hmdc.vdcnet.dsb.impl; import java.util.*; import org.apache.commons.lang.builder.*; import org.apache.commons.lang.*; import java.util.logging.*; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.nio.channels.ReadableByteChannel; import java.nio.BufferUnderflowException; import static java.lang.System.*; /** * @author asone * */ public class DvnNewJavaFieldCutter { // static public int NBUFSIZ = 32767; private static int REC_LEN = 0; private static int OUT_LEN = 0; private static String defaultDelimitor = "\t"; public static int[] outbounds = new int[8192]; private static Logger dbgLog = Logger.getLogger(DvnNewJavaFieldCutter.class.getPackage().getName()); public Map<Long, List<List<Integer>>> cargSet = new LinkedHashMap<Long, List<List<Integer>>>(); public int colwidth; public int noVars; public DvnNewJavaFieldCutter(String list) { parseList(list); } public DvnNewJavaFieldCutter(Map<Long, List<List<Integer>>> cargSet) { this.cargSet = cargSet; int collength = 0; for (Map.Entry<Long, List<List<Integer>>> cargSeti : cargSet.entrySet()){ for (int i= 0; i < cargSeti.getValue().size(); i++){ collength = cargSeti.getValue().get(i).get(1) - cargSeti.getValue().get(i).get(0) +2; colwidth += collength; } //out.println("key = "+ cargSeti.getKey() + ":colwidth"+colwidth); } //out.println("colwidth="+colwidth); } /** * * * @param * @return */ public void cutColumns(File fl, int noCardsPerCase, int caseLength, String delimitor, String tabFileName) throws FileNotFoundException { if (delimitor == null) { delimitor = defaultDelimitor; } int[] lineLength = new int[noCardsPerCase]; InputStream in = null; String line = null; // caseLength info is not available // check all lines have the same length int columnCounter = 0; in = new FileInputStream(fl); Set<Integer> lengthSet = new LinkedHashSet<Integer>(); if (caseLength == 0) { BufferedReader rd = new BufferedReader(new InputStreamReader(in)); try { for (int l = 0; l < noCardsPerCase; l++) { line = rd.readLine(); lengthSet.add(line.length()); lineLength[l] = line.length(); dbgLog.fine(l + "th line=" + line); } } catch (IOException ex) { ex.printStackTrace(); } finally { } if (lengthSet.size() == 1) { // all lines have the same length columnCounter = lineLength[0]; } else { // TODO // temporary solution columnCounter = lineLength[0]; } dbgLog.fine("final columnCounter=" + columnCounter); } // close in try { in.close(); } catch (IOException e) { e.printStackTrace(); } REC_LEN = columnCounter; REC_LEN++; dbgLog.fine("REC_LEN=" + REC_LEN); OUT_LEN = colwidth; // calculated by parseList dbgLog.fine("out_len=" + OUT_LEN); Boolean dottednotation = false; Boolean foundData = false; // cutting a data file InputStream inx = new FileInputStream(fl); ReadableByteChannel rbc = Channels.newChannel(inx); // input byte-buffer size = row-length + 1(=> new line char) ByteBuffer inbuffer = ByteBuffer.allocate(REC_LEN); OutputStream outs = new FileOutputStream(tabFileName); WritableByteChannel outc = Channels.newChannel(outs); ByteBuffer outbuffer = null; int pos = 0; int offset = 0; int outoffset = 0; int begin = 0; int end = 0; int blankoffset = 0; int blanktail = 0; int k; try { // lc: line counter int lc = 0; while (rbc.read(inbuffer) != -1) { // calculate i-th card number lc++; k = lc % noCardsPerCase; if (k == 0) { k = noCardsPerCase; } - out - .println("***** " +lc+ "-th line, recod k=" + k + " *****"); + //out.println("***** " +lc+ "-th line, recod k=" + k + " *****"); byte[] line_read = new byte[OUT_LEN]; byte[] junk = new byte[REC_LEN]; byte[] line_final = new byte[OUT_LEN]; //out.println("READ: " + offset); inbuffer.rewind(); offset = 0; outoffset = 0; // how many variables are cut from this k-th card int noColumns = cargSet.get(Long.valueOf(k)).size(); //out.println("noColumns=" + noColumns); //out.println("cargSet k =" + cargSet.get(Long.valueOf(k))); for (int i = 0; i < noColumns; i++) { //out.println("**** " + i +"-th col ****"); begin = cargSet.get(Long.valueOf(k)).get(i) .get(0); // bounds[2 * i]; end = cargSet.get(Long.valueOf(k)).get(i).get(1); // bounds[2 * i + 1]; //out.println("i: begin: " + begin + "\ti: end:" + end); try { // throw away offect bytes if (begin - offset - 1 > 0) { inbuffer.get(junk, 0, (begin - offset - 1)); } // get requested bytes inbuffer.get(line_read, outoffset, (end - begin + 1)); // set outbound data outbounds[2 * i] = outoffset; outbounds[2 * i + 1] = outoffset + (end - begin); // current position moved to outoffset pos = outoffset; dottednotation = false; foundData = false; blankoffset = 0; blanktail = 0; // as position increases while (pos <= (outoffset + (end - begin))) { //out.println("pos=" + pos + "\tline_read[pos]=" + // new String(line_read).replace("\000", "\052")); // decimal octal // 48 =>0 60 // 46 => . 56 // 32 = space 40 // dot: if (line_read[pos] == '\056') { dottednotation = true; } // space: if (line_read[pos] == '\040') { if ( foundData ) { blanktail = blanktail > 0 ? blanktail : pos - 1; } else { blankoffset = pos + 1; } } else { foundData = true; blanktail = 0; } pos++; } // increase the outoffset by width outoffset += (end - begin + 1); // dot false if (!dottednotation) { if (blankoffset > 0) { // set outbound value to blankoffset outbounds[2 * i] = blankoffset; } if (blanktail > 0) { outbounds[2 * i + 1] = blanktail; } } } catch (BufferUnderflowException bufe) { bufe.printStackTrace(); } // set offset to the value of end-position offset = end; } outoffset = 0; // for each var for (int i = 0; i < noColumns; i++) { begin = outbounds[2 * i]; end = outbounds[2 * i + 1]; //out.println("begin=" + begin + "\t end=" + end); for (int j = begin; j <= end; j++) { line_final[outoffset++] = line_read[j]; } if (i < (noColumns - 1)) { line_final[outoffset++] = '\011'; // tab x09 } else { if (k == cargSet.size()) { line_final[outoffset++] = '\012'; // LF x0A } else { line_final[outoffset++] = '\011'; // tab x09 } } } //out.println("line_final=" + // new String(line_final).replace("\000", "\052")); outbuffer = ByteBuffer.wrap(line_final, 0, outoffset); outc.write(outbuffer); inbuffer.clear(); } // while loop } catch (IOException ex) { ex.printStackTrace(); } } /** * * * @param * @return */ public void parseList(String columns) { String[] vars = columns.split(","); colwidth = 0; for (String v : vars) { String[] col = v.split(":"); String[] be = col[1].split("-"); Long cardNo = Long.parseLong(col[0]); int collength = 0; if (cargSet.containsKey(cardNo)) { List<Integer> tmp = new ArrayList<Integer>(); if (be.length == 1) { tmp.add(Integer.parseInt(be[0])); tmp.add(Integer.parseInt(be[0])); collength = 2; } else { tmp.add(Integer.parseInt(be[0])); tmp.add(Integer.parseInt(be[1])); collength = Integer.parseInt(be[1]) - Integer.parseInt(be[0]) + 2; } cargSet.get(cardNo).add(tmp); } else { List<Integer> tmp = new ArrayList<Integer>(); List<List<Integer>> lst = new ArrayList<List<Integer>>(); if (be.length == 1) { tmp.add(Integer.parseInt(be[0])); tmp.add(Integer.parseInt(be[0])); collength = 2; } else { tmp.add(Integer.parseInt(be[0])); tmp.add(Integer.parseInt(be[1])); collength = Integer.parseInt(be[1]) - Integer.parseInt(be[0]) + 2; } lst.add(tmp); cargSet.put(cardNo, lst); } colwidth += collength; //out.println("map=" + cargSet); //out.println("card no=" + col[0] + "\begin=" + be[0] + "\tend=" + be[1]); //out.println("collength=" + collength); } noVars = vars.length; //out.println("no vars=" + noVars); //out.println("no of cols required=" + colwidth); } }
true
true
public void cutColumns(File fl, int noCardsPerCase, int caseLength, String delimitor, String tabFileName) throws FileNotFoundException { if (delimitor == null) { delimitor = defaultDelimitor; } int[] lineLength = new int[noCardsPerCase]; InputStream in = null; String line = null; // caseLength info is not available // check all lines have the same length int columnCounter = 0; in = new FileInputStream(fl); Set<Integer> lengthSet = new LinkedHashSet<Integer>(); if (caseLength == 0) { BufferedReader rd = new BufferedReader(new InputStreamReader(in)); try { for (int l = 0; l < noCardsPerCase; l++) { line = rd.readLine(); lengthSet.add(line.length()); lineLength[l] = line.length(); dbgLog.fine(l + "th line=" + line); } } catch (IOException ex) { ex.printStackTrace(); } finally { } if (lengthSet.size() == 1) { // all lines have the same length columnCounter = lineLength[0]; } else { // TODO // temporary solution columnCounter = lineLength[0]; } dbgLog.fine("final columnCounter=" + columnCounter); } // close in try { in.close(); } catch (IOException e) { e.printStackTrace(); } REC_LEN = columnCounter; REC_LEN++; dbgLog.fine("REC_LEN=" + REC_LEN); OUT_LEN = colwidth; // calculated by parseList dbgLog.fine("out_len=" + OUT_LEN); Boolean dottednotation = false; Boolean foundData = false; // cutting a data file InputStream inx = new FileInputStream(fl); ReadableByteChannel rbc = Channels.newChannel(inx); // input byte-buffer size = row-length + 1(=> new line char) ByteBuffer inbuffer = ByteBuffer.allocate(REC_LEN); OutputStream outs = new FileOutputStream(tabFileName); WritableByteChannel outc = Channels.newChannel(outs); ByteBuffer outbuffer = null; int pos = 0; int offset = 0; int outoffset = 0; int begin = 0; int end = 0; int blankoffset = 0; int blanktail = 0; int k; try { // lc: line counter int lc = 0; while (rbc.read(inbuffer) != -1) { // calculate i-th card number lc++; k = lc % noCardsPerCase; if (k == 0) { k = noCardsPerCase; } out .println("***** " +lc+ "-th line, recod k=" + k + " *****"); byte[] line_read = new byte[OUT_LEN]; byte[] junk = new byte[REC_LEN]; byte[] line_final = new byte[OUT_LEN]; //out.println("READ: " + offset); inbuffer.rewind(); offset = 0; outoffset = 0; // how many variables are cut from this k-th card int noColumns = cargSet.get(Long.valueOf(k)).size(); //out.println("noColumns=" + noColumns); //out.println("cargSet k =" + cargSet.get(Long.valueOf(k))); for (int i = 0; i < noColumns; i++) { //out.println("**** " + i +"-th col ****"); begin = cargSet.get(Long.valueOf(k)).get(i) .get(0); // bounds[2 * i]; end = cargSet.get(Long.valueOf(k)).get(i).get(1); // bounds[2 * i + 1]; //out.println("i: begin: " + begin + "\ti: end:" + end); try { // throw away offect bytes if (begin - offset - 1 > 0) { inbuffer.get(junk, 0, (begin - offset - 1)); } // get requested bytes inbuffer.get(line_read, outoffset, (end - begin + 1)); // set outbound data outbounds[2 * i] = outoffset; outbounds[2 * i + 1] = outoffset + (end - begin); // current position moved to outoffset pos = outoffset; dottednotation = false; foundData = false; blankoffset = 0; blanktail = 0; // as position increases while (pos <= (outoffset + (end - begin))) { //out.println("pos=" + pos + "\tline_read[pos]=" + // new String(line_read).replace("\000", "\052")); // decimal octal // 48 =>0 60 // 46 => . 56 // 32 = space 40 // dot: if (line_read[pos] == '\056') { dottednotation = true; } // space: if (line_read[pos] == '\040') { if ( foundData ) { blanktail = blanktail > 0 ? blanktail : pos - 1; } else { blankoffset = pos + 1; } } else { foundData = true; blanktail = 0; } pos++; } // increase the outoffset by width outoffset += (end - begin + 1); // dot false if (!dottednotation) { if (blankoffset > 0) { // set outbound value to blankoffset outbounds[2 * i] = blankoffset; } if (blanktail > 0) { outbounds[2 * i + 1] = blanktail; } } } catch (BufferUnderflowException bufe) { bufe.printStackTrace(); } // set offset to the value of end-position offset = end; } outoffset = 0; // for each var for (int i = 0; i < noColumns; i++) { begin = outbounds[2 * i]; end = outbounds[2 * i + 1]; //out.println("begin=" + begin + "\t end=" + end); for (int j = begin; j <= end; j++) { line_final[outoffset++] = line_read[j]; } if (i < (noColumns - 1)) { line_final[outoffset++] = '\011'; // tab x09 } else { if (k == cargSet.size()) { line_final[outoffset++] = '\012'; // LF x0A } else { line_final[outoffset++] = '\011'; // tab x09 } } } //out.println("line_final=" + // new String(line_final).replace("\000", "\052")); outbuffer = ByteBuffer.wrap(line_final, 0, outoffset); outc.write(outbuffer); inbuffer.clear(); } // while loop } catch (IOException ex) { ex.printStackTrace(); } }
public void cutColumns(File fl, int noCardsPerCase, int caseLength, String delimitor, String tabFileName) throws FileNotFoundException { if (delimitor == null) { delimitor = defaultDelimitor; } int[] lineLength = new int[noCardsPerCase]; InputStream in = null; String line = null; // caseLength info is not available // check all lines have the same length int columnCounter = 0; in = new FileInputStream(fl); Set<Integer> lengthSet = new LinkedHashSet<Integer>(); if (caseLength == 0) { BufferedReader rd = new BufferedReader(new InputStreamReader(in)); try { for (int l = 0; l < noCardsPerCase; l++) { line = rd.readLine(); lengthSet.add(line.length()); lineLength[l] = line.length(); dbgLog.fine(l + "th line=" + line); } } catch (IOException ex) { ex.printStackTrace(); } finally { } if (lengthSet.size() == 1) { // all lines have the same length columnCounter = lineLength[0]; } else { // TODO // temporary solution columnCounter = lineLength[0]; } dbgLog.fine("final columnCounter=" + columnCounter); } // close in try { in.close(); } catch (IOException e) { e.printStackTrace(); } REC_LEN = columnCounter; REC_LEN++; dbgLog.fine("REC_LEN=" + REC_LEN); OUT_LEN = colwidth; // calculated by parseList dbgLog.fine("out_len=" + OUT_LEN); Boolean dottednotation = false; Boolean foundData = false; // cutting a data file InputStream inx = new FileInputStream(fl); ReadableByteChannel rbc = Channels.newChannel(inx); // input byte-buffer size = row-length + 1(=> new line char) ByteBuffer inbuffer = ByteBuffer.allocate(REC_LEN); OutputStream outs = new FileOutputStream(tabFileName); WritableByteChannel outc = Channels.newChannel(outs); ByteBuffer outbuffer = null; int pos = 0; int offset = 0; int outoffset = 0; int begin = 0; int end = 0; int blankoffset = 0; int blanktail = 0; int k; try { // lc: line counter int lc = 0; while (rbc.read(inbuffer) != -1) { // calculate i-th card number lc++; k = lc % noCardsPerCase; if (k == 0) { k = noCardsPerCase; } //out.println("***** " +lc+ "-th line, recod k=" + k + " *****"); byte[] line_read = new byte[OUT_LEN]; byte[] junk = new byte[REC_LEN]; byte[] line_final = new byte[OUT_LEN]; //out.println("READ: " + offset); inbuffer.rewind(); offset = 0; outoffset = 0; // how many variables are cut from this k-th card int noColumns = cargSet.get(Long.valueOf(k)).size(); //out.println("noColumns=" + noColumns); //out.println("cargSet k =" + cargSet.get(Long.valueOf(k))); for (int i = 0; i < noColumns; i++) { //out.println("**** " + i +"-th col ****"); begin = cargSet.get(Long.valueOf(k)).get(i) .get(0); // bounds[2 * i]; end = cargSet.get(Long.valueOf(k)).get(i).get(1); // bounds[2 * i + 1]; //out.println("i: begin: " + begin + "\ti: end:" + end); try { // throw away offect bytes if (begin - offset - 1 > 0) { inbuffer.get(junk, 0, (begin - offset - 1)); } // get requested bytes inbuffer.get(line_read, outoffset, (end - begin + 1)); // set outbound data outbounds[2 * i] = outoffset; outbounds[2 * i + 1] = outoffset + (end - begin); // current position moved to outoffset pos = outoffset; dottednotation = false; foundData = false; blankoffset = 0; blanktail = 0; // as position increases while (pos <= (outoffset + (end - begin))) { //out.println("pos=" + pos + "\tline_read[pos]=" + // new String(line_read).replace("\000", "\052")); // decimal octal // 48 =>0 60 // 46 => . 56 // 32 = space 40 // dot: if (line_read[pos] == '\056') { dottednotation = true; } // space: if (line_read[pos] == '\040') { if ( foundData ) { blanktail = blanktail > 0 ? blanktail : pos - 1; } else { blankoffset = pos + 1; } } else { foundData = true; blanktail = 0; } pos++; } // increase the outoffset by width outoffset += (end - begin + 1); // dot false if (!dottednotation) { if (blankoffset > 0) { // set outbound value to blankoffset outbounds[2 * i] = blankoffset; } if (blanktail > 0) { outbounds[2 * i + 1] = blanktail; } } } catch (BufferUnderflowException bufe) { bufe.printStackTrace(); } // set offset to the value of end-position offset = end; } outoffset = 0; // for each var for (int i = 0; i < noColumns; i++) { begin = outbounds[2 * i]; end = outbounds[2 * i + 1]; //out.println("begin=" + begin + "\t end=" + end); for (int j = begin; j <= end; j++) { line_final[outoffset++] = line_read[j]; } if (i < (noColumns - 1)) { line_final[outoffset++] = '\011'; // tab x09 } else { if (k == cargSet.size()) { line_final[outoffset++] = '\012'; // LF x0A } else { line_final[outoffset++] = '\011'; // tab x09 } } } //out.println("line_final=" + // new String(line_final).replace("\000", "\052")); outbuffer = ByteBuffer.wrap(line_final, 0, outoffset); outc.write(outbuffer); inbuffer.clear(); } // while loop } catch (IOException ex) { ex.printStackTrace(); } }
diff --git a/wheelmap/wheelmap-it/src/main/java/org/wheelmap/android/test/TestPOIContentProvider.java b/wheelmap/wheelmap-it/src/main/java/org/wheelmap/android/test/TestPOIContentProvider.java index 4bf992b1..5d1689d9 100644 --- a/wheelmap/wheelmap-it/src/main/java/org/wheelmap/android/test/TestPOIContentProvider.java +++ b/wheelmap/wheelmap-it/src/main/java/org/wheelmap/android/test/TestPOIContentProvider.java @@ -1,95 +1,95 @@ /* Copyright (C) 2011 Michal Harakal and Michael Kroez 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.wheelmap.android.test; import org.wheelmap.android.model.POIsProvider; import org.wheelmap.android.model.Wheelmap; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.test.ProviderTestCase2; public class TestPOIContentProvider extends ProviderTestCase2<POIsProvider> { private Location mLocation; public TestPOIContentProvider() { super(POIsProvider.class, Wheelmap.AUTHORITY); } protected void setUp() throws Exception { super.setUp(); // Berlin, Andreasstra�e 10 mLocation = new Location(""); mLocation.setLongitude(13.431240); mLocation.setLatitude(52.512523); } public String[] createWhereValues() { String[] lonlat = new String[] { String.valueOf(mLocation.getLongitude()), String.valueOf(mLocation.getLatitude()) }; return lonlat; } protected void tearDown() throws Exception { super.tearDown(); } private void insertDummyPOI() { final ContentResolver resolver = getMockContentResolver(); // create new POI and start editing ContentValues cv = new ContentValues(); cv.put(Wheelmap.POIs.NAME, "default"); cv.put(Wheelmap.POIs.COORD_LAT, Math.ceil(mLocation.getLatitude() * 1E6)); cv.put(Wheelmap.POIs.COORD_LON, Math.ceil(mLocation.getLongitude() * 1E6)); cv.put(Wheelmap.POIs.CATEGORY_ID, 1); cv.put(Wheelmap.POIs.NODETYPE_ID, 1); resolver.insert(Wheelmap.POIs.CONTENT_URI, cv); } public void testLocalHandler() throws Exception { Uri uri = Wheelmap.POIs.CONTENT_URI_POI_SORTED; final ContentResolver resolver = getMockContentResolver(); Cursor cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, createWhereValues(), ""); assertEquals(0, cursor.getCount()); insertDummyPOI(); uri = Wheelmap.POIs.CONTENT_URI_POI_SORTED; cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, createWhereValues(), ""); assertEquals(1, cursor.getCount()); - cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, - createWhereValues(), ""); - assertEquals(2, cursor.getCount()); + //cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, + // createWhereValues(), ""); + //assertEquals(2, cursor.getCount()); } }
true
true
public void testLocalHandler() throws Exception { Uri uri = Wheelmap.POIs.CONTENT_URI_POI_SORTED; final ContentResolver resolver = getMockContentResolver(); Cursor cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, createWhereValues(), ""); assertEquals(0, cursor.getCount()); insertDummyPOI(); uri = Wheelmap.POIs.CONTENT_URI_POI_SORTED; cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, createWhereValues(), ""); assertEquals(1, cursor.getCount()); cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, createWhereValues(), ""); assertEquals(2, cursor.getCount()); }
public void testLocalHandler() throws Exception { Uri uri = Wheelmap.POIs.CONTENT_URI_POI_SORTED; final ContentResolver resolver = getMockContentResolver(); Cursor cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, createWhereValues(), ""); assertEquals(0, cursor.getCount()); insertDummyPOI(); uri = Wheelmap.POIs.CONTENT_URI_POI_SORTED; cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, createWhereValues(), ""); assertEquals(1, cursor.getCount()); //cursor = resolver.query(uri, Wheelmap.POIs.PROJECTION, null, // createWhereValues(), ""); //assertEquals(2, cursor.getCount()); }
diff --git a/src/org/apache/ws/security/message/WSSAddUsernameToken.java b/src/org/apache/ws/security/message/WSSAddUsernameToken.java index e86132739..de8269720 100644 --- a/src/org/apache/ws/security/message/WSSAddUsernameToken.java +++ b/src/org/apache/ws/security/message/WSSAddUsernameToken.java @@ -1,120 +1,120 @@ /* * Copyright 2003-2004 The Apache Software Foundation. * * 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.apache.ws.security.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ws.security.WSConstants; import org.apache.ws.security.message.token.UsernameToken; import org.apache.ws.security.util.WSSecurityUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Builds a WS UsernameToken and inserts it into the SOAP Envelope. * Refer to the WS specification, UsernameToken profile * * @author Werner Dittmann ([email protected]). */ public class WSSAddUsernameToken extends WSBaseMessage { private static Log log = LogFactory.getLog(WSSAddUsernameToken.class.getName()); private String passwordType = WSConstants.PASSWORD_DIGEST; private UsernameToken ut = null; /** * Constructor. */ public WSSAddUsernameToken() { } /** * Constructor. * <p/> * * @param actor the name of the actor of the <code>wsse:Security</code> header */ public WSSAddUsernameToken(String actor) { super(actor); } /** * Constructor. * <p/> * * @param actor The name of the actor of the <code>wsse:Security</code> header * @param mu Set <code>mustUnderstand</code> to true or false */ public WSSAddUsernameToken(String actor, boolean mu) { super(actor, mu); } /** * Defines how to construct the password element of the * <code>UsernameToken</code>. * * @param pwType contains the password type. Only allowed values are * {@link WSConstants#PASSWORD_DIGEST} and * {@link WSConstants#PASSWORD_TEXT}. */ public void setPasswordType(String pwType) { if (pwType == null) { passwordType = WSConstants.PASSWORD_DIGEST; } else if (pwType.equals(WSConstants.PASSWORD_DIGEST) || pwType.equals(WSConstants.PASSWORD_TEXT)) { passwordType = pwType; } } /** * Creates and adds a Nonce element to the UsernameToken */ public void addNonce(Document doc) { ut.addNonce(doc); } /** * Creates and adds a Created element to the UsernameToken */ public void addCreated(Document doc) { ut.addCreated(doc); } /** * Adds a new <code>UsernameToken</code> to a soap envelope. * <p/> * A complete <code>UsernameToken</code> is constructed and added to * the <code>wsse:Security</code> header. * * @param doc The SOAP enevlope as W3C document * @param username The username to set in the UsernameToken * @param password The password of the user * @return Document with UsernameToken added * @throws Exception */ public Document build(Document doc, String username, String password) { // throws Exception { log.debug("Begin add username token..."); Element securityHeader = insertSecurityHeader(doc, false); ut = new UsernameToken(doc, passwordType); ut.setName(username); ut.setPassword(password); - WSSecurityUtil.appendChildElement(doc, securityHeader, ut.getElement()); + WSSecurityUtil.prependChildElement(doc, securityHeader, ut.getElement(), true); return doc; } }
true
true
public Document build(Document doc, String username, String password) { // throws Exception { log.debug("Begin add username token..."); Element securityHeader = insertSecurityHeader(doc, false); ut = new UsernameToken(doc, passwordType); ut.setName(username); ut.setPassword(password); WSSecurityUtil.appendChildElement(doc, securityHeader, ut.getElement()); return doc; } }
public Document build(Document doc, String username, String password) { // throws Exception { log.debug("Begin add username token..."); Element securityHeader = insertSecurityHeader(doc, false); ut = new UsernameToken(doc, passwordType); ut.setName(username); ut.setPassword(password); WSSecurityUtil.prependChildElement(doc, securityHeader, ut.getElement(), true); return doc; } }
diff --git a/src/de/unifr/acp/trafo/TransClass.java b/src/de/unifr/acp/trafo/TransClass.java index 160ab22..411729f 100644 --- a/src/de/unifr/acp/trafo/TransClass.java +++ b/src/de/unifr/acp/trafo/TransClass.java @@ -1,1003 +1,1003 @@ package de.unifr.acp.trafo; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.NotFoundException; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.AttributeInfo; import javassist.bytecode.ClassFile; import javassist.bytecode.ConstPool; import javassist.bytecode.ParameterAnnotationsAttribute; import javassist.bytecode.SyntheticAttribute; import javassist.bytecode.annotation.Annotation; import javassist.bytecode.annotation.ClassMemberValue; import javassist.bytecode.annotation.IntegerMemberValue; import javassist.bytecode.annotation.StringMemberValue; import javassist.expr.Cast; import javassist.expr.ConstructorCall; import javassist.expr.ExprEditor; import javassist.expr.FieldAccess; import javassist.expr.Handler; import javassist.expr.Instanceof; import javassist.expr.MethodCall; import javassist.expr.NewArray; import javassist.expr.NewExpr; import de.unifr.acp.annot.Grant; import de.unifr.acp.templates.TraversalTarget__; // TODO: consider fully qualified field names public class TransClass { static { try { logger = Logger.getLogger("de.unifr.acp.trafo.TransClass"); fh = new FileHandler("mylog.txt"); TransClass.logger.addHandler(TransClass.fh); TransClass.logger.setLevel(Level.ALL); } catch (SecurityException | IOException e) { throw new RuntimeException(e); } } private static Logger logger; private static FileHandler fh; private static final String TRAVERSAL_TARGET = "de.unifr.acp.templates.TraversalTarget__"; private static final String FST_CACHE_FIELD_NAME = "$fstMap"; //private final CtClass objectClass = ClassPool.getDefault().get(Object.class.getName()); public final String FILTER_TRANSFORM_REGEX_DEFAULT = "java\\..*"; private String filterTransformRegex = FILTER_TRANSFORM_REGEX_DEFAULT; public final String FILTER_VISIT_REGEX_DEFAULT = "java\\..*"; private String filterVisitRegex = FILTER_VISIT_REGEX_DEFAULT; //private final Map<CtClass, Boolean> visited = new HashMap<CtClass, Boolean>(); //private final HashSet<CtClass> visited = new HashSet<CtClass>(); //private final HashSet<CtClass> transformed = new HashSet<CtClass>(); //private final Queue<CtClass> pending; // protected Set<CtClass> getVisited() { // return Collections.unmodifiableSet(visited); // } // protected Collection<CtClass> getPending() { // return Collections.unmodifiableCollection(pending); // } /** * Transformer class capable of statically adding heap traversal code to a * set of reachable classes. * * @param classname * the name of the class forming the starting point for the * reachable classes * @throws NotFoundException */ protected TransClass() throws NotFoundException { } /** * Transforms all classes that are reachable from the class corresponding * to the specified class name. * @param className the class name of the class spanning a reachable classes tree * @throws ClassNotFoundException */ public static Set<CtClass> transformHierarchy(String className) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { TransClass tc = new TransClass(); Set<CtClass> reachable = tc.computeReachableClasses(ClassPool.getDefault().get(className)); Set<CtClass> transformed = tc.performTransformation(reachable); return transformed; } public static Set<CtClass> defaultAnnotateHierarchy(String className) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { TransClass tc = new TransClass(); Set<CtClass> reachable = tc.computeReachableClasses(ClassPool.getDefault().get(className)); Set<CtClass> transformed = tc.performDefaultAnnotatation(reachable); return transformed; } /** * Transforms all classes that are reachable from the class corresponding * to the specified class name and flushes the resulting classes to the * specified output directory. * @param className the class name of the class spanning a reachable classes tree * @param outputDir the relative output directory * @throws ClassNotFoundException */ public static void transformAndFlushHierarchy(String className, String outputDir) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Set<CtClass> transformed = transformHierarchy(className); TransClass.flushTransform(transformed, outputDir); } public static void defaultAnnotateAndFlushHierarchy(String className, String outputDir) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Set<CtClass> transformed = defaultAnnotateHierarchy(className); TransClass.flushTransform(transformed, outputDir); } protected Set<CtClass> computeReachableClasses(CtClass root) throws NotFoundException, IOException, CannotCompileException { Queue<CtClass> pending = new LinkedList<CtClass>(); HashSet<CtClass> visited = new HashSet<CtClass>(); pending.add(root); while (!pending.isEmpty()) { CtClass clazz = pending.remove(); if (!visited.contains(clazz)) { doTraverse(clazz, pending, visited); } } return visited; } /* * Helper method for <code>computeReachableClasses</code>. Traverses the * specified target class and adds it to the list of visited classes. Adds * all classes the class' fields to queue of pending classes, if not already * visited. */ private void doTraverse(CtClass target, Queue<CtClass> pending, Set<CtClass> visited) throws NotFoundException { visited.add(target); // collect all types this type refers to in this set final Set<CtClass> referredTypes = new HashSet<CtClass>(); CtClass superclazz = target.getSuperclass(); if (superclazz != null) { referredTypes.add(superclazz); } // for (CtClass clazz : target.getInterfaces()) { // referredTypes.add(clazz); // } CtField[] fs = target.getDeclaredFields(); for (CtField f : fs) { CtClass ft = f.getType(); if (ft.isPrimitive()) continue; referredTypes.add(ft); } List<CtMethod> methods = Arrays.asList(target.getMethods()); for (CtMethod method : methods) { List<CtClass> returnType = Arrays.asList(method.getReturnType()); referredTypes.addAll(returnType); } List<CtConstructor> ctors = Arrays.asList(target.getConstructors()); List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); methodsAndCtors.addAll(methods); methodsAndCtors.addAll(ctors); for (CtBehavior methodOrCtor : methodsAndCtors) { List<CtClass> exceptionTypes = Arrays.asList(methodOrCtor.getExceptionTypes()); referredTypes.addAll(exceptionTypes); List<CtClass> paramTypes = Arrays.asList(methodOrCtor.getParameterTypes()); referredTypes.addAll(paramTypes); try { final List<NotFoundException> notFoundexceptions = new ArrayList<NotFoundException>(1); methodOrCtor.instrument(new ExprEditor() { public void edit(NewExpr expr) throws CannotCompileException { try { CtClass type = expr.getConstructor().getDeclaringClass(); logger.finer("Reference to instantiated type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(Instanceof expr) throws CannotCompileException { try { CtClass type = expr.getType(); logger.finer("Reference to instanceof right-hand side type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(NewArray expr) throws CannotCompileException { try { CtClass type = expr.getComponentType(); logger.finer("Reference to array component type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(MethodCall expr) throws CannotCompileException { try { CtClass type = expr.getMethod().getDeclaringClass(); logger.finer("Reference to method-declaring type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(Handler expr) throws CannotCompileException { try { CtClass type = expr.getType(); logger.finer("Reference to handler type " + ((type != null) ? type.getName() : type) + " at " + expr.getFileName() + ":" + expr.getLineNumber()); // type can be null in case of synchronized blocks // which are compiled to handler for type 'any' if (type != null) { referredTypes.add(type); } } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(FieldAccess expr) throws CannotCompileException { try { CtClass type = expr.getField().getDeclaringClass(); logger.finer("Reference to field-declaring type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(Cast expr) throws CannotCompileException { try { CtClass type = expr.getType(); logger.finer("Reference to cast target type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); if (!notFoundexceptions.isEmpty()) { throw notFoundexceptions.get(0); } } catch (CannotCompileException e) { // we do not compile and therefore expect no such exception assert(false); } } // basic filtering of referred types for (CtClass type : referredTypes) { if (type.isPrimitive()) continue; if (type.getName().matches(filterVisitRegex)) continue; enter(type, pending, visited); } } /* * Helper method for <code>computeReachableClasses</code>. Adds the * specified class to queue of pending classes, if not already visited. */ private void enter(CtClass clazz, Queue<CtClass> pending, Set<CtClass> visited) { logger.entering(TransClass.class.getSimpleName(), "enter", (clazz != null) ? clazz.getName() : clazz); if (!visited.contains(clazz)) { pending.add(clazz); } logger.exiting("TransClass", "enter"); } private Set<CtClass> filterClassesToTransform(Set<CtClass> visited) { HashSet<CtClass> toTransform = new HashSet<CtClass>(); for (CtClass clazz : visited) { if (!clazz.getName().matches(filterTransformRegex)) { toTransform.add(clazz); } } return toTransform; } protected Set<CtClass> performDefaultAnnotatation(Set<CtClass> classes) throws NotFoundException { Set<CtClass> toTransform = filterClassesToTransform(classes); if (logger.isLoggable(Level.FINEST)) { StringBuilder sb = new StringBuilder(); for (CtClass visitedClazz : toTransform) { sb.append(visitedClazz.getName()+"\n"); } logger.finest("Classes to transform:\n" +sb.toString()); } final HashSet<CtClass> transformed = new HashSet<CtClass>(); for (CtClass cc : toTransform) { if (cc.isFrozen()) { continue; } // collect all methods and constructors // List<CtMethod> ownMethods = Arrays.asList(cc.getDeclaredMethods()); // List<CtConstructor> ctors = Arrays.asList(cc.getConstructors()); // List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); // methodsAndCtors.addAll(ownMethods); // methodsAndCtors.addAll(ctors); List<CtBehavior> methodsAndCtors = Arrays.asList(cc.getDeclaredBehaviors()); ClassFile ccFile = cc.getClassFile(); ConstPool constpool = ccFile.getConstPool(); for (CtBehavior methodOrCtor : methodsAndCtors) { logger.fine("Annotating method or ctor: " + ((methodOrCtor != null) ? methodOrCtor.getLongName() : methodOrCtor)); // create and add the method-level annotation AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); Annotation annot = new Annotation(Grant.class.getName(), constpool); annot.addMemberValue("value", new StringMemberValue("this.*", constpool)); attr.addAnnotation(annot); methodOrCtor.getMethodInfo().addAttribute(attr); // create and add the parameter-level annotation final CtClass[] parameterTypes = methodOrCtor.getParameterTypes(); Annotation parameterAnnotation = new Annotation( Grant.class.getName(), constpool); StringMemberValue parameterMemberValue = new StringMemberValue( "*", constpool); parameterAnnotation.addMemberValue("value", parameterMemberValue); logger.fine("parameterAnnotation: " + parameterAnnotation); AttributeInfo paramAttributeInfo = methodOrCtor.getMethodInfo().getAttribute(ParameterAnnotationsAttribute.visibleTag); // or invisibleTag logger.finest("paramAttributeInfo: " + paramAttributeInfo); if (paramAttributeInfo != null) { ParameterAnnotationsAttribute parameterAtrribute = ((ParameterAnnotationsAttribute) paramAttributeInfo); Annotation[][] paramAnnots = parameterAtrribute .getAnnotations(); for (int orderNum = 0; orderNum < paramAnnots.length; orderNum++) { Annotation[] addAnno = paramAnnots[orderNum]; if (!parameterTypes[orderNum].isPrimitive()) { Annotation[] newAnno = null; if (addAnno.length == 0) { newAnno = new Annotation[1]; } else { newAnno = Arrays.copyOf(addAnno, addAnno.length + 1); } newAnno[addAnno.length] = parameterAnnotation; paramAnnots[orderNum] = newAnno; } } parameterAtrribute.setAnnotations(paramAnnots); } else { ParameterAnnotationsAttribute parameterAtrribute = new ParameterAnnotationsAttribute( constpool, ParameterAnnotationsAttribute.visibleTag); Annotation[][] paramAnnots = new Annotation[parameterCountOf(methodOrCtor)][]; for (int orderNum = 0; orderNum < paramAnnots.length; orderNum++) { Annotation[] annots = {parameterAnnotation}; if (parameterTypes[orderNum].isPrimitive()) { annots = new Annotation[0]; } paramAnnots[orderNum]= annots; } parameterAtrribute.setAnnotations(paramAnnots); methodOrCtor.getMethodInfo().addAttribute(parameterAtrribute); } } } // conservatively assume all classes have been transformed transformed.addAll(toTransform); return transformed; } /* * Transforms all reachable classes. */ protected Set<CtClass> performTransformation(Set<CtClass> classes) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { ClassPool.getDefault().importPackage("java.util"); Set<CtClass> toTransform = filterClassesToTransform(classes); if (logger.isLoggable(Level.FINEST)) { StringBuilder sb = new StringBuilder(); for (CtClass visitedClazz : toTransform) { sb.append(visitedClazz.getName()+"\n"); } logger.finest("Classes to transform:\n" +sb.toString()); } final HashSet<CtClass> transformed = new HashSet<CtClass>(); for (CtClass clazz : toTransform) { Deque<CtClass> stack = new ArrayDeque<CtClass>(); CtClass current = clazz; stack.push(current); while (toTransform.contains(current.getSuperclass())) { current = current.getSuperclass(); stack.push(current); } while (!stack.isEmpty()) { CtClass superclass = stack.pop(); // if this does not hold we might miss some superclass fields assert (transformed.contains(superclass.getSuperclass()) == toTransform .contains(superclass.getSuperclass())); doTransform(superclass, transformed.contains(superclass.getSuperclass())); transformed.add(superclass); } } if (logger.isLoggable(Level.FINEST)) { StringBuilder sb = new StringBuilder(); for (CtClass transformedClazz : transformed) { sb.append(transformedClazz.getName()+"\n"); } logger.finest("Transformed types:\n" +sb.toString()); } return transformed; } /** * Flushes all reachable classes back to disk. * @param outputDir the relative output directory */ protected static void flushTransform(Set<CtClass> classes, String outputDir) throws NotFoundException, IOException, CannotCompileException { for (CtClass tc : classes) { if (!tc.isArray()) { tc.writeFile(outputDir); for (CtClass inner : tc.getNestedClasses()) { inner.writeFile(outputDir); } } } // String[] libClassNames = { "de.unifr.acp.templates.TraversalTarget__", // "de.unifr.acp.templates.TraversalImpl", // "de.unifr.acp.templates.Traversal__", // "de.unifr.acp.templates.Global", "de.unifr.acp.fst.Permission" }; // ClassPool defaultPool = ClassPool.getDefault(); // CtClass[] libClasses = defaultPool.get(libClassNames); // for (CtClass libClass : libClasses) { // libClass.writeFile(outputDir); // } } /** * Transforms a single class if not already done. * @param target the class to transform * @param hasTransformedSuperclass the target has an already transformed superclass * @throws NotFoundException * @throws IOException * @throws CannotCompileException * @throws ClassNotFoundException */ public static void doTransform(CtClass target, boolean hasTransformedSuperclass) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Object[] params4Logging = new Object[2]; params4Logging[0] = (target != null) ? target.getName() : target; params4Logging[1] = hasTransformedSuperclass; logger.entering("TransClass", "doTransform", params4Logging); if (target.isArray() || target.isInterface()) { return; } ClassPool.getDefault().importPackage("java.util"); // add: implements TRAVERSALTARGET List<CtClass> targetIfs = Arrays.asList(target.getInterfaces()); Collection<CtClass> newTargetIfs = new HashSet<CtClass>(targetIfs); // NOTE: Given the equality semantics of CtClass the condition is only // valid if the CtClass instance representing the traversal interface is // never detached from the ClassPool as this would result in a new // CtClass instance (representing the traversal interface) to be generated // by a call to ClassPool.get(...) not being equal to the old instance. // only generate implementation of traversal interface if not yet present // use traversal interface as marker for availability of other instrumentation CtClass traversalTargetInterface = ClassPool.getDefault().get(TRAVERSAL_TARGET); if (!newTargetIfs.contains(traversalTargetInterface)) { newTargetIfs.add(traversalTargetInterface); target.setInterfaces(newTargetIfs.toArray(new CtClass[0])); // add: method traverse__ (create body before adding new technically required fields) String methodbody = createBody(target, hasTransformedSuperclass); CtMethod m = CtNewMethod.make(methodbody, target); target.addMethod(m); // change methods carrying contracts // 1. Find all methods carrying contracts // 2. For each annotated method // 1. Get method annotation // 2. Generate code to generate automaton for contract // (generate code to get contract string and call into automation generation library) // 3. Use insertBefore() and insertAfter() to insert permission installation/deinstallation code // according to tutorial there's no support for generics in Javassist, thus we use raw types CtField f = CtField.make("private static java.util.HashMap "+FST_CACHE_FIELD_NAME+" = new java.util.HashMap();", target); target.addField(f); // collect all methods and constructors // List<CtMethod> methods = Arrays.asList(target.getDeclaredMethods()); List<CtConstructor> ctors = Arrays.asList(target.getDeclaredConstructors()); // List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); // methodsAndCtors.addAll(methods); // methodsAndCtors.addAll(ctors); List<CtBehavior> methodsAndCtors = Arrays.asList(target.getDeclaredBehaviors()); for (CtConstructor ctor : ctors) { instrumentNew(ctor); } for (CtBehavior methodOrCtor : methodsAndCtors) { logger.fine("Consider adding traversal to behavior: "+methodOrCtor.getLongName()); if ((methodOrCtor.getModifiers() & Modifier.ABSTRACT) != 0) { continue; } instrumentFieldAccess(methodOrCtor); if (hasMethodGrantAnnotations(methodOrCtor)) { logger.fine("Add traversal to behavior: "+methodOrCtor.getLongName()); /* generate header and footer */ // filter synthetic methods if (methodOrCtor.getMethodInfo().getAttribute(SyntheticAttribute.tag) != null) { continue; } // generate method header /* * We keep method contract and all parameter contracts separate. */ StringBuilder sb = new StringBuilder(); // uniquely identifies a method globally String longName = methodOrCtor.getLongName(); // check if automata for this method already exist sb.append("String longName = \"" + longName + "\";"); // FSTs indexed by parameter position (0: FST for this & type-anchored // contracts, 1 to n: FTSs for unanchored parameter contracts) sb.append("de.unifr.acp.fst.FST[] fSTs;"); sb.append("if ("+FST_CACHE_FIELD_NAME+".containsKey(longName)) {"); sb.append(" fSTs = ((de.unifr.acp.fst.FST[])"+FST_CACHE_FIELD_NAME+".get(longName));"); sb.append("}"); sb.append("else {"); // build array of FSTs indexed by parameter sb.append(" fSTs = new de.unifr.acp.fst.FST["+(parameterCountOf(methodOrCtor)+1)+"];"); for (int i=0; i<parameterCountOf(methodOrCtor)+1; i++) { Grant grant = grantAnno(methodOrCtor, i); if (grant != null) { sb.append(" fSTs[" + i + "] = new de.unifr.acp.fst.FST(\"" + grant.value() + "\");"); } } // cache generated automata indexed by long method name sb.append(" "+FST_CACHE_FIELD_NAME+".put(longName, fSTs);"); sb.append("}"); // now we expect to have all FSTs available and cached sb.append(" Map allLocPerms = new de.unifr.acp.util.WeakIdentityHashMap();"); int i= ((isStatic(methodOrCtor)) ? 1 : 0); int limit = ((isStatic(methodOrCtor)) ? (parameterCountOf(methodOrCtor)) : parameterCountOf(methodOrCtor)+1); for (; i<limit; i++) { // only grant-annotated methods/parameters require any action if (grantAnno(methodOrCtor, i) == null) { continue; } if (!mightBeReferenceParameter(methodOrCtor, i)) { continue; } // TODO: factor out this code in external class, parameterize over i and allPermissions // a location permission is a Map<Object, Map<String, Permission>> sb.append("{"); sb.append(" de.unifr.acp.fst.FST fst = fSTs["+i+"];"); sb.append(" de.unifr.acp.fst.FSTRunner runner = new de.unifr.acp.fst.FSTRunner(fst);"); // step to reach FST runner state that corresponds to anchor object // for explicitly anchored contracts if (i == 0) { sb.append(" runner.resetAndStep(\"this\");"); } // here the runner should be in synch with the parameter object // (as far as non-static fields are concerned), the visitor implicitly joins locPerms - if (i > 0 && !methodOrCtor.getParameterTypes()[i-1].isArray()) { + if (i == 0 || !methodOrCtor.getParameterTypes()[i-1].isArray()) { sb.append(" if ($" + i + " instanceof de.unifr.acp.templates.TraversalTarget__) {"); sb.append(" de.unifr.acp.templates.TraversalImpl visitor = new de.unifr.acp.templates.TraversalImpl(runner,allLocPerms);"); sb.append(" ((de.unifr.acp.templates.TraversalTarget__)$" + i + ").traverse__(visitor);"); sb.append(" }"); } // TODO: explicit representation of locations and location permissions (supporting join) // (currently it's all generic maps and implicit joins in visitor similar to Maxine implementation) sb.append("}"); } // install allLocPerms and push new objects set on (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.push(allLocPerms);"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.push(Collections.newSetFromMap(new de.unifr.acp.util.WeakIdentityHashMap()));"); // TODO: figure out how to instrument thread start/end and field access String header = sb.toString(); methodOrCtor.insertBefore(header); // generate method footer sb = new StringBuilder(); // pop location permissions and new locations entry from // (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.pop();"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.pop();"); String footer = sb.toString(); // make sure all method exits are covered (exceptions, multiple returns) methodOrCtor.insertAfter(footer, true); } // end if (hasMethodGrantAnnotations(methodOrCtor)) } } logger.exiting("TransClass", "doTransform"); } private static boolean isStatic(CtBehavior methodOrCtor) { return ((methodOrCtor.getModifiers() & Modifier.STATIC) != 0); } private static void instrumentFieldAccess(final CtBehavior methodOrCtor) throws CannotCompileException { // if (!isInstrumented.get()) { methodOrCtor.instrument(new ExprEditor() { public void edit(FieldAccess expr) throws CannotCompileException { if (!expr.isStatic()) { String qualifiedFieldName = expr.getClassName() + "." + expr.getFieldName(); // exclude standard API (to be factored out) if (!(qualifiedFieldName.startsWith("java") || qualifiedFieldName .startsWith("javax"))) { StringBuilder code = new StringBuilder(); code.append("{"); // get active permission for location to access code.append("if (!de.unifr.acp.templates.Global.newObjectsStack.isEmpty()) {"); code.append("de.unifr.acp.fst.Permission effectivePerm = de.unifr.acp.templates.Global.installedPermissionStackNotEmpty($0, \"" + qualifiedFieldName + "\");"); // get permission needed for this access code.append("de.unifr.acp.fst.Permission accessPerm = de.unifr.acp.fst.Permission." + (expr.isReader() ? "READ_ONLY" : "WRITE_ONLY") + ";"); // code.append("de.unifr.acp.fst.Permission accessPerm = de.unifr.acp.fst.Permission.values()[" // + (expr.isReader() ? "1" : "2") // + "];"); // code.append("if (!effectivePerm.containsAll(accessPerm)) {"); code.append("if (!de.unifr.acp.fst.Permission.containsAll(effectivePerm, accessPerm)) {"); code.append(" de.unifr.acp.templates.Global.printViolation($0, \"" + qualifiedFieldName + "\", \"" + methodOrCtor.getLongName() + "\",effectivePerm, accessPerm);"); code.append("}"); code.append("}"); if (expr.isReader()) { code.append(" $_ = $proceed();"); } else { code.append(" $proceed($$);"); } code.append("}"); expr.replace(code.toString()); } } } }); // } } /* * Instruments constructors to such that the constructed object is added to * the new objects stack's top entry. */ private static void instrumentNew(CtConstructor ctor) throws CannotCompileException { // Apparently Javassist does not support instrumentation between new // bytecode and constructor using the expression editor on new // expressions (in AspectJ this might work using Initialization Pointcut // Designators). Hence, we go for instrumenting the constructor, but // we need to make sure that the object is a valid by the time we // add it to the new objects (after this() or super() call). ctor.instrument(new ExprEditor() { public void edit(ConstructorCall expr) throws CannotCompileException { StringBuilder code = new StringBuilder(); code.append("{"); code.append(" $_ = $proceed($$);"); code.append(" de.unifr.acp.templates.Global.addNewObject($0);"); code.append("}"); expr.replace(code.toString()); } }); } /* * Instrument array creation such that the new array is added to the new * objects stack's top entry. */ private static void instrumentNewArray(CtBehavior methodOrCtor) throws CannotCompileException { methodOrCtor.instrument(new ExprEditor() { public void edit(NewArray expr) throws CannotCompileException { StringBuilder code = new StringBuilder(); code.append("{"); code.append(" $_ = $proceed($$);"); code.append(" de.unifr.acp.templates.Global.addNewObject($0);"); code.append("}"); expr.replace(code.toString()); } }); } private static int parameterCountOf(CtBehavior methodOrCtor) { return methodOrCtor.getAvailableParameterAnnotations().length; } /** * Currently is an under-approximation (might return false for primitive parameters) * @param methodOrCtor * @param index the parameter index * @return false if non-primitive or primitive, true if primitive */ private static boolean mightBeReferenceParameter(CtBehavior methodOrCtor, int index) { if (index == 0) { return true; } else { try { return !(methodOrCtor.getParameterTypes()[index-1].isPrimitive()); } catch (NotFoundException e) { // TODO: fix this return true; } } } /** * Return the grant annotation for the specified parameter (1 to n) or * behavior (0) if available. * * @param methodOrCtor * the behavior * @param index * 1 to n refers to a parameter index, 0 refers to the behavior * itself * @return the grant annotation if available, <code>null</code> otherwise * @throws ClassNotFoundException */ private static Grant grantAnno(CtBehavior methodOrCtor, int index) throws ClassNotFoundException { if (index == 0) { Grant methodGrantAnnot = ((Grant) methodOrCtor .getAnnotation(Grant.class)); return methodGrantAnnot; } else { // optional parameter types annotations indexed by parameter position Object[][] availParamAnnot = methodOrCtor .getAvailableParameterAnnotations(); final Object[] oa = availParamAnnot[index-1]; for (Object o : oa) { if (o instanceof Grant) { // there's one grant annotation per parameter only return (Grant) o; } } return null; } } /** * @deprecated */ private String concateSingleContracts(Grant methodGrantAnnot, Grant[] paramGrantAnnots) { String compositeContract; // list of single contracts to form the composite contract final ArrayList<String> singleContracts = new ArrayList<String>(); // add method contract if available if (methodGrantAnnot != null) { singleContracts.add(methodGrantAnnot.value()); } // add anchor-prefixed parameter contracts for (int i = 0; i < paramGrantAnnots.length; i++) { Grant grant = paramGrantAnnots[i]; String[] singleParamContracts = grant.value().split(","); for (String contract : singleParamContracts) { singleContracts.add((i + 1) + "." + contract); // add anchor prefix } } // append comma-separated single contracts final StringBuilder compositeBuilder = new StringBuilder(); if (singleContracts.size() > 0) { for (int i = 0; i < singleContracts.size() - 1; i++) { String contract = singleContracts.get(i); compositeBuilder.append(contract + ","); } compositeBuilder.append(singleContracts.get(singleContracts.size() -1)); } compositeContract = compositeBuilder.toString(); return compositeContract; } /** * Returns true if the specified method/constructor or one of its parameters * has a Grant annotation. * @param methodOrCtor the method/constructor to check * @return true if Grant annotation exists, false otherwise. * @throws NotFoundException * @throws CannotCompileException */ private static boolean hasMethodGrantAnnotations(CtBehavior methodOrCtor) throws NotFoundException, CannotCompileException { if (methodOrCtor.hasAnnotation(Grant.class)) return true; CtClass[] parameterTypes = methodOrCtor.getParameterTypes(); int i = 0; for (Object[] oa : methodOrCtor.getAvailableParameterAnnotations()) { CtClass paramType = parameterTypes[i++]; // we can savely ignore grant annotations on primitive formal // parameters if (!paramType.isPrimitive()) { for (Object o : oa) { if (o instanceof Grant) { return true; } } } } return false; } protected static String createBody(CtClass target, boolean hasSuperclass) throws NotFoundException { StringBuilder sb = new StringBuilder(); sb.append("public void traverse__(de.unifr.acp.templates.Traversal__ t) {\n"); for (CtField f : target.getDeclaredFields()) { CtClass tf = f.getType(); String fname = f.getName(); if (!fname.equals(FST_CACHE_FIELD_NAME)) { appendVisitorCalls(sb, target, tf, fname); } } if (hasSuperclass) { sb.append("super.traverse__(t);\n"); } sb.append('}'); return sb.toString(); } protected static void appendVisitorCalls(StringBuilder sb, CtClass target, CtClass tf, String fname) throws NotFoundException { int nesting = 0; String index = ""; while (tf.isArray()) { String var = "i" + nesting; /* generate for header */ sb.append("for (int " + var + " = 0; "); // static type of 'this' corresponds to field's declaring class, no cast needed sb.append(var + "<this."+fname+index+".length; "); sb.append(var + "++"); sb.append(")\n"); index = index + "[" + var + "]"; nesting++; tf = tf.getComponentType(); } if (tf.isPrimitive()) { sb.append("t.visitPrimitive__("); } else { sb.append("t.visit__("); } sb.append("this, "); sb.append('"'); sb.append(target.getName()); sb.append('.'); sb.append(fname); sb.append('"'); if (!tf.isPrimitive()) { // static type of 'this' corresponds to field's declaring class, no cast needed sb.append(", this."); sb.append(fname + index); } sb.append(");\n"); } }
true
true
public static void doTransform(CtClass target, boolean hasTransformedSuperclass) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Object[] params4Logging = new Object[2]; params4Logging[0] = (target != null) ? target.getName() : target; params4Logging[1] = hasTransformedSuperclass; logger.entering("TransClass", "doTransform", params4Logging); if (target.isArray() || target.isInterface()) { return; } ClassPool.getDefault().importPackage("java.util"); // add: implements TRAVERSALTARGET List<CtClass> targetIfs = Arrays.asList(target.getInterfaces()); Collection<CtClass> newTargetIfs = new HashSet<CtClass>(targetIfs); // NOTE: Given the equality semantics of CtClass the condition is only // valid if the CtClass instance representing the traversal interface is // never detached from the ClassPool as this would result in a new // CtClass instance (representing the traversal interface) to be generated // by a call to ClassPool.get(...) not being equal to the old instance. // only generate implementation of traversal interface if not yet present // use traversal interface as marker for availability of other instrumentation CtClass traversalTargetInterface = ClassPool.getDefault().get(TRAVERSAL_TARGET); if (!newTargetIfs.contains(traversalTargetInterface)) { newTargetIfs.add(traversalTargetInterface); target.setInterfaces(newTargetIfs.toArray(new CtClass[0])); // add: method traverse__ (create body before adding new technically required fields) String methodbody = createBody(target, hasTransformedSuperclass); CtMethod m = CtNewMethod.make(methodbody, target); target.addMethod(m); // change methods carrying contracts // 1. Find all methods carrying contracts // 2. For each annotated method // 1. Get method annotation // 2. Generate code to generate automaton for contract // (generate code to get contract string and call into automation generation library) // 3. Use insertBefore() and insertAfter() to insert permission installation/deinstallation code // according to tutorial there's no support for generics in Javassist, thus we use raw types CtField f = CtField.make("private static java.util.HashMap "+FST_CACHE_FIELD_NAME+" = new java.util.HashMap();", target); target.addField(f); // collect all methods and constructors // List<CtMethod> methods = Arrays.asList(target.getDeclaredMethods()); List<CtConstructor> ctors = Arrays.asList(target.getDeclaredConstructors()); // List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); // methodsAndCtors.addAll(methods); // methodsAndCtors.addAll(ctors); List<CtBehavior> methodsAndCtors = Arrays.asList(target.getDeclaredBehaviors()); for (CtConstructor ctor : ctors) { instrumentNew(ctor); } for (CtBehavior methodOrCtor : methodsAndCtors) { logger.fine("Consider adding traversal to behavior: "+methodOrCtor.getLongName()); if ((methodOrCtor.getModifiers() & Modifier.ABSTRACT) != 0) { continue; } instrumentFieldAccess(methodOrCtor); if (hasMethodGrantAnnotations(methodOrCtor)) { logger.fine("Add traversal to behavior: "+methodOrCtor.getLongName()); /* generate header and footer */ // filter synthetic methods if (methodOrCtor.getMethodInfo().getAttribute(SyntheticAttribute.tag) != null) { continue; } // generate method header /* * We keep method contract and all parameter contracts separate. */ StringBuilder sb = new StringBuilder(); // uniquely identifies a method globally String longName = methodOrCtor.getLongName(); // check if automata for this method already exist sb.append("String longName = \"" + longName + "\";"); // FSTs indexed by parameter position (0: FST for this & type-anchored // contracts, 1 to n: FTSs for unanchored parameter contracts) sb.append("de.unifr.acp.fst.FST[] fSTs;"); sb.append("if ("+FST_CACHE_FIELD_NAME+".containsKey(longName)) {"); sb.append(" fSTs = ((de.unifr.acp.fst.FST[])"+FST_CACHE_FIELD_NAME+".get(longName));"); sb.append("}"); sb.append("else {"); // build array of FSTs indexed by parameter sb.append(" fSTs = new de.unifr.acp.fst.FST["+(parameterCountOf(methodOrCtor)+1)+"];"); for (int i=0; i<parameterCountOf(methodOrCtor)+1; i++) { Grant grant = grantAnno(methodOrCtor, i); if (grant != null) { sb.append(" fSTs[" + i + "] = new de.unifr.acp.fst.FST(\"" + grant.value() + "\");"); } } // cache generated automata indexed by long method name sb.append(" "+FST_CACHE_FIELD_NAME+".put(longName, fSTs);"); sb.append("}"); // now we expect to have all FSTs available and cached sb.append(" Map allLocPerms = new de.unifr.acp.util.WeakIdentityHashMap();"); int i= ((isStatic(methodOrCtor)) ? 1 : 0); int limit = ((isStatic(methodOrCtor)) ? (parameterCountOf(methodOrCtor)) : parameterCountOf(methodOrCtor)+1); for (; i<limit; i++) { // only grant-annotated methods/parameters require any action if (grantAnno(methodOrCtor, i) == null) { continue; } if (!mightBeReferenceParameter(methodOrCtor, i)) { continue; } // TODO: factor out this code in external class, parameterize over i and allPermissions // a location permission is a Map<Object, Map<String, Permission>> sb.append("{"); sb.append(" de.unifr.acp.fst.FST fst = fSTs["+i+"];"); sb.append(" de.unifr.acp.fst.FSTRunner runner = new de.unifr.acp.fst.FSTRunner(fst);"); // step to reach FST runner state that corresponds to anchor object // for explicitly anchored contracts if (i == 0) { sb.append(" runner.resetAndStep(\"this\");"); } // here the runner should be in synch with the parameter object // (as far as non-static fields are concerned), the visitor implicitly joins locPerms if (i > 0 && !methodOrCtor.getParameterTypes()[i-1].isArray()) { sb.append(" if ($" + i + " instanceof de.unifr.acp.templates.TraversalTarget__) {"); sb.append(" de.unifr.acp.templates.TraversalImpl visitor = new de.unifr.acp.templates.TraversalImpl(runner,allLocPerms);"); sb.append(" ((de.unifr.acp.templates.TraversalTarget__)$" + i + ").traverse__(visitor);"); sb.append(" }"); } // TODO: explicit representation of locations and location permissions (supporting join) // (currently it's all generic maps and implicit joins in visitor similar to Maxine implementation) sb.append("}"); } // install allLocPerms and push new objects set on (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.push(allLocPerms);"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.push(Collections.newSetFromMap(new de.unifr.acp.util.WeakIdentityHashMap()));"); // TODO: figure out how to instrument thread start/end and field access String header = sb.toString(); methodOrCtor.insertBefore(header); // generate method footer sb = new StringBuilder(); // pop location permissions and new locations entry from // (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.pop();"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.pop();"); String footer = sb.toString(); // make sure all method exits are covered (exceptions, multiple returns) methodOrCtor.insertAfter(footer, true); } // end if (hasMethodGrantAnnotations(methodOrCtor)) } } logger.exiting("TransClass", "doTransform"); }
public static void doTransform(CtClass target, boolean hasTransformedSuperclass) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Object[] params4Logging = new Object[2]; params4Logging[0] = (target != null) ? target.getName() : target; params4Logging[1] = hasTransformedSuperclass; logger.entering("TransClass", "doTransform", params4Logging); if (target.isArray() || target.isInterface()) { return; } ClassPool.getDefault().importPackage("java.util"); // add: implements TRAVERSALTARGET List<CtClass> targetIfs = Arrays.asList(target.getInterfaces()); Collection<CtClass> newTargetIfs = new HashSet<CtClass>(targetIfs); // NOTE: Given the equality semantics of CtClass the condition is only // valid if the CtClass instance representing the traversal interface is // never detached from the ClassPool as this would result in a new // CtClass instance (representing the traversal interface) to be generated // by a call to ClassPool.get(...) not being equal to the old instance. // only generate implementation of traversal interface if not yet present // use traversal interface as marker for availability of other instrumentation CtClass traversalTargetInterface = ClassPool.getDefault().get(TRAVERSAL_TARGET); if (!newTargetIfs.contains(traversalTargetInterface)) { newTargetIfs.add(traversalTargetInterface); target.setInterfaces(newTargetIfs.toArray(new CtClass[0])); // add: method traverse__ (create body before adding new technically required fields) String methodbody = createBody(target, hasTransformedSuperclass); CtMethod m = CtNewMethod.make(methodbody, target); target.addMethod(m); // change methods carrying contracts // 1. Find all methods carrying contracts // 2. For each annotated method // 1. Get method annotation // 2. Generate code to generate automaton for contract // (generate code to get contract string and call into automation generation library) // 3. Use insertBefore() and insertAfter() to insert permission installation/deinstallation code // according to tutorial there's no support for generics in Javassist, thus we use raw types CtField f = CtField.make("private static java.util.HashMap "+FST_CACHE_FIELD_NAME+" = new java.util.HashMap();", target); target.addField(f); // collect all methods and constructors // List<CtMethod> methods = Arrays.asList(target.getDeclaredMethods()); List<CtConstructor> ctors = Arrays.asList(target.getDeclaredConstructors()); // List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); // methodsAndCtors.addAll(methods); // methodsAndCtors.addAll(ctors); List<CtBehavior> methodsAndCtors = Arrays.asList(target.getDeclaredBehaviors()); for (CtConstructor ctor : ctors) { instrumentNew(ctor); } for (CtBehavior methodOrCtor : methodsAndCtors) { logger.fine("Consider adding traversal to behavior: "+methodOrCtor.getLongName()); if ((methodOrCtor.getModifiers() & Modifier.ABSTRACT) != 0) { continue; } instrumentFieldAccess(methodOrCtor); if (hasMethodGrantAnnotations(methodOrCtor)) { logger.fine("Add traversal to behavior: "+methodOrCtor.getLongName()); /* generate header and footer */ // filter synthetic methods if (methodOrCtor.getMethodInfo().getAttribute(SyntheticAttribute.tag) != null) { continue; } // generate method header /* * We keep method contract and all parameter contracts separate. */ StringBuilder sb = new StringBuilder(); // uniquely identifies a method globally String longName = methodOrCtor.getLongName(); // check if automata for this method already exist sb.append("String longName = \"" + longName + "\";"); // FSTs indexed by parameter position (0: FST for this & type-anchored // contracts, 1 to n: FTSs for unanchored parameter contracts) sb.append("de.unifr.acp.fst.FST[] fSTs;"); sb.append("if ("+FST_CACHE_FIELD_NAME+".containsKey(longName)) {"); sb.append(" fSTs = ((de.unifr.acp.fst.FST[])"+FST_CACHE_FIELD_NAME+".get(longName));"); sb.append("}"); sb.append("else {"); // build array of FSTs indexed by parameter sb.append(" fSTs = new de.unifr.acp.fst.FST["+(parameterCountOf(methodOrCtor)+1)+"];"); for (int i=0; i<parameterCountOf(methodOrCtor)+1; i++) { Grant grant = grantAnno(methodOrCtor, i); if (grant != null) { sb.append(" fSTs[" + i + "] = new de.unifr.acp.fst.FST(\"" + grant.value() + "\");"); } } // cache generated automata indexed by long method name sb.append(" "+FST_CACHE_FIELD_NAME+".put(longName, fSTs);"); sb.append("}"); // now we expect to have all FSTs available and cached sb.append(" Map allLocPerms = new de.unifr.acp.util.WeakIdentityHashMap();"); int i= ((isStatic(methodOrCtor)) ? 1 : 0); int limit = ((isStatic(methodOrCtor)) ? (parameterCountOf(methodOrCtor)) : parameterCountOf(methodOrCtor)+1); for (; i<limit; i++) { // only grant-annotated methods/parameters require any action if (grantAnno(methodOrCtor, i) == null) { continue; } if (!mightBeReferenceParameter(methodOrCtor, i)) { continue; } // TODO: factor out this code in external class, parameterize over i and allPermissions // a location permission is a Map<Object, Map<String, Permission>> sb.append("{"); sb.append(" de.unifr.acp.fst.FST fst = fSTs["+i+"];"); sb.append(" de.unifr.acp.fst.FSTRunner runner = new de.unifr.acp.fst.FSTRunner(fst);"); // step to reach FST runner state that corresponds to anchor object // for explicitly anchored contracts if (i == 0) { sb.append(" runner.resetAndStep(\"this\");"); } // here the runner should be in synch with the parameter object // (as far as non-static fields are concerned), the visitor implicitly joins locPerms if (i == 0 || !methodOrCtor.getParameterTypes()[i-1].isArray()) { sb.append(" if ($" + i + " instanceof de.unifr.acp.templates.TraversalTarget__) {"); sb.append(" de.unifr.acp.templates.TraversalImpl visitor = new de.unifr.acp.templates.TraversalImpl(runner,allLocPerms);"); sb.append(" ((de.unifr.acp.templates.TraversalTarget__)$" + i + ").traverse__(visitor);"); sb.append(" }"); } // TODO: explicit representation of locations and location permissions (supporting join) // (currently it's all generic maps and implicit joins in visitor similar to Maxine implementation) sb.append("}"); } // install allLocPerms and push new objects set on (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.push(allLocPerms);"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.push(Collections.newSetFromMap(new de.unifr.acp.util.WeakIdentityHashMap()));"); // TODO: figure out how to instrument thread start/end and field access String header = sb.toString(); methodOrCtor.insertBefore(header); // generate method footer sb = new StringBuilder(); // pop location permissions and new locations entry from // (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.pop();"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.pop();"); String footer = sb.toString(); // make sure all method exits are covered (exceptions, multiple returns) methodOrCtor.insertAfter(footer, true); } // end if (hasMethodGrantAnnotations(methodOrCtor)) } } logger.exiting("TransClass", "doTransform"); }
diff --git a/jfact/src/uk/ac/manchester/cs/jfact/datatypes/DataTypeSituation.java b/jfact/src/uk/ac/manchester/cs/jfact/datatypes/DataTypeSituation.java index df4afff..9e6d4ec 100644 --- a/jfact/src/uk/ac/manchester/cs/jfact/datatypes/DataTypeSituation.java +++ b/jfact/src/uk/ac/manchester/cs/jfact/datatypes/DataTypeSituation.java @@ -1,281 +1,285 @@ package uk.ac.manchester.cs.jfact.datatypes; /* This file is part of the JFact DL reasoner Copyright 2011 by Ignazio Palmisano, Dmitry Tsarkov, University of Manchester This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA*/ import java.util.*; import uk.ac.manchester.cs.jfact.dep.DepSet; import uk.ac.manchester.cs.jfact.helpers.FastSetSimple; /** @author ignazio * @param <R> */ public class DataTypeSituation<R extends Comparable<R>> { /** positive type appearance */ private DepSet pType; /** negative type appearance */ private DepSet nType; /** interval of possible values */ private Set<DepInterval<R>> constraints = new HashSet<DepInterval<R>>(); /** accumulated dep-set */ private final DepSet accDep = DepSet.create(); /** dep-set for the clash */ private final DataTypeReasoner reasoner; private final Datatype<R> type; private final List<Literal<?>> literals = new ArrayList<Literal<?>>(); protected DataTypeSituation(Datatype<R> p, DataTypeReasoner dep) { if (p == null) { throw new IllegalArgumentException("p cannot be null"); } this.type = p; this.reasoner = dep; this.constraints.add(new DepInterval<R>()); } /** update and add a single interval I to the constraints. * * @return true iff clash occurs */ private boolean addUpdatedInterval(DepInterval<R> i, Datatype<R> interval, DepSet localDep) { if (!i.consistent(interval)) { localDep.add(i.locDep); this.reasoner.reportClash(localDep, "C-IT"); return true; } if (!i.update(interval, localDep)) { this.constraints.add(i); } if (!this.hasPType()) { this.constraints.add(i); } if (!i.checkMinMaxClash()) { this.constraints.add(i); } else { this.accDep.add(i.locDep); } return false; } /** @return type */ public Datatype<?> getType() { return this.type; } /** add restrictions [POS]INT to intervals * * @param pos * @param interval * @param dep * @return true if clash occurs */ public boolean addInterval(boolean pos, Datatype<R> interval, DepSet dep) { if (interval instanceof DatatypeEnumeration) { this.literals.addAll(interval.listValues()); } Datatype<R> realInterval = pos ? interval : new DatatypeNegation<R>(interval); Set<DepInterval<R>> c = this.constraints; this.constraints = new HashSet<DepInterval<R>>(); if (!c.isEmpty()) { for (DepInterval<R> d : c) { if (this.addUpdatedInterval(d, realInterval, DepSet.create(dep))) { return true; } } } if (this.constraints.isEmpty()) { this.reasoner.reportClash(this.accDep, "C-MM"); return true; } return false; } /** @return true iff PType and NType leads to clash */ public boolean checkPNTypeClash() { if (this.hasNType() && this.hasPType()) { this.reasoner.reportClash(DepSet.plus(this.pType, this.nType), "TNT"); return true; } for (DepInterval<R> d : this.constraints) { boolean checkMinMaxClash = d.checkMinMaxClash(); if (checkMinMaxClash) { this.accDep.add(d.locDep); this.reasoner.reportClash(this.accDep, "C-MM"); } return checkMinMaxClash; } return false; } private boolean emptyConstraints() { return this.constraints.isEmpty() || this.constraints.iterator().next().e == null; } /** @param other * @return true if compatible */ public boolean checkCompatibleValue(DataTypeSituation<?> other) { if (!this.type.isCompatible(other.type)) { return false; } if (this.emptyConstraints() && other.emptyConstraints()) { return true; } List<Literal<?>> allLiterals = new ArrayList<Literal<?>>(this.literals); allLiterals.addAll(other.literals); List<Datatype<?>> allRestrictions = new ArrayList<Datatype<?>>(); for (DepInterval<?> d : other.constraints) { if (d.e != null) { allRestrictions.add(d.e); } } for (DepInterval<?> d : this.constraints) { if (d.e != null) { allRestrictions.add(d.e); } } boolean toReturn = compareLiterals(other, allLiterals, allRestrictions); // if signs are the same, return the comparison if (hasNType() == other.hasNType() || hasPType() == other.hasPType()) { return toReturn; } - // otherwise signs differ; return the opposite + if (!allRestrictions.isEmpty()) { + return toReturn; + } + // otherwise signs differ and there are no constraints; return the + // opposite // example: -short and {0} return !toReturn; } private boolean compareLiterals(DataTypeSituation<?> other, List<Literal<?>> allLiterals, List<Datatype<?>> allRestrictions) { boolean toReturn = true; for (Literal<?> l : allLiterals) { if (!this.type.isCompatible(l) || !other.type.isCompatible(l)) { toReturn = false; } for (Datatype<?> d : allRestrictions) { if (!d.isCompatible(l)) { toReturn = false; } } } return toReturn; } /** data interval with dep-sets */ static class DepInterval<R extends Comparable<R>> { DatatypeExpression<R> e; /** local dep-set */ FastSetSimple locDep; @Override public String toString() { return "depInterval{" + this.e + "}"; } /** update MIN border of an TYPE's interval with VALUE wrt EXCL * * @param value * @param dep * @return true if updated */ public boolean update(Datatype<R> value, DepSet dep) { if (this.e == null) { if (value.isExpression()) { this.e = value.asExpression(); } else { this.e = DatatypeFactory.getDatatypeExpression(value); } this.locDep = dep == null ? null : dep.getDelegate(); return false; } else { // TODO compare value spaces if (this.e instanceof DatatypeEnumeration || this.e instanceof DatatypeNegation) { // cannot update an enumeration return false; } for (Map.Entry<Facet, Object> f : value.getKnownFacetValues().entrySet()) { this.e = this.e.addFacet(f.getKey(), f.getValue()); } } // TODO needs to return false if the new expression has the same // value space as the old one this.locDep = dep == null ? null : dep.getDelegate(); return true; } /** check if the interval is consistent wrt given type * * @param type * @return true if consistent */ public boolean consistent(Datatype<R> type) { return this.e == null || this.e.isCompatible(type); } public boolean checkMinMaxClash() { if (this.e == null) { return false; } return this.e.emptyValueSpace(); } @Override public boolean equals(Object obj) { if (super.equals(obj)) { return true; } if (obj instanceof DepInterval) { return (this.e == null ? ((DepInterval<?>) obj).e == null : this.e .equals(((DepInterval<?>) obj).e)) && this.locDep == null ? ((DepInterval<?>) obj).locDep == null : this.locDep.equals(((DepInterval<?>) obj).locDep); } return false; } @Override public int hashCode() { return (this.e == null ? 0 : this.e.hashCode()) + (this.locDep == null ? 0 : this.locDep.hashCode()); } } // presence interface /** check if type is present positively in the node * * @return true if pType not null */ public boolean hasPType() { return this.pType != null; } /** check if type is present negatively in the node * * @return true if nType not null */ public boolean hasNType() { return this.nType != null; } /** set the precense of the PType * * @param type */ public void setPType(DepSet type) { this.pType = type; } /** @param t */ public void setNType(DepSet t) { this.nType = t; } /** @return pType */ public DepSet getPType() { return this.pType; } /** @return nType */ public DepSet getNType() { return this.nType; } @Override public String toString() { return this.getClass().getSimpleName() + this.constraints; } }
true
true
public boolean checkCompatibleValue(DataTypeSituation<?> other) { if (!this.type.isCompatible(other.type)) { return false; } if (this.emptyConstraints() && other.emptyConstraints()) { return true; } List<Literal<?>> allLiterals = new ArrayList<Literal<?>>(this.literals); allLiterals.addAll(other.literals); List<Datatype<?>> allRestrictions = new ArrayList<Datatype<?>>(); for (DepInterval<?> d : other.constraints) { if (d.e != null) { allRestrictions.add(d.e); } } for (DepInterval<?> d : this.constraints) { if (d.e != null) { allRestrictions.add(d.e); } } boolean toReturn = compareLiterals(other, allLiterals, allRestrictions); // if signs are the same, return the comparison if (hasNType() == other.hasNType() || hasPType() == other.hasPType()) { return toReturn; } // otherwise signs differ; return the opposite // example: -short and {0} return !toReturn; }
public boolean checkCompatibleValue(DataTypeSituation<?> other) { if (!this.type.isCompatible(other.type)) { return false; } if (this.emptyConstraints() && other.emptyConstraints()) { return true; } List<Literal<?>> allLiterals = new ArrayList<Literal<?>>(this.literals); allLiterals.addAll(other.literals); List<Datatype<?>> allRestrictions = new ArrayList<Datatype<?>>(); for (DepInterval<?> d : other.constraints) { if (d.e != null) { allRestrictions.add(d.e); } } for (DepInterval<?> d : this.constraints) { if (d.e != null) { allRestrictions.add(d.e); } } boolean toReturn = compareLiterals(other, allLiterals, allRestrictions); // if signs are the same, return the comparison if (hasNType() == other.hasNType() || hasPType() == other.hasPType()) { return toReturn; } if (!allRestrictions.isEmpty()) { return toReturn; } // otherwise signs differ and there are no constraints; return the // opposite // example: -short and {0} return !toReturn; }
diff --git a/src/main/java/com/google/gwtexpui/linker/server/UserAgentRule.java b/src/main/java/com/google/gwtexpui/linker/server/UserAgentRule.java index f57db87f7..366b6c57a 100644 --- a/src/main/java/com/google/gwtexpui/linker/server/UserAgentRule.java +++ b/src/main/java/com/google/gwtexpui/linker/server/UserAgentRule.java @@ -1,87 +1,93 @@ // 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.google.gwtexpui.linker.server; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.regex.Pattern.compile; import javax.servlet.http.HttpServletRequest; /** * Selects the value for the {@code user.agent} property. * <p> * Examines the {@code User-Agent} HTTP request header, and tries to match it to * known {@code user.agent} values. * <p> * Ported from JavaScript in {@code com.google.gwt.user.UserAgent.gwt.xml}. */ public class UserAgentRule implements Rule { private static final Pattern msie = compile(".*msie ([0-9]+)\\.([0-9]+).*"); private static final Pattern gecko = compile(".*rv:([0-9]+)\\.([0-9]+).*"); public String getName() { return "user.agent"; } @Override public String select(HttpServletRequest req) { String ua = req.getHeader("User-Agent"); if (ua == null) { return null; } ua = ua.toLowerCase(); if (ua.indexOf("opera") != -1) { return "opera"; } else if (ua.indexOf("webkit") != -1) { return "safari"; } else if (ua.indexOf("msie") != -1) { // GWT 2.0 uses document.documentMode here, which we can't do // on the server side. Matcher m = msie.matcher(ua); if (m.matches() && m.groupCount() == 2) { int v = makeVersion(m); + if (v >= 10000) { + return "ie10"; + } + if (v >= 9000) { + return "ie9"; + } if (v >= 8000) { return "ie8"; } if (v >= 6000) { return "ie6"; } } return null; } else if (ua.indexOf("gecko") != -1) { Matcher m = gecko.matcher(ua); if (m.matches() && m.groupCount() == 2) { if (makeVersion(m) >= 1008) { return "gecko1_8"; } } return "gecko"; } return null; } private int makeVersion(Matcher result) { return (Integer.parseInt(result.group(1)) * 1000) + Integer.parseInt(result.group(2)); } }
true
true
public String select(HttpServletRequest req) { String ua = req.getHeader("User-Agent"); if (ua == null) { return null; } ua = ua.toLowerCase(); if (ua.indexOf("opera") != -1) { return "opera"; } else if (ua.indexOf("webkit") != -1) { return "safari"; } else if (ua.indexOf("msie") != -1) { // GWT 2.0 uses document.documentMode here, which we can't do // on the server side. Matcher m = msie.matcher(ua); if (m.matches() && m.groupCount() == 2) { int v = makeVersion(m); if (v >= 8000) { return "ie8"; } if (v >= 6000) { return "ie6"; } } return null; } else if (ua.indexOf("gecko") != -1) { Matcher m = gecko.matcher(ua); if (m.matches() && m.groupCount() == 2) { if (makeVersion(m) >= 1008) { return "gecko1_8"; } } return "gecko"; } return null; }
public String select(HttpServletRequest req) { String ua = req.getHeader("User-Agent"); if (ua == null) { return null; } ua = ua.toLowerCase(); if (ua.indexOf("opera") != -1) { return "opera"; } else if (ua.indexOf("webkit") != -1) { return "safari"; } else if (ua.indexOf("msie") != -1) { // GWT 2.0 uses document.documentMode here, which we can't do // on the server side. Matcher m = msie.matcher(ua); if (m.matches() && m.groupCount() == 2) { int v = makeVersion(m); if (v >= 10000) { return "ie10"; } if (v >= 9000) { return "ie9"; } if (v >= 8000) { return "ie8"; } if (v >= 6000) { return "ie6"; } } return null; } else if (ua.indexOf("gecko") != -1) { Matcher m = gecko.matcher(ua); if (m.matches() && m.groupCount() == 2) { if (makeVersion(m) >= 1008) { return "gecko1_8"; } } return "gecko"; } return null; }
diff --git a/src/nl/giantit/minecraft/GiantShop/core/Logger/Logger.java b/src/nl/giantit/minecraft/GiantShop/core/Logger/Logger.java index 6ba18c2..8f599fa 100644 --- a/src/nl/giantit/minecraft/GiantShop/core/Logger/Logger.java +++ b/src/nl/giantit/minecraft/GiantShop/core/Logger/Logger.java @@ -1,92 +1,92 @@ package nl.giantit.minecraft.GiantShop.core.Logger; import nl.giantit.minecraft.GiantShop.core.config; import nl.giantit.minecraft.GiantShop.core.Database.db; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; public class Logger { public static void Log(String data) { Log("Unknown", data); } public static void Log(String n, String data) { Log(LoggerType.UNKNOWN, n, data); } public static void Log(Player p, String data) { Log(LoggerType.UNKNOWN, p, data); } public static void Log(CommandSender s, String data) { Log(LoggerType.UNKNOWN, s, data); } public static void Log(LoggerType t, String data) { Log(t, "Unknown", data); } public static void Log(LoggerType t, CommandSender s, String data) { if(s instanceof Player) { Log(t, (Player) s, data); }else{ Log(t, "Console", data); } } public static void Log(LoggerType t, Player p, String data) { Log(t, p.getName(), data); } public static void Log(LoggerType t, String n, String data) { config conf = config.Obtain(); if(conf.getBoolean("GiantShop.global.logActions")) { db DB = db.Obtain(); int type = t.getID(); ArrayList<String> fields = new ArrayList<String>(); ArrayList<HashMap<Integer, HashMap<String, String>>> values = new ArrayList<HashMap<Integer, HashMap<String, String>>>(); fields.add("type"); fields.add("user"); fields.add("data"); fields.add("date"); HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>(); int i = 0; for(String field : fields) { HashMap<String, String> temp = new HashMap<String, String>(); if(field.equalsIgnoreCase("type")) { temp.put("kind", "INT"); temp.put("data", "" + type); tmp.put(i, temp); }else if(field.equalsIgnoreCase("user")) { temp.put("data", "" + n); tmp.put(i, temp); }else if(field.equalsIgnoreCase("data")) { temp.put("data", "" + data); tmp.put(i, temp); }else if(field.equalsIgnoreCase("date")) { - temp.put("data", "" + Logger.getTimestamp()); + temp.put("data", "" + (int) Logger.getTimestamp()); tmp.put(i, temp); } i++; } values.add(tmp); DB.insert("#__log", fields, values).updateQuery(); } } public static long getTimestamp() { Date d = new Date(); return d.getTime(); } }
true
true
public static void Log(LoggerType t, String n, String data) { config conf = config.Obtain(); if(conf.getBoolean("GiantShop.global.logActions")) { db DB = db.Obtain(); int type = t.getID(); ArrayList<String> fields = new ArrayList<String>(); ArrayList<HashMap<Integer, HashMap<String, String>>> values = new ArrayList<HashMap<Integer, HashMap<String, String>>>(); fields.add("type"); fields.add("user"); fields.add("data"); fields.add("date"); HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>(); int i = 0; for(String field : fields) { HashMap<String, String> temp = new HashMap<String, String>(); if(field.equalsIgnoreCase("type")) { temp.put("kind", "INT"); temp.put("data", "" + type); tmp.put(i, temp); }else if(field.equalsIgnoreCase("user")) { temp.put("data", "" + n); tmp.put(i, temp); }else if(field.equalsIgnoreCase("data")) { temp.put("data", "" + data); tmp.put(i, temp); }else if(field.equalsIgnoreCase("date")) { temp.put("data", "" + Logger.getTimestamp()); tmp.put(i, temp); } i++; } values.add(tmp); DB.insert("#__log", fields, values).updateQuery(); } }
public static void Log(LoggerType t, String n, String data) { config conf = config.Obtain(); if(conf.getBoolean("GiantShop.global.logActions")) { db DB = db.Obtain(); int type = t.getID(); ArrayList<String> fields = new ArrayList<String>(); ArrayList<HashMap<Integer, HashMap<String, String>>> values = new ArrayList<HashMap<Integer, HashMap<String, String>>>(); fields.add("type"); fields.add("user"); fields.add("data"); fields.add("date"); HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>(); int i = 0; for(String field : fields) { HashMap<String, String> temp = new HashMap<String, String>(); if(field.equalsIgnoreCase("type")) { temp.put("kind", "INT"); temp.put("data", "" + type); tmp.put(i, temp); }else if(field.equalsIgnoreCase("user")) { temp.put("data", "" + n); tmp.put(i, temp); }else if(field.equalsIgnoreCase("data")) { temp.put("data", "" + data); tmp.put(i, temp); }else if(field.equalsIgnoreCase("date")) { temp.put("data", "" + (int) Logger.getTimestamp()); tmp.put(i, temp); } i++; } values.add(tmp); DB.insert("#__log", fields, values).updateQuery(); } }
diff --git a/bundles/com.eclipsesource.jshint.ui/src/com/eclipsesource/jshint/ui/internal/preferences/ui/JSHintPreferencePage.java b/bundles/com.eclipsesource.jshint.ui/src/com/eclipsesource/jshint/ui/internal/preferences/ui/JSHintPreferencePage.java index 1ea22d6..ba19fae 100644 --- a/bundles/com.eclipsesource.jshint.ui/src/com/eclipsesource/jshint/ui/internal/preferences/ui/JSHintPreferencePage.java +++ b/bundles/com.eclipsesource.jshint.ui/src/com/eclipsesource/jshint/ui/internal/preferences/ui/JSHintPreferencePage.java @@ -1,235 +1,235 @@ /******************************************************************************* * Copyright (c) 2012, 2013 EclipseSource 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: * Ralf Sternberg - initial implementation and API ******************************************************************************/ package com.eclipsesource.jshint.ui.internal.preferences.ui; import java.io.File; import java.io.FileInputStream; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import com.eclipsesource.jshint.JSHint; import com.eclipsesource.jshint.ui.internal.Activator; import com.eclipsesource.jshint.ui.internal.builder.BuilderUtil; import com.eclipsesource.jshint.ui.internal.builder.JSHintBuilder; import com.eclipsesource.jshint.ui.internal.preferences.JSHintPreferences; import static com.eclipsesource.jshint.ui.internal.util.LayoutUtil.gridData; import static com.eclipsesource.jshint.ui.internal.util.LayoutUtil.gridLayout; public class JSHintPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private final JSHintPreferences preferences; private Button defaultLibButton; private Button customLibButton; private Text customLibPathText; private Button customLibPathButton; public JSHintPreferencePage() { setPreferenceStore( Activator.getDefault().getPreferenceStore() ); setDescription( "General settings for JSHint" ); preferences = new JSHintPreferences(); } public void init( IWorkbench workbench ) { } @Override protected IPreferenceStore doGetPreferenceStore() { return null; } @Override protected Control createContents( Composite parent ) { Composite composite = new Composite( parent, SWT.NONE ); gridLayout( composite ).columns( 3 ).marginTop( 10 ); createCustomJSHintArea( composite ); updateControls(); return composite; } @Override public boolean performOk() { try { if( preferences.hasChanged() ) { preferences.save(); triggerRebuild(); } } catch( CoreException exception ) { Activator.logError( "Failed to save preferences", exception ); return false; } return true; } @Override protected void performDefaults() { preferences.resetToDefaults(); updateControls(); super.performDefaults(); } private void createCustomJSHintArea( Composite parent ) { defaultLibButton = new Button( parent, SWT.RADIO ); defaultLibButton.setText( "Use the &built-in JSHint library (version " + JSHint.getDefaultLibraryVersion() + ")" ); - gridData( defaultLibButton ).fillBoth().span( 3, 1 ); + gridData( defaultLibButton ).fillHorizontal().span( 3, 1 ); customLibButton = new Button( parent, SWT.RADIO ); customLibButton.setText( "Provide a &custom JSHint library file" ); - gridData( customLibButton ).fillBoth().span( 3, 1 ); + gridData( customLibButton ).fillHorizontal().span( 3, 1 ); customLibButton.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { updateValuesFromControls(); updateControls(); } } ); customLibPathText = new Text( parent, SWT.BORDER ); - gridData( customLibPathText ).fillBoth().span( 2, 1 ).indent( 25, 0 ); + gridData( customLibPathText ).fillHorizontal().span( 2, 1 ).indent( 25, 0 ); customLibPathText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { updateValuesFromControls(); } } ); customLibPathButton = new Button( parent, SWT.PUSH ); customLibPathButton.setText( "Select" ); customLibPathButton.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { selectFile(); } } ); Text customLibPathLabelText = new Text( parent, SWT.READ_ONLY | SWT.WRAP ); customLibPathLabelText.setText( "This file is usually named 'jshint.js'." ); customLibPathLabelText.setBackground( parent.getBackground() ); gridData( customLibPathLabelText ).fillBoth().span( 2, 1 ).indent( 25, 1 ); } private void selectFile() { FileDialog fileDialog = new FileDialog( getShell(), SWT.OPEN ); fileDialog.setText( "Select JSHint library file" ); File file = new File( preferences.getCustomLibPath() ); fileDialog.setFileName( file.getName() ); fileDialog.setFilterPath( file.getParent() ); fileDialog.setFilterNames( new String[] { "JavaScript files" } ); fileDialog.setFilterExtensions( new String[] { "*.js", "" } ); String selectedPath = fileDialog.open(); if( selectedPath != null ) { preferences.setCustomLibPath( selectedPath ); updateControls(); } } private void updateValuesFromControls() { preferences.setUseCustomLib( customLibButton.getSelection() ); preferences.setCustomLibPath( customLibPathText.getText() ); validate(); } private void validate() { setErrorMessage( null ); setValid( false ); final Display display = getShell().getDisplay(); Job validator = new Job( "JSHint preferences validation" ) { @Override protected IStatus run( IProgressMonitor monitor ) { try { monitor.beginTask( "checking preferences", 1 ); validatePrefs(); display.asyncExec( new Runnable() { public void run() { setValid( true ); } } ); } catch( final IllegalArgumentException exception ) { display.asyncExec( new Runnable() { public void run() { setErrorMessage( exception.getMessage() ); } } ); } finally { monitor.done(); } return Status.OK_STATUS; } }; validator.schedule(); } private void validatePrefs() { if( preferences.getUseCustomLib() ) { String path = preferences.getCustomLibPath(); File file = new File( path ); validateFile( file ); } } private static void validateFile( File file ) throws IllegalArgumentException { if( !file.isFile() ) { throw new IllegalArgumentException( "File does not exist" ); } if( !file.canRead() ) { throw new IllegalArgumentException( "File is not readable" ); } try { FileInputStream inputStream = new FileInputStream( file ); try { JSHint jsHint = new JSHint(); jsHint.load( inputStream ); } finally { inputStream.close(); } } catch( Exception exception ) { throw new IllegalArgumentException( "File is not a valid JSHint library", exception ); } } private void updateControls() { boolean useCustomLib = preferences.getUseCustomLib(); defaultLibButton.setSelection( !useCustomLib ); customLibButton.setSelection( useCustomLib ); customLibPathText.setText( preferences.getCustomLibPath() ); customLibPathText.setEnabled( useCustomLib ); customLibPathButton.setEnabled( useCustomLib ); } private void triggerRebuild() throws CoreException { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for( IProject project : projects ) { if( project.isAccessible() ) { BuilderUtil.triggerClean( project, JSHintBuilder.ID ); } } } }
false
true
private void createCustomJSHintArea( Composite parent ) { defaultLibButton = new Button( parent, SWT.RADIO ); defaultLibButton.setText( "Use the &built-in JSHint library (version " + JSHint.getDefaultLibraryVersion() + ")" ); gridData( defaultLibButton ).fillBoth().span( 3, 1 ); customLibButton = new Button( parent, SWT.RADIO ); customLibButton.setText( "Provide a &custom JSHint library file" ); gridData( customLibButton ).fillBoth().span( 3, 1 ); customLibButton.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { updateValuesFromControls(); updateControls(); } } ); customLibPathText = new Text( parent, SWT.BORDER ); gridData( customLibPathText ).fillBoth().span( 2, 1 ).indent( 25, 0 ); customLibPathText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { updateValuesFromControls(); } } ); customLibPathButton = new Button( parent, SWT.PUSH ); customLibPathButton.setText( "Select" ); customLibPathButton.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { selectFile(); } } ); Text customLibPathLabelText = new Text( parent, SWT.READ_ONLY | SWT.WRAP ); customLibPathLabelText.setText( "This file is usually named 'jshint.js'." ); customLibPathLabelText.setBackground( parent.getBackground() ); gridData( customLibPathLabelText ).fillBoth().span( 2, 1 ).indent( 25, 1 ); }
private void createCustomJSHintArea( Composite parent ) { defaultLibButton = new Button( parent, SWT.RADIO ); defaultLibButton.setText( "Use the &built-in JSHint library (version " + JSHint.getDefaultLibraryVersion() + ")" ); gridData( defaultLibButton ).fillHorizontal().span( 3, 1 ); customLibButton = new Button( parent, SWT.RADIO ); customLibButton.setText( "Provide a &custom JSHint library file" ); gridData( customLibButton ).fillHorizontal().span( 3, 1 ); customLibButton.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { updateValuesFromControls(); updateControls(); } } ); customLibPathText = new Text( parent, SWT.BORDER ); gridData( customLibPathText ).fillHorizontal().span( 2, 1 ).indent( 25, 0 ); customLibPathText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { updateValuesFromControls(); } } ); customLibPathButton = new Button( parent, SWT.PUSH ); customLibPathButton.setText( "Select" ); customLibPathButton.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { selectFile(); } } ); Text customLibPathLabelText = new Text( parent, SWT.READ_ONLY | SWT.WRAP ); customLibPathLabelText.setText( "This file is usually named 'jshint.js'." ); customLibPathLabelText.setBackground( parent.getBackground() ); gridData( customLibPathLabelText ).fillBoth().span( 2, 1 ).indent( 25, 1 ); }
diff --git a/org.eclipse.epp.mpc.tests/src/org/eclipse/epp/mpc/tests/util/TransportFactoryTest.java b/org.eclipse.epp.mpc.tests/src/org/eclipse/epp/mpc/tests/util/TransportFactoryTest.java index a18d5f8..96423ed 100644 --- a/org.eclipse.epp.mpc.tests/src/org/eclipse/epp/mpc/tests/util/TransportFactoryTest.java +++ b/org.eclipse.epp.mpc.tests/src/org/eclipse/epp/mpc/tests/util/TransportFactoryTest.java @@ -1,42 +1,42 @@ /******************************************************************************* * Copyright (c) 2010 The Eclipse Foundation 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: * The Eclipse Foundation - initial API and implementation *******************************************************************************/ package org.eclipse.epp.mpc.tests.util; import static org.junit.Assert.assertNotNull; import java.io.InputStream; import java.net.URI; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.epp.internal.mpc.core.util.ITransport; import org.eclipse.epp.internal.mpc.core.util.TransportFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; @RunWith(BlockJUnit4ClassRunner.class) public class TransportFactoryTest { @Test public void testTansportFactoryInstance() { ITransport transport = TransportFactory.instance().getTransport(); assertNotNull(transport); } @Test public void testStream() throws Exception { ITransport transport = TransportFactory.instance().getTransport(); - URI uri = new URI("http://www.eclipse.org"); + URI uri = new URI("http://www.eclipse.org/index.php"); InputStream stream = transport.stream(uri, new NullProgressMonitor()); assertNotNull(stream); stream.close(); } }
true
true
public void testStream() throws Exception { ITransport transport = TransportFactory.instance().getTransport(); URI uri = new URI("http://www.eclipse.org"); InputStream stream = transport.stream(uri, new NullProgressMonitor()); assertNotNull(stream); stream.close(); }
public void testStream() throws Exception { ITransport transport = TransportFactory.instance().getTransport(); URI uri = new URI("http://www.eclipse.org/index.php"); InputStream stream = transport.stream(uri, new NullProgressMonitor()); assertNotNull(stream); stream.close(); }
diff --git a/overdue/src/main/java/com/ning/billing/overdue/applicator/OverdueStateApplicator.java b/overdue/src/main/java/com/ning/billing/overdue/applicator/OverdueStateApplicator.java index 2d4bb2119..ee412f375 100644 --- a/overdue/src/main/java/com/ning/billing/overdue/applicator/OverdueStateApplicator.java +++ b/overdue/src/main/java/com/ning/billing/overdue/applicator/OverdueStateApplicator.java @@ -1,291 +1,290 @@ /* * Copyright 2010-2013 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.billing.overdue.applicator; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.UUID; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.Period; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ning.billing.ErrorCode; import com.ning.billing.ObjectType; import com.ning.billing.account.api.Account; import com.ning.billing.account.api.AccountApiException; import com.ning.billing.bus.api.PersistentBus; import com.ning.billing.catalog.api.BillingActionPolicy; import com.ning.billing.clock.Clock; import com.ning.billing.entitlement.api.BlockingApiException; import com.ning.billing.entitlement.api.BlockingStateType; import com.ning.billing.entitlement.api.Entitlement; import com.ning.billing.entitlement.api.EntitlementApi; import com.ning.billing.entitlement.api.EntitlementApiException; import com.ning.billing.ovedue.notification.OverdueCheckPoster; import com.ning.billing.overdue.OverdueApiException; import com.ning.billing.overdue.OverdueCancellationPolicy; import com.ning.billing.overdue.OverdueService; import com.ning.billing.overdue.OverdueState; import com.ning.billing.overdue.config.api.BillingState; import com.ning.billing.overdue.config.api.OverdueException; import com.ning.billing.callcontext.InternalCallContext; import com.ning.billing.callcontext.InternalTenantContext; import com.ning.billing.util.dao.NonEntityDao; import com.ning.billing.util.email.DefaultEmailSender; import com.ning.billing.util.email.EmailApiException; import com.ning.billing.util.email.EmailConfig; import com.ning.billing.util.email.EmailSender; import com.ning.billing.events.OverdueChangeInternalEvent; import com.ning.billing.account.api.AccountInternalApi; import com.ning.billing.junction.BlockingInternalApi; import com.ning.billing.junction.DefaultBlockingState; import com.ning.billing.tag.TagInternalApi; import com.ning.billing.util.tag.ControlTagType; import com.ning.billing.util.tag.Tag; import com.google.common.collect.ImmutableList; import com.google.inject.Inject; import com.samskivert.mustache.MustacheException; public class OverdueStateApplicator { private static final Logger log = LoggerFactory.getLogger(OverdueStateApplicator.class); private final BlockingInternalApi blockingApi; private final Clock clock; private final OverdueCheckPoster poster; private final PersistentBus bus; private final AccountInternalApi accountApi; private final EntitlementApi entitlementApi; private final OverdueEmailGenerator overdueEmailGenerator; private final TagInternalApi tagApi; private final EmailSender emailSender; private final NonEntityDao nonEntityDao; @Inject public OverdueStateApplicator(final BlockingInternalApi accessApi, final AccountInternalApi accountApi, final EntitlementApi entitlementApi, final Clock clock, final OverdueCheckPoster poster, final OverdueEmailGenerator overdueEmailGenerator, final EmailConfig config, final PersistentBus bus, final NonEntityDao nonEntityDao, final TagInternalApi tagApi) { this.blockingApi = accessApi; this.accountApi = accountApi; this.entitlementApi = entitlementApi; this.clock = clock; this.poster = poster; this.overdueEmailGenerator = overdueEmailGenerator; this.tagApi = tagApi; this.nonEntityDao = nonEntityDao; this.emailSender = new DefaultEmailSender(config); this.bus = bus; } public void apply(final OverdueState firstOverdueState, final BillingState billingState, final Account overdueable, final String previousOverdueStateName, final OverdueState nextOverdueState, final InternalCallContext context) throws OverdueException { try { if (isAccountTaggedWith_OVERDUE_ENFORCEMENT_OFF(context)) { log.debug("OverdueStateApplicator:apply returns because account (recordId = " + context.getAccountRecordId() + ") is set with OVERDUE_ENFORCEMENT_OFF "); return; } log.debug("OverdueStateApplicator:apply <enter> : time = " + clock.getUTCNow() + ", previousState = " + previousOverdueStateName + ", nextState = " + nextOverdueState); final boolean conditionForNextNotfication = !nextOverdueState.isClearState() || // We did not reach the first state yet but we have an unpaid invoice (firstOverdueState != null && billingState != null && billingState.getDateOfEarliestUnpaidInvoice() != null); if (conditionForNextNotfication) { final Period reevaluationInterval = nextOverdueState.isClearState() ? firstOverdueState.getReevaluationInterval() : nextOverdueState.getReevaluationInterval(); createFutureNotification(overdueable, clock.getUTCNow().plus(reevaluationInterval), context); log.debug("OverdueStateApplicator <notificationQ> : inserting notification for time = " + clock.getUTCNow().plus(reevaluationInterval)); + } else if (nextOverdueState.isClearState()) { + clearFutureNotification(overdueable, context); } if (previousOverdueStateName.equals(nextOverdueState.getName())) { return; } storeNewState(overdueable, nextOverdueState, context); cancelSubscriptionsIfRequired(overdueable, nextOverdueState, context); sendEmailIfRequired(billingState, overdueable, nextOverdueState, context); } catch (OverdueApiException e) { if (e.getCode() != ErrorCode.OVERDUE_NO_REEVALUATION_INTERVAL.getCode()) { throw new OverdueException(e); } } - if (nextOverdueState.isClearState()) { - clearFutureNotification(overdueable, context); - } try { bus.post(createOverdueEvent(overdueable, previousOverdueStateName, nextOverdueState.getName(), context)); } catch (Exception e) { log.error("Error posting overdue change event to bus", e); } } public void clear(final Account overdueable, final String previousOverdueStateName, final OverdueState clearState, final InternalCallContext context) throws OverdueException { log.debug("OverdueStateApplicator:clear : time = " + clock.getUTCNow() + ", previousState = " + previousOverdueStateName); storeNewState(overdueable, clearState, context); clearFutureNotification(overdueable, context); try { bus.post(createOverdueEvent(overdueable, previousOverdueStateName, clearState.getName(), context)); } catch (Exception e) { log.error("Error posting overdue change event to bus", e); } } private OverdueChangeInternalEvent createOverdueEvent(final Account overdueable, final String previousOverdueStateName, final String nextOverdueStateName, final InternalCallContext context) throws BlockingApiException { return new DefaultOverdueChangeEvent(overdueable.getId(), previousOverdueStateName, nextOverdueStateName, context.getAccountRecordId(), context.getTenantRecordId(), context.getUserToken()); } protected void storeNewState(final Account blockable, final OverdueState nextOverdueState, final InternalCallContext context) throws OverdueException { try { blockingApi.setBlockingState(new DefaultBlockingState(blockable.getId(), BlockingStateType.ACCOUNT, nextOverdueState.getName(), OverdueService.OVERDUE_SERVICE_NAME, blockChanges(nextOverdueState), blockEntitlement(nextOverdueState), blockBilling(nextOverdueState), clock.getUTCNow()), context); } catch (Exception e) { throw new OverdueException(e, ErrorCode.OVERDUE_CAT_ERROR_ENCOUNTERED, blockable.getId(), blockable.getClass().getName()); } } private boolean blockChanges(final OverdueState nextOverdueState) { return nextOverdueState.blockChanges(); } private boolean blockBilling(final OverdueState nextOverdueState) { return nextOverdueState.disableEntitlementAndChangesBlocked(); } private boolean blockEntitlement(final OverdueState nextOverdueState) { return nextOverdueState.disableEntitlementAndChangesBlocked(); } protected void createFutureNotification(final Account overdueable, final DateTime timeOfNextCheck, final InternalCallContext context) { poster.insertOverdueCheckNotification(overdueable, timeOfNextCheck, context); } protected void clearFutureNotification(final Account blockable, final InternalCallContext context) { // Need to clear the override table here too (when we add it) poster.clearNotificationsFor(blockable, context); } private void cancelSubscriptionsIfRequired(final Account account, final OverdueState nextOverdueState, final InternalCallContext context) throws OverdueException { if (nextOverdueState.getSubscriptionCancellationPolicy() == OverdueCancellationPolicy.NONE) { return; } try { final BillingActionPolicy actionPolicy; switch (nextOverdueState.getSubscriptionCancellationPolicy()) { case END_OF_TERM: actionPolicy = BillingActionPolicy.END_OF_TERM; break; case IMMEDIATE: actionPolicy = BillingActionPolicy.IMMEDIATE; break; default: throw new IllegalStateException("Unexpected OverdueCancellationPolicy " + nextOverdueState.getSubscriptionCancellationPolicy()); } final List<Entitlement> toBeCancelled = new LinkedList<Entitlement>(); computeEntitlementsToCancel(account, toBeCancelled, context); for (final Entitlement cur : toBeCancelled) { cur.cancelEntitlementWithDateOverrideBillingPolicy(new LocalDate(clock.getUTCNow(), account.getTimeZone()), actionPolicy, context.toCallContext()); } } catch (EntitlementApiException e) { throw new OverdueException(e); } } @SuppressWarnings("unchecked") private void computeEntitlementsToCancel(final Account account, final List<Entitlement> result, final InternalTenantContext context) throws EntitlementApiException { final UUID tenantId = nonEntityDao.retrieveIdFromObject(context.getTenantRecordId(), ObjectType.TENANT); result.addAll(entitlementApi.getAllEntitlementsForAccountId(account.getId(), context.toTenantContext(tenantId))); } private void sendEmailIfRequired(final BillingState billingState, final Account account, final OverdueState nextOverdueState, final InternalTenantContext context) { // Note: we don't want to fail the full refresh call because sending the email failed. // That's the reason why we catch all exceptions here. // The alternative would be to: throw new OverdueApiException(e, ErrorCode.EMAIL_SENDING_FAILED); // If sending is not configured, skip if (nextOverdueState.getEnterStateEmailNotification() == null) { return; } final List<String> to = ImmutableList.<String>of(account.getEmail()); // TODO - should we look at the account CC: list? final List<String> cc = ImmutableList.<String>of(); final String subject = nextOverdueState.getEnterStateEmailNotification().getSubject(); try { // Generate and send the email final String emailBody = overdueEmailGenerator.generateEmail(account, billingState, account, nextOverdueState); if (nextOverdueState.getEnterStateEmailNotification().isHTML()) { emailSender.sendHTMLEmail(to, cc, subject, emailBody); } else { emailSender.sendPlainTextEmail(to, cc, subject, emailBody); } } catch (IOException e) { log.warn(String.format("Unable to generate or send overdue notification email for account %s and overdueable %s", account.getId(), account.getId()), e); } catch (EmailApiException e) { log.warn(String.format("Unable to send overdue notification email for account %s and overdueable %s", account.getId(), account.getId()), e); } catch (MustacheException e) { log.warn(String.format("Unable to generate overdue notification email for account %s and overdueable %s", account.getId(), account.getId()), e); } } // // Uses callcontext information to retrieve account matching the Overduable object and check whether we should do any overdue processing // private boolean isAccountTaggedWith_OVERDUE_ENFORCEMENT_OFF(final InternalCallContext context) throws OverdueException { try { final UUID accountId = accountApi.getByRecordId(context.getAccountRecordId(), context); final List<Tag> accountTags = tagApi.getTags(accountId, ObjectType.ACCOUNT, context); for (Tag cur : accountTags) { if (cur.getTagDefinitionId().equals(ControlTagType.OVERDUE_ENFORCEMENT_OFF.getId())) { return true; } } return false; } catch (AccountApiException e) { throw new OverdueException(e); } } }
false
true
public void apply(final OverdueState firstOverdueState, final BillingState billingState, final Account overdueable, final String previousOverdueStateName, final OverdueState nextOverdueState, final InternalCallContext context) throws OverdueException { try { if (isAccountTaggedWith_OVERDUE_ENFORCEMENT_OFF(context)) { log.debug("OverdueStateApplicator:apply returns because account (recordId = " + context.getAccountRecordId() + ") is set with OVERDUE_ENFORCEMENT_OFF "); return; } log.debug("OverdueStateApplicator:apply <enter> : time = " + clock.getUTCNow() + ", previousState = " + previousOverdueStateName + ", nextState = " + nextOverdueState); final boolean conditionForNextNotfication = !nextOverdueState.isClearState() || // We did not reach the first state yet but we have an unpaid invoice (firstOverdueState != null && billingState != null && billingState.getDateOfEarliestUnpaidInvoice() != null); if (conditionForNextNotfication) { final Period reevaluationInterval = nextOverdueState.isClearState() ? firstOverdueState.getReevaluationInterval() : nextOverdueState.getReevaluationInterval(); createFutureNotification(overdueable, clock.getUTCNow().plus(reevaluationInterval), context); log.debug("OverdueStateApplicator <notificationQ> : inserting notification for time = " + clock.getUTCNow().plus(reevaluationInterval)); } if (previousOverdueStateName.equals(nextOverdueState.getName())) { return; } storeNewState(overdueable, nextOverdueState, context); cancelSubscriptionsIfRequired(overdueable, nextOverdueState, context); sendEmailIfRequired(billingState, overdueable, nextOverdueState, context); } catch (OverdueApiException e) { if (e.getCode() != ErrorCode.OVERDUE_NO_REEVALUATION_INTERVAL.getCode()) { throw new OverdueException(e); } } if (nextOverdueState.isClearState()) { clearFutureNotification(overdueable, context); } try { bus.post(createOverdueEvent(overdueable, previousOverdueStateName, nextOverdueState.getName(), context)); } catch (Exception e) { log.error("Error posting overdue change event to bus", e); } }
public void apply(final OverdueState firstOverdueState, final BillingState billingState, final Account overdueable, final String previousOverdueStateName, final OverdueState nextOverdueState, final InternalCallContext context) throws OverdueException { try { if (isAccountTaggedWith_OVERDUE_ENFORCEMENT_OFF(context)) { log.debug("OverdueStateApplicator:apply returns because account (recordId = " + context.getAccountRecordId() + ") is set with OVERDUE_ENFORCEMENT_OFF "); return; } log.debug("OverdueStateApplicator:apply <enter> : time = " + clock.getUTCNow() + ", previousState = " + previousOverdueStateName + ", nextState = " + nextOverdueState); final boolean conditionForNextNotfication = !nextOverdueState.isClearState() || // We did not reach the first state yet but we have an unpaid invoice (firstOverdueState != null && billingState != null && billingState.getDateOfEarliestUnpaidInvoice() != null); if (conditionForNextNotfication) { final Period reevaluationInterval = nextOverdueState.isClearState() ? firstOverdueState.getReevaluationInterval() : nextOverdueState.getReevaluationInterval(); createFutureNotification(overdueable, clock.getUTCNow().plus(reevaluationInterval), context); log.debug("OverdueStateApplicator <notificationQ> : inserting notification for time = " + clock.getUTCNow().plus(reevaluationInterval)); } else if (nextOverdueState.isClearState()) { clearFutureNotification(overdueable, context); } if (previousOverdueStateName.equals(nextOverdueState.getName())) { return; } storeNewState(overdueable, nextOverdueState, context); cancelSubscriptionsIfRequired(overdueable, nextOverdueState, context); sendEmailIfRequired(billingState, overdueable, nextOverdueState, context); } catch (OverdueApiException e) { if (e.getCode() != ErrorCode.OVERDUE_NO_REEVALUATION_INTERVAL.getCode()) { throw new OverdueException(e); } } try { bus.post(createOverdueEvent(overdueable, previousOverdueStateName, nextOverdueState.getName(), context)); } catch (Exception e) { log.error("Error posting overdue change event to bus", e); } }
diff --git a/src/com/bekvon/bukkit/residence/listeners/ResidenceEntityListener.java b/src/com/bekvon/bukkit/residence/listeners/ResidenceEntityListener.java index 4fa1938..21276cc 100644 --- a/src/com/bekvon/bukkit/residence/listeners/ResidenceEntityListener.java +++ b/src/com/bekvon/bukkit/residence/listeners/ResidenceEntityListener.java @@ -1,384 +1,384 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.bekvon.bukkit.residence.listeners; import org.bukkit.ChatColor; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.bekvon.bukkit.residence.protection.FlagPermissions; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.BrewingStand; import org.bukkit.block.Chest; import org.bukkit.block.Dispenser; import org.bukkit.block.Furnace; import org.bukkit.block.Jukebox; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityCombustEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityInteractEvent; import org.bukkit.event.entity.PotionSplashEvent; import com.bekvon.bukkit.residence.Residence; import com.bekvon.bukkit.residence.protection.ClaimedResidence; import org.bukkit.Material; import org.bukkit.entity.Arrow; import org.bukkit.entity.Chicken; import org.bukkit.entity.Cow; import org.bukkit.entity.Creeper; import org.bukkit.entity.EntityType; import org.bukkit.entity.IronGolem; import org.bukkit.entity.Ocelot; import org.bukkit.entity.Pig; import org.bukkit.entity.Sheep; import org.bukkit.entity.Snowman; import org.bukkit.entity.Squid; import org.bukkit.entity.Villager; import org.bukkit.entity.Wolf; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.painting.PaintingBreakEvent; import org.bukkit.event.painting.PaintingPlaceEvent; import org.bukkit.event.painting.PaintingBreakByEntityEvent; import org.bukkit.inventory.ItemStack; /** * * @author Administrator */ public class ResidenceEntityListener implements Listener { protected Map<BlockState, ItemStack[]> ExplodeRestore = new HashMap<BlockState,ItemStack[]>(); @EventHandler(priority = EventPriority.NORMAL) public void onEndermanChangeBlock(EntityChangeBlockEvent event) { if(event.getEntityType() != EntityType.ENDERMAN){ return; } FlagPermissions perms = Residence.getPermsByLoc(event.getBlock().getLocation()); if (!perms.has("build", true)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.NORMAL) public void onEntityInteract(EntityInteractEvent event){ Block block = event.getBlock(); Material mat = block.getType(); Entity entity = event.getEntity(); FlagPermissions perms = Residence.getPermsByLoc(block.getLocation()); boolean hastrample = perms.has("trample", perms.has("hasbuild", true)); if(!hastrample && !(entity.getType() == EntityType.FALLING_BLOCK) && (mat == Material.SOIL || mat == Material.SOUL_SAND)){ event.setCancelled(true); } } /* @EventHandler(priority = EventPriority.NORMAL) public void onEndermanPlace(EndermanPlaceEvent event) { ClaimedResidence res = Residence.getResidenceManager().getByLoc(event.getLocation()); if (res != null) { ResidencePermissions perms = res.getPermissions(); if (!perms.has("build", true)) { event.setCancelled(true); } } else { FlagPermissions perms = Residence.getWorldFlags().getPerms(event.getLocation().getWorld().getName()); if (!perms.has("build", true)) { event.setCancelled(true); } } } */ @EventHandler(priority = EventPriority.NORMAL) public void onCreatureSpawn(CreatureSpawnEvent event) { if(event.isCancelled()) return; FlagPermissions perms = Residence.getPermsByLoc(event.getLocation()); Entity ent = event.getEntity(); if(ent instanceof Snowman || ent instanceof IronGolem || ent instanceof Ocelot || ent instanceof Pig || ent instanceof Sheep || ent instanceof Chicken || ent instanceof Wolf || ent instanceof Cow || ent instanceof Squid || ent instanceof Villager){ if(!perms.has("animals", true)){ event.setCancelled(true); } } else { if (!perms.has("monsters", true)) { event.setCancelled(true); } } } @EventHandler(priority = EventPriority.NORMAL) public void onPaintingPlace(PaintingPlaceEvent event) { Player player = event.getPlayer(); if(Residence.isResAdminOn(player)){ return; } FlagPermissions perms = Residence.getPermsByLocForPlayer(event.getPainting().getLocation(),player); String pname = player.getName(); String world = event.getBlock().getWorld().getName(); boolean hasplace = perms.playerHas(pname, world, "place", perms.playerHas(pname, world, "build", true)); if (!hasplace) { event.setCancelled(true); player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("NoPermission")); } } @EventHandler(priority = EventPriority.NORMAL) public void onPaintingBreak(PaintingBreakEvent event) { if(event instanceof PaintingBreakByEntityEvent){ PaintingBreakByEntityEvent evt = (PaintingBreakByEntityEvent) event; if(evt.getRemover() instanceof Player){ Player player = (Player) evt.getRemover(); if(Residence.isResAdminOn(player)){ return; } String pname = player.getName(); FlagPermissions perms = Residence.getPermsByLocForPlayer(event.getPainting().getLocation(),player); String world = event.getPainting().getWorld().getName(); boolean hasplace = perms.playerHas(pname, world, "place", perms.playerHas(pname, world, "build", true)); if (!hasplace){ event.setCancelled(true); player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("NoPermission")); } } } } @EventHandler(priority = EventPriority.NORMAL) public void onEntityCombust(EntityCombustEvent event) { if(event.isCancelled()) return; FlagPermissions perms = Residence.getPermsByLoc(event.getEntity().getLocation()); if (!perms.has("burn", true)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.NORMAL) public void onExplosionPrime(ExplosionPrimeEvent event) { if(event.isCancelled()) return; EntityType entity = event.getEntityType(); FlagPermissions perms = Residence.getPermsByLoc(event.getEntity().getLocation()); if (entity == EntityType.CREEPER) { if (!perms.has("creeper", perms.has("explode", true))) { event.setCancelled(true); event.getEntity().remove(); } } if (entity == EntityType.PRIMED_TNT) { if (!perms.has("tnt", perms.has("explode", true))) { event.setCancelled(true); event.getEntity().remove(); } } if (entity == EntityType.FIREBALL) { if(!perms.has("fireball", perms.has("explode", true))){ event.setCancelled(true); event.getEntity().remove(); } } } @EventHandler(priority = EventPriority.NORMAL) public void onEntityExplode(EntityExplodeEvent event) { if(event.isCancelled()||event.getEntity()==null) return; Boolean cancel = false; EntityType entity = event.getEntityType(); FlagPermissions perms = Residence.getPermsByLoc(event.getEntity().getLocation()); if (entity == EntityType.CREEPER) { if (!perms.has("creeper", perms.has("explode", true))) { cancel = true; } } if (entity == EntityType.PRIMED_TNT) { if (!perms.has("tnt", perms.has("explode", true))) { cancel = true; } } if (entity == EntityType.FIREBALL) { if(!perms.has("fireball", perms.has("explode", true))){ event.setCancelled(true); event.getEntity().remove(); } } if(cancel){ event.setCancelled(true); event.getEntity().remove(); } else { for(Block block: event.blockList()){ FlagPermissions blockperms = Residence.getPermsByLoc(block.getLocation()); if((!blockperms.has("fireball", perms.has("explode", true))&&entity==EntityType.FIREBALL)||(!blockperms.has("tnt", perms.has("explode", true))&&entity==EntityType.PRIMED_TNT)||(!blockperms.has("creeper", perms.has("explode", true))&&entity==EntityType.CREEPER)){ if(block!=null){ ItemStack[] inventory = null; BlockState save = block.getState(); if(block.getType()==Material.CHEST){ Chest chest = (Chest)save; inventory = chest.getBlockInventory().getContents(); - chest.getInventory().clear(); + chest.getBlockInventory().clear(); } if(block.getType()==Material.FURNACE||block.getType()==Material.BURNING_FURNACE){ Furnace furnace = (Furnace)save; inventory = furnace.getInventory().getContents(); furnace.getInventory().clear(); } if(block.getType()==Material.BREWING_STAND){ BrewingStand brew = (BrewingStand)save; inventory = brew.getInventory().getContents(); brew.getInventory().clear(); } if(block.getType()==Material.DISPENSER){ Dispenser dispenser = (Dispenser)save; inventory = dispenser.getInventory().getContents(); dispenser.getInventory().clear(); } if(block.getType()==Material.JUKEBOX){ Jukebox jukebox = (Jukebox)save; if(jukebox.isPlaying()){ inventory = new ItemStack[1]; inventory[0] = new ItemStack(jukebox.getPlaying()); jukebox.setPlaying(null); } } ExplodeRestore.put(save, inventory); block.setType(Material.AIR); } } } Residence.getServ().getScheduler().scheduleSyncDelayedTask(Residence.getServ().getPluginManager().getPlugin("Residence"), new Runnable() { public void run() { for(BlockState block: ExplodeRestore.keySet().toArray(new BlockState[0])){ ItemStack[] inventory = ExplodeRestore.get(block); block.update(true); if(inventory!=null){ if(block.getType()==Material.CHEST) ((Chest)block.getLocation().getBlock().getState()).getBlockInventory().setContents(inventory); if(block.getType()==Material.FURNACE||block.getType()==Material.BURNING_FURNACE) ((Furnace)block.getLocation().getBlock().getState()).getInventory().setContents(inventory); if(block.getType()==Material.BREWING_STAND) ((BrewingStand)block.getLocation().getBlock().getState()).getInventory().setContents(inventory); if(block.getType()==Material.DISPENSER) ((Dispenser)block.getLocation().getBlock().getState()).getInventory().setContents(inventory); if(block.getType()==Material.JUKEBOX) ((Jukebox)block.getLocation().getBlock().getState()).setPlaying(inventory[0].getType()); } } ExplodeRestore.clear(); } }, 1L); } } @EventHandler(priority = EventPriority.NORMAL) public void onSplashPotion(PotionSplashEvent event) { if(event.isCancelled()) return; Entity ent = event.getEntity(); boolean srcpvp = Residence.getPermsByLoc(ent.getLocation()).has("pvp", true); Iterator<LivingEntity> it = event.getAffectedEntities().iterator(); while(it.hasNext()){ LivingEntity target = it.next(); if(target.getType()==EntityType.PLAYER){ Boolean tgtpvp = Residence.getPermsByLoc(target.getLocation()).has("pvp", true); if(!srcpvp||!tgtpvp){ event.setIntensity(target, 0); } } } } @EventHandler(priority = EventPriority.NORMAL) public void onEntityDamage(EntityDamageEvent event) { if(event.isCancelled()) return; Entity ent = event.getEntity(); if(ent.hasMetadata("NPC")) { return; } boolean tamedWolf = ent instanceof Wolf ? ((Wolf)ent).isTamed() : false; ClaimedResidence area = Residence.getResidenceManager().getByLoc(ent.getLocation()); /* Living Entities */ if (event instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent attackevent = (EntityDamageByEntityEvent) event; Entity damager = attackevent.getDamager(); ClaimedResidence srcarea = null; if(damager!=null) srcarea = Residence.getResidenceManager().getByLoc(damager.getLocation()); boolean srcpvp = true; if(srcarea !=null) srcpvp = srcarea.getPermissions().has("pvp", true); ent = attackevent.getEntity(); if ((ent instanceof Player || tamedWolf) && (damager instanceof Player || (damager instanceof Arrow && (((Arrow)damager).getShooter() instanceof Player)))) { Player attacker = null; if(damager instanceof Player) attacker = (Player) damager; else if(damager instanceof Arrow) attacker = (Player)((Arrow)damager).getShooter(); if(!srcpvp) { attacker.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("NoPVPZone")); event.setCancelled(true); return; } /* Check for Player vs Player */ if (area == null) { /* World PvP */ if (!Residence.getWorldFlags().getPerms(damager.getWorld().getName()).has("pvp", true)) { attacker.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("WorldPVPDisabled")); event.setCancelled(true); } } else { /* Normal PvP */ if (!area.getPermissions().has("pvp", true)) { attacker.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("NoPVPZone")); event.setCancelled(true); } } return; } else if ((ent instanceof Player || tamedWolf) && (damager instanceof Creeper)) { if (area == null) { if (!Residence.getWorldFlags().getPerms(damager.getWorld().getName()).has("creeper", true)) { event.setCancelled(true); } } else { if (!area.getPermissions().has("creeper", true)) { event.setCancelled(true); } } } } if (area == null) { if (!Residence.getWorldFlags().getPerms(ent.getWorld().getName()).has("damage", true) && (ent instanceof Player || tamedWolf)) { event.setCancelled(true); } } else { if (!area.getPermissions().has("damage", true) && (ent instanceof Player || tamedWolf)) { event.setCancelled(true); } } if (event.isCancelled()) { /* Put out a fire on a player */ if ((ent instanceof Player || tamedWolf) && (event.getCause() == EntityDamageEvent.DamageCause.FIRE || event.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK)) { ent.setFireTicks(0); } } } }
true
true
public void onEntityExplode(EntityExplodeEvent event) { if(event.isCancelled()||event.getEntity()==null) return; Boolean cancel = false; EntityType entity = event.getEntityType(); FlagPermissions perms = Residence.getPermsByLoc(event.getEntity().getLocation()); if (entity == EntityType.CREEPER) { if (!perms.has("creeper", perms.has("explode", true))) { cancel = true; } } if (entity == EntityType.PRIMED_TNT) { if (!perms.has("tnt", perms.has("explode", true))) { cancel = true; } } if (entity == EntityType.FIREBALL) { if(!perms.has("fireball", perms.has("explode", true))){ event.setCancelled(true); event.getEntity().remove(); } } if(cancel){ event.setCancelled(true); event.getEntity().remove(); } else { for(Block block: event.blockList()){ FlagPermissions blockperms = Residence.getPermsByLoc(block.getLocation()); if((!blockperms.has("fireball", perms.has("explode", true))&&entity==EntityType.FIREBALL)||(!blockperms.has("tnt", perms.has("explode", true))&&entity==EntityType.PRIMED_TNT)||(!blockperms.has("creeper", perms.has("explode", true))&&entity==EntityType.CREEPER)){ if(block!=null){ ItemStack[] inventory = null; BlockState save = block.getState(); if(block.getType()==Material.CHEST){ Chest chest = (Chest)save; inventory = chest.getBlockInventory().getContents(); chest.getInventory().clear(); } if(block.getType()==Material.FURNACE||block.getType()==Material.BURNING_FURNACE){ Furnace furnace = (Furnace)save; inventory = furnace.getInventory().getContents(); furnace.getInventory().clear(); } if(block.getType()==Material.BREWING_STAND){ BrewingStand brew = (BrewingStand)save; inventory = brew.getInventory().getContents(); brew.getInventory().clear(); } if(block.getType()==Material.DISPENSER){ Dispenser dispenser = (Dispenser)save; inventory = dispenser.getInventory().getContents(); dispenser.getInventory().clear(); } if(block.getType()==Material.JUKEBOX){ Jukebox jukebox = (Jukebox)save; if(jukebox.isPlaying()){ inventory = new ItemStack[1]; inventory[0] = new ItemStack(jukebox.getPlaying()); jukebox.setPlaying(null); } } ExplodeRestore.put(save, inventory); block.setType(Material.AIR); } } } Residence.getServ().getScheduler().scheduleSyncDelayedTask(Residence.getServ().getPluginManager().getPlugin("Residence"), new Runnable() { public void run() { for(BlockState block: ExplodeRestore.keySet().toArray(new BlockState[0])){ ItemStack[] inventory = ExplodeRestore.get(block); block.update(true); if(inventory!=null){ if(block.getType()==Material.CHEST) ((Chest)block.getLocation().getBlock().getState()).getBlockInventory().setContents(inventory); if(block.getType()==Material.FURNACE||block.getType()==Material.BURNING_FURNACE) ((Furnace)block.getLocation().getBlock().getState()).getInventory().setContents(inventory); if(block.getType()==Material.BREWING_STAND) ((BrewingStand)block.getLocation().getBlock().getState()).getInventory().setContents(inventory); if(block.getType()==Material.DISPENSER) ((Dispenser)block.getLocation().getBlock().getState()).getInventory().setContents(inventory); if(block.getType()==Material.JUKEBOX) ((Jukebox)block.getLocation().getBlock().getState()).setPlaying(inventory[0].getType()); } } ExplodeRestore.clear(); } }, 1L); } }
public void onEntityExplode(EntityExplodeEvent event) { if(event.isCancelled()||event.getEntity()==null) return; Boolean cancel = false; EntityType entity = event.getEntityType(); FlagPermissions perms = Residence.getPermsByLoc(event.getEntity().getLocation()); if (entity == EntityType.CREEPER) { if (!perms.has("creeper", perms.has("explode", true))) { cancel = true; } } if (entity == EntityType.PRIMED_TNT) { if (!perms.has("tnt", perms.has("explode", true))) { cancel = true; } } if (entity == EntityType.FIREBALL) { if(!perms.has("fireball", perms.has("explode", true))){ event.setCancelled(true); event.getEntity().remove(); } } if(cancel){ event.setCancelled(true); event.getEntity().remove(); } else { for(Block block: event.blockList()){ FlagPermissions blockperms = Residence.getPermsByLoc(block.getLocation()); if((!blockperms.has("fireball", perms.has("explode", true))&&entity==EntityType.FIREBALL)||(!blockperms.has("tnt", perms.has("explode", true))&&entity==EntityType.PRIMED_TNT)||(!blockperms.has("creeper", perms.has("explode", true))&&entity==EntityType.CREEPER)){ if(block!=null){ ItemStack[] inventory = null; BlockState save = block.getState(); if(block.getType()==Material.CHEST){ Chest chest = (Chest)save; inventory = chest.getBlockInventory().getContents(); chest.getBlockInventory().clear(); } if(block.getType()==Material.FURNACE||block.getType()==Material.BURNING_FURNACE){ Furnace furnace = (Furnace)save; inventory = furnace.getInventory().getContents(); furnace.getInventory().clear(); } if(block.getType()==Material.BREWING_STAND){ BrewingStand brew = (BrewingStand)save; inventory = brew.getInventory().getContents(); brew.getInventory().clear(); } if(block.getType()==Material.DISPENSER){ Dispenser dispenser = (Dispenser)save; inventory = dispenser.getInventory().getContents(); dispenser.getInventory().clear(); } if(block.getType()==Material.JUKEBOX){ Jukebox jukebox = (Jukebox)save; if(jukebox.isPlaying()){ inventory = new ItemStack[1]; inventory[0] = new ItemStack(jukebox.getPlaying()); jukebox.setPlaying(null); } } ExplodeRestore.put(save, inventory); block.setType(Material.AIR); } } } Residence.getServ().getScheduler().scheduleSyncDelayedTask(Residence.getServ().getPluginManager().getPlugin("Residence"), new Runnable() { public void run() { for(BlockState block: ExplodeRestore.keySet().toArray(new BlockState[0])){ ItemStack[] inventory = ExplodeRestore.get(block); block.update(true); if(inventory!=null){ if(block.getType()==Material.CHEST) ((Chest)block.getLocation().getBlock().getState()).getBlockInventory().setContents(inventory); if(block.getType()==Material.FURNACE||block.getType()==Material.BURNING_FURNACE) ((Furnace)block.getLocation().getBlock().getState()).getInventory().setContents(inventory); if(block.getType()==Material.BREWING_STAND) ((BrewingStand)block.getLocation().getBlock().getState()).getInventory().setContents(inventory); if(block.getType()==Material.DISPENSER) ((Dispenser)block.getLocation().getBlock().getState()).getInventory().setContents(inventory); if(block.getType()==Material.JUKEBOX) ((Jukebox)block.getLocation().getBlock().getState()).setPlaying(inventory[0].getType()); } } ExplodeRestore.clear(); } }, 1L); } }
diff --git a/framework/test/integrationtest-java/test/test/SimpleTest.java b/framework/test/integrationtest-java/test/test/SimpleTest.java index 9b960a730..ea80c2232 100644 --- a/framework/test/integrationtest-java/test/test/SimpleTest.java +++ b/framework/test/integrationtest-java/test/test/SimpleTest.java @@ -1,313 +1,313 @@ /* * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com> */ package test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import controllers.routes; import com.fasterxml.jackson.databind.JsonNode; import org.junit.*; import play.libs.Json; import play.mvc.*; import play.test.*; import play.data.DynamicForm; import play.data.validation.ValidationError; import play.data.validation.Constraints.RequiredValidator; import play.i18n.Lang; import play.libs.F; import play.libs.F.*; import play.libs.ws.*; import models.JCustomer; import play.data.Form; import static play.test.Helpers.*; import static org.fest.assertions.Assertions.*; public class SimpleTest { @Test public void simpleCheck() { int a = 1 + 1; assertThat(a).isEqualTo(2); } @Test public void sessionCookieShouldOverrideOldValue() { running(fakeApplication(), new Runnable() { Boolean shouldNotBeCalled = false; @Override public void run() { FakeRequest req = fakeRequest(); for (int i = 0; i < 5; i++) { req = req.withSession("key" + i, "value" + i); } for (int i = 0; i < 5; i++) { if (!req.getWrappedRequest().session().get("key" + i).isDefined()) { shouldNotBeCalled = true; } } assertThat(shouldNotBeCalled).isEqualTo(false); } }); } @Test public void renderTemplate() { Content html = views.html.index.render("Coco"); assertThat(contentType(html)).isEqualTo("text/html"); assertThat(contentAsString(html)).contains("Coco"); } @Test public void callIndex() { Result result = callAction(controllers.routes.ref.Application.index("Kiki")); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("text/html"); assertThat(charset(result)).isEqualTo("utf-8"); assertThat(contentAsString(result)).contains("Hello Kiki"); } @Test public void badRoute() { Result result = routeAndCall(fakeRequest(GET, "/xx/Kiki")); assertThat(result).isNull(); } @Test public void routeIndex() { Result result = routeAndCall(fakeRequest(GET, "/Kiki")); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("text/html"); assertThat(charset(result)).isEqualTo("utf-8"); assertThat(contentAsString(result)).contains("Hello Kiki"); } @Test public void inApp() { running(fakeApplication(), new Runnable() { public void run() { Result result = routeAndCall(fakeRequest(GET, "/key")); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("text/plain"); assertThat(charset(result)).isEqualTo("utf-8"); assertThat(contentAsString(result)).contains("secret"); } }); } @Test public void inServer() { running(testServer(3333), HTMLUNIT, new Callback<TestBrowser>() { public void invoke(TestBrowser browser) { browser.goTo("http://localhost:3333"); assertThat(browser.$("#title").getTexts().get(0)).isEqualTo("Hello Guest"); browser.$("a").click(); assertThat(browser.url()).isEqualTo("http://localhost:3333/Coco"); assertThat(browser.$("#title", 0).getText()).isEqualTo("Hello Coco"); } }); } @Test public void errorsAsJson() { running(fakeApplication(), new Runnable() { @Override public void run() { Lang lang = new Lang(new play.api.i18n.Lang("en", "")); Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>(); List<ValidationError> error = new ArrayList<ValidationError>(); error.add(new ValidationError("foo", RequiredValidator.message, new ArrayList<Object>())); errors.put("foo", error); DynamicForm form = new DynamicForm(new HashMap<String, String>(), errors, F.None()); JsonNode jsonErrors = form.errorsAsJson(lang); assertThat(jsonErrors.findPath("foo").iterator().next().asText()).isEqualTo(play.i18n.Messages.get(lang, RequiredValidator.message)); } }); } /** * Checks that we can build fake request with a json body. * In this test, we use the default method (POST). */ @Test public void withJsonBody() { running(fakeApplication(), new Runnable() { @Override public void run() { Map map = new HashMap(); map.put("key1", "val1"); map.put("key2", 2); map.put("key3", true); JsonNode node = Json.toJson(map); Result result = routeAndCall(fakeRequest("POST", "/json").withJsonBody(node)); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("application/json"); JsonNode node2 = Json.parse(contentAsString(result)); assertThat(node2.get("key1").asText()).isEqualTo("val1"); assertThat(node2.get("key2").asInt()).isEqualTo(2); assertThat(node2.get("key3").asBoolean()).isTrue(); } }); } /** * Checks that we can build fake request with a json body. * In this test we specify the method to use (DELETE) */ @Test public void withJsonBodyAndSpecifyMethod() { running(fakeApplication(), new Runnable() { @Override public void run() { Map map = new HashMap(); map.put("key1", "val1"); map.put("key2", 2); map.put("key3", true); JsonNode node = Json.toJson(map); Result result = callAction(routes.ref.Application.getIdenticalJson(), fakeRequest().withJsonBody(node, "DELETE")); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("application/json"); JsonNode node2 = Json.parse(contentAsString(result)); assertThat(node2.get("key1").asText()).isEqualTo("val1"); assertThat(node2.get("key2").asInt()).isEqualTo(2); assertThat(node2.get("key3").asBoolean()).isTrue(); } }); } @Test public void asyncResult() { running(fakeApplication(), new Runnable() { @Override public void run() { Result result = route(fakeRequest( GET, "/async")); assertThat(status(result)).isEqualTo(OK); assertThat(charset(result)).isEqualTo("utf-8"); assertThat(contentAsString(result)).isEqualTo("success"); assertThat(contentType(result)).isEqualTo("text/plain"); assertThat(header("header_test", result)).isEqualTo( "header_val"); assertThat(session(result).get("session_test")).isEqualTo( "session_val"); assertThat(cookie("cookie_test", result).value()).isEqualTo( "cookie_val"); assertThat(flash(result).get("flash_test")).isEqualTo( "flash_val"); } }); } @Test - public void nestedContraints() { + public void nestedConstraints() { Form<JCustomer> customerForm = new Form<JCustomer>(JCustomer.class); // email constraints assertThat(customerForm.field("email").constraints().size()).as( "field(\"email\").constraints().size()").isEqualTo(2); assertThat(customerForm.field("email").constraints().get(0)._1).as( "field(\"email\").constraints(0)") .isEqualTo("constraint.email"); assertThat(customerForm.field("email").constraints().get(1)._1).as( "field(\"email\").constraints(1)").isEqualTo( "constraint.required"); // orders[0].date constraints assertThat(customerForm.field("orders[0].date").constraints().size()) .as("field(\"orders[0].date\").constraints().size()") .isEqualTo(1); assertThat(customerForm.field("orders[0].date").constraints().get(0)._1) .as("field(\"orders[0].date\").constraints(0)").isEqualTo( "constraint.required"); // orders[0].date format assertThat(customerForm.field("orders[0].date").format()._1).as( "field(\"orders[0].date\").format()._1").isEqualTo( "format.date"); assertThat(customerForm.field("orders[0].date").format()._2.toString()) .as("field(\"orders[0].date\").format()._2").isEqualTo( "[yyyy-MM-dd]"); // orders[0].items[0].qty constraints assertThat( customerForm.field("orders[0].items[0].qty").constraints() .size()).as( "field(\"orders[0].items[0].qty\").constraints().size()") .isEqualTo(2); assertThat( customerForm.field("orders[0].items[0].qty").constraints() .get(0)._1).as( "field(\"orders[0].items[0].qty\").constraints(0)").isEqualTo( "constraint.min"); assertThat( customerForm.field("orders[0].items[0].qty").constraints() .get(0)._2.toString()).as( "field(\"orders[0].items[0].qty\").constraints(0)._2") .isEqualTo("[1]"); assertThat( customerForm.field("orders[0].items[0].qty").constraints() .get(1)._1).as( "field(\"orders[0].items[0].qty\").constraints(1)").isEqualTo( "constraint.required"); // orders[0].items[0].productCode constraints assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().size()) .as("field(\"orders[0].items[0].productCode\").constraints().size()") .isEqualTo(2); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(0)._1).as( "field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo("constraint.pattern"); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(0)._2.size()).as( "field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo(1); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(0)._2.get(0)).as( "field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo("[A-Z]{4}-[0-9]{3,}"); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(1)._1).as( "field(\"orders[0].items[0].productCode\").constraints(1)") .isEqualTo("constraint.required"); // orders[0].items[0].deliveryDate constraints assertThat( customerForm.field("orders[0].items[0].deliveryDate") .constraints().size()) .as("field(\"orders[0].items[0].deliveryDate\").constraints().size()") .isEqualTo(0); // orders[0].items[0].deliveryDate format assertThat( customerForm.field("orders[0].items[0].deliveryDate").format()._1) .as("field(\"orders[0].items[0].deliveryDate\").format()._1") .isEqualTo("format.date"); assertThat( customerForm.field("orders[0].items[0].deliveryDate").format()._2 .toString()).as( "field(\"orders[0].items[0].deliveryDate\").format()._2") .isEqualTo("[yyyy-MM-dd]"); } @Test public void actionShouldBeExecutedInCorrectThread() { running(testServer(3333), new Runnable() { public void run() { WSResponse response = WS.url("http://localhost:3333/thread").get().get(10000); assertThat(response.getBody()).startsWith("play-akka.actor.default-dispatcher-"); } }); } }
true
true
public void nestedContraints() { Form<JCustomer> customerForm = new Form<JCustomer>(JCustomer.class); // email constraints assertThat(customerForm.field("email").constraints().size()).as( "field(\"email\").constraints().size()").isEqualTo(2); assertThat(customerForm.field("email").constraints().get(0)._1).as( "field(\"email\").constraints(0)") .isEqualTo("constraint.email"); assertThat(customerForm.field("email").constraints().get(1)._1).as( "field(\"email\").constraints(1)").isEqualTo( "constraint.required"); // orders[0].date constraints assertThat(customerForm.field("orders[0].date").constraints().size()) .as("field(\"orders[0].date\").constraints().size()") .isEqualTo(1); assertThat(customerForm.field("orders[0].date").constraints().get(0)._1) .as("field(\"orders[0].date\").constraints(0)").isEqualTo( "constraint.required"); // orders[0].date format assertThat(customerForm.field("orders[0].date").format()._1).as( "field(\"orders[0].date\").format()._1").isEqualTo( "format.date"); assertThat(customerForm.field("orders[0].date").format()._2.toString()) .as("field(\"orders[0].date\").format()._2").isEqualTo( "[yyyy-MM-dd]"); // orders[0].items[0].qty constraints assertThat( customerForm.field("orders[0].items[0].qty").constraints() .size()).as( "field(\"orders[0].items[0].qty\").constraints().size()") .isEqualTo(2); assertThat( customerForm.field("orders[0].items[0].qty").constraints() .get(0)._1).as( "field(\"orders[0].items[0].qty\").constraints(0)").isEqualTo( "constraint.min"); assertThat( customerForm.field("orders[0].items[0].qty").constraints() .get(0)._2.toString()).as( "field(\"orders[0].items[0].qty\").constraints(0)._2") .isEqualTo("[1]"); assertThat( customerForm.field("orders[0].items[0].qty").constraints() .get(1)._1).as( "field(\"orders[0].items[0].qty\").constraints(1)").isEqualTo( "constraint.required"); // orders[0].items[0].productCode constraints assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().size()) .as("field(\"orders[0].items[0].productCode\").constraints().size()") .isEqualTo(2); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(0)._1).as( "field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo("constraint.pattern"); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(0)._2.size()).as( "field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo(1); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(0)._2.get(0)).as( "field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo("[A-Z]{4}-[0-9]{3,}"); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(1)._1).as( "field(\"orders[0].items[0].productCode\").constraints(1)") .isEqualTo("constraint.required"); // orders[0].items[0].deliveryDate constraints assertThat( customerForm.field("orders[0].items[0].deliveryDate") .constraints().size()) .as("field(\"orders[0].items[0].deliveryDate\").constraints().size()") .isEqualTo(0); // orders[0].items[0].deliveryDate format assertThat( customerForm.field("orders[0].items[0].deliveryDate").format()._1) .as("field(\"orders[0].items[0].deliveryDate\").format()._1") .isEqualTo("format.date"); assertThat( customerForm.field("orders[0].items[0].deliveryDate").format()._2 .toString()).as( "field(\"orders[0].items[0].deliveryDate\").format()._2") .isEqualTo("[yyyy-MM-dd]"); }
public void nestedConstraints() { Form<JCustomer> customerForm = new Form<JCustomer>(JCustomer.class); // email constraints assertThat(customerForm.field("email").constraints().size()).as( "field(\"email\").constraints().size()").isEqualTo(2); assertThat(customerForm.field("email").constraints().get(0)._1).as( "field(\"email\").constraints(0)") .isEqualTo("constraint.email"); assertThat(customerForm.field("email").constraints().get(1)._1).as( "field(\"email\").constraints(1)").isEqualTo( "constraint.required"); // orders[0].date constraints assertThat(customerForm.field("orders[0].date").constraints().size()) .as("field(\"orders[0].date\").constraints().size()") .isEqualTo(1); assertThat(customerForm.field("orders[0].date").constraints().get(0)._1) .as("field(\"orders[0].date\").constraints(0)").isEqualTo( "constraint.required"); // orders[0].date format assertThat(customerForm.field("orders[0].date").format()._1).as( "field(\"orders[0].date\").format()._1").isEqualTo( "format.date"); assertThat(customerForm.field("orders[0].date").format()._2.toString()) .as("field(\"orders[0].date\").format()._2").isEqualTo( "[yyyy-MM-dd]"); // orders[0].items[0].qty constraints assertThat( customerForm.field("orders[0].items[0].qty").constraints() .size()).as( "field(\"orders[0].items[0].qty\").constraints().size()") .isEqualTo(2); assertThat( customerForm.field("orders[0].items[0].qty").constraints() .get(0)._1).as( "field(\"orders[0].items[0].qty\").constraints(0)").isEqualTo( "constraint.min"); assertThat( customerForm.field("orders[0].items[0].qty").constraints() .get(0)._2.toString()).as( "field(\"orders[0].items[0].qty\").constraints(0)._2") .isEqualTo("[1]"); assertThat( customerForm.field("orders[0].items[0].qty").constraints() .get(1)._1).as( "field(\"orders[0].items[0].qty\").constraints(1)").isEqualTo( "constraint.required"); // orders[0].items[0].productCode constraints assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().size()) .as("field(\"orders[0].items[0].productCode\").constraints().size()") .isEqualTo(2); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(0)._1).as( "field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo("constraint.pattern"); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(0)._2.size()).as( "field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo(1); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(0)._2.get(0)).as( "field(\"orders[0].items[0].productCode\").constraints(0)") .isEqualTo("[A-Z]{4}-[0-9]{3,}"); assertThat( customerForm.field("orders[0].items[0].productCode") .constraints().get(1)._1).as( "field(\"orders[0].items[0].productCode\").constraints(1)") .isEqualTo("constraint.required"); // orders[0].items[0].deliveryDate constraints assertThat( customerForm.field("orders[0].items[0].deliveryDate") .constraints().size()) .as("field(\"orders[0].items[0].deliveryDate\").constraints().size()") .isEqualTo(0); // orders[0].items[0].deliveryDate format assertThat( customerForm.field("orders[0].items[0].deliveryDate").format()._1) .as("field(\"orders[0].items[0].deliveryDate\").format()._1") .isEqualTo("format.date"); assertThat( customerForm.field("orders[0].items[0].deliveryDate").format()._2 .toString()).as( "field(\"orders[0].items[0].deliveryDate\").format()._2") .isEqualTo("[yyyy-MM-dd]"); }
diff --git a/GPSTools/src/main/java/com/ijmacd/gpstools/mobile/DatabaseHelper.java b/GPSTools/src/main/java/com/ijmacd/gpstools/mobile/DatabaseHelper.java index 8c828c3..fb71e4e 100644 --- a/GPSTools/src/main/java/com/ijmacd/gpstools/mobile/DatabaseHelper.java +++ b/GPSTools/src/main/java/com/ijmacd/gpstools/mobile/DatabaseHelper.java @@ -1,91 +1,91 @@ package com.ijmacd.gpstools.mobile; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * Created with IntelliJ IDEA. * User: Iain * Date: 28/06/13 * Time: 12:35 * To change this template use File | Settings | File Templates. */ class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "GPSTools.db"; private static final int DATABASE_VERSION = 2; public static final String ID_COLUMN = "_id"; public static final String TYPE_COLUMN = "type"; public static final String ORDER_COLUMN = "child"; public static final String WIDTH_COLUMN = "width"; public static final String HEIGHT_COLUMN = "height"; public static final String UNITS_COLUMN = "units"; public static final String WIDGET_TABLE_NAME = "Widgets"; public static final String TRACK_TABLE_NAME = "Tracks"; public static final String TRACKPOINT_TABLE_NAME = "Trackpoints"; public static final String DATE_COLUMN = "date"; public static final String NAME_COLUMN = "name" ; public static final String DISTANCE_COLUMN = "distance"; public static final String DURATION_COLUMN = "duration"; public static final String TRACK_ID_COLUMN = "track_id"; public static final String LAT_COLUMN = "latitude"; public static final String LON_COLUMN = "longitude"; public static final String ALTITUDE_COLUMN = "altitude"; public static final String ACCURACY_COLUMN = "accuracy"; public static final String SPEED_COLUMN = "speed"; public static final String HEADING_COLUMN = "heading"; public static final String COMPLETE_COLUMN = "complete"; private static final String LOG_TAG = "GPSTools"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + WIDGET_TABLE_NAME + " (" + ID_COLUMN + " INTEGER PRIMARY KEY, " + ORDER_COLUMN + " INTEGER, " + TYPE_COLUMN + " INTEGER, " + WIDTH_COLUMN + " INTEGER, " + HEIGHT_COLUMN + " INTEGER, " + UNITS_COLUMN + " INTEGER" + ");"); db.execSQL("CREATE TABLE " + TRACK_TABLE_NAME + " (" + ID_COLUMN + " INTEGER PRIMARY KEY, " + DATE_COLUMN + " INTEGER, " + NAME_COLUMN + " INTEGER, " + DISTANCE_COLUMN + " INTEGER, " + - DURATION_COLUMN + " INTEGER" + + DURATION_COLUMN + " INTEGER, " + + COMPLETE_COLUMN + " INTEGER" + ");"); db.execSQL("CREATE TABLE " + TRACKPOINT_TABLE_NAME + " (" + ID_COLUMN + " INTEGER PRIMARY KEY, " + TRACK_ID_COLUMN + " INTEGER, " + DATE_COLUMN + " INTEGER, " + LAT_COLUMN + " REAL, " + LON_COLUMN + " REAL, " + ALTITUDE_COLUMN + " REAL, " + ACCURACY_COLUMN + " REAL, " + SPEED_COLUMN + " REAL, " + - HEADING_COLUMN + " INTEGER, " + - COMPLETE_COLUMN + " INTEGER" + + HEADING_COLUMN + " INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if(oldVersion < 2){ db.execSQL("ALTER TABLE " + TRACK_TABLE_NAME + " ADD COLUMN " + COMPLETE_COLUMN + " INTEGER"); db.execSQL("UPDATE " + TRACK_TABLE_NAME + " SET " + COMPLETE_COLUMN + " = 1"); Log.v(LOG_TAG, "Updated database version: " + oldVersion + " -> " + newVersion); }else { db.execSQL("DROP TABLE IF EXISTS " + WIDGET_TABLE_NAME + ", " + TRACK_TABLE_NAME + ", " + TRACKPOINT_TABLE_NAME); onCreate(db); } } }
false
true
public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + WIDGET_TABLE_NAME + " (" + ID_COLUMN + " INTEGER PRIMARY KEY, " + ORDER_COLUMN + " INTEGER, " + TYPE_COLUMN + " INTEGER, " + WIDTH_COLUMN + " INTEGER, " + HEIGHT_COLUMN + " INTEGER, " + UNITS_COLUMN + " INTEGER" + ");"); db.execSQL("CREATE TABLE " + TRACK_TABLE_NAME + " (" + ID_COLUMN + " INTEGER PRIMARY KEY, " + DATE_COLUMN + " INTEGER, " + NAME_COLUMN + " INTEGER, " + DISTANCE_COLUMN + " INTEGER, " + DURATION_COLUMN + " INTEGER" + ");"); db.execSQL("CREATE TABLE " + TRACKPOINT_TABLE_NAME + " (" + ID_COLUMN + " INTEGER PRIMARY KEY, " + TRACK_ID_COLUMN + " INTEGER, " + DATE_COLUMN + " INTEGER, " + LAT_COLUMN + " REAL, " + LON_COLUMN + " REAL, " + ALTITUDE_COLUMN + " REAL, " + ACCURACY_COLUMN + " REAL, " + SPEED_COLUMN + " REAL, " + HEADING_COLUMN + " INTEGER, " + COMPLETE_COLUMN + " INTEGER" + ");"); }
public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + WIDGET_TABLE_NAME + " (" + ID_COLUMN + " INTEGER PRIMARY KEY, " + ORDER_COLUMN + " INTEGER, " + TYPE_COLUMN + " INTEGER, " + WIDTH_COLUMN + " INTEGER, " + HEIGHT_COLUMN + " INTEGER, " + UNITS_COLUMN + " INTEGER" + ");"); db.execSQL("CREATE TABLE " + TRACK_TABLE_NAME + " (" + ID_COLUMN + " INTEGER PRIMARY KEY, " + DATE_COLUMN + " INTEGER, " + NAME_COLUMN + " INTEGER, " + DISTANCE_COLUMN + " INTEGER, " + DURATION_COLUMN + " INTEGER, " + COMPLETE_COLUMN + " INTEGER" + ");"); db.execSQL("CREATE TABLE " + TRACKPOINT_TABLE_NAME + " (" + ID_COLUMN + " INTEGER PRIMARY KEY, " + TRACK_ID_COLUMN + " INTEGER, " + DATE_COLUMN + " INTEGER, " + LAT_COLUMN + " REAL, " + LON_COLUMN + " REAL, " + ALTITUDE_COLUMN + " REAL, " + ACCURACY_COLUMN + " REAL, " + SPEED_COLUMN + " REAL, " + HEADING_COLUMN + " INTEGER" + ");"); }
diff --git a/src/cs437/som/visualization/GreenToRedHeat.java b/src/cs437/som/visualization/GreenToRedHeat.java index a59dc8f..35e7e0a 100644 --- a/src/cs437/som/visualization/GreenToRedHeat.java +++ b/src/cs437/som/visualization/GreenToRedHeat.java @@ -1,24 +1,24 @@ package cs437.som.visualization; import java.awt.Color; /** * A color progression from green (#00FF00) to red (#FF0000). */ public class GreenToRedHeat implements ColorProgression { private static final float GREEN_HUE_SCALE = 1.2f; private static final float CIRCLE_DEG = 360.0f; @Override public Color getColor(int intensity) { if (intensity < 0) return Color.green; else if (intensity > 100) return Color.red; else { - final float hue = ((100-intensity) * GREEN_HUE_SCALE) / CIRCLE_DEG; + final float hue = ((intensity) * GREEN_HUE_SCALE) / CIRCLE_DEG; final int rgb = Color.HSBtoRGB(hue, 1.0f, 1.0f); return new Color(rgb); } } }
true
true
public Color getColor(int intensity) { if (intensity < 0) return Color.green; else if (intensity > 100) return Color.red; else { final float hue = ((100-intensity) * GREEN_HUE_SCALE) / CIRCLE_DEG; final int rgb = Color.HSBtoRGB(hue, 1.0f, 1.0f); return new Color(rgb); } }
public Color getColor(int intensity) { if (intensity < 0) return Color.green; else if (intensity > 100) return Color.red; else { final float hue = ((intensity) * GREEN_HUE_SCALE) / CIRCLE_DEG; final int rgb = Color.HSBtoRGB(hue, 1.0f, 1.0f); return new Color(rgb); } }
diff --git a/AdamBots-FIRST-2013-Robot-Code/src/robot/sensors/RobotSensors.java b/AdamBots-FIRST-2013-Robot-Code/src/robot/sensors/RobotSensors.java index 6575b3c..c73bef8 100644 --- a/AdamBots-FIRST-2013-Robot-Code/src/robot/sensors/RobotSensors.java +++ b/AdamBots-FIRST-2013-Robot-Code/src/robot/sensors/RobotSensors.java @@ -1,233 +1,233 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package robot.sensors; import edu.wpi.first.wpilibj.*; import robot.RobotMain; /** * <p>Contains static instances of every sensor on the robot. Classes that * require input from sensors should access them through one of the instances * here; some sensors have been wrapped with a "Fancy" class, simplifying their * use elsewhere.</p> <p><h3>Additional Notes</h3> <ul> <li>The Axis Camera is * handled within RobotCamera.</li> <li>Pairs of Limit Switches are labeled with * either A or B, corresponding to "ABOVE" and "BELOW," respectively.</li> </ul> * </p> <p>Note that the Axis Camera is handled within RobotCamera.</p> * * @author Ben */ public class RobotSensors { //// CONSTANTS ------------------------------------------------------------- // TODO: Constants // Encoders (Distance Per Pulse) public static final double DPP_ENCODER_DRIVE_LEFT_INCHES = 1.0; // Inches public static final double DPP_ENCODER_DRIVE_RIGHT_INCHES = 1.0; // Inches public static final double DPP_ENCODER_WINCH = 1.0; // ? public static final double DPP_ENCODER_ELEVATOR = 1.0; // Degrees // Encoders (Degrees Per Inch) public static final double DPI_ENCODER_DRIVE_LEFT_DEGREES = 1.0; // Degrees Per Inch public static final double DPI_ENCODER_DRIVE_RIGHT_DEGREES = 1.0; // Degrees Per Inch // FancyCounters (Ticks Per Period) public static final int TPP_COUNTER_SHOOTER_ANGLE = 1; // ? public static final int TPP_COUNTER_SHOOTER_SPEED = 1; // ? // Gyro public static final double GYRO_VPDPS = 1.0; // Volts per Degree Per Second //// PORT CONSTANTS -------------------------------------------------------- // Card Constants (by card, not by slot) public static final int ANA1 = 1; public static final int DIO1 = 1; public static final int DIO2 = 2; public static final int SOL1 = 1; /** * Port constants for the competition bot. */ public static final class CompetitionBot { /** Analog Card 1 Port Constants. */ public static final class Analog { public static final int GYRO = 1; public static final int CONFIG_A = 2; public static final int CONFIG_B = 3; public static final int CONFIG_C = 4; } /** Digital Card 1 Port Constants. */ public static final class DigitalIn1 { public static final int LEFT_DRIVE_ENCODER_A = 1; public static final int LEFT_DRIVE_ENCODER_B = 2; public static final int RIGHT_DRIVE_ENCODER_A = 3; public static final int RIGHT_DRIVE_ENCODER_B = 4; public static final int WINCH_ENCODER_A = 5; public static final int WINCH_ENCODER_B = 6; public static final int WINCH_LIMIT_A = 7; public static final int WINCH_LIMIT_B = 8; public static final int ARM_LIMIT_A = 9; public static final int ARM_LIMIT_B = 10; public static final int SHOOTER_ANGLE_ENCODER = 11; public static final int ELEVATOR_LIMIT_A = 12; public static final int ELEVATOR_LIMIT_B = 13; public static final int SHOOTER_SPEED_ENCODER = 14; } /** Digital Card 2 Port Constants. */ public static final class DigitalIn2 { public static final int ELEVATOR_ENCODER_A = 1; public static final int ELEVATOR_ENCODER_B = 2; public static final int HOOK_LEFT_BASE_LIMIT = 5; public static final int HOOK_RIGHT_BASE_LIMIT = 6; public static final int DISC_ORIENTATION_LIMIT_A = 7; public static final int DISC_ORIENTATION_LIMIT_B = 8; public static final int SHOOTER_LIMIT_A = 9; public static final int SHOOTER_LIMIT_B = 10; public static final int PRESSURE_SWITCH = 11; } /** Digital Card 1 Serial Port Constants. */ public static final class DigitalSerial1 { public static final int ACCELEROMETER = 1; } } //// SENSOR INSTANCES ------------------------------------------------------ // Drive public static Encoder encoderDriveLeft; public static Encoder encoderDriveRight; // Winch public static Encoder encoderWinch; public static DigitalInput limitWinchA; public static DigitalInput limitWinchB; public static DigitalInput limitArmA; public static DigitalInput limitArmB; // Elevator public static Encoder encoderElevator; public static DigitalInput limitElevatorA; public static DigitalInput limitElevatorB; // Climb Hooks public static DigitalInput limitHookLeftBase; public static DigitalInput limitHookRightBase; // Chassis public static Gyro gyroChassis; public static Accelerometer accelerometerChassis; // ?? ?? Is this the right class? public static AnalogChannel configA; public static AnalogChannel configB; public static AnalogChannel configC; // Shooter public static FancyCounter counterShooterSpeed; public static FancyCounter counterShooterAngle; public static DigitalInput limitShooterA; public static DigitalInput limitShooterB; // Disc Pickup public static DigitalInput limitDiscTop; public static DigitalInput limitDiscBottom; // Compressor public static DigitalInput pressureSwitch; //// INITIALIZATION -------------------------------------------------------- /** * Instantiates all sensors handled by class. */ public static void init() { initCompetition(); // Configure configure(); } private static void initCompetition(){ //// ANALOG CARD ------------------------------------------------------- gyroChassis = new Gyro(ANA1, CompetitionBot.Analog.GYRO); //? configA = new AnalogChannel(ANA1, CompetitionBot.Analog.CONFIG_A); configB = new AnalogChannel(ANA1, CompetitionBot.Analog.CONFIG_B); configC = new AnalogChannel(ANA1, CompetitionBot.Analog.CONFIG_C); //// DIGITAL CARD 1 ---------------------------------------------------- encoderDriveLeft = new Encoder(DIO1, CompetitionBot.DigitalIn1.LEFT_DRIVE_ENCODER_A, DIO1, CompetitionBot.DigitalIn1.LEFT_DRIVE_ENCODER_B); encoderDriveRight = new Encoder(DIO1, CompetitionBot.DigitalIn1.RIGHT_DRIVE_ENCODER_A, DIO1, CompetitionBot.DigitalIn1.RIGHT_DRIVE_ENCODER_B); encoderWinch = new Encoder(DIO1, CompetitionBot.DigitalIn1.WINCH_ENCODER_A, DIO1, CompetitionBot.DigitalIn1.WINCH_ENCODER_B); limitWinchA = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.WINCH_LIMIT_A); limitWinchB = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.WINCH_LIMIT_B); limitArmA = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ARM_LIMIT_A); limitArmB = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ARM_LIMIT_B); limitElevatorA = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ELEVATOR_LIMIT_A); limitElevatorB = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ELEVATOR_LIMIT_B); counterShooterSpeed = new FancyCounter(DIO1, CompetitionBot.DigitalIn1.SHOOTER_SPEED_ENCODER, TPP_COUNTER_SHOOTER_SPEED); counterShooterAngle = new FancyCounter(DIO1, CompetitionBot.DigitalIn1.SHOOTER_ANGLE_ENCODER, TPP_COUNTER_SHOOTER_ANGLE); //// DIGITAL CARD 2 ---------------------------------------------------- - encoderElevator = new Encoder(DIO1, CompetitionBot.DigitalIn2.ELEVATOR_ENCODER_A, DIO2, CompetitionBot.DigitalIn2.ELEVATOR_ENCODER_B); + encoderElevator = new Encoder(DIO2, CompetitionBot.DigitalIn2.ELEVATOR_ENCODER_A, DIO2, CompetitionBot.DigitalIn2.ELEVATOR_ENCODER_B); encoderElevator.start(); limitHookLeftBase = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.HOOK_LEFT_BASE_LIMIT); limitHookRightBase = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.HOOK_RIGHT_BASE_LIMIT); limitDiscTop = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.DISC_ORIENTATION_LIMIT_A); limitDiscBottom = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.DISC_ORIENTATION_LIMIT_B); limitShooterA = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.SHOOTER_LIMIT_A); limitShooterB = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.SHOOTER_LIMIT_B); pressureSwitch = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.PRESSURE_SWITCH); //// DIGITAL SERIAL 1 // TODO: Accelerometer? } //// CONFIGURATION --------------------------------------------------------- private static void configure(){ // Encoders encoderDriveLeft.setDistancePerPulse(DPP_ENCODER_DRIVE_LEFT_INCHES); encoderDriveRight.setDistancePerPulse(DPP_ENCODER_DRIVE_RIGHT_INCHES); encoderWinch.setDistancePerPulse(DPP_ENCODER_WINCH); encoderElevator.setDistancePerPulse(DPP_ENCODER_ELEVATOR); //encoderDriveLeft.start(); //encoderDriveRight.start(); encoderWinch.start(); encoderElevator.start(); counterShooterAngle.start(); // Shooter Counters counterShooterAngle.setTicksPerPeriod(TPP_COUNTER_SHOOTER_ANGLE); counterShooterAngle.start(); counterShooterAngle.setMaxPeriod(10000); counterShooterAngle.setUpSourceEdge(true, false); // TODO: Determine Correct Values counterShooterSpeed.start(); counterShooterSpeed.setMaxPeriod(10000); counterShooterSpeed.setUpSourceEdge(true, false); // Gyro // TODO: Gyro Config? //gyroChassis.setSensitivity(GYRO_VPDPS); } }
true
true
private static void initCompetition(){ //// ANALOG CARD ------------------------------------------------------- gyroChassis = new Gyro(ANA1, CompetitionBot.Analog.GYRO); //? configA = new AnalogChannel(ANA1, CompetitionBot.Analog.CONFIG_A); configB = new AnalogChannel(ANA1, CompetitionBot.Analog.CONFIG_B); configC = new AnalogChannel(ANA1, CompetitionBot.Analog.CONFIG_C); //// DIGITAL CARD 1 ---------------------------------------------------- encoderDriveLeft = new Encoder(DIO1, CompetitionBot.DigitalIn1.LEFT_DRIVE_ENCODER_A, DIO1, CompetitionBot.DigitalIn1.LEFT_DRIVE_ENCODER_B); encoderDriveRight = new Encoder(DIO1, CompetitionBot.DigitalIn1.RIGHT_DRIVE_ENCODER_A, DIO1, CompetitionBot.DigitalIn1.RIGHT_DRIVE_ENCODER_B); encoderWinch = new Encoder(DIO1, CompetitionBot.DigitalIn1.WINCH_ENCODER_A, DIO1, CompetitionBot.DigitalIn1.WINCH_ENCODER_B); limitWinchA = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.WINCH_LIMIT_A); limitWinchB = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.WINCH_LIMIT_B); limitArmA = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ARM_LIMIT_A); limitArmB = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ARM_LIMIT_B); limitElevatorA = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ELEVATOR_LIMIT_A); limitElevatorB = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ELEVATOR_LIMIT_B); counterShooterSpeed = new FancyCounter(DIO1, CompetitionBot.DigitalIn1.SHOOTER_SPEED_ENCODER, TPP_COUNTER_SHOOTER_SPEED); counterShooterAngle = new FancyCounter(DIO1, CompetitionBot.DigitalIn1.SHOOTER_ANGLE_ENCODER, TPP_COUNTER_SHOOTER_ANGLE); //// DIGITAL CARD 2 ---------------------------------------------------- encoderElevator = new Encoder(DIO1, CompetitionBot.DigitalIn2.ELEVATOR_ENCODER_A, DIO2, CompetitionBot.DigitalIn2.ELEVATOR_ENCODER_B); encoderElevator.start(); limitHookLeftBase = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.HOOK_LEFT_BASE_LIMIT); limitHookRightBase = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.HOOK_RIGHT_BASE_LIMIT); limitDiscTop = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.DISC_ORIENTATION_LIMIT_A); limitDiscBottom = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.DISC_ORIENTATION_LIMIT_B); limitShooterA = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.SHOOTER_LIMIT_A); limitShooterB = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.SHOOTER_LIMIT_B); pressureSwitch = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.PRESSURE_SWITCH); //// DIGITAL SERIAL 1 // TODO: Accelerometer? }
private static void initCompetition(){ //// ANALOG CARD ------------------------------------------------------- gyroChassis = new Gyro(ANA1, CompetitionBot.Analog.GYRO); //? configA = new AnalogChannel(ANA1, CompetitionBot.Analog.CONFIG_A); configB = new AnalogChannel(ANA1, CompetitionBot.Analog.CONFIG_B); configC = new AnalogChannel(ANA1, CompetitionBot.Analog.CONFIG_C); //// DIGITAL CARD 1 ---------------------------------------------------- encoderDriveLeft = new Encoder(DIO1, CompetitionBot.DigitalIn1.LEFT_DRIVE_ENCODER_A, DIO1, CompetitionBot.DigitalIn1.LEFT_DRIVE_ENCODER_B); encoderDriveRight = new Encoder(DIO1, CompetitionBot.DigitalIn1.RIGHT_DRIVE_ENCODER_A, DIO1, CompetitionBot.DigitalIn1.RIGHT_DRIVE_ENCODER_B); encoderWinch = new Encoder(DIO1, CompetitionBot.DigitalIn1.WINCH_ENCODER_A, DIO1, CompetitionBot.DigitalIn1.WINCH_ENCODER_B); limitWinchA = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.WINCH_LIMIT_A); limitWinchB = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.WINCH_LIMIT_B); limitArmA = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ARM_LIMIT_A); limitArmB = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ARM_LIMIT_B); limitElevatorA = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ELEVATOR_LIMIT_A); limitElevatorB = new DigitalInput(DIO1, CompetitionBot.DigitalIn1.ELEVATOR_LIMIT_B); counterShooterSpeed = new FancyCounter(DIO1, CompetitionBot.DigitalIn1.SHOOTER_SPEED_ENCODER, TPP_COUNTER_SHOOTER_SPEED); counterShooterAngle = new FancyCounter(DIO1, CompetitionBot.DigitalIn1.SHOOTER_ANGLE_ENCODER, TPP_COUNTER_SHOOTER_ANGLE); //// DIGITAL CARD 2 ---------------------------------------------------- encoderElevator = new Encoder(DIO2, CompetitionBot.DigitalIn2.ELEVATOR_ENCODER_A, DIO2, CompetitionBot.DigitalIn2.ELEVATOR_ENCODER_B); encoderElevator.start(); limitHookLeftBase = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.HOOK_LEFT_BASE_LIMIT); limitHookRightBase = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.HOOK_RIGHT_BASE_LIMIT); limitDiscTop = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.DISC_ORIENTATION_LIMIT_A); limitDiscBottom = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.DISC_ORIENTATION_LIMIT_B); limitShooterA = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.SHOOTER_LIMIT_A); limitShooterB = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.SHOOTER_LIMIT_B); pressureSwitch = new DigitalInput(DIO2, CompetitionBot.DigitalIn2.PRESSURE_SWITCH); //// DIGITAL SERIAL 1 // TODO: Accelerometer? }
diff --git a/java/src/strings/RegexMatching.java b/java/src/strings/RegexMatching.java index 2f4bf3d..66b35b6 100644 --- a/java/src/strings/RegexMatching.java +++ b/java/src/strings/RegexMatching.java @@ -1,94 +1,94 @@ package strings; /** * Write a function to match a given string to a regular expression. * * '.' Matches any single character. '*' Matches zero or more of the preceding * element. * * The matching should cover the entire input string (not partial). * * Some examples: * * isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") * → false isMatch("aa", "a*") → true isMatch("aa", ".*") → true * isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true */ public class RegexMatching { public static boolean isMatch(String str, String regex) { if (str == null || regex == null) { return false; } return isMatch(str, 0, regex, 0); } private static boolean isMatch(String str, int strIndex, String regex, int regexIndex) { if (strIndex >= str.length() && regexIndex == regex.length()) { return true; } if (regexIndex == regex.length()) { return false; } char regexChar = regex.charAt(regexIndex); if (regexIndex < regex.length() - 1) { char nextRegexChar = regex.charAt(regexIndex + 1); if (nextRegexChar == '*') { // Check if we could skip this wild card and still match the // regex. if (isMatch(str, strIndex, regex, regexIndex + 2)) { return true; } // We could have clubbed the two for loops below into one, // but having a separate loop for the '.' character prevents // checking of the matching condition for every iteration, // because '.' matches any character. For 1,2,...,N // possible occurrences of the '.' character, we // recursively check if there is a regex match. if (regexChar == '.') { for (int wildCardMatcher = strIndex; wildCardMatcher < str .length(); wildCardMatcher++) { if (isMatch(str, wildCardMatcher + 1, regex, regexIndex + 2)) { return true; } } } // For 1,2,...,N possible occurrences of the current regex // character, we recursively check if there is a regex match. for (int wildCardMatcher = strIndex; wildCardMatcher < str .length() && str.charAt(wildCardMatcher) == regexChar; wildCardMatcher++) { if (isMatch(str, wildCardMatcher + 1, regex, regexIndex + 2)) { return true; } } return false; } } if (regexChar == '*') { - throw new RuntimeException("Invalid regex input."); + throw new IllegalArgumentException("Invalid regex input."); } // We need a concrete match for a single character now before we // recursively check the rest. So if there are no more characters left, // we bail out. if (strIndex >= str.length()) { return false; } if (regexChar == '.' || (regexChar == str.charAt(strIndex))) { return isMatch(str, strIndex + 1, regex, regexIndex + 1); } return false; } }
true
true
private static boolean isMatch(String str, int strIndex, String regex, int regexIndex) { if (strIndex >= str.length() && regexIndex == regex.length()) { return true; } if (regexIndex == regex.length()) { return false; } char regexChar = regex.charAt(regexIndex); if (regexIndex < regex.length() - 1) { char nextRegexChar = regex.charAt(regexIndex + 1); if (nextRegexChar == '*') { // Check if we could skip this wild card and still match the // regex. if (isMatch(str, strIndex, regex, regexIndex + 2)) { return true; } // We could have clubbed the two for loops below into one, // but having a separate loop for the '.' character prevents // checking of the matching condition for every iteration, // because '.' matches any character. For 1,2,...,N // possible occurrences of the '.' character, we // recursively check if there is a regex match. if (regexChar == '.') { for (int wildCardMatcher = strIndex; wildCardMatcher < str .length(); wildCardMatcher++) { if (isMatch(str, wildCardMatcher + 1, regex, regexIndex + 2)) { return true; } } } // For 1,2,...,N possible occurrences of the current regex // character, we recursively check if there is a regex match. for (int wildCardMatcher = strIndex; wildCardMatcher < str .length() && str.charAt(wildCardMatcher) == regexChar; wildCardMatcher++) { if (isMatch(str, wildCardMatcher + 1, regex, regexIndex + 2)) { return true; } } return false; } } if (regexChar == '*') { throw new RuntimeException("Invalid regex input."); } // We need a concrete match for a single character now before we // recursively check the rest. So if there are no more characters left, // we bail out. if (strIndex >= str.length()) { return false; } if (regexChar == '.' || (regexChar == str.charAt(strIndex))) { return isMatch(str, strIndex + 1, regex, regexIndex + 1); } return false; }
private static boolean isMatch(String str, int strIndex, String regex, int regexIndex) { if (strIndex >= str.length() && regexIndex == regex.length()) { return true; } if (regexIndex == regex.length()) { return false; } char regexChar = regex.charAt(regexIndex); if (regexIndex < regex.length() - 1) { char nextRegexChar = regex.charAt(regexIndex + 1); if (nextRegexChar == '*') { // Check if we could skip this wild card and still match the // regex. if (isMatch(str, strIndex, regex, regexIndex + 2)) { return true; } // We could have clubbed the two for loops below into one, // but having a separate loop for the '.' character prevents // checking of the matching condition for every iteration, // because '.' matches any character. For 1,2,...,N // possible occurrences of the '.' character, we // recursively check if there is a regex match. if (regexChar == '.') { for (int wildCardMatcher = strIndex; wildCardMatcher < str .length(); wildCardMatcher++) { if (isMatch(str, wildCardMatcher + 1, regex, regexIndex + 2)) { return true; } } } // For 1,2,...,N possible occurrences of the current regex // character, we recursively check if there is a regex match. for (int wildCardMatcher = strIndex; wildCardMatcher < str .length() && str.charAt(wildCardMatcher) == regexChar; wildCardMatcher++) { if (isMatch(str, wildCardMatcher + 1, regex, regexIndex + 2)) { return true; } } return false; } } if (regexChar == '*') { throw new IllegalArgumentException("Invalid regex input."); } // We need a concrete match for a single character now before we // recursively check the rest. So if there are no more characters left, // we bail out. if (strIndex >= str.length()) { return false; } if (regexChar == '.' || (regexChar == str.charAt(strIndex))) { return isMatch(str, strIndex + 1, regex, regexIndex + 1); } return false; }
diff --git a/core/src/main/java/hudson/StructuredForm.java b/core/src/main/java/hudson/StructuredForm.java index f457ae550..099d4eff9 100644 --- a/core/src/main/java/hudson/StructuredForm.java +++ b/core/src/main/java/hudson/StructuredForm.java @@ -1,74 +1,74 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import javax.servlet.ServletException; import java.util.Collections; import java.util.List; /** * Obtains the structured form data from {@link StaplerRequest}. * See http://hudson.gotdns.com/wiki/display/HUDSON/Structured+Form+Submission * * @author Kohsuke Kawaguchi */ public class StructuredForm { /** * @deprecated * Use {@link StaplerRequest#getSubmittedForm()}. Since 1.238. */ public static JSONObject get(StaplerRequest req) throws ServletException { return req.getSubmittedForm(); } /** * Retrieves the property of the given object and returns it as a list of {@link JSONObject}. * * <p> * If the value doesn't exist, this method returns an empty list. If the value is * a {@link JSONObject}, this method will return a singleton list. If it's a {@link JSONArray}, * the contents will be returned as a list. * * <p> * Because of the way structured form submission work, this is convenient way of * handling repeated multi-value entries. * * @since 1.233 */ public static List<JSONObject> toList(JSONObject parent, String propertyName) { Object v = parent.get(propertyName); if(v==null) return Collections.emptyList(); if(v instanceof JSONObject) return Collections.singletonList((JSONObject)v); if(v instanceof JSONArray) - return (JSONArray)v; + return (List)(JSONArray)v; throw new IllegalArgumentException(); } }
true
true
public static List<JSONObject> toList(JSONObject parent, String propertyName) { Object v = parent.get(propertyName); if(v==null) return Collections.emptyList(); if(v instanceof JSONObject) return Collections.singletonList((JSONObject)v); if(v instanceof JSONArray) return (JSONArray)v; throw new IllegalArgumentException(); }
public static List<JSONObject> toList(JSONObject parent, String propertyName) { Object v = parent.get(propertyName); if(v==null) return Collections.emptyList(); if(v instanceof JSONObject) return Collections.singletonList((JSONObject)v); if(v instanceof JSONArray) return (List)(JSONArray)v; throw new IllegalArgumentException(); }
diff --git a/src/me/guillaumin/android/osmtracker/db/TracklistAdapter.java b/src/me/guillaumin/android/osmtracker/db/TracklistAdapter.java index 37abbb5..06f9cff 100644 --- a/src/me/guillaumin/android/osmtracker/db/TracklistAdapter.java +++ b/src/me/guillaumin/android/osmtracker/db/TracklistAdapter.java @@ -1,93 +1,93 @@ package me.guillaumin.android.osmtracker.db; import me.guillaumin.android.osmtracker.R; import me.guillaumin.android.osmtracker.db.TrackContentProvider.Schema; import me.guillaumin.android.osmtracker.db.model.Track; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; /** * Adapter for track list in {@link me.guillaumin.android.osmtracker.activity.TrackManager Track Manager}. * For each row's contents, see <tt>tracklist_item.xml</tt>. * * @author Nicolas Guillaumin * */ public class TracklistAdapter extends CursorAdapter { public TracklistAdapter(Context context, Cursor c) { super(context, c); } @Override public void bindView(View view, Context context, Cursor cursor) { bind(cursor, view, context); } @Override public View newView(Context context, Cursor cursor, ViewGroup vg) { View view = LayoutInflater.from(vg.getContext()).inflate(R.layout.tracklist_item, vg, false); return view; } /** * Do the binding between data and item view. * * @param cursor * Cursor to pull data * @param v * RelativeView representing one item * @param context * Context, to get resources * @return The relative view with data bound. */ private View bind(Cursor cursor, View v, Context context) { TextView vId = (TextView) v.findViewById(R.id.trackmgr_item_id); TextView vNameOrStartDate = (TextView) v.findViewById(R.id.trackmgr_item_nameordate); TextView vWps = (TextView) v.findViewById(R.id.trackmgr_item_wps); TextView vTps = (TextView) v.findViewById(R.id.trackmgr_item_tps); ImageView vStatus = (ImageView) v.findViewById(R.id.trackmgr_item_statusicon); ImageView vUploadStatus = (ImageView) v.findViewById(R.id.trackmgr_item_upload_statusicon); // Is track active ? int active = cursor.getInt(cursor.getColumnIndex(Schema.COL_ACTIVE)); if (Schema.VAL_TRACK_ACTIVE == active) { // Yellow clock icon for Active vStatus.setImageResource(android.R.drawable.presence_away); vStatus.setVisibility(View.VISIBLE); } else if (cursor.isNull(cursor.getColumnIndex(Schema.COL_EXPORT_DATE))) { // Hide green circle icon: Track not yet exported - ((ViewGroup) v).removeView(vStatus); + vStatus.setVisibility(View.GONE); } else { // Show green circle icon (don't assume already visible with this drawable; may be a re-query) vStatus.setImageResource(android.R.drawable.presence_online); vStatus.setVisibility(View.VISIBLE); } // Upload status if (cursor.isNull(cursor.getColumnIndex(Schema.COL_OSM_UPLOAD_DATE))) { - ((ViewGroup) v).removeView(vUploadStatus); + vUploadStatus.setVisibility(View.GONE); } // Bind id long trackId = cursor.getLong(cursor.getColumnIndex(Schema.COL_ID)); String strTrackId = Long.toString(trackId); vId.setText("#" + strTrackId); // Bind WP count, TP count, name Track t = Track.build(trackId, cursor, context.getContentResolver(), false); vTps.setText(Integer.toString(t.getTpCount())); vWps.setText(Integer.toString(t.getWpCount())); vNameOrStartDate.setText(t.getName()); return v; } }
false
true
private View bind(Cursor cursor, View v, Context context) { TextView vId = (TextView) v.findViewById(R.id.trackmgr_item_id); TextView vNameOrStartDate = (TextView) v.findViewById(R.id.trackmgr_item_nameordate); TextView vWps = (TextView) v.findViewById(R.id.trackmgr_item_wps); TextView vTps = (TextView) v.findViewById(R.id.trackmgr_item_tps); ImageView vStatus = (ImageView) v.findViewById(R.id.trackmgr_item_statusicon); ImageView vUploadStatus = (ImageView) v.findViewById(R.id.trackmgr_item_upload_statusicon); // Is track active ? int active = cursor.getInt(cursor.getColumnIndex(Schema.COL_ACTIVE)); if (Schema.VAL_TRACK_ACTIVE == active) { // Yellow clock icon for Active vStatus.setImageResource(android.R.drawable.presence_away); vStatus.setVisibility(View.VISIBLE); } else if (cursor.isNull(cursor.getColumnIndex(Schema.COL_EXPORT_DATE))) { // Hide green circle icon: Track not yet exported ((ViewGroup) v).removeView(vStatus); } else { // Show green circle icon (don't assume already visible with this drawable; may be a re-query) vStatus.setImageResource(android.R.drawable.presence_online); vStatus.setVisibility(View.VISIBLE); } // Upload status if (cursor.isNull(cursor.getColumnIndex(Schema.COL_OSM_UPLOAD_DATE))) { ((ViewGroup) v).removeView(vUploadStatus); } // Bind id long trackId = cursor.getLong(cursor.getColumnIndex(Schema.COL_ID)); String strTrackId = Long.toString(trackId); vId.setText("#" + strTrackId); // Bind WP count, TP count, name Track t = Track.build(trackId, cursor, context.getContentResolver(), false); vTps.setText(Integer.toString(t.getTpCount())); vWps.setText(Integer.toString(t.getWpCount())); vNameOrStartDate.setText(t.getName()); return v; }
private View bind(Cursor cursor, View v, Context context) { TextView vId = (TextView) v.findViewById(R.id.trackmgr_item_id); TextView vNameOrStartDate = (TextView) v.findViewById(R.id.trackmgr_item_nameordate); TextView vWps = (TextView) v.findViewById(R.id.trackmgr_item_wps); TextView vTps = (TextView) v.findViewById(R.id.trackmgr_item_tps); ImageView vStatus = (ImageView) v.findViewById(R.id.trackmgr_item_statusicon); ImageView vUploadStatus = (ImageView) v.findViewById(R.id.trackmgr_item_upload_statusicon); // Is track active ? int active = cursor.getInt(cursor.getColumnIndex(Schema.COL_ACTIVE)); if (Schema.VAL_TRACK_ACTIVE == active) { // Yellow clock icon for Active vStatus.setImageResource(android.R.drawable.presence_away); vStatus.setVisibility(View.VISIBLE); } else if (cursor.isNull(cursor.getColumnIndex(Schema.COL_EXPORT_DATE))) { // Hide green circle icon: Track not yet exported vStatus.setVisibility(View.GONE); } else { // Show green circle icon (don't assume already visible with this drawable; may be a re-query) vStatus.setImageResource(android.R.drawable.presence_online); vStatus.setVisibility(View.VISIBLE); } // Upload status if (cursor.isNull(cursor.getColumnIndex(Schema.COL_OSM_UPLOAD_DATE))) { vUploadStatus.setVisibility(View.GONE); } // Bind id long trackId = cursor.getLong(cursor.getColumnIndex(Schema.COL_ID)); String strTrackId = Long.toString(trackId); vId.setText("#" + strTrackId); // Bind WP count, TP count, name Track t = Track.build(trackId, cursor, context.getContentResolver(), false); vTps.setText(Integer.toString(t.getTpCount())); vWps.setText(Integer.toString(t.getWpCount())); vNameOrStartDate.setText(t.getName()); return v; }
diff --git a/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/analysis/KMPlotForm.java b/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/analysis/KMPlotForm.java index 587ae5ed9..3cc70f9f8 100644 --- a/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/analysis/KMPlotForm.java +++ b/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/analysis/KMPlotForm.java @@ -1,181 +1,183 @@ /** * The software subject to this notice and license includes both human readable * source code form and machine readable, binary, object code form. The caArray * Software was developed in conjunction with the National Cancer Institute * (NCI) by NCI employees, 5AM Solutions, Inc. (5AM), ScenPro, Inc. (ScenPro) * and Science Applications International Corporation (SAIC). To the extent * government employees are authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * * This caArray Software License (the License) is between NCI and You. You (or * Your) shall mean a person or an entity, and all other entities that control, * are controlled by, or are under common control with the entity. Control for * purposes of this definition means (i) the direct or indirect power to cause * the direction or management of such entity, whether by contract or otherwise, * or (ii) ownership of fifty percent (50%) or more of the outstanding shares, * or (iii) beneficial ownership of such entity. * * This License is granted provided that You agree to the conditions described * below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up, * no-charge, irrevocable, transferable and royalty-free right and license in * its rights in the caArray Software to (i) use, install, access, operate, * execute, copy, modify, translate, market, publicly display, publicly perform, * and prepare derivative works of the caArray Software; (ii) distribute and * have distributed to and by third parties the caIntegrator Software and any * modifications and derivative works thereof; and (iii) sublicense the * foregoing rights set out in (i) and (ii) to third parties, including the * right to license such rights to further third parties. For sake of clarity, * and not by way of limitation, NCI shall have no right of accounting or right * of payment from You or Your sub-licensees for the rights granted under this * License. This License is granted at no charge to You. * * Your redistributions of the source code for the Software must retain the * above copyright notice, this list of conditions and the disclaimer and * limitation of liability of Article 6, below. Your redistributions in object * code form must reproduce the above copyright notice, this list of conditions * and the disclaimer of Article 6 in the documentation and/or other materials * provided with the distribution, if any. * * Your end-user documentation included with the redistribution, if any, must * include the following acknowledgment: This product includes software * developed by 5AM, ScenPro, SAIC and the National Cancer Institute. If You do * not include such end-user documentation, You shall include this acknowledgment * in the Software itself, wherever such third-party acknowledgments normally * appear. * * You may not use the names "The National Cancer Institute", "NCI", "ScenPro", * "SAIC" or "5AM" to endorse or promote products derived from this Software. * This License does not authorize You to use any trademarks, service marks, * trade names, logos or product names of either NCI, ScenPro, SAID or 5AM, * except as required to comply with the terms of this License. * * For sake of clarity, and not by way of limitation, You may incorporate this * Software into Your proprietary programs and into any third party proprietary * programs. However, if You incorporate the Software into third party * proprietary programs, You agree that You are solely responsible for obtaining * any permission from such third parties required to incorporate the Software * into such third party proprietary programs and for informing Your a * sub-licensees, including without limitation Your end-users, of their * obligation to secure any required permissions from such third parties before * incorporating the Software into such third party proprietary software * programs. In the event that You fail to obtain such permissions, You agree * to indemnify NCI for any claims against NCI by such third parties, except to * the extent prohibited by law, resulting from Your failure to obtain such * permissions. * * For sake of clarity, and not by way of limitation, You may add Your own * copyright statement to Your modifications and to the derivative works, and * You may provide additional or different license terms and conditions in Your * sublicenses of modifications of the Software, or any derivative works of the * Software as a whole, provided Your use, reproduction, and distribution of the * Work otherwise complies with the conditions stated in this License. * * THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, * (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO * EVENT SHALL THE NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC., SCENPRO, INC., * SCIENCE APPLICATIONS INTERNATIONAL CORPORATION OR THEIR * AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package gov.nih.nci.caintegrator2.web.action.analysis; import gov.nih.nci.caintegrator2.domain.annotation.SurvivalValueDefinition; import gov.nih.nci.caintegrator2.web.SessionHelper; import java.util.HashMap; import java.util.Map; /** * Holder for the different types of KM Plot Forms. */ public class KMPlotForm { private KMPlotAnnotationBasedActionForm annotationBasedForm = new KMPlotAnnotationBasedActionForm(); private KMPlotGeneExpressionBasedActionForm geneExpressionBasedForm = new KMPlotGeneExpressionBasedActionForm(); private KMPlotQueryBasedActionForm queryBasedForm = new KMPlotQueryBasedActionForm(); private Map<String, SurvivalValueDefinition> survivalValueDefinitions = new HashMap<String, SurvivalValueDefinition>(); private String survivalValueDefinitionId; /** * Clears all forms and the KM Plots out of the session. */ public void clear() { SessionHelper.clearKmPlots(); + survivalValueDefinitions.clear(); + survivalValueDefinitionId = null; annotationBasedForm.clear(); geneExpressionBasedForm.clear(); queryBasedForm.clear(); } /** * @return the annotationBasedForm */ public KMPlotAnnotationBasedActionForm getAnnotationBasedForm() { return annotationBasedForm; } /** * @param annotationBasedForm the annotationBasedForm to set */ public void setAnnotationBasedForm(KMPlotAnnotationBasedActionForm annotationBasedForm) { this.annotationBasedForm = annotationBasedForm; } /** * @return the survivalValueDefinitions */ public Map<String, SurvivalValueDefinition> getSurvivalValueDefinitions() { return survivalValueDefinitions; } /** * @param survivalValueDefinitions the survivalValueDefinitions to set */ public void setSurvivalValueDefinitions(Map<String, SurvivalValueDefinition> survivalValueDefinitions) { this.survivalValueDefinitions = survivalValueDefinitions; } /** * @return the survivalValueDefinitionId */ public String getSurvivalValueDefinitionId() { return survivalValueDefinitionId; } /** * @param survivalValueDefinitionId the survivalValueDefinitionId to set */ public void setSurvivalValueDefinitionId(String survivalValueDefinitionId) { this.survivalValueDefinitionId = survivalValueDefinitionId; } /** * @return the geneExpressionBasedForm */ public KMPlotGeneExpressionBasedActionForm getGeneExpressionBasedForm() { return geneExpressionBasedForm; } /** * @param geneExpressionBasedForm the geneExpressionBasedForm to set */ public void setGeneExpressionBasedForm(KMPlotGeneExpressionBasedActionForm geneExpressionBasedForm) { this.geneExpressionBasedForm = geneExpressionBasedForm; } /** * @return the queryBasedForm */ public KMPlotQueryBasedActionForm getQueryBasedForm() { return queryBasedForm; } /** * @param queryBasedForm the queryBasedForm to set */ public void setQueryBasedForm(KMPlotQueryBasedActionForm queryBasedForm) { this.queryBasedForm = queryBasedForm; } }
true
true
public void clear() { SessionHelper.clearKmPlots(); annotationBasedForm.clear(); geneExpressionBasedForm.clear(); queryBasedForm.clear(); }
public void clear() { SessionHelper.clearKmPlots(); survivalValueDefinitions.clear(); survivalValueDefinitionId = null; annotationBasedForm.clear(); geneExpressionBasedForm.clear(); queryBasedForm.clear(); }
diff --git a/svnkit-cli/src/org/tmatesoft/svn/cli/svn/SVNStatusPrinter.java b/svnkit-cli/src/org/tmatesoft/svn/cli/svn/SVNStatusPrinter.java index 8a61b8217..cd243c730 100644 --- a/svnkit-cli/src/org/tmatesoft/svn/cli/svn/SVNStatusPrinter.java +++ b/svnkit-cli/src/org/tmatesoft/svn/cli/svn/SVNStatusPrinter.java @@ -1,160 +1,157 @@ /* * ==================================================================== * Copyright (c) 2004-2009 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import org.tmatesoft.svn.core.internal.util.SVNFormatUtil; import org.tmatesoft.svn.core.internal.wc.SVNTreeConflictUtil; import org.tmatesoft.svn.core.internal.wc17.SVNStatus17; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNStatusPrinter { private SVNCommandEnvironment myEnvironment; public SVNStatusPrinter(SVNCommandEnvironment env) { myEnvironment = env; } public void printStatus(String path, SVNStatus status, boolean detailed, boolean showLastCommitted, boolean skipUnrecognized, boolean showReposLocks) { if (status == null || (skipUnrecognized && !(status.isVersioned() || status.getTreeConflict() != null)) || (status.getContentsStatus() == SVNStatusType.STATUS_NONE && status.getRemoteContentsStatus() == SVNStatusType.STATUS_NONE)) { return; } char treeStatusCode = ' '; String treeDescriptionLine = ""; if (status.getTreeConflict() != null) { String description = SVNTreeConflictUtil.getHumanReadableConflictDescription(status.getTreeConflict()); treeStatusCode = 'C'; treeDescriptionLine = "\n > " + description; } StringBuffer result = new StringBuffer(); if (detailed) { String wcRevision; char remoteStatus; if (!status.isVersioned()) { wcRevision = ""; } else if (status.isCopied()) { wcRevision = "-"; } else if (!status.getRevision().isValid()) { if(status.getStatus17()!=null) { SVNStatus17 status17 = status.getStatus17(); - if (status17.getNodeStatus() == SVNStatusType.STATUS_ADDED || - status17.getNodeStatus() == SVNStatusType.STATUS_REPLACED) - wcRevision = "0"; - else if(status17.getNodeStatus()==SVNStatusType.STATUS_DELETED) + if(status17.getNodeStatus()==SVNStatusType.STATUS_DELETED) wcRevision = Long.toString(status17.getChangedRev()); else - wcRevision = " - "; + wcRevision = "-"; } else - wcRevision = " ? "; + wcRevision = "?"; } else { wcRevision = Long.toString(status.getRevision().getNumber()); } if (status.getRemotePropertiesStatus() != SVNStatusType.STATUS_NONE || status.getRemoteContentsStatus() != SVNStatusType.STATUS_NONE) { remoteStatus = '*'; } else { remoteStatus = ' '; } char lockStatus; if (showReposLocks) { if (status.getRemoteLock() != null) { if (status.getLocalLock() != null) { lockStatus = status.getLocalLock().getID().equals(status.getRemoteLock().getID()) ? 'K' : 'T'; } else { lockStatus = 'O'; } } else if (status.getLocalLock() != null) { lockStatus = 'B'; } else { lockStatus = ' '; } } else { lockStatus = status.getLocalLock() != null ? 'K' : ' '; } if (showLastCommitted) { String commitRevision = ""; String commitAuthor = ""; if (status.isVersioned() && status.getCommittedRevision().isValid()) { commitRevision = status.getCommittedRevision().toString(); } else if (status.isVersioned()) { commitRevision = " ? "; } if (status.isVersioned() && status.getAuthor() != null) { commitAuthor = status.getAuthor(); } else if (status.isVersioned()) { commitAuthor = " ? "; } result.append(status.getContentsStatus().getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(lockStatus); result.append(treeStatusCode); // tree status result.append(" "); result.append(remoteStatus); result.append(" "); result.append(SVNFormatUtil.formatString(wcRevision, 6, false)); // 6 chars result.append(" "); result.append(SVNFormatUtil.formatString(commitRevision, 6, false)); // 6 chars result.append(" "); result.append(SVNFormatUtil.formatString(commitAuthor, 12, true)); // 12 chars result.append(" "); result.append(path); result.append(treeDescriptionLine); } else { result.append(status.getContentsStatus().getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(lockStatus); result.append(treeStatusCode); // tree status result.append(" "); result.append(remoteStatus); result.append(" "); result.append(SVNFormatUtil.formatString(wcRevision, 6, false)); // 6 chars result.append(" "); result.append(path); result.append(treeDescriptionLine); } } else { result.append(status.getContentsStatus().getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(status.getLocalLock() != null ? 'K' : ' '); result.append(treeStatusCode); // tree status result.append(" "); result.append(path); result.append(treeDescriptionLine); } myEnvironment.getOut().println(result); } private static char getSwitchCharacter(SVNStatus status) { if (status == null) { return ' '; } return status.isSwitched() ? 'S' : (status.isFileExternal() ? 'X' : ' '); } }
false
true
public void printStatus(String path, SVNStatus status, boolean detailed, boolean showLastCommitted, boolean skipUnrecognized, boolean showReposLocks) { if (status == null || (skipUnrecognized && !(status.isVersioned() || status.getTreeConflict() != null)) || (status.getContentsStatus() == SVNStatusType.STATUS_NONE && status.getRemoteContentsStatus() == SVNStatusType.STATUS_NONE)) { return; } char treeStatusCode = ' '; String treeDescriptionLine = ""; if (status.getTreeConflict() != null) { String description = SVNTreeConflictUtil.getHumanReadableConflictDescription(status.getTreeConflict()); treeStatusCode = 'C'; treeDescriptionLine = "\n > " + description; } StringBuffer result = new StringBuffer(); if (detailed) { String wcRevision; char remoteStatus; if (!status.isVersioned()) { wcRevision = ""; } else if (status.isCopied()) { wcRevision = "-"; } else if (!status.getRevision().isValid()) { if(status.getStatus17()!=null) { SVNStatus17 status17 = status.getStatus17(); if (status17.getNodeStatus() == SVNStatusType.STATUS_ADDED || status17.getNodeStatus() == SVNStatusType.STATUS_REPLACED) wcRevision = "0"; else if(status17.getNodeStatus()==SVNStatusType.STATUS_DELETED) wcRevision = Long.toString(status17.getChangedRev()); else wcRevision = " - "; } else wcRevision = " ? "; } else { wcRevision = Long.toString(status.getRevision().getNumber()); } if (status.getRemotePropertiesStatus() != SVNStatusType.STATUS_NONE || status.getRemoteContentsStatus() != SVNStatusType.STATUS_NONE) { remoteStatus = '*'; } else { remoteStatus = ' '; } char lockStatus; if (showReposLocks) { if (status.getRemoteLock() != null) { if (status.getLocalLock() != null) { lockStatus = status.getLocalLock().getID().equals(status.getRemoteLock().getID()) ? 'K' : 'T'; } else { lockStatus = 'O'; } } else if (status.getLocalLock() != null) { lockStatus = 'B'; } else { lockStatus = ' '; } } else { lockStatus = status.getLocalLock() != null ? 'K' : ' '; } if (showLastCommitted) { String commitRevision = ""; String commitAuthor = ""; if (status.isVersioned() && status.getCommittedRevision().isValid()) { commitRevision = status.getCommittedRevision().toString(); } else if (status.isVersioned()) { commitRevision = " ? "; } if (status.isVersioned() && status.getAuthor() != null) { commitAuthor = status.getAuthor(); } else if (status.isVersioned()) { commitAuthor = " ? "; } result.append(status.getContentsStatus().getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(lockStatus); result.append(treeStatusCode); // tree status result.append(" "); result.append(remoteStatus); result.append(" "); result.append(SVNFormatUtil.formatString(wcRevision, 6, false)); // 6 chars result.append(" "); result.append(SVNFormatUtil.formatString(commitRevision, 6, false)); // 6 chars result.append(" "); result.append(SVNFormatUtil.formatString(commitAuthor, 12, true)); // 12 chars result.append(" "); result.append(path); result.append(treeDescriptionLine); } else { result.append(status.getContentsStatus().getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(lockStatus); result.append(treeStatusCode); // tree status result.append(" "); result.append(remoteStatus); result.append(" "); result.append(SVNFormatUtil.formatString(wcRevision, 6, false)); // 6 chars result.append(" "); result.append(path); result.append(treeDescriptionLine); } } else { result.append(status.getContentsStatus().getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(status.getLocalLock() != null ? 'K' : ' '); result.append(treeStatusCode); // tree status result.append(" "); result.append(path); result.append(treeDescriptionLine); } myEnvironment.getOut().println(result); }
public void printStatus(String path, SVNStatus status, boolean detailed, boolean showLastCommitted, boolean skipUnrecognized, boolean showReposLocks) { if (status == null || (skipUnrecognized && !(status.isVersioned() || status.getTreeConflict() != null)) || (status.getContentsStatus() == SVNStatusType.STATUS_NONE && status.getRemoteContentsStatus() == SVNStatusType.STATUS_NONE)) { return; } char treeStatusCode = ' '; String treeDescriptionLine = ""; if (status.getTreeConflict() != null) { String description = SVNTreeConflictUtil.getHumanReadableConflictDescription(status.getTreeConflict()); treeStatusCode = 'C'; treeDescriptionLine = "\n > " + description; } StringBuffer result = new StringBuffer(); if (detailed) { String wcRevision; char remoteStatus; if (!status.isVersioned()) { wcRevision = ""; } else if (status.isCopied()) { wcRevision = "-"; } else if (!status.getRevision().isValid()) { if(status.getStatus17()!=null) { SVNStatus17 status17 = status.getStatus17(); if(status17.getNodeStatus()==SVNStatusType.STATUS_DELETED) wcRevision = Long.toString(status17.getChangedRev()); else wcRevision = "-"; } else wcRevision = "?"; } else { wcRevision = Long.toString(status.getRevision().getNumber()); } if (status.getRemotePropertiesStatus() != SVNStatusType.STATUS_NONE || status.getRemoteContentsStatus() != SVNStatusType.STATUS_NONE) { remoteStatus = '*'; } else { remoteStatus = ' '; } char lockStatus; if (showReposLocks) { if (status.getRemoteLock() != null) { if (status.getLocalLock() != null) { lockStatus = status.getLocalLock().getID().equals(status.getRemoteLock().getID()) ? 'K' : 'T'; } else { lockStatus = 'O'; } } else if (status.getLocalLock() != null) { lockStatus = 'B'; } else { lockStatus = ' '; } } else { lockStatus = status.getLocalLock() != null ? 'K' : ' '; } if (showLastCommitted) { String commitRevision = ""; String commitAuthor = ""; if (status.isVersioned() && status.getCommittedRevision().isValid()) { commitRevision = status.getCommittedRevision().toString(); } else if (status.isVersioned()) { commitRevision = " ? "; } if (status.isVersioned() && status.getAuthor() != null) { commitAuthor = status.getAuthor(); } else if (status.isVersioned()) { commitAuthor = " ? "; } result.append(status.getContentsStatus().getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(lockStatus); result.append(treeStatusCode); // tree status result.append(" "); result.append(remoteStatus); result.append(" "); result.append(SVNFormatUtil.formatString(wcRevision, 6, false)); // 6 chars result.append(" "); result.append(SVNFormatUtil.formatString(commitRevision, 6, false)); // 6 chars result.append(" "); result.append(SVNFormatUtil.formatString(commitAuthor, 12, true)); // 12 chars result.append(" "); result.append(path); result.append(treeDescriptionLine); } else { result.append(status.getContentsStatus().getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(lockStatus); result.append(treeStatusCode); // tree status result.append(" "); result.append(remoteStatus); result.append(" "); result.append(SVNFormatUtil.formatString(wcRevision, 6, false)); // 6 chars result.append(" "); result.append(path); result.append(treeDescriptionLine); } } else { result.append(status.getContentsStatus().getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(status.getLocalLock() != null ? 'K' : ' '); result.append(treeStatusCode); // tree status result.append(" "); result.append(path); result.append(treeDescriptionLine); } myEnvironment.getOut().println(result); }
diff --git a/src/Ficha.java b/src/Ficha.java index ac371c8..c4eec08 100755 --- a/src/Ficha.java +++ b/src/Ficha.java @@ -1,163 +1,163 @@ import java.awt.BorderLayout; import java.awt.Color; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; /** * @author (Luis Ballinas, Gabriel Ramos Olvera, Fernando Gomez, Francisco * Barros) * @version (9/13/2013) */ public class Ficha extends JLabel { private ImageIcon fondoFicha; private Posicion posicion; CuadroTablero cuadro; protected ArrayList<Posicion> posiblesMovs; public final static String FICHA_A = "src/atomic/images/fichas_A.png"; public final static String FICHA_B = "src/atomic/images/fichas_B.png"; public Ficha(String imagenFicha, Posicion posicion) { super(new ImageIcon(imagenFicha)); this.posicion = posicion; this.fondoFicha = new ImageIcon(imagenFicha); } // Métodos de instancia public void mover(int posicionX, int posicionY) { } public void comerFicha(int posicionX, int posicionY) { } // Getters & Setters public Posicion getPosicion() { return posicion; } public void setPosicion(Posicion posicion) { this.posicion = posicion; } public ArrayList<Posicion> getPosiblesMovs() { return posiblesMovs; } public void setPosiblesMovs(ArrayList<Posicion> posiblesMovs) { this.posiblesMovs = posiblesMovs; } void determinarPosiblesMovimientos() { // Posibles movimientos por defecto (aún sin validar si hay fichas en las posiciones posibles // a mover ni si puede comer o no) ArrayList<Posicion> posiblesMovs = new ArrayList<Posicion>(); this.posiblesMovs = posiblesMovs; int incrementoY = 0; // Si es una FichaA, entonces sólo se puede mover hacia abajo if (this instanceof FichaB) { incrementoY = 1; } else if (this instanceof FichaA) { // Si es una FichaB, entonces sólo se puede mover hacia arriba incrementoY = -1; } // Movimientos en diagonal de sólo un brinco int incrementoX = 0; if (posicion.getX() > 1 && posicion.getX() < 8) { // Se puede mover tanto en diagonal izquierda como diagonal derecha incrementoX = 1; posiblesMovs.add(new Posicion(posicion.getX() - 1, posicion.getY() + incrementoY)); } else if (posicion.getX() == 1) { // Sólo se puede mover en diagonal derecha incrementoX = 1; } else if (posicion.getX() == 8) { // Sólo se puede mover en diagonal izquierda incrementoX = -1; } posiblesMovs.add(new Posicion(posicion.getX() + incrementoX, posicion.getY() + incrementoY)); ArrayList<Posicion> movsAEliminar = new ArrayList<Posicion>(); // Determinar si hay ficha dentro de los posibles movimientos ArrayList<Posicion> movsAComer = new ArrayList<Posicion>(); for (Posicion p : posiblesMovs) { int x = p.getX(); int y = p.getY(); CuadroTablero cuadro = Tablero.cuadros[x - 1][y - 1]; // Si hay ficha entonces determinar si se puede comer o no if (cuadro.hayFicha()) { if (cuadro.getFicha().getClass() == this.getClass()) { // Son del mismo tipo, no se puede comer. Se eliminan los posibles movs movsAEliminar.add(p); } else { // No son del mismo tipo, tal vez puede comer // Determinar si existe un cuadro vacío en diagonal a la ficha // que tal vez que pueda comer // Determinar si es que puede comer hacia la derecha o izquierda int incrementoX2 = 0; if (x < posicion.getX()) { incrementoX2 = -1; } else { incrementoX2 = 1; } int x2 = x + incrementoX2; int y2 = y + incrementoY; // Validación para bordes - if (x2 >= 1 && x2 <= 8) { + if (x2 >= 1 && x2 <= 8 && y2 >= 1 && y2 <= 8) { // Puede comer hacia la izquierda if (!Tablero.cuadros[x2 - 1][y2 - 1].hayFicha()) { // Puede comer System.out.println("ESTÁ VACÍA. PUEDE COMER"); movsAEliminar.add(p); movsAComer.add(new Posicion(x2, y2)); } else { // No puede comer, eliminar posible mov movsAEliminar.add(p); } } else { // No puede comer, eliminar posible mov movsAEliminar.add(p); } } } } // Añadir los movimientos posibles a comer ficha for (Posicion p : movsAComer) { posiblesMovs.add(p); } // Eliminar movimientos inválidos for (Posicion p : movsAEliminar) { posiblesMovs.remove(p); } // Resaltar cuadros a los que puede mover if (posiblesMovs.size() > 0) { System.out.println("POSIBLES MOVS:"); for (Posicion p : posiblesMovs) { System.out.println(p); CuadroTablero cuadro = Tablero.cuadros[p.getX() - 1][p.getY() - 1]; cuadro.setBackground(Color.GREEN); } } else { System.out.println("NO HAY POSIBLES MOVS, ENVIAR AVISO"); JOptionPane.showMessageDialog(this, "NO HAY POSIBLES MOVIMIENTOS PARA ESTA FICHA"); } } public CuadroTablero getCuadro() { return cuadro; } public void setCuadro(CuadroTablero cuadro) { this.cuadro = cuadro; } }
true
true
void determinarPosiblesMovimientos() { // Posibles movimientos por defecto (aún sin validar si hay fichas en las posiciones posibles // a mover ni si puede comer o no) ArrayList<Posicion> posiblesMovs = new ArrayList<Posicion>(); this.posiblesMovs = posiblesMovs; int incrementoY = 0; // Si es una FichaA, entonces sólo se puede mover hacia abajo if (this instanceof FichaB) { incrementoY = 1; } else if (this instanceof FichaA) { // Si es una FichaB, entonces sólo se puede mover hacia arriba incrementoY = -1; } // Movimientos en diagonal de sólo un brinco int incrementoX = 0; if (posicion.getX() > 1 && posicion.getX() < 8) { // Se puede mover tanto en diagonal izquierda como diagonal derecha incrementoX = 1; posiblesMovs.add(new Posicion(posicion.getX() - 1, posicion.getY() + incrementoY)); } else if (posicion.getX() == 1) { // Sólo se puede mover en diagonal derecha incrementoX = 1; } else if (posicion.getX() == 8) { // Sólo se puede mover en diagonal izquierda incrementoX = -1; } posiblesMovs.add(new Posicion(posicion.getX() + incrementoX, posicion.getY() + incrementoY)); ArrayList<Posicion> movsAEliminar = new ArrayList<Posicion>(); // Determinar si hay ficha dentro de los posibles movimientos ArrayList<Posicion> movsAComer = new ArrayList<Posicion>(); for (Posicion p : posiblesMovs) { int x = p.getX(); int y = p.getY(); CuadroTablero cuadro = Tablero.cuadros[x - 1][y - 1]; // Si hay ficha entonces determinar si se puede comer o no if (cuadro.hayFicha()) { if (cuadro.getFicha().getClass() == this.getClass()) { // Son del mismo tipo, no se puede comer. Se eliminan los posibles movs movsAEliminar.add(p); } else { // No son del mismo tipo, tal vez puede comer // Determinar si existe un cuadro vacío en diagonal a la ficha // que tal vez que pueda comer // Determinar si es que puede comer hacia la derecha o izquierda int incrementoX2 = 0; if (x < posicion.getX()) { incrementoX2 = -1; } else { incrementoX2 = 1; } int x2 = x + incrementoX2; int y2 = y + incrementoY; // Validación para bordes if (x2 >= 1 && x2 <= 8) { // Puede comer hacia la izquierda if (!Tablero.cuadros[x2 - 1][y2 - 1].hayFicha()) { // Puede comer System.out.println("ESTÁ VACÍA. PUEDE COMER"); movsAEliminar.add(p); movsAComer.add(new Posicion(x2, y2)); } else { // No puede comer, eliminar posible mov movsAEliminar.add(p); } } else { // No puede comer, eliminar posible mov movsAEliminar.add(p); } } } } // Añadir los movimientos posibles a comer ficha for (Posicion p : movsAComer) { posiblesMovs.add(p); } // Eliminar movimientos inválidos for (Posicion p : movsAEliminar) { posiblesMovs.remove(p); } // Resaltar cuadros a los que puede mover if (posiblesMovs.size() > 0) { System.out.println("POSIBLES MOVS:"); for (Posicion p : posiblesMovs) { System.out.println(p); CuadroTablero cuadro = Tablero.cuadros[p.getX() - 1][p.getY() - 1]; cuadro.setBackground(Color.GREEN); } } else { System.out.println("NO HAY POSIBLES MOVS, ENVIAR AVISO"); JOptionPane.showMessageDialog(this, "NO HAY POSIBLES MOVIMIENTOS PARA ESTA FICHA"); } }
void determinarPosiblesMovimientos() { // Posibles movimientos por defecto (aún sin validar si hay fichas en las posiciones posibles // a mover ni si puede comer o no) ArrayList<Posicion> posiblesMovs = new ArrayList<Posicion>(); this.posiblesMovs = posiblesMovs; int incrementoY = 0; // Si es una FichaA, entonces sólo se puede mover hacia abajo if (this instanceof FichaB) { incrementoY = 1; } else if (this instanceof FichaA) { // Si es una FichaB, entonces sólo se puede mover hacia arriba incrementoY = -1; } // Movimientos en diagonal de sólo un brinco int incrementoX = 0; if (posicion.getX() > 1 && posicion.getX() < 8) { // Se puede mover tanto en diagonal izquierda como diagonal derecha incrementoX = 1; posiblesMovs.add(new Posicion(posicion.getX() - 1, posicion.getY() + incrementoY)); } else if (posicion.getX() == 1) { // Sólo se puede mover en diagonal derecha incrementoX = 1; } else if (posicion.getX() == 8) { // Sólo se puede mover en diagonal izquierda incrementoX = -1; } posiblesMovs.add(new Posicion(posicion.getX() + incrementoX, posicion.getY() + incrementoY)); ArrayList<Posicion> movsAEliminar = new ArrayList<Posicion>(); // Determinar si hay ficha dentro de los posibles movimientos ArrayList<Posicion> movsAComer = new ArrayList<Posicion>(); for (Posicion p : posiblesMovs) { int x = p.getX(); int y = p.getY(); CuadroTablero cuadro = Tablero.cuadros[x - 1][y - 1]; // Si hay ficha entonces determinar si se puede comer o no if (cuadro.hayFicha()) { if (cuadro.getFicha().getClass() == this.getClass()) { // Son del mismo tipo, no se puede comer. Se eliminan los posibles movs movsAEliminar.add(p); } else { // No son del mismo tipo, tal vez puede comer // Determinar si existe un cuadro vacío en diagonal a la ficha // que tal vez que pueda comer // Determinar si es que puede comer hacia la derecha o izquierda int incrementoX2 = 0; if (x < posicion.getX()) { incrementoX2 = -1; } else { incrementoX2 = 1; } int x2 = x + incrementoX2; int y2 = y + incrementoY; // Validación para bordes if (x2 >= 1 && x2 <= 8 && y2 >= 1 && y2 <= 8) { // Puede comer hacia la izquierda if (!Tablero.cuadros[x2 - 1][y2 - 1].hayFicha()) { // Puede comer System.out.println("ESTÁ VACÍA. PUEDE COMER"); movsAEliminar.add(p); movsAComer.add(new Posicion(x2, y2)); } else { // No puede comer, eliminar posible mov movsAEliminar.add(p); } } else { // No puede comer, eliminar posible mov movsAEliminar.add(p); } } } } // Añadir los movimientos posibles a comer ficha for (Posicion p : movsAComer) { posiblesMovs.add(p); } // Eliminar movimientos inválidos for (Posicion p : movsAEliminar) { posiblesMovs.remove(p); } // Resaltar cuadros a los que puede mover if (posiblesMovs.size() > 0) { System.out.println("POSIBLES MOVS:"); for (Posicion p : posiblesMovs) { System.out.println(p); CuadroTablero cuadro = Tablero.cuadros[p.getX() - 1][p.getY() - 1]; cuadro.setBackground(Color.GREEN); } } else { System.out.println("NO HAY POSIBLES MOVS, ENVIAR AVISO"); JOptionPane.showMessageDialog(this, "NO HAY POSIBLES MOVIMIENTOS PARA ESTA FICHA"); } }
diff --git a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/URIParameter.java b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/URIParameter.java index b8d0dadaa..81cc58805 100644 --- a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/URIParameter.java +++ b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/URIParameter.java @@ -1,146 +1,151 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo 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. * * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.foundation.viewpoint; import java.lang.reflect.Type; import java.util.Vector; import org.openflexo.antar.binding.BindingDefinition; import org.openflexo.antar.binding.BindingDefinition.BindingDefinitionType; import org.openflexo.antar.expr.Expression; import org.openflexo.antar.expr.TypeMismatchException; import org.openflexo.antar.expr.Variable; import org.openflexo.antar.expr.parser.ParseException; import org.openflexo.foundation.view.action.EditionSchemeAction; import org.openflexo.foundation.viewpoint.binding.ViewPointDataBinding; import org.openflexo.toolbox.JavaUtils; import org.openflexo.toolbox.StringUtils; public class URIParameter extends EditionSchemeParameter { private ViewPointDataBinding baseURI; private BindingDefinition BASE_URI = new BindingDefinition("baseURI", String.class, BindingDefinitionType.GET, false); public BindingDefinition getBaseURIBindingDefinition() { return BASE_URI; } public ViewPointDataBinding getBaseURI() { if (baseURI == null) { baseURI = new ViewPointDataBinding(this, ParameterBindingAttribute.baseURI, getBaseURIBindingDefinition()); } return baseURI; } public void setBaseURI(ViewPointDataBinding baseURI) { baseURI.setOwner(this); baseURI.setBindingAttribute(ParameterBindingAttribute.baseURI); baseURI.setBindingDefinition(getBaseURIBindingDefinition()); this.baseURI = baseURI; } @Override public Type getType() { return String.class; } @Override public WidgetType getWidget() { return WidgetType.URI; } @Override public boolean isMandatory() { return true; } @Override public boolean isValid(EditionSchemeAction action, Object value) { if (!(value instanceof String)) { return false; } String proposedURI = (String) value; if (StringUtils.isEmpty(proposedURI)) { return false; } if (action.getProject().getProjectOntologyLibrary().isDuplicatedURI(action.getProject().getProjectOntology().getURI(), proposedURI)) { // declared_uri_must_be_unique_please_choose_an_other_uri return false; } else if (!action.getProject().getProjectOntologyLibrary() .testValidURI(action.getProject().getProjectOntology().getURI(), proposedURI)) { // declared_uri_is_not_well_formed_please_choose_an_other_uri return false; } return true; } @Override public Object getDefaultValue(EditionSchemeAction<?> action) { if (getBaseURI().isValid()) { String baseProposal = (String) getBaseURI().getBindingValue(action); if (baseProposal == null) { return null; } baseProposal = JavaUtils.getClassName(baseProposal); String proposal = baseProposal; Integer i = null; while (action.getProject().getProjectOntologyLibrary() .isDuplicatedURI(action.getProject().getProjectOntology().getURI(), proposal)) { if (i == null) { i = 1; } else { i++; } proposal = baseProposal + i; } return proposal; } return null; } public Vector<EditionSchemeParameter> getDependancies() { if (getBaseURI().isSet() && getBaseURI().isValid()) { Vector<EditionSchemeParameter> returned = new Vector<EditionSchemeParameter>(); try { Vector<Variable> variables = Expression.extractVariables(getBaseURI().toString()); for (Variable v : variables) { EditionSchemeParameter p = getScheme().getParameter(v.getName()); if (p != null) { returned.add(p); + } else { + p = getScheme().getParameter(v.getName().substring(0, v.getName().indexOf("."))); + if (p != null) { + returned.add(p); + } } } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TypeMismatchException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returned; } else { return null; } } }
true
true
public Vector<EditionSchemeParameter> getDependancies() { if (getBaseURI().isSet() && getBaseURI().isValid()) { Vector<EditionSchemeParameter> returned = new Vector<EditionSchemeParameter>(); try { Vector<Variable> variables = Expression.extractVariables(getBaseURI().toString()); for (Variable v : variables) { EditionSchemeParameter p = getScheme().getParameter(v.getName()); if (p != null) { returned.add(p); } } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TypeMismatchException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returned; } else { return null; } }
public Vector<EditionSchemeParameter> getDependancies() { if (getBaseURI().isSet() && getBaseURI().isValid()) { Vector<EditionSchemeParameter> returned = new Vector<EditionSchemeParameter>(); try { Vector<Variable> variables = Expression.extractVariables(getBaseURI().toString()); for (Variable v : variables) { EditionSchemeParameter p = getScheme().getParameter(v.getName()); if (p != null) { returned.add(p); } else { p = getScheme().getParameter(v.getName().substring(0, v.getName().indexOf("."))); if (p != null) { returned.add(p); } } } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TypeMismatchException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returned; } else { return null; } }
diff --git a/src/algorithms/Denclue.java b/src/algorithms/Denclue.java index 912f522..ebf605e 100644 --- a/src/algorithms/Denclue.java +++ b/src/algorithms/Denclue.java @@ -1,271 +1,271 @@ package algorithms; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import structures.Clusters; import structures.HyperCube; import structures.HyperSpace; import structures.Point; import structures.Points; public class Denclue extends ClusteringAlgorithm { private final double SIGMA = 0.7; private final int MIN_PNT = 5; private final Set<Point> unvisited = Collections.newSetFromMap(new ConcurrentHashMap<Point, Boolean>()); private final HyperSpace hyperspace = new HyperSpace(SIGMA, MIN_PNT); private final Map<Point, Points> attractorsWithPoints = new HashMap<Point, Points>(); public Denclue(Points input) { super(input); } @Override public Clusters getClusters() { final Clusters clusters = new Clusters(); unvisited.addAll(input); // System.out.println("Get populated cubes"); detPopulatedCubes(); // System.out.println("Get highly populated cubes and create their connection map"); hyperspace.connectMap(); // System.out.println("Find density attractors"); detDensAttractors(); // System.out.println("Find paths between attractors"); while (mergeClusters()) { ; } for (final Point point : attractorsWithPoints.keySet()) { if (attractorsWithPoints.get(point).size() > MIN_PNT) { clusters.add(attractorsWithPoints.get(point)); } } return clusters; } private boolean mergeClusters() { for (final Point p1 : attractorsWithPoints.keySet()) { for (final Point p2 : attractorsWithPoints.keySet()) { if (!p1.params.equals(p2.params)) { if (pathBetweenExists(p1, attractorsWithPoints.get(p1), p2, attractorsWithPoints.get(p2))) { final Points union_points = new Points(); final Point union_point = p1; union_points.addAll(attractorsWithPoints.get(p1)); union_points.addAll(attractorsWithPoints.get(p2)); attractorsWithPoints.remove(p1); attractorsWithPoints.remove(p2); attractorsWithPoints.put(union_point, union_points); return true; } } } } return false; } private void detPopulatedCubes() { for (final Point point : unvisited) { hyperspace.addPoint(point); unvisited.remove(point); } } private Clusters detDensAttractors() { for (final HyperCube cube : hyperspace.map.values()) { for (final Point point : cube.points) { point.density = calculateDensity(point); final Point densityPoint = getDensityAttractor(point); if (!attractorsWithPoints.containsValue(densityPoint)) { final Points points = new Points(); points.add(point); attractorsWithPoints.put(densityPoint, points); } } } return null; } /** Calculate the influence of an entity in another. I(x,y) = exp { - [distance(x,y)**2] / [2*(sigma**2)] } */ private double calculateInfluence(Point point1, Point point2) { final double distance = point1.distanceTo(point2); if (distance == 0) { return 0; // Influence is zero if entities are the same } final double exponent = -(distance * distance) / (2.0 * (SIGMA * SIGMA)); final double influence = Math.exp(exponent); return influence; } /** Calculate the density in an entity. It's defined as the sum of the influence of each another entity of dataset. */ private double calculateDensity(Point point) { double density = 0.0; for (final HyperCube cube : hyperspace.map.values()) { for (final Point p : cube.points) { density += calculateInfluence(point, p); } } return density; } /** Calculate gradient of density functions in a given spatial point. */ private double[] calculateGradient(Point point) { final double[] gradient = new double[point.params.length]; // Iterate over all entities and calculate the factors of gradient for (final HyperCube cube : hyperspace.map.values()) { for (final Point other_point : cube.points) { final double curr_influence = calculateInfluence(point, other_point); // Calculate the gradient function for each dimension of data for (int i = 0; i < point.params.length; i++) { final double curr_difference = other_point.params[i] - point.params[i]; gradient[i] += curr_difference * curr_influence; } } } return gradient; } /** Find density-attractor for an entity (a hill climbing algorithm). */ private Point getDensityAttractor(Point point) { final double delta = 1; - Point curr_attractor = point; + Point curr_attractor = new Point(point.params, point.clusterId); Point found_attractor = null; int MAX_ITERATIONS = 5; Boolean reachedTop = false; do { // Avoid infinite loops if (--MAX_ITERATIONS <= 0) { break; } // Store last calculated values for further comparison final Point last_attractor = curr_attractor; // Calculate the gradient of density function at current candidate to attractor final double[] curr_gradient = calculateGradient(last_attractor); // Build an entity to represent the gradient final Point grad_point = new Point(curr_gradient, 0); // Calculate next candidate to attractor final double grad_entity_norm = grad_point.getEuclideanNorm(); // if( grad_entity_norm < 0 ) // System.out.println("\n\n\n>>>>>\n\n\n"); curr_attractor = last_attractor; for (int i = 0; i < curr_gradient.length; i++) { curr_attractor.params[i] += delta / grad_entity_norm * grad_point.params[i]; } // Calculate density in current attractor final double curr_density = calculateDensity(curr_attractor); curr_attractor.density = curr_density; // Verify whether local maxima was found reachedTop = curr_attractor.density < last_attractor.density; if (reachedTop) { found_attractor = last_attractor; } } while (!reachedTop); if (MAX_ITERATIONS <= 0) { found_attractor = curr_attractor; } // System.out.println(MAX_ITERATIONS +"\t"+ Arrays.toString(found_attractor.params)); return found_attractor; } /** Find path between two attractors. */ private Boolean pathBetweenExists(Point point1, Points points1, Point point2, Points points2) { final Map<Point, Boolean> usedEntities = new HashMap<Point, Boolean>(); usedEntities.put(point1, true); usedEntities.put(point2, true); // If the distance between points <= sigma, a path exist if (point1.distanceTo(point2) <= SIGMA) { return true; } for (final Point dependent_point1 : points1) { for (final Point dependent_point2 : points2) { if (dependent_point1.distanceTo(dependent_point2) <= SIGMA) { return true; } } } return false; } @Override public String toString() { return "DENCLUE"; } }
true
true
private Point getDensityAttractor(Point point) { final double delta = 1; Point curr_attractor = point; Point found_attractor = null; int MAX_ITERATIONS = 5; Boolean reachedTop = false; do { // Avoid infinite loops if (--MAX_ITERATIONS <= 0) { break; } // Store last calculated values for further comparison final Point last_attractor = curr_attractor; // Calculate the gradient of density function at current candidate to attractor final double[] curr_gradient = calculateGradient(last_attractor); // Build an entity to represent the gradient final Point grad_point = new Point(curr_gradient, 0); // Calculate next candidate to attractor final double grad_entity_norm = grad_point.getEuclideanNorm(); // if( grad_entity_norm < 0 ) // System.out.println("\n\n\n>>>>>\n\n\n"); curr_attractor = last_attractor; for (int i = 0; i < curr_gradient.length; i++) { curr_attractor.params[i] += delta / grad_entity_norm * grad_point.params[i]; } // Calculate density in current attractor final double curr_density = calculateDensity(curr_attractor); curr_attractor.density = curr_density; // Verify whether local maxima was found reachedTop = curr_attractor.density < last_attractor.density; if (reachedTop) { found_attractor = last_attractor; } } while (!reachedTop); if (MAX_ITERATIONS <= 0) { found_attractor = curr_attractor; } // System.out.println(MAX_ITERATIONS +"\t"+ Arrays.toString(found_attractor.params)); return found_attractor; }
private Point getDensityAttractor(Point point) { final double delta = 1; Point curr_attractor = new Point(point.params, point.clusterId); Point found_attractor = null; int MAX_ITERATIONS = 5; Boolean reachedTop = false; do { // Avoid infinite loops if (--MAX_ITERATIONS <= 0) { break; } // Store last calculated values for further comparison final Point last_attractor = curr_attractor; // Calculate the gradient of density function at current candidate to attractor final double[] curr_gradient = calculateGradient(last_attractor); // Build an entity to represent the gradient final Point grad_point = new Point(curr_gradient, 0); // Calculate next candidate to attractor final double grad_entity_norm = grad_point.getEuclideanNorm(); // if( grad_entity_norm < 0 ) // System.out.println("\n\n\n>>>>>\n\n\n"); curr_attractor = last_attractor; for (int i = 0; i < curr_gradient.length; i++) { curr_attractor.params[i] += delta / grad_entity_norm * grad_point.params[i]; } // Calculate density in current attractor final double curr_density = calculateDensity(curr_attractor); curr_attractor.density = curr_density; // Verify whether local maxima was found reachedTop = curr_attractor.density < last_attractor.density; if (reachedTop) { found_attractor = last_attractor; } } while (!reachedTop); if (MAX_ITERATIONS <= 0) { found_attractor = curr_attractor; } // System.out.println(MAX_ITERATIONS +"\t"+ Arrays.toString(found_attractor.params)); return found_attractor; }
diff --git a/src/com/iver/cit/gvsig/gui/cad/MyFinishAction.java b/src/com/iver/cit/gvsig/gui/cad/MyFinishAction.java index e097f95..01633b4 100644 --- a/src/com/iver/cit/gvsig/gui/cad/MyFinishAction.java +++ b/src/com/iver/cit/gvsig/gui/cad/MyFinishAction.java @@ -1,85 +1,92 @@ package com.iver.cit.gvsig.gui.cad; import jwizardcomponent.FinishAction; import jwizardcomponent.JWizardComponents; import com.hardcode.gdbms.driver.exceptions.ReadDriverException; import com.iver.andami.messages.NotificationManager; import com.iver.cit.gvsig.CADExtension; import com.iver.cit.gvsig.StartEditing; import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException; import com.iver.cit.gvsig.fmap.MapControl; import com.iver.cit.gvsig.fmap.core.FShape; import com.iver.cit.gvsig.fmap.drivers.ITableDefinition; import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter; import com.iver.cit.gvsig.fmap.edition.rules.IRule; import com.iver.cit.gvsig.fmap.edition.rules.RulePolygon; import com.iver.cit.gvsig.fmap.layers.FLyrVect; import com.iver.cit.gvsig.gui.cad.createLayer.NewLayerWizard; import com.iver.cit.gvsig.project.documents.view.gui.View; public class MyFinishAction extends FinishAction { JWizardComponents myWizardComponents; FinishAction oldAction; ITableDefinition lyrDef = null; View view; private NewLayerWizard wizard; public MyFinishAction(JWizardComponents wizardComponents, View view, NewLayerWizard wizard) { super(wizardComponents); oldAction = wizardComponents.getFinishAction(); myWizardComponents = wizardComponents; this.view = view; this.wizard = wizard; // TODO Auto-generated constructor stub } @Override public void performAction() { FLyrVect lyr = null; MapControl mapCtrl = view.getMapControl(); try { mapCtrl.getMapContext().beginAtomicEvent(); lyr = wizard.createLayer(mapCtrl.getProjection()); } catch (Exception e) { - NotificationManager.showMessageError(e.getLocalizedMessage(), e); + Throwable cause = e.getCause(); + if (cause != null) { + NotificationManager.showMessageError( + cause.getLocalizedMessage(), e); + } else { + NotificationManager + .showMessageError(e.getLocalizedMessage(), e); + } return; } if (lyr == null) { return; } lyr.setVisible(true); mapCtrl.getMapContext().getLayers().addLayer(lyr); mapCtrl.getMapContext().endAtomicEvent(); lyr.addLayerListener(CADExtension.getEditionManager()); lyr.setActive(true); try { lyr.setEditing(true); VectorialEditableAdapter vea = (VectorialEditableAdapter) lyr .getSource(); vea.getRules().clear(); // TODO: ESTO ES PROVISIONAL, DESCOMENTAR LUEGO if (vea.getShapeType() == FShape.POLYGON) { IRule rulePol = new RulePolygon(); vea.getRules().add(rulePol); } StartEditing.startCommandsApplicable(view, lyr); vea.getCommandRecord().addCommandListener(mapCtrl); view.showConsole(); // Para cerrar el cuadro de di�logo. oldAction.performAction(); } catch (ReadDriverException e) { NotificationManager.addError(e); } catch (StartEditionLayerException e) { NotificationManager.addError(e); } } }
true
true
public void performAction() { FLyrVect lyr = null; MapControl mapCtrl = view.getMapControl(); try { mapCtrl.getMapContext().beginAtomicEvent(); lyr = wizard.createLayer(mapCtrl.getProjection()); } catch (Exception e) { NotificationManager.showMessageError(e.getLocalizedMessage(), e); return; } if (lyr == null) { return; } lyr.setVisible(true); mapCtrl.getMapContext().getLayers().addLayer(lyr); mapCtrl.getMapContext().endAtomicEvent(); lyr.addLayerListener(CADExtension.getEditionManager()); lyr.setActive(true); try { lyr.setEditing(true); VectorialEditableAdapter vea = (VectorialEditableAdapter) lyr .getSource(); vea.getRules().clear(); // TODO: ESTO ES PROVISIONAL, DESCOMENTAR LUEGO if (vea.getShapeType() == FShape.POLYGON) { IRule rulePol = new RulePolygon(); vea.getRules().add(rulePol); } StartEditing.startCommandsApplicable(view, lyr); vea.getCommandRecord().addCommandListener(mapCtrl); view.showConsole(); // Para cerrar el cuadro de di�logo. oldAction.performAction(); } catch (ReadDriverException e) { NotificationManager.addError(e); } catch (StartEditionLayerException e) { NotificationManager.addError(e); } }
public void performAction() { FLyrVect lyr = null; MapControl mapCtrl = view.getMapControl(); try { mapCtrl.getMapContext().beginAtomicEvent(); lyr = wizard.createLayer(mapCtrl.getProjection()); } catch (Exception e) { Throwable cause = e.getCause(); if (cause != null) { NotificationManager.showMessageError( cause.getLocalizedMessage(), e); } else { NotificationManager .showMessageError(e.getLocalizedMessage(), e); } return; } if (lyr == null) { return; } lyr.setVisible(true); mapCtrl.getMapContext().getLayers().addLayer(lyr); mapCtrl.getMapContext().endAtomicEvent(); lyr.addLayerListener(CADExtension.getEditionManager()); lyr.setActive(true); try { lyr.setEditing(true); VectorialEditableAdapter vea = (VectorialEditableAdapter) lyr .getSource(); vea.getRules().clear(); // TODO: ESTO ES PROVISIONAL, DESCOMENTAR LUEGO if (vea.getShapeType() == FShape.POLYGON) { IRule rulePol = new RulePolygon(); vea.getRules().add(rulePol); } StartEditing.startCommandsApplicable(view, lyr); vea.getCommandRecord().addCommandListener(mapCtrl); view.showConsole(); // Para cerrar el cuadro de di�logo. oldAction.performAction(); } catch (ReadDriverException e) { NotificationManager.addError(e); } catch (StartEditionLayerException e) { NotificationManager.addError(e); } }
diff --git a/src/uk/org/ownage/dmdirc/ui/components/Frame.java b/src/uk/org/ownage/dmdirc/ui/components/Frame.java index d92729f71..f24cba416 100644 --- a/src/uk/org/ownage/dmdirc/ui/components/Frame.java +++ b/src/uk/org/ownage/dmdirc/ui/components/Frame.java @@ -1,799 +1,799 @@ /* * Copyright (c) 2006-2007 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 uk.org.ownage.dmdirc.ui.components; import java.awt.AWTException; import java.awt.Dimension; import java.awt.HeadlessException; import java.awt.Point; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.Date; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.JInternalFrame; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameListener; import javax.swing.plaf.basic.BasicInternalFrameUI; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import uk.org.ownage.dmdirc.BrowserLauncher; import uk.org.ownage.dmdirc.Config; import uk.org.ownage.dmdirc.FrameContainer; import uk.org.ownage.dmdirc.commandparser.CommandWindow; import uk.org.ownage.dmdirc.logger.ErrorLevel; import uk.org.ownage.dmdirc.logger.Logger; import uk.org.ownage.dmdirc.ui.MainFrame; import uk.org.ownage.dmdirc.ui.dialogs.PasteDialog; import uk.org.ownage.dmdirc.ui.input.InputHandler; import uk.org.ownage.dmdirc.ui.input.TabCompleter; import uk.org.ownage.dmdirc.ui.messages.ColourManager; import uk.org.ownage.dmdirc.ui.messages.Formatter; import uk.org.ownage.dmdirc.ui.messages.Styliser; /** * Frame component. */ public abstract class Frame extends JInternalFrame implements CommandWindow, PropertyChangeListener, InternalFrameListener, MouseListener, ActionListener, KeyListener { /** * 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; /** Frame input field. */ private JTextField inputField; /** Frame output pane. */ private JTextPane textPane; /** scrollpane. */ private JScrollPane scrollPane; /** holds the scrollbar for the frame. */ private final JScrollBar scrollBar; /** The InputHandler for our input field. */ private InputHandler inputHandler; /** The channel object that owns this frame. */ private final FrameContainer parent; /** The border used when the frame is not maximised. */ private Border myborder; /** The dimensions of the titlebar of the frame. **/ private Dimension titlebarSize; /** Popupmenu for this frame. */ private JPopupMenu popup; /** Popupmenu for this frame. */ private JPopupMenu inputFieldPopup; /** popup menu item. */ private JMenuItem copyMI; /** popup menu item. */ private JMenuItem inputPasteMI; /** popup menu item. */ private JMenuItem inputCopyMI; /** popup menu item. */ private JMenuItem inputCutMI; /** search bar. */ private SearchBar searchBar; /** Robot for the frame. */ private Robot robot; /** * Creates a new instance of Frame. * * @param owner FrameContainer owning this frame. */ public Frame(final FrameContainer owner) { super(); parent = owner; try { robot = new Robot(); } catch (AWTException ex) { Logger.error(ErrorLevel.TRIVIAL, "Error creating robot", ex); } setFrameIcon(MainFrame.getMainFrame().getIcon()); initComponents(); setMaximizable(true); setClosable(true); setResizable(true); setIconifiable(true); setPreferredSize(new Dimension(MainFrame.getMainFrame().getWidth() / 2, MainFrame.getMainFrame().getHeight() / 3)); addPropertyChangeListener("maximum", this); addInternalFrameListener(this); scrollBar = getScrollPane().getVerticalScrollBar(); try { getTextPane().setBackground(ColourManager.getColour( Integer.parseInt(owner.getConfigManager().getOption("ui", "backgroundcolour")))); } catch (NumberFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to set textpane background colour", ex); } try { getTextPane().setForeground(ColourManager.getColour( Integer.parseInt(owner.getConfigManager().getOption("ui", "foregroundcolour")))); } catch (NumberFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to set textpane foreground colour", ex); } try { getInputField().setBackground(ColourManager.getColour( Integer.parseInt(owner.getConfigManager().getOption("ui", "backgroundcolour")))); } catch (NumberFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to set input field background colour", ex); } try { getInputField().setForeground(ColourManager.getColour( Integer.parseInt(owner.getConfigManager().getOption("ui", "foregroundcolour")))); } catch (NumberFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to set input field background colour", ex); } try { getInputField().setCaretColor(ColourManager.getColour( Integer.parseInt(owner.getConfigManager().getOption("ui", "foregroundcolour")))); } catch (NumberFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to set caret colour", ex); } final Boolean pref = Boolean.parseBoolean(Config.getOption("ui", "maximisewindows")); if (pref || MainFrame.getMainFrame().getMaximised()) { hideBorder(); } } /** * Makes this frame visible. We don't call this from the constructor * so that we can register an actionlistener for the open event before * the frame is opened. */ public final void open() { setVisible(true); } /** * Adds a line of text to the main text area (with a timestamp). * @param line text to add */ public final void addLine(final String line) { addLine(line, true); } /** * Adds a line of text to the main text area. * @param line text to add * @param timestamp Whether to timestamp the line or not */ public final void addLine(final String line, final boolean timestamp) { SwingUtilities.invokeLater(new Runnable() { public void run() { for (String myLine : line.split("\n")) { if (timestamp) { String ts = Formatter.formatMessage("timestamp", new Date()); if (!getTextPane().getText().equals("")) { ts = "\n" + ts; } Styliser.addStyledString(getTextPane().getStyledDocument(), ts); } Styliser.addStyledString(getTextPane().getStyledDocument(), myLine); } int frameBufferSize = Integer.MAX_VALUE; if (parent.getConfigManager().hasOption("ui", "frameBufferSize")) { try { frameBufferSize = Integer.parseInt( parent.getConfigManager().getOption("ui", "frameBufferSize")); } catch (NumberFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to set frame buffer size", ex); } } final Document doc = getTextPane().getDocument(); try { if (doc.getLength() > frameBufferSize) { doc.remove(0, 1 + doc.getText(doc.getLength() - frameBufferSize, 512).indexOf('\n') + doc.getLength() - frameBufferSize); } } catch (BadLocationException ex) { Logger.error(ErrorLevel.WARNING, "Unable to trim buffer", ex); } if (scrollBar.getValue() + Math.round(scrollBar.getVisibleAmount() * 1.5) < scrollBar.getMaximum()) { SwingUtilities.invokeLater(new Runnable() { private Rectangle prevRect = getTextPane().getVisibleRect(); public void run() { getTextPane().scrollRectToVisible(prevRect); } }); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { getTextPane().setCaretPosition(getTextPane().getDocument().getLength()); } }); } } }); } /** * Formats the arguments using the Formatter, then adds the result to the * main text area. * @param messageType The type of this message * @param args The arguments for the message */ public final void addLine(final String messageType, final Object... args) { addLine(Formatter.formatMessage(messageType, args)); } /** * Clears the main text area of the frame. */ public final void clear() { getTextPane().setText(""); } /** * Sets the tab completer for this frame's input handler. * @param tabCompleter The tab completer to use */ public final void setTabCompleter(final TabCompleter tabCompleter) { getInputHandler().setTabCompleter(tabCompleter); } /** * Initialises the components for this frame. */ private void initComponents() { setScrollPane(new JScrollPane()); setInputField(new JTextField()); setTextPane(new JTextPane()); getInputField().setBorder( BorderFactory.createCompoundBorder( getInputField().getBorder(), new EmptyBorder(2, 2, 2, 2))); getTextPane().addMouseListener(this); getTextPane().addKeyListener(this); getScrollPane().addKeyListener(this); getInputField().addKeyListener(this); getInputField().addMouseListener(this); popup = new JPopupMenu(); inputFieldPopup = new JPopupMenu(); copyMI = new JMenuItem("Copy"); copyMI.addActionListener(this); inputPasteMI = new JMenuItem("Paste"); inputPasteMI.addActionListener(this); inputCopyMI = new JMenuItem("Copy"); inputCopyMI.addActionListener(this); inputCutMI = new JMenuItem("Cut"); inputCutMI.addActionListener(this); popup.add(copyMI); popup.setOpaque(true); popup.setLightWeightPopupEnabled(true); inputFieldPopup.add(inputCutMI); inputFieldPopup.add(inputCopyMI); inputFieldPopup.add(inputPasteMI); inputFieldPopup.setOpaque(true); inputFieldPopup.setLightWeightPopupEnabled(true); searchBar = new SearchBar(this); searchBar.setVisible(false); } /** * Removes and reinserts the border of an internal frame on maximising. * {@inheritDoc} */ public final void propertyChange(final PropertyChangeEvent propertyChangeEvent) { if (propertyChangeEvent.getNewValue().equals(Boolean.TRUE)) { hideBorder(); MainFrame.getMainFrame().setMaximised(true); } else { setBorder(myborder); ((BasicInternalFrameUI) getUI()).getNorthPane() .setPreferredSize(titlebarSize); ((BasicInternalFrameUI) getUI()).getNorthPane() .setMaximumSize(titlebarSize); myborder = null; MainFrame.getMainFrame().setMaximised(false); MainFrame.getMainFrame().setActiveFrame(this); } } /** * Hides the border around the frame. */ private void hideBorder() { if (myborder == null) { myborder = getBorder(); titlebarSize = ((BasicInternalFrameUI) getUI()) .getNorthPane().getPreferredSize(); ((BasicInternalFrameUI) getUI()).getNorthPane() .setPreferredSize(new Dimension(0, 0)); ((BasicInternalFrameUI) getUI()).getNorthPane() .setMaximumSize(new Dimension(0, 0)); setBorder(new EmptyBorder(0, 0, 0, 0)); } } /** * Not needed for this class. {@inheritDoc} */ public void internalFrameOpened(final InternalFrameEvent internalFrameEvent) { //Ignore. } /** * Not needed for this class. {@inheritDoc} */ public void internalFrameClosing(final InternalFrameEvent internalFrameEvent) { //Ignore. } /** * Not needed for this class. {@inheritDoc} */ public void internalFrameClosed(final InternalFrameEvent internalFrameEvent) { //Ignore. } /** * Makes the internal frame invisible. {@inheritDoc} */ public void internalFrameIconified(final InternalFrameEvent internalFrameEvent) { internalFrameEvent.getInternalFrame().setVisible(false); } /** * Not needed for this class. {@inheritDoc} */ public void internalFrameDeiconified(final InternalFrameEvent internalFrameEvent) { //Ignore. } /** * Activates the input field on frame focus. {@inheritDoc} */ public void internalFrameActivated(final InternalFrameEvent internalFrameEvent) { getInputField().requestFocus(); } /** * Not needed for this class. {@inheritDoc} */ public void internalFrameDeactivated(final InternalFrameEvent internalFrameEvent) { //Ignore. } /** * Returns the parent Frame container for this frame. * * @return FrameContainer parent */ public final FrameContainer getFrameParent() { return parent; } /** * Returns the input handler associated with this frame. * * @return Input handlers for this frame */ public final InputHandler getInputHandler() { return inputHandler; } /** * Sets the input handler for this frame. * * @param newInputHandler input handler to set for this frame */ public final void setInputHandler(final InputHandler newInputHandler) { this.inputHandler = newInputHandler; } /** * returns the input field for this frame. * * @return JTextField input field for the frame. */ public final JTextField getInputField() { return inputField; } /** * Returns the text pane for this frame. * * @return JTextPane text pane for this frame */ public final JTextPane getTextPane() { return textPane; } /** * Sets the frames input field. * * @param newInputField new input field to use */ protected final void setInputField(final JTextField newInputField) { this.inputField = newInputField; } /** * Sets the frames text pane. * * @param newTextPane new text pane to use */ protected final void setTextPane(final JTextPane newTextPane) { this.textPane = newTextPane; } /** * Gets the frames input field. * * @return returns the JScrollPane used in this frame. */ protected final JScrollPane getScrollPane() { return scrollPane; } /** * Sets the frames scroll pane. * * @param newScrollPane new scroll pane to use */ protected final void setScrollPane(final JScrollPane newScrollPane) { this.scrollPane = newScrollPane; } /** * Checks for url's, channels and nicknames. {@inheritDoc} */ public void mouseClicked(final MouseEvent mouseEvent) { if (mouseEvent.getSource() == getTextPane()) { final int pos = getTextPane().getCaretPosition(); final int length = getTextPane().getDocument().getLength(); String text; if (pos == 0) { return; } int start = (pos - 510 < 0) ? 0 : pos - 510; int end = (start + 1020 >= length) ? length - start : 1020; try { text = getTextPane().getText(start, end); } catch (BadLocationException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to select text (start: " + start + ", end: " + end + ")"); return; } start = pos - start; end = start; // Traverse backwards while (start > 0 && start < text.length() && text.charAt(start) != ' ' && text.charAt(start) != '\n') { start--; } if (start + 1 < text.length() && text.charAt(start) == ' ') { start++; } // And forwards while (end < text.length() && end > 0 && text.charAt(end) != ' ' && text.charAt(end) != '\n') { end++; } if (start > end) { return; } text = text.substring(start, end); if (text.length() < 4) { return; } checkClickText(text); processMouseEvent(mouseEvent); } } /** * Not needed for this class. {@inheritDoc} */ public void mousePressed(final MouseEvent mouseEvent) { processMouseEvent(mouseEvent); } /** * Not needed for this class. {@inheritDoc} */ public void mouseReleased(final MouseEvent mouseEvent) { if (Boolean.parseBoolean(Config.getOption("ui", "quickCopy"))) { getTextPane().copy(); getTextPane().setCaretPosition(getTextPane().getCaretPosition()); getTextPane().moveCaretPosition(getTextPane().getCaretPosition()); } processMouseEvent(mouseEvent); } /** * Not needed for this class. {@inheritDoc} */ public void mouseEntered(final MouseEvent mouseEvent) { //Ignore. } /** * Not needed for this class. {@inheritDoc} */ public void mouseExited(final MouseEvent mouseEvent) { //Ignore. } /** * Processes every mouse button event to check for a popup trigger. * @param e mouse event */ public void processMouseEvent(final MouseEvent e) { if (e.isPopupTrigger() && e.getSource() == getTextPane()) { final Point point = getScrollPane().getMousePosition(); getPopup().show(this, (int) point.getX(), (int) point.getY()); } else if (e.isPopupTrigger() && e.getSource() == getInputField()) { inputFieldPopup.show(this, e.getX(), e.getY() + getInputField().getY()); } else if (e.getSource() == getTextPane()) { getTextPane().requestFocus(); } else if (e.getSource() == getInputField()) { getInputField().requestFocus(); } else { super.processMouseEvent(e); } } /** {@inheritDoc}. */ public void actionPerformed(final ActionEvent actionEvent) { if (actionEvent.getSource() == copyMI) { getTextPane().copy(); } else if (actionEvent.getSource() == inputCopyMI) { getInputField().copy(); } else if (actionEvent.getSource() == inputPasteMI) { getInputField().paste(); } else if (actionEvent.getSource() == inputCutMI) { getInputField().cut(); } } /** * returns the popup menu for this frame. * @return JPopupMenu for this frame */ public final JPopupMenu getPopup() { return popup; } /** {@inheritDoc}. */ public void keyTyped(final KeyEvent event) { //Ignore. } /** {@inheritDoc}. */ public void keyPressed(final KeyEvent event) { String clipboardContents = null; String[] clipboardContentsLines = new String[]{"", }; if (event.getKeyCode() == KeyEvent.VK_F3) { getSearchBar().open(); } if (event.getSource() == getTextPane()) { if ((Boolean.parseBoolean(Config.getOption("ui", "quickCopy")) || (event.getModifiers() & KeyEvent.CTRL_MASK) == 0)) { event.setSource(getInputField()); getInputField().requestFocus(); if (robot != null) { robot.keyPress(event.getKeyCode()); } } else if (event.getKeyCode() == KeyEvent.VK_C) { getTextPane().copy(); } } else if (event.getSource() == getInputField() && (event.getModifiers() & KeyEvent.CTRL_MASK) != 0 && event.getKeyCode() == KeyEvent.VK_V) { try { clipboardContents = (String) Toolkit.getDefaultToolkit().getSystemClipboard() .getData(DataFlavor.stringFlavor); clipboardContentsLines = clipboardContents.split(System.getProperty("line.separator")); } catch (HeadlessException ex) { Logger.error(ErrorLevel.WARNING, "Unable to get clipboard contents", ex); } catch (IOException ex) { Logger.error(ErrorLevel.WARNING, "Unable to get clipboard contents", ex); } catch (UnsupportedFlavorException ex) { Logger.error(ErrorLevel.WARNING, "Unable to get clipboard contents", ex); } if (clipboardContents.indexOf('\n') >= 0) { event.consume(); int pasteTrigger = 1; if (Config.hasOption("ui", "pasteProtectionLimit")) { try { pasteTrigger = Integer.parseInt(Config.getOption("ui", "pasteProtectionLimit")); } catch (NumberFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to set paste protection limit", ex); } } if (getNumLines(clipboardContents) > pasteTrigger) { final String[] options = {"Send", "Edit", "Cancel", }; final int n = JOptionPane.showOptionDialog(this, "<html>Paste would be sent as " - + clipboardContentsLines.length + " lines.<br>" + + getNumLines(clipboardContents) + " lines.<br>" + "Do you want to continue?</html>", "Multi-line Paste", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); switch (n) { case 0: for (String clipboardLine : clipboardContentsLines) { this.sendLine(clipboardLine); } break; case 1: new PasteDialog(this, clipboardContents).setVisible(true); break; case 2: break; default: break; } } else { for (String clipboardLine : clipboardContentsLines) { this.sendLine(clipboardLine); } } } } } /** {@inheritDoc}. */ public void keyReleased(final KeyEvent event) { //Ignore. } /** * Checks text clicked on by the user, takes appropriate action. * @param text text to check */ private void checkClickText(final String text) { //System.out.print("Clicked text: '" + text + "' "); if (text.toLowerCase(Locale.getDefault()).startsWith("http://") || text.toLowerCase(Locale.getDefault()).startsWith("https://") || text.toLowerCase(Locale.getDefault()).startsWith("www.")) { //System.out.print("opening browser."); MainFrame.getMainFrame().getStatusBar().setMessage("Opening: " + text); BrowserLauncher.openURL(text); } else if (parent.getServer().getParser().isValidChannelName(text)) { //System.out.print("is a valid channel "); if (parent.getServer().getParser().getChannelInfo(text) == null) { //System.out.print("joining."); parent.getServer().getParser().joinChannel(text); } else { //System.out.print("activating."); parent.getServer().getChannel(text).activateFrame(); } } // else { //System.out.print("ignoring."); //} //System.out.println(); } /** * Send the line to the frame container. * * @param line the line to send */ public abstract void sendLine(final String line); /** * Gets the search bar. * * @return the frames search bar */ public final SearchBar getSearchBar() { return searchBar; } /** * Returns the number of lines the specified string would be sent as. * @param line line to be checked * @return number of lines that would be sent */ public final int getNumLines(final String line) { int lines; final String[] splitLines = line.split("\n"); lines = splitLines.length; for (String splitLine : splitLines) { lines += (int) Math.ceil(splitLine.length() / getMaxLineLength()); } return lines; } /** * Returns the maximum length a line can be in this frame. * @return max line length */ public abstract int getMaxLineLength(); }
true
true
public void keyPressed(final KeyEvent event) { String clipboardContents = null; String[] clipboardContentsLines = new String[]{"", }; if (event.getKeyCode() == KeyEvent.VK_F3) { getSearchBar().open(); } if (event.getSource() == getTextPane()) { if ((Boolean.parseBoolean(Config.getOption("ui", "quickCopy")) || (event.getModifiers() & KeyEvent.CTRL_MASK) == 0)) { event.setSource(getInputField()); getInputField().requestFocus(); if (robot != null) { robot.keyPress(event.getKeyCode()); } } else if (event.getKeyCode() == KeyEvent.VK_C) { getTextPane().copy(); } } else if (event.getSource() == getInputField() && (event.getModifiers() & KeyEvent.CTRL_MASK) != 0 && event.getKeyCode() == KeyEvent.VK_V) { try { clipboardContents = (String) Toolkit.getDefaultToolkit().getSystemClipboard() .getData(DataFlavor.stringFlavor); clipboardContentsLines = clipboardContents.split(System.getProperty("line.separator")); } catch (HeadlessException ex) { Logger.error(ErrorLevel.WARNING, "Unable to get clipboard contents", ex); } catch (IOException ex) { Logger.error(ErrorLevel.WARNING, "Unable to get clipboard contents", ex); } catch (UnsupportedFlavorException ex) { Logger.error(ErrorLevel.WARNING, "Unable to get clipboard contents", ex); } if (clipboardContents.indexOf('\n') >= 0) { event.consume(); int pasteTrigger = 1; if (Config.hasOption("ui", "pasteProtectionLimit")) { try { pasteTrigger = Integer.parseInt(Config.getOption("ui", "pasteProtectionLimit")); } catch (NumberFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to set paste protection limit", ex); } } if (getNumLines(clipboardContents) > pasteTrigger) { final String[] options = {"Send", "Edit", "Cancel", }; final int n = JOptionPane.showOptionDialog(this, "<html>Paste would be sent as " + clipboardContentsLines.length + " lines.<br>" + "Do you want to continue?</html>", "Multi-line Paste", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); switch (n) { case 0: for (String clipboardLine : clipboardContentsLines) { this.sendLine(clipboardLine); } break; case 1: new PasteDialog(this, clipboardContents).setVisible(true); break; case 2: break; default: break; } } else { for (String clipboardLine : clipboardContentsLines) { this.sendLine(clipboardLine); } } } } }
public void keyPressed(final KeyEvent event) { String clipboardContents = null; String[] clipboardContentsLines = new String[]{"", }; if (event.getKeyCode() == KeyEvent.VK_F3) { getSearchBar().open(); } if (event.getSource() == getTextPane()) { if ((Boolean.parseBoolean(Config.getOption("ui", "quickCopy")) || (event.getModifiers() & KeyEvent.CTRL_MASK) == 0)) { event.setSource(getInputField()); getInputField().requestFocus(); if (robot != null) { robot.keyPress(event.getKeyCode()); } } else if (event.getKeyCode() == KeyEvent.VK_C) { getTextPane().copy(); } } else if (event.getSource() == getInputField() && (event.getModifiers() & KeyEvent.CTRL_MASK) != 0 && event.getKeyCode() == KeyEvent.VK_V) { try { clipboardContents = (String) Toolkit.getDefaultToolkit().getSystemClipboard() .getData(DataFlavor.stringFlavor); clipboardContentsLines = clipboardContents.split(System.getProperty("line.separator")); } catch (HeadlessException ex) { Logger.error(ErrorLevel.WARNING, "Unable to get clipboard contents", ex); } catch (IOException ex) { Logger.error(ErrorLevel.WARNING, "Unable to get clipboard contents", ex); } catch (UnsupportedFlavorException ex) { Logger.error(ErrorLevel.WARNING, "Unable to get clipboard contents", ex); } if (clipboardContents.indexOf('\n') >= 0) { event.consume(); int pasteTrigger = 1; if (Config.hasOption("ui", "pasteProtectionLimit")) { try { pasteTrigger = Integer.parseInt(Config.getOption("ui", "pasteProtectionLimit")); } catch (NumberFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to set paste protection limit", ex); } } if (getNumLines(clipboardContents) > pasteTrigger) { final String[] options = {"Send", "Edit", "Cancel", }; final int n = JOptionPane.showOptionDialog(this, "<html>Paste would be sent as " + getNumLines(clipboardContents) + " lines.<br>" + "Do you want to continue?</html>", "Multi-line Paste", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); switch (n) { case 0: for (String clipboardLine : clipboardContentsLines) { this.sendLine(clipboardLine); } break; case 1: new PasteDialog(this, clipboardContents).setVisible(true); break; case 2: break; default: break; } } else { for (String clipboardLine : clipboardContentsLines) { this.sendLine(clipboardLine); } } } } }
diff --git a/runtime/core/src/main/java/fr/imag/adele/apam/impl/CompositeImpl.java b/runtime/core/src/main/java/fr/imag/adele/apam/impl/CompositeImpl.java index 5ceeb2bc..789d3f32 100644 --- a/runtime/core/src/main/java/fr/imag/adele/apam/impl/CompositeImpl.java +++ b/runtime/core/src/main/java/fr/imag/adele/apam/impl/CompositeImpl.java @@ -1,444 +1,448 @@ /** * Copyright 2011-2012 Universite Joseph Fourier, LIG, ADELE team * 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 fr.imag.adele.apam.impl; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import fr.imag.adele.apam.CST; import fr.imag.adele.apam.Composite; import fr.imag.adele.apam.CompositeType; import fr.imag.adele.apam.Implementation; import fr.imag.adele.apam.Instance; import fr.imag.adele.apam.ManagerModel; import fr.imag.adele.apam.apform.ApformInstance; public class CompositeImpl extends InstanceImpl implements Composite { private static final long serialVersionUID = 1L; /** * The root of the composite hierarchy * */ private static final Composite rootComposite ; /** * The list of all composites in the APAM state model */ private static final Map<String, Composite> composites = new ConcurrentHashMap<String, Composite>(); public static Collection<Composite> getComposites() { return Collections.unmodifiableCollection(CompositeImpl.composites.values()); } public static Composite getComposite(String name) { return CompositeImpl.composites.get(name); } /* * the contained instances */ private Instance mainInst; private Set<Instance> hasInstance = Collections.newSetFromMap(new ConcurrentHashMap<Instance, Boolean>()); /* * The father-son relationship of the composite hierarchy * * This is a subset of the instance hierarchy restricted only to composites. */ private Set<Composite> sons = Collections.newSetFromMap(new ConcurrentHashMap<Composite, Boolean>()); private Composite father; // null if root composite // private Composite appliComposite; // root of father relationship /* * the dependencies between composites */ private Set<Composite> depend = Collections.newSetFromMap(new ConcurrentHashMap<Composite, Boolean>()); private Set<Composite> invDepend = Collections.newSetFromMap(new ConcurrentHashMap<Composite, Boolean>()); //==== initialisations == /** * NOTE We can not directly initialize the field because the constructor may throw an exception, so we need to * make an static block to be able to catch the exception. The root composite bootstraps the system, so normally * we SHOULD always be able to create it; if there is an exception, that means there is some bug an we can not * normally continue so we throw a class initialization exception. */ static { Composite bootstrap = null; try { bootstrap = new CompositeImpl(CompositeTypeImpl.getRootCompositeType(),"rootComposite"); } catch (Exception e) { throw new ExceptionInInitializerError(e); } finally { rootComposite = bootstrap; } } /** * The root instance and the root composite are the same object. getComposite() returns this. * @return */ public static Composite getRootAllComposites() { return CompositeImpl.rootComposite; } public static Composite getRootInstance() { return CompositeImpl.rootComposite; } public static Collection<Composite> getRootComposites() { return Collections.unmodifiableSet(CompositeImpl.rootComposite.getSons()); } //=== /** * This is an special constructor only used for the root instance of the system, and the dummy instance during construction */ CompositeImpl(CompositeType compoType, String name) throws InvalidConfiguration { super(compoType, name); this.mainInst = null; /* * NOTE the root instance is automatically registered in Apam in a specific way that * allows bootstraping the system * */ this.father = null; //this.appliComposite = null; } /** * Whether this is the system root composite * */ public boolean isSystemRoot() { return this == rootComposite; } /** * Builds a new Apam composite to represent the specified platform instance in the Apam model. */ protected CompositeImpl(Composite composite, ApformInstance apformInst) throws InvalidConfiguration { // First create the composite, as a normal instance super(composite, apformInst); /* * Reference the enclosing composite hierarchy */ father = ((CompositeImpl)composite).isSystemRoot() ? null : composite; // appliComposite = father == null ? this : father.getAppliComposite(); } @Override public void register(Map<String, String> initialProperties) throws InvalidConfiguration { // true if Abstract composite or unused main instance boolean registerMain = false; /* * Initialize the contained instances. The main instance will be eagerly created and the other * components will be lazily instantiated. It is also possible to specify an unused external main * instance in the configuration properties. * * Attribute A_MAIN_INSTANCE is set when a running unused instance makes its first resolution: * it become the main instance of a new default composite * */ if (initialProperties != null && initialProperties.get(CST.APAM_MAIN_INSTANCE) != null) { mainInst = CST.componentBroker.getInst(initialProperties.remove(CST.APAM_MAIN_INSTANCE)); if (mainInst.isUsed()) throw new InvalidConfiguration("Error creating composite : already used main instance "+mainInst); assert ! mainInst.isUsed(); } else { - //Abstract composites do not have main instance + /* + * Abstract composites do not have main instance. + * + * TODO should there be a way to specify the properties of the main instance? + */ if ((ImplementationImpl) getMainImpl() != null) - mainInst = ((ImplementationImpl) getMainImpl()).instantiate(this, initialProperties); + mainInst = ((ImplementationImpl) getMainImpl()).instantiate(this, null); } // If not an abstract composite if (mainInst != null) { /* * If the main instance is external, it is already registered but we need to remove it from the root * composite and add it to this */ if (mainInst.isUsed()) { registerMain = true ; } else ((InstanceImpl)mainInst).setOwner(this); /* * main instance is never shared */ mainInst.getDeclaration().setShared(false) ; ((InstanceImpl) mainInst).put(CST.SHARED, CST.V_FALSE); } /* * Opposite reference from the enclosing composite. * Notice that root application are sons of the all root composite, but their father reference is null. */ ((CompositeImpl)getComposite()).addSon(this); /* * add to list of composites */ CompositeImpl.composites.put(getName(),this); /* * Complete normal registration */ super.register(initialProperties); /* * After composite is registered, register main instance that was eagerly created */ if (registerMain) ((InstanceImpl)mainInst).register(null); } @Override public void unregister() { /* * Unbind from the enclosing composite */ ((CompositeImpl)getComposite()).removeSon(this); father = null; // appliComposite = null; /* * Remove depend relationships. * * NOTE We have to copy the list because we update it while iterating it * */ for (Composite dependsOn : new HashSet<Composite>(depend)) { removeDepend(dependsOn); } for (Composite dependant : new HashSet<Composite>(invDepend)) { ((CompositeImpl)dependant).removeDepend(this); } /* * TODO Should we destroy the whole hierarchy rooted at this composite? or should we try * to reuse all created instances in the pool of unused instances? what to do with wires * that enter or leave this hierarchy? what to do of shared instances with other hierarchies? * can we reuse the main instance? */ /* * Remove from list of composites */ CompositeImpl.composites.remove(getName()); /* * Notify managers and remove the instance from the broker * * TODO perhaps we should notify managers before actually destroying the composite hierarchy, this * will need a refactoring of the superclass to allow a more fine control of unregistration. */ super.unregister(); } @Override public void setOwner(Composite owner) { assert (isUsed() && owner == rootComposite) || ( !isUsed() && owner != null); CompositeImpl previousOwner = (CompositeImpl)getComposite(); super.setOwner(owner); previousOwner.removeSon(this); this.father = owner; ((CompositeImpl)owner).addSon(this); } @Override public Instance getMainInst() { return mainInst; } /** * Overrides the instance method. A composite has no object, returns the * main instance object */ @Override public Object getServiceObject() { assert (mainInst != null); return mainInst.getApformInst().getServiceObject(); } @Override public final Implementation getMainImpl() { return getCompType().getMainImpl(); } @Override public final CompositeType getCompType() { return (CompositeType) getImpl(); } @Override public boolean containsInst(Instance instance) { assert (instance != null); return hasInstance.contains(instance); } @Override public Set<Instance> getContainInsts() { return Collections.unmodifiableSet(hasInstance); } public void addContainInst(Instance instance) { assert (instance != null); hasInstance.add(instance); } public void removeInst(Instance instance) { assert (instance != null); hasInstance.remove(instance); } @Override public Composite getFather() { return father; } @Override public Set<Composite> getSons() { return Collections.unmodifiableSet(sons); } // Father-son relationship management. Hidden, Internal; public void addSon(Composite destination) { assert destination != null && !sons.contains(destination); sons.add(destination); } /** * A son can be removed only when deleted. Warning : not checked. */ public boolean removeSon(Composite destination) { assert destination != null && sons.contains(destination); return sons.remove(destination); } @Override public Composite getAppliComposite() { return (father == null) ? this : father.getAppliComposite(); } // Composite relation management =============== @Override public void addDepend(Composite destination) { assert destination != null && !depend.contains(destination); depend.add(destination); ((CompositeImpl) destination).addInvDepend(this); } /** * A composite cannot be isolated. Therefore remove is prohibited if the * destination will be isolated. */ public boolean removeDepend(Composite destination) { assert destination != null && depend.contains(destination); depend.remove(destination); ((CompositeImpl)destination).removeInvDepend(this); return true; } /** * returns the reverse dependencies ! * * @return */ @Override public Set<Composite> getInvDepend() { return Collections.unmodifiableSet(invDepend); } /** * Ajoute une dependance inverse. Hidden, Internal; * * @param origin * @return */ private void addInvDepend(Composite origin) { assert origin != null && !invDepend.contains(origin); invDepend.add(origin); return; } /** * Retire une dependance inverse. Hidden, Internal; * * @param origin * @return */ private boolean removeInvDepend(Composite origin) { assert origin != null && invDepend.contains(origin); invDepend.remove(origin); return true; } @Override public Set<Composite> getDepend() { return Collections.unmodifiableSet(depend); } @Override public boolean dependsOn(Composite dest) { if (dest == null) return false; return (depend.contains(dest)); } @Override public ManagerModel getModel(String name) { return getCompType().getModel(name); } @Override public Set<ManagerModel> getModels() { return getCompType().getModels(); } @Override public String toString() { return "COMPOSITE " + getName(); } }
false
true
public void register(Map<String, String> initialProperties) throws InvalidConfiguration { // true if Abstract composite or unused main instance boolean registerMain = false; /* * Initialize the contained instances. The main instance will be eagerly created and the other * components will be lazily instantiated. It is also possible to specify an unused external main * instance in the configuration properties. * * Attribute A_MAIN_INSTANCE is set when a running unused instance makes its first resolution: * it become the main instance of a new default composite * */ if (initialProperties != null && initialProperties.get(CST.APAM_MAIN_INSTANCE) != null) { mainInst = CST.componentBroker.getInst(initialProperties.remove(CST.APAM_MAIN_INSTANCE)); if (mainInst.isUsed()) throw new InvalidConfiguration("Error creating composite : already used main instance "+mainInst); assert ! mainInst.isUsed(); } else { //Abstract composites do not have main instance if ((ImplementationImpl) getMainImpl() != null) mainInst = ((ImplementationImpl) getMainImpl()).instantiate(this, initialProperties); } // If not an abstract composite if (mainInst != null) { /* * If the main instance is external, it is already registered but we need to remove it from the root * composite and add it to this */ if (mainInst.isUsed()) { registerMain = true ; } else ((InstanceImpl)mainInst).setOwner(this); /* * main instance is never shared */ mainInst.getDeclaration().setShared(false) ; ((InstanceImpl) mainInst).put(CST.SHARED, CST.V_FALSE); } /* * Opposite reference from the enclosing composite. * Notice that root application are sons of the all root composite, but their father reference is null. */ ((CompositeImpl)getComposite()).addSon(this); /* * add to list of composites */ CompositeImpl.composites.put(getName(),this); /* * Complete normal registration */ super.register(initialProperties); /* * After composite is registered, register main instance that was eagerly created */ if (registerMain) ((InstanceImpl)mainInst).register(null); }
public void register(Map<String, String> initialProperties) throws InvalidConfiguration { // true if Abstract composite or unused main instance boolean registerMain = false; /* * Initialize the contained instances. The main instance will be eagerly created and the other * components will be lazily instantiated. It is also possible to specify an unused external main * instance in the configuration properties. * * Attribute A_MAIN_INSTANCE is set when a running unused instance makes its first resolution: * it become the main instance of a new default composite * */ if (initialProperties != null && initialProperties.get(CST.APAM_MAIN_INSTANCE) != null) { mainInst = CST.componentBroker.getInst(initialProperties.remove(CST.APAM_MAIN_INSTANCE)); if (mainInst.isUsed()) throw new InvalidConfiguration("Error creating composite : already used main instance "+mainInst); assert ! mainInst.isUsed(); } else { /* * Abstract composites do not have main instance. * * TODO should there be a way to specify the properties of the main instance? */ if ((ImplementationImpl) getMainImpl() != null) mainInst = ((ImplementationImpl) getMainImpl()).instantiate(this, null); } // If not an abstract composite if (mainInst != null) { /* * If the main instance is external, it is already registered but we need to remove it from the root * composite and add it to this */ if (mainInst.isUsed()) { registerMain = true ; } else ((InstanceImpl)mainInst).setOwner(this); /* * main instance is never shared */ mainInst.getDeclaration().setShared(false) ; ((InstanceImpl) mainInst).put(CST.SHARED, CST.V_FALSE); } /* * Opposite reference from the enclosing composite. * Notice that root application are sons of the all root composite, but their father reference is null. */ ((CompositeImpl)getComposite()).addSon(this); /* * add to list of composites */ CompositeImpl.composites.put(getName(),this); /* * Complete normal registration */ super.register(initialProperties); /* * After composite is registered, register main instance that was eagerly created */ if (registerMain) ((InstanceImpl)mainInst).register(null); }
diff --git a/src/main/java/com/md_5/district/Commands.java b/src/main/java/com/md_5/district/Commands.java index fc7f7a6..66f5ffb 100644 --- a/src/main/java/com/md_5/district/Commands.java +++ b/src/main/java/com/md_5/district/Commands.java @@ -1,247 +1,249 @@ package com.md_5.district; import java.util.ArrayList; import org.bukkit.*; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.Vector; public class Commands { public static void claim(final Player player, final String[] args, final int count) { if (args.length != count) { invalidArgs(player); return; } int size = 0, height; try { size = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { player.sendMessage(args[1] + " is not a valid number"); + return; } if (size % 2 == 0) { player.sendMessage("Size must be odd"); + return; } World world = player.getWorld(); // Limit height to world height height = Math.min(size, world.getMaxHeight()); size /= 2; height /= 2; size = (int) Math.floor(size); height = (int) Math.floor(size); Location point1 = player.getLocation(); Location point2 = player.getLocation(); point1.add(size, height, size); point2.add(-size, -size, -size); if (((Util.getTotalVolume(player.getName()) + Util.getVolume(point1, point2)) > Util.getMaxVolume(player)) && Util.getMaxVolume(player) != -1) { player.sendMessage(ChatColor.RED + "District: You cannot claim a region that big!"); player.sendMessage(ChatColor.RED + "District: Use /district quota to view your remaining quota"); return; } if (Loader.load(args[2]) != null) { player.sendMessage(ChatColor.RED + "District: Region " + args[2] + " is already claimed"); return; } if (Util.isOverlapping(point1, point2)) { player.sendMessage(ChatColor.RED + "District: Error! A region already exists here"); return; } Region creation = new Region(point1.getWorld(), point1, point2, player.getName(), new ArrayList<String>(), args[2]); Loader.save(creation); player.sendMessage(ChatColor.GREEN + "District: A " + args[1] + "x" + args[1] + "x" + args[1] + " (" + creation.getVolume() + " blocks) region named " + creation.getName() + " has been claimed for you!"); } public static void quota(final Player player, final String[] args) { int used = Util.getTotalVolume(player); int total = Util.getMaxVolume(player); String totalStr = total == -1 ? "infinite" : "" + total; player.sendMessage(ChatColor.GREEN + "District: You have claimed " + used + " blocks of your " + totalStr + " block quota."); if (total != -1) { int remaining = total - used; int root = (int) Math.round(Math.sqrt(used)); player.sendMessage(ChatColor.GREEN + "District: You have " + remaining + " blocks remaining (About " + root + "x" + root + "x" + root + ")"); } } public static void show(final Player player, final String[] args, final Region r) { if (args.length != 2) { invalidArgs(player); return; } if (r.canUse(player)) { Util.outline(player, r); Vector size = r.getSize(); player.sendMessage(ChatColor.GREEN + "District: Your " + (size.getBlockX() + 1) + "x" + (size.getBlockY() + 1) + "x" + (size.getBlockZ() + 1) + " (" + r.getVolume() + " blocks) region has been outlined just for you"); } else { Region.sendDeny(player); } } public static void hide(final Player player, final String[] args, final Region r) { if (args.length != 2) { invalidArgs(player); } if (r.canUse(player)) { Util.removeOutline(player, r); Vector size = r.getSize(); player.sendMessage(ChatColor.GREEN + "District: Your " + (size.getBlockX() + 1) + "x" + (size.getBlockY() + 1) + "x" + (size.getBlockZ() + 1) + " region has been hidden"); } else { Region.sendDeny(player); } } public static void remove(final Player player, final String[] args, final Region r) { if (args.length != 2) { invalidArgs(player); return; } if (r.canAdmin(player)) { Loader.remove(r.getName()); player.sendMessage(ChatColor.GREEN + "District: Region " + r.getName() + " removed"); } else { Region.sendDeny(player); } } public static void addMember(final Player player, final String[] args, final Region r) { if (args.length != 3) { invalidArgs(player); return; } if (r.canAdmin(player)) { if (!r.isMember(args[2])) { r.addMember(args[2]); Loader.save(r); player.sendMessage(ChatColor.GREEN + "District: Player " + args[2] + " added to " + r.getName()); } else { player.sendMessage(ChatColor.RED + "District: Player " + args[2] + " is already a member of " + r.getName()); } } else { Region.sendDeny(player); } } public static void delMember(final Player player, String[] args, final Region r) { if (args.length != 3) { invalidArgs(player); return; } if (r.canAdmin(player)) { if (r.isMember(args[2])) { r.removeMember(args[2]); Loader.save(r); player.sendMessage(ChatColor.GREEN + "District: Player " + args[2] + " removed from " + r.getName()); } else { player.sendMessage(ChatColor.RED + "District: Player " + args[2] + " is not a member of " + r.getName()); } } else { Region.sendDeny(player); } } public static void list(final String player, final CommandSender sender) { String owns = ""; String isMemberOf = ""; for (Region r : Loader.byOwner(player)) { owns += r.getName() + ", "; } Boolean isSender = player.equals(sender.getName()); if (!isMemberOf.equals("")) { sender.sendMessage(ChatColor.GREEN + "District: " + (isSender ? "You are" : (player + " is")) + " a member of these regions: " + isMemberOf); } else { sender.sendMessage(ChatColor.GREEN + "District: " + (isSender ? "You are" : (player + " is")) + " not a member of any regions"); } if (!owns.equals("")) { sender.sendMessage(ChatColor.GREEN + "District: " + (isSender ? "You own" : (player + " owns")) + " these regions: " + owns); } else { sender.sendMessage(ChatColor.GREEN + "District: " + (isSender ? "You own" : (player + " owns")) + " no regions"); } } public static void listAll(final Player sender, final String[] args) { if (!sender.hasPermission("district.listall")) { sender.sendMessage("You don't have permission to access that command!"); } if (args.length == 2) { String player = args[1]; list(player, sender); } else if (args.length == 1) { String result = ""; for (String r : Loader.listAll()) { result += r + ", "; } sender.sendMessage(ChatColor.GREEN + "District: The following regions exist: " + result); } else { invalidArgs(sender); } } public static void listMembers(final Player player, final String[] args, final Region r) { if (args.length != 2) { invalidArgs(player); return; } String peeps = ""; if (r.canAdmin(player)) { for (String member : r.getMembers()) { peeps += member + ", "; } if (!peeps.isEmpty()) { player.sendMessage(ChatColor.GREEN + "District: " + r.getName() + " has these members: " + peeps); } else { player.sendMessage(ChatColor.GREEN + "District: " + r.getName() + " has no members"); } } else { Region.sendDeny(player); } } private static void invalidArgs(final Player p) { p.sendMessage("Invalid number of arguments for that command"); } public static void setOwner(final Player player, final String[] args, final Region region) { if (!player.hasPermission("district.setowner")) { player.sendMessage("You don't have permission to access that command!"); } if (args.length != 3) { invalidArgs(player); return; } String newOwnerName = args[2]; OfflinePlayer newOwner = Bukkit.getServer().getOfflinePlayer(newOwnerName); if (!newOwner.hasPlayedBefore()) { player.sendMessage(newOwnerName + " has never been on this server!"); } region.setOwner(newOwnerName); player.sendMessage(ChatColor.GREEN + "District: Owner of region " + region.getName() + " set to " + newOwnerName); } }
false
true
public static void claim(final Player player, final String[] args, final int count) { if (args.length != count) { invalidArgs(player); return; } int size = 0, height; try { size = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { player.sendMessage(args[1] + " is not a valid number"); } if (size % 2 == 0) { player.sendMessage("Size must be odd"); } World world = player.getWorld(); // Limit height to world height height = Math.min(size, world.getMaxHeight()); size /= 2; height /= 2; size = (int) Math.floor(size); height = (int) Math.floor(size); Location point1 = player.getLocation(); Location point2 = player.getLocation(); point1.add(size, height, size); point2.add(-size, -size, -size); if (((Util.getTotalVolume(player.getName()) + Util.getVolume(point1, point2)) > Util.getMaxVolume(player)) && Util.getMaxVolume(player) != -1) { player.sendMessage(ChatColor.RED + "District: You cannot claim a region that big!"); player.sendMessage(ChatColor.RED + "District: Use /district quota to view your remaining quota"); return; } if (Loader.load(args[2]) != null) { player.sendMessage(ChatColor.RED + "District: Region " + args[2] + " is already claimed"); return; } if (Util.isOverlapping(point1, point2)) { player.sendMessage(ChatColor.RED + "District: Error! A region already exists here"); return; } Region creation = new Region(point1.getWorld(), point1, point2, player.getName(), new ArrayList<String>(), args[2]); Loader.save(creation); player.sendMessage(ChatColor.GREEN + "District: A " + args[1] + "x" + args[1] + "x" + args[1] + " (" + creation.getVolume() + " blocks) region named " + creation.getName() + " has been claimed for you!"); }
public static void claim(final Player player, final String[] args, final int count) { if (args.length != count) { invalidArgs(player); return; } int size = 0, height; try { size = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { player.sendMessage(args[1] + " is not a valid number"); return; } if (size % 2 == 0) { player.sendMessage("Size must be odd"); return; } World world = player.getWorld(); // Limit height to world height height = Math.min(size, world.getMaxHeight()); size /= 2; height /= 2; size = (int) Math.floor(size); height = (int) Math.floor(size); Location point1 = player.getLocation(); Location point2 = player.getLocation(); point1.add(size, height, size); point2.add(-size, -size, -size); if (((Util.getTotalVolume(player.getName()) + Util.getVolume(point1, point2)) > Util.getMaxVolume(player)) && Util.getMaxVolume(player) != -1) { player.sendMessage(ChatColor.RED + "District: You cannot claim a region that big!"); player.sendMessage(ChatColor.RED + "District: Use /district quota to view your remaining quota"); return; } if (Loader.load(args[2]) != null) { player.sendMessage(ChatColor.RED + "District: Region " + args[2] + " is already claimed"); return; } if (Util.isOverlapping(point1, point2)) { player.sendMessage(ChatColor.RED + "District: Error! A region already exists here"); return; } Region creation = new Region(point1.getWorld(), point1, point2, player.getName(), new ArrayList<String>(), args[2]); Loader.save(creation); player.sendMessage(ChatColor.GREEN + "District: A " + args[1] + "x" + args[1] + "x" + args[1] + " (" + creation.getVolume() + " blocks) region named " + creation.getName() + " has been claimed for you!"); }
diff --git a/src/com/monitoring/munin_node/munin_service.java b/src/com/monitoring/munin_node/munin_service.java index 15a6455..6a25425 100644 --- a/src/com/monitoring/munin_node/munin_service.java +++ b/src/com/monitoring/munin_node/munin_service.java @@ -1,225 +1,205 @@ package com.monitoring.munin_node; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPOutputStream; import org.acra.ErrorReporter; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Debug; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.provider.Settings.Secure; import com.monitoring.munin_node.protos.Plugins; import com.monitoring.munin_node.plugin_api.LoadPlugins; import com.monitoring.munin_node.plugin_api.PluginFactory; import com.monitoring.munin_node.plugin_api.Plugin_API; public class munin_service extends Service{ final int MUNIN_NOTIFICATION = 1; List<Plugin_API> plugin_objects; @Override public void onDestroy() { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); mNotificationManager.cancel(MUNIN_NOTIFICATION); } @Override public int onStartCommand(Intent intent, int flags, int startId) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Munin Wake Lock"); wakeLock.acquire(); long when = System.currentTimeMillis(); final SharedPreferences settings = this.getSharedPreferences("Munin_Node", 0); final Editor editor = settings.edit(); editor.putLong("new_start_time", when); editor.commit(); final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.notification, "Munin Node Started", when); Context context = getApplicationContext(); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, munin_node.class), 0); notification.setLatestEventInfo(context, "Munin Node", "Just letting you know I am running", contentIntent); notification.flags |= Notification.FLAG_NO_CLEAR; mNotificationManager.notify(MUNIN_NOTIFICATION, notification); class Count{ int ran = 0; int done = 0; public void ranincrement(){ ran++; } public void doneincrement(){ done++; } public Boolean Done(){ if(done == ran){ return true; } else{ return false; } } public void Reset(){ ran = 0; done = 0; } } final Count count = new Count(); final Plugins.Builder plugins = Plugins.newBuilder(); final Handler service_Handler = new Handler(){ @Override public void handleMessage(Message msg){ super.handleMessage(msg); if(msg.what == 42){ Bundle bundle = (Bundle)msg.obj; Plugins.Plugin.Builder plugin = Plugins.Plugin.newBuilder(); plugin.setName(bundle.getString("name")).setConfig(bundle.getString("config")).setUpdate(bundle.getString("update")); plugins.addPlugin(plugin); count.doneincrement(); if(count.Done()){ count.Reset(); ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzipped = null; try { gzipped = new GZIPOutputStream(out); plugins.build().writeTo(gzipped); gzipped.close(); gzipped = null; plugins.clear(); } catch (IOException e) { ErrorReporter.getInstance().handleException(e); } editor.putLong("new_plugin_end_time", System.currentTimeMillis()); String Server = settings.getString("Server", "Server"); Server = Server+Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID); editor.putLong("new_upload_start_time", System.currentTimeMillis()).commit(); new UploadURL(this,Server,out).start(); try { out.close(); out = null; } catch (IOException e) { ErrorReporter.getInstance().handleException(e); } } } else if (msg.what == 43){ editor.putLong("new_upload_end_time", System.currentTimeMillis()).commit(); System.out.println("Upload Finished"); mNotificationManager.cancel(MUNIN_NOTIFICATION);//Cancel Notification that the "service" is running editor.putLong("end_time", System.currentTimeMillis()).commit(); - Integer loopcount = settings.getInt("count", 0); - System.out.println("Loop: "+loopcount); - if (loopcount == 500){ - try { - editor.putInt("count", 0).commit(); - if (settings.getBoolean("enabled", true)){ - editor.putBoolean("enabled", false).commit(); - Debug.dumpHprofData("/sdcard/munin.hprof"); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - else if(loopcount >500){ - editor.putInt("count", 0).commit(); - } - else{ - editor.putInt("count", loopcount+1).commit(); - } System.gc(); wakeLock.release(); } } }; LoadPlugins loadplugins = new LoadPlugins(); List<String> plugin_list = loadplugins.getPluginList(context); /*class plugin_thread extends Thread{ Context Context = null; String p = null; public plugin_thread(Context newcontext, String newp){ Context = new ContextWrapper(newcontext); p = newp; } @Override public void run(){ SharedPreferences settings = Context.getSharedPreferences("Munin_Node", 0); Plugin_API plugin = (Plugin_API)PluginFactory.getPlugin(p); Boolean enabled = settings.getBoolean(plugin.getName(), true); if(enabled){ if(plugin.needsContext()){ plugin.setContext(Context); } plugin.run(service_Handler); } else{ Bundle bundle = new Bundle(); bundle.putString("name", ""); bundle.putString("config", ""); bundle.putString("update", ""); Message msg = Message.obtain(service_Handler, 42, bundle); service_Handler.sendMessage(msg); } return; } }*/ editor.putLong("new_plugin_start_time", System.currentTimeMillis()); editor.commit(); if (plugin_objects == null){ plugin_objects = new ArrayList<Plugin_API>(); for (String p :plugin_list){ Plugin_API plugin = (Plugin_API)PluginFactory.getPlugin(p); Boolean enabled = settings.getBoolean(plugin.getName(), true); if(plugin.needsContext()){ plugin.setContext(this); } if(enabled){ count.ranincrement(); plugin.run(service_Handler); } plugin_objects.add(plugin); } } else{ for(Plugin_API plugin : plugin_objects){ Boolean enabled = settings.getBoolean(plugin.getName(), true); if(enabled){ count.ranincrement(); plugin.run(service_Handler); } } } /*for(final String p : plugin_list){ plugin_thread thread = new plugin_thread(this,p); thread.setDaemon(true); thread.setName(p); thread.start(); count.ranincrement(); }*/ return START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } }
true
true
public int onStartCommand(Intent intent, int flags, int startId) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Munin Wake Lock"); wakeLock.acquire(); long when = System.currentTimeMillis(); final SharedPreferences settings = this.getSharedPreferences("Munin_Node", 0); final Editor editor = settings.edit(); editor.putLong("new_start_time", when); editor.commit(); final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.notification, "Munin Node Started", when); Context context = getApplicationContext(); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, munin_node.class), 0); notification.setLatestEventInfo(context, "Munin Node", "Just letting you know I am running", contentIntent); notification.flags |= Notification.FLAG_NO_CLEAR; mNotificationManager.notify(MUNIN_NOTIFICATION, notification); class Count{ int ran = 0; int done = 0; public void ranincrement(){ ran++; } public void doneincrement(){ done++; } public Boolean Done(){ if(done == ran){ return true; } else{ return false; } } public void Reset(){ ran = 0; done = 0; } } final Count count = new Count(); final Plugins.Builder plugins = Plugins.newBuilder(); final Handler service_Handler = new Handler(){ @Override public void handleMessage(Message msg){ super.handleMessage(msg); if(msg.what == 42){ Bundle bundle = (Bundle)msg.obj; Plugins.Plugin.Builder plugin = Plugins.Plugin.newBuilder(); plugin.setName(bundle.getString("name")).setConfig(bundle.getString("config")).setUpdate(bundle.getString("update")); plugins.addPlugin(plugin); count.doneincrement(); if(count.Done()){ count.Reset(); ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzipped = null; try { gzipped = new GZIPOutputStream(out); plugins.build().writeTo(gzipped); gzipped.close(); gzipped = null; plugins.clear(); } catch (IOException e) { ErrorReporter.getInstance().handleException(e); } editor.putLong("new_plugin_end_time", System.currentTimeMillis()); String Server = settings.getString("Server", "Server"); Server = Server+Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID); editor.putLong("new_upload_start_time", System.currentTimeMillis()).commit(); new UploadURL(this,Server,out).start(); try { out.close(); out = null; } catch (IOException e) { ErrorReporter.getInstance().handleException(e); } } } else if (msg.what == 43){ editor.putLong("new_upload_end_time", System.currentTimeMillis()).commit(); System.out.println("Upload Finished"); mNotificationManager.cancel(MUNIN_NOTIFICATION);//Cancel Notification that the "service" is running editor.putLong("end_time", System.currentTimeMillis()).commit(); Integer loopcount = settings.getInt("count", 0); System.out.println("Loop: "+loopcount); if (loopcount == 500){ try { editor.putInt("count", 0).commit(); if (settings.getBoolean("enabled", true)){ editor.putBoolean("enabled", false).commit(); Debug.dumpHprofData("/sdcard/munin.hprof"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if(loopcount >500){ editor.putInt("count", 0).commit(); } else{ editor.putInt("count", loopcount+1).commit(); } System.gc(); wakeLock.release(); } } }; LoadPlugins loadplugins = new LoadPlugins(); List<String> plugin_list = loadplugins.getPluginList(context); /*class plugin_thread extends Thread{ Context Context = null; String p = null; public plugin_thread(Context newcontext, String newp){ Context = new ContextWrapper(newcontext); p = newp; } @Override public void run(){ SharedPreferences settings = Context.getSharedPreferences("Munin_Node", 0); Plugin_API plugin = (Plugin_API)PluginFactory.getPlugin(p); Boolean enabled = settings.getBoolean(plugin.getName(), true); if(enabled){ if(plugin.needsContext()){ plugin.setContext(Context); } plugin.run(service_Handler); } else{ Bundle bundle = new Bundle(); bundle.putString("name", ""); bundle.putString("config", ""); bundle.putString("update", ""); Message msg = Message.obtain(service_Handler, 42, bundle); service_Handler.sendMessage(msg); } return; } }*/
public int onStartCommand(Intent intent, int flags, int startId) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Munin Wake Lock"); wakeLock.acquire(); long when = System.currentTimeMillis(); final SharedPreferences settings = this.getSharedPreferences("Munin_Node", 0); final Editor editor = settings.edit(); editor.putLong("new_start_time", when); editor.commit(); final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.notification, "Munin Node Started", when); Context context = getApplicationContext(); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, munin_node.class), 0); notification.setLatestEventInfo(context, "Munin Node", "Just letting you know I am running", contentIntent); notification.flags |= Notification.FLAG_NO_CLEAR; mNotificationManager.notify(MUNIN_NOTIFICATION, notification); class Count{ int ran = 0; int done = 0; public void ranincrement(){ ran++; } public void doneincrement(){ done++; } public Boolean Done(){ if(done == ran){ return true; } else{ return false; } } public void Reset(){ ran = 0; done = 0; } } final Count count = new Count(); final Plugins.Builder plugins = Plugins.newBuilder(); final Handler service_Handler = new Handler(){ @Override public void handleMessage(Message msg){ super.handleMessage(msg); if(msg.what == 42){ Bundle bundle = (Bundle)msg.obj; Plugins.Plugin.Builder plugin = Plugins.Plugin.newBuilder(); plugin.setName(bundle.getString("name")).setConfig(bundle.getString("config")).setUpdate(bundle.getString("update")); plugins.addPlugin(plugin); count.doneincrement(); if(count.Done()){ count.Reset(); ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzipped = null; try { gzipped = new GZIPOutputStream(out); plugins.build().writeTo(gzipped); gzipped.close(); gzipped = null; plugins.clear(); } catch (IOException e) { ErrorReporter.getInstance().handleException(e); } editor.putLong("new_plugin_end_time", System.currentTimeMillis()); String Server = settings.getString("Server", "Server"); Server = Server+Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID); editor.putLong("new_upload_start_time", System.currentTimeMillis()).commit(); new UploadURL(this,Server,out).start(); try { out.close(); out = null; } catch (IOException e) { ErrorReporter.getInstance().handleException(e); } } } else if (msg.what == 43){ editor.putLong("new_upload_end_time", System.currentTimeMillis()).commit(); System.out.println("Upload Finished"); mNotificationManager.cancel(MUNIN_NOTIFICATION);//Cancel Notification that the "service" is running editor.putLong("end_time", System.currentTimeMillis()).commit(); System.gc(); wakeLock.release(); } } }; LoadPlugins loadplugins = new LoadPlugins(); List<String> plugin_list = loadplugins.getPluginList(context); /*class plugin_thread extends Thread{ Context Context = null; String p = null; public plugin_thread(Context newcontext, String newp){ Context = new ContextWrapper(newcontext); p = newp; } @Override public void run(){ SharedPreferences settings = Context.getSharedPreferences("Munin_Node", 0); Plugin_API plugin = (Plugin_API)PluginFactory.getPlugin(p); Boolean enabled = settings.getBoolean(plugin.getName(), true); if(enabled){ if(plugin.needsContext()){ plugin.setContext(Context); } plugin.run(service_Handler); } else{ Bundle bundle = new Bundle(); bundle.putString("name", ""); bundle.putString("config", ""); bundle.putString("update", ""); Message msg = Message.obtain(service_Handler, 42, bundle); service_Handler.sendMessage(msg); } return; } }*/
diff --git a/src/haven/RemoteUI.java b/src/haven/RemoteUI.java index 96a5f87..290c112 100644 --- a/src/haven/RemoteUI.java +++ b/src/haven/RemoteUI.java @@ -1,73 +1,73 @@ /* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; public class RemoteUI implements UI.Receiver { Session sess; UI ui; public RemoteUI(Session sess) { this.sess = sess; Widget.initbardas(); } public void rcvmsg(int id, String name, Object... args) { Message msg = new Message(Message.RMSG_WDGMSG); msg.adduint16(id); msg.addstring(name); msg.addlist(args); sess.queuemsg(msg); } public void run(UI ui) throws InterruptedException { this.ui = ui; ui.setreceiver(this); - while (true) { + while (sess.alive()) { Message msg; while ((msg = sess.getuimsg()) != null) { if (msg.type == Message.RMSG_NEWWDG) { int id = msg.uint16(); String type = msg.string(); int parent = msg.uint16(); Object[] pargs = msg.list(); Object[] cargs = msg.list(); ui.newwidget(id, type, parent, pargs, cargs); } else if (msg.type == Message.RMSG_WDGMSG) { int id = msg.uint16(); String name = msg.string(); ui.uimsg(id, name, msg.list()); } else if (msg.type == Message.RMSG_DSTWDG) { int id = msg.uint16(); ui.destroy(id); } } synchronized (sess) { sess.wait(); } } } }
true
true
public void run(UI ui) throws InterruptedException { this.ui = ui; ui.setreceiver(this); while (true) { Message msg; while ((msg = sess.getuimsg()) != null) { if (msg.type == Message.RMSG_NEWWDG) { int id = msg.uint16(); String type = msg.string(); int parent = msg.uint16(); Object[] pargs = msg.list(); Object[] cargs = msg.list(); ui.newwidget(id, type, parent, pargs, cargs); } else if (msg.type == Message.RMSG_WDGMSG) { int id = msg.uint16(); String name = msg.string(); ui.uimsg(id, name, msg.list()); } else if (msg.type == Message.RMSG_DSTWDG) { int id = msg.uint16(); ui.destroy(id); } } synchronized (sess) { sess.wait(); } } }
public void run(UI ui) throws InterruptedException { this.ui = ui; ui.setreceiver(this); while (sess.alive()) { Message msg; while ((msg = sess.getuimsg()) != null) { if (msg.type == Message.RMSG_NEWWDG) { int id = msg.uint16(); String type = msg.string(); int parent = msg.uint16(); Object[] pargs = msg.list(); Object[] cargs = msg.list(); ui.newwidget(id, type, parent, pargs, cargs); } else if (msg.type == Message.RMSG_WDGMSG) { int id = msg.uint16(); String name = msg.string(); ui.uimsg(id, name, msg.list()); } else if (msg.type == Message.RMSG_DSTWDG) { int id = msg.uint16(); ui.destroy(id); } } synchronized (sess) { sess.wait(); } } }
diff --git a/src/common/wustendorf/House.java b/src/common/wustendorf/House.java index f9fa55a..6df00d5 100644 --- a/src/common/wustendorf/House.java +++ b/src/common/wustendorf/House.java @@ -1,708 +1,710 @@ package wustendorf; import net.minecraft.src.*; import java.util.*; public class House { public static final House NO_HOUSE = new House(false); public static final House TOO_MANY_ROOMS = new House(false); public List<Room> rooms = new ArrayList<Room>(); public boolean valid = true; public House() { } public House(boolean valid) { this.valid = valid; } public static House detectHouse(World world, int x, int y, int z) { House house = new House(); Stack<Room> new_rooms = new Stack<Room>(); Room start = Room.detectRoom(new Location(world, x, y, z)); new_rooms.add(start); if (!start.valid) { System.out.println("No house."); return NO_HOUSE; } while (!new_rooms.empty()) { if (house.rooms.size() + new_rooms.size() > 100) { System.out.println("Too many rooms."); return TOO_MANY_ROOMS; } Room room = new_rooms.pop(); room.connect(house.rooms); house.rooms.add(room); for (Location connector : room.unexploredConnections()) { // This will update new_rooms if it finds a new valid room. room.explore(connector, new_rooms); } } return house; } public static class Room { public static final Room OUTSIDE = new Room(false); public static final Room SPACE = OUTSIDE; public static final Room DANGEROUS = new Room(false); public static final Room NONCONTIGUOUS = new Room(false); public Location origin = null; public Map<Location, BlockType> blocks = new HashMap<Location, BlockType>(); public Map<Location, Room> connections = new HashMap<Location, Room>(); public boolean valid = true; public Room() { } public Room(boolean valid) { this.valid = valid; } public static void reportBlock(String message, int x, int y, int z) { System.out.println("@(" + x + "," + y + "," + z + "): " + message); } public static void reportBlock(String message, Location loc) { reportBlock(message, loc.x, loc.y, loc.z); } public static Room detectRoom(Location start) { Room room = new Room(); World world = start.world; int x = start.x; int y = start.y; int z = start.z; BlockType type; // Descend to the bottom of the first air pocket at or below start. boolean found_air = false; int min_y = Math.max(0, y-5); for (y = start.y; y >= 0; y--) { type = BlockType.typeOf(new Location(world, x, y, z)); - if (type == BlockType.AIR_LIKE) { + if (type.isFlag()) { + continue; + } else if (type.isLadder() || !type.isSolidOrUnsafe()) { found_air = true; } else if (found_air) { y++; // Go back into the air. break; } else if (y < min_y) { break; } } if (!found_air || BlockType.typeOf(new Location(world, x, y+1, z)).isSolid()) { reportBlock("No air pocket found.", x, y, z); return OUTSIDE; } Stack<Location> new_columns = new Stack<Location>(); Stack<Location> wall_columns = new Stack<Location>(); Stack<Location> doors = new Stack<Location>(); Stack<Location> required_blocks = new Stack<Location>(); new_columns.add(new Location(world, x, y, z)); int loop_count = 0; while (!new_columns.empty()) { loop_count++; if (room.blocks.size() > 10000 || loop_count > 5000) { System.out.println("Too many blocks in room."); return OUTSIDE; } // One of the horizontal neighbors of this is a ground-level block: empty on solid. // (or this is the starting spot) Location block = new_columns.pop(); type = BlockType.typeOf(block); Location block_above = block.above(); BlockType type_above = BlockType.typeOf(block_above); Location block_below = block.below(); BlockType type_below = BlockType.typeOf(block_below); //reportBlock("Visiting.", block); if (type_above.isSolidOrUnsafe()) { wall_columns.add(block_above); continue; } else if (!type.isSafe()) { wall_columns.add(block); continue; } else if (type.isSolid()) { if (!BlockType.typeOf(block.above(2)).isSolidOrUnsafe()) { block = block_above; type = type_above; } else { wall_columns.add(block); wall_columns.add(block.above(2)); continue; } } else if (!type_below.isSafe()) { reportBlock("Unsafe floor tile.", block); return DANGEROUS; } else if (!type_below.isSolid()) { if (type_below.isLadder() || BlockType.typeOf(block.below(2)).isSolidAndSafe()) { block = block_below; type = type_below; } else { Location safe_landing = null; for (int depth=2; depth<5; depth++) { block_below = block.below(depth); type_below = BlockType.typeOf(block_below); if (!type_below.isSafe()) { reportBlock("Drop into unsafe tile.", block_below); return DANGEROUS; } else if (type_below.isSolid()) { safe_landing = block_below; break; } } if (safe_landing == null) { reportBlock("Unsafe drop distance.", block_below); return DANGEROUS; } else { required_blocks.add(safe_landing); continue; } } } // block now contains the ground-level block. if (room.origin == null) { room.origin = block; } if (type.isLadder()) { //reportBlock("Ladder", block); boolean bottom_ok = false; for (int depth=1; depth <= block.y; depth++) { block_below = block.below(depth); type_below = BlockType.typeOf(block_below); room.blocks.put(block_below, type_below); if (type_below.isLadder()) { continue; } else if (type_below.isSolidAndSafe()) { if (type_below.isDoor()) { doors.add(block_below); } bottom_ok = true; break; } else { reportBlock("Unsafe block below ladder.", block_below); return DANGEROUS; } } if (!bottom_ok) { reportBlock("Ladder to the void.", block_below); return DANGEROUS; } Location ladder_bottom = block_below; BlockType ladder_bottom_type = type_below; boolean top_ok = false; for (int height=1; height + block.y < 255; height++) { block_above = block.above(height); type_above = BlockType.typeOf(block_above); room.blocks.put(block_above, type_above); if (type_above.isLadder()) { continue; } else if (!type_above.isSafe()) { reportBlock("Unsafe block above ladder.", block_above); return DANGEROUS; } else { room.blocks.put(block_above, type_above); if (type_above.isDoor()) { doors.add(block_above); } top_ok = true; break; } } if (!top_ok) { reportBlock("Ladder to space.", block_above); return SPACE; } Location ladder_top = block_above; BlockType ladder_top_type = type_above; boolean[] had_floor = new boolean[] {false, false, false, false}; for (y=ladder_bottom.y - 1; y < ladder_top.y; y++) { Location ladder = new Location(world, ladder_bottom.x, y, ladder_bottom.z); if (y >= ladder_bottom.y) { room.blocks.put(ladder, BlockType.LADDER_LIKE); } for (int dir=0; dir<4; dir++) { Location neighbor = ladder.step(dir); BlockType neighbor_type = room.blocks.get(neighbor); //reportBlock("Next to ladder.", neighbor); if (neighbor_type != null) { // We've already visited here, so just note down if it's a floor // and continue. had_floor[dir] = neighbor_type.isSolidAndSafe(); continue; } neighbor_type = BlockType.typeOf(neighbor); if (neighbor_type.isSolidAndSafe()) { had_floor[dir] = true; if (y > ladder_bottom.y) { //reportBlock("Ladder's wall.", neighbor); // Register it as a wall. room.blocks.put(neighbor, neighbor_type); // And a door, if applicable. if (neighbor_type.isDoor()) { doors.add(neighbor); } } continue; } else if (had_floor[dir] && neighbor_type.isSafe()) { if (!BlockType.typeOf(neighbor.above()).isSolidOrUnsafe()) { if (y == ladder_bottom.y && !BlockType.typeOf(neighbor.above(2)).isSolidOrUnsafe()) { had_floor[dir] = false; continue; } new_columns.add(neighbor); } } had_floor[dir] = false; } } if (ladder_top_type.isSolid() || BlockType.typeOf(ladder_top.above()).isSolid()) { continue; } block = ladder_top; } // Register the floor. block_below = block.below(); room.blocks.put(block_below, BlockType.typeOf(block_below)); if (BlockType.typeOf(block_below).isDoor()) { doors.add(block_below); } // Register what's above the floor, up to the ceiling. for (int height=0; height<8; height++) { // This will include block itself. block_above = block.above(height); type = BlockType.typeOf(block_above); room.blocks.put(block_above, type); if (type.isSolid()) { break; } } for (int dir=0; dir<4; dir++) { Location neighbor = block.step(dir); if (!room.blocks.containsKey(neighbor)) { //reportBlock("Adding at spot 2", neighbor); new_columns.add(neighbor); } } } // Register the walls for (Location wall_start : wall_columns) { for (int depth=0; depth <= wall_start.y; depth++) { Location wall = wall_start.below(depth); BlockType wall_type = room.blocks.get(wall); if (wall_type != null) { // Already registered; break; } wall_type = BlockType.typeOf(wall); if (!wall_type.isSolidOrUnsafe()) { break; } boolean found_room = false; for (int dir=0; dir<6; dir++) { Location neighbor = wall.step(dir); BlockType neighbor_type = room.blocks.get(neighbor); if (neighbor_type != null) { // In the room. if (!neighbor_type.isSolidOrUnsafe()) { // Empty block. found_room = true; } } } if (found_room) { room.blocks.put(wall, wall_type); if (wall_type.isDoor()) { doors.add(wall); } } } } // Add connections for doors. List<Location> unexplored_blocks = new ArrayList<Location>(); for (Location door : doors) { unexplored_blocks.clear(); for (int dir=0; dir<6; dir++) { Location neighbor = door.step(dir); BlockType neighbor_type = room.blocks.get(neighbor); if (neighbor_type == null) { // Not in the room. neighbor_type = BlockType.typeOf(neighbor); if (!neighbor_type.isSolidOrUnsafe()) { unexplored_blocks.add(neighbor); } } } if (unexplored_blocks.size() > 0) { for (Location connector : unexplored_blocks) { room.connections.put(connector, null); } } } // Ensure that anywhere you can safely fall to is still in the room. for (Location landing : required_blocks) { if (!room.containsBlock(landing)) { reportBlock("Drop to outside room.", landing); return NONCONTIGUOUS; } } return room; } public List<Location> unexploredConnections() { // Get all the connections that don't have a known room to connect // to yet. List<Location> unexplored = new ArrayList<Location>(); for (Location connector : connections.keySet()) { if (connections.get(connector) == null) { unexplored.add(connector); } } return unexplored; } public boolean containsBlock(Location block) { // Is this location anywhere in the room? if (blocks.containsKey(block)) { return true; } return false; } public void connect(List<Room> known_rooms) { // For each connector... for (Location connector : connections.keySet()) { // ...that doesn't know where it connects... if (connections.get(connector) == null) { // ...see if it connects to any of the known rooms. for (Room neighbor : known_rooms) { // If it does... if (neighbor.containsBlock(connector)) { // ...note the connection. connections.put(connector, neighbor); break; } } } } } public void explore(Location connector, List<Room> recent_additions) { // Explore the room at this connector, and add it to recent_additions. if (!connections.containsKey(connector) || connections.get(connector) != null) { // This isn't an unexplored connector. return; } for (Room candidate : recent_additions) { if (candidate.containsBlock(connector)) { // Nothing to do, just record the connection. connections.put(connector, candidate); return; } } // Seems to be a new room; explore it. Room neighbor = detectRoom(connector); connections.put(connector, neighbor); if (neighbor.valid) { recent_additions.add(neighbor); } } } public static class Location { World world; public int x; public int y; public int z; public Location(World world, int x, int y, int z) { this.world = world; this.x = x; this.y = y; this.z = z; } public Location above(int dist) { return new Location(world, x, y+dist, z); } public Location below(int dist) { return new Location(world, x, y-dist, z); } public Location above() { return above(1); } public Location below() { return below(1); } public Location step(int dir) { int new_x = x; int new_y = y; int new_z = z; if (dir == 0) { new_x++; } else if (dir == 1) { new_z++; } else if (dir == 2) { new_x--; } else if (dir == 3) { new_z--; } else if (dir == 4) { new_y++; } else if (dir == 5) { new_y--; } else { throw new IllegalArgumentException("Bad direction."); } return new Location(world, new_x, new_y, new_z); } public int hashCode() { int hash = 0; hash += (x & 0xff); hash += (y & 0xff) << 8; hash += (z & 0xff) << 16; return hash; } public boolean equals(Object other) { if (other instanceof Location) { Location other_loc = (Location) other; return (world == other_loc.world && x == other_loc.x && y == other_loc.y && z == other_loc.z); } else { return false; } } } public static class BlockType { public static final int PLAIN = 0; public static final int DOOR = 1; public static final int LADDER = 2; public static final int FENCE = 4; public static final int FAKE = 8; public static final int FLAG = 16; public static final int TILE_ENTITY = 32; public static BlockType AIR_LIKE = new BlockType(false, true, PLAIN); public static BlockType STONE_LIKE = new BlockType(true, true, PLAIN); public static BlockType ABOVE_FENCE = new BlockType(true, true, FAKE); public static BlockType LAVA_LIKE = new BlockType(false, false, PLAIN); public static BlockType CACTUS_LIKE = new BlockType(true, false, PLAIN); public static BlockType DOOR_LIKE = new BlockType(true, true, DOOR); public static BlockType LADDER_LIKE = new BlockType(false, true, LADDER); public static BlockType FENCE_LIKE = new BlockType(false, true, FENCE); public static BlockType HOUSE_FLAG = new BlockType(false, true, FLAG); public static BlockType CHEST_LIKE = new BlockType(true, true, TILE_ENTITY); boolean solid; boolean safe; int flags; public BlockType(boolean solid, boolean safe, int flags) { this.solid = solid; this.safe = safe; this.flags = flags; } public boolean isSolid() { return solid; } public boolean isSafe() { return safe; } public boolean isSolidAndSafe() { return solid && safe; } public boolean isSolidOrUnsafe() { return solid || !safe; } public boolean isLadder() { return (flags & LADDER) == LADDER; } public boolean isDoor() { return (flags & DOOR) == DOOR; } public boolean isFence() { return (flags & FENCE) == FENCE; } public boolean isFake() { return (flags & FAKE) == FAKE; } public boolean isFlag() { return (flags & FLAG) == FLAG; } public boolean isInteresting() { // We may add more flags to the "interesting" list later. return (flags & (TILE_ENTITY)) > 0; } public boolean equals(Object other) { if (other instanceof BlockType) { BlockType other_type = (BlockType) other; if (solid == other_type.solid && safe == other_type.safe && flags == other_type.flags) { return true; } } return false; } public static BlockType typeOf(Location loc) { return typeOf(loc, true); } public static BlockType typeOf(Location loc, boolean check_for_fence) { int id = loc.world.getBlockId(loc.x, loc.y, loc.z); int meta = loc.world.getBlockMetadata(loc.x, loc.y, loc.z); if (id == 0) { if (check_for_fence) { return fenceCheck(loc); } else { return AIR_LIKE; } } BlockType override = Wustendorf.getTypeOverride(id, meta); if (override != null) { return override; } Block block = Block.blocksList[id]; if (block instanceof WustendorfMarker) { return HOUSE_FLAG; } else if (block.isLadder(loc.world, loc.x, loc.y, loc.z)) { return LADDER_LIKE; } else if (id == Block.doorWood.blockID || id == Block.trapdoor.blockID) { return DOOR_LIKE; } int flags = PLAIN; if (block.hasTileEntity(meta)) { flags |= TILE_ENTITY; } AxisAlignedBB bb = block.getCollisionBoundingBoxFromPool(loc.world, loc.x, loc.y, loc.z); boolean solid = (bb != null); if (solid) { Vec3 above = Vec3.createVectorHelper(loc.x+0.5, loc.y+1.3, loc.z+0.5); if (bb.isVecInside(above)) { flags |= FENCE; } } boolean safe = true; if ( id == Block.fire.blockID || id == Block.lavaMoving.blockID || id == Block.lavaStill.blockID || id == Block.cactus.blockID) { safe = false; } BlockType type = new BlockType(solid, safe, flags); if (check_for_fence && type.equals(AIR_LIKE)) { return fenceCheck(loc); } return type; } public static BlockType fenceCheck(Location loc) { BlockType type_below = typeOf(loc.below(), false); if (type_below.isFence()) { return ABOVE_FENCE; } return AIR_LIKE; } } }
true
true
public static Room detectRoom(Location start) { Room room = new Room(); World world = start.world; int x = start.x; int y = start.y; int z = start.z; BlockType type; // Descend to the bottom of the first air pocket at or below start. boolean found_air = false; int min_y = Math.max(0, y-5); for (y = start.y; y >= 0; y--) { type = BlockType.typeOf(new Location(world, x, y, z)); if (type == BlockType.AIR_LIKE) { found_air = true; } else if (found_air) { y++; // Go back into the air. break; } else if (y < min_y) { break; } } if (!found_air || BlockType.typeOf(new Location(world, x, y+1, z)).isSolid()) { reportBlock("No air pocket found.", x, y, z); return OUTSIDE; } Stack<Location> new_columns = new Stack<Location>(); Stack<Location> wall_columns = new Stack<Location>(); Stack<Location> doors = new Stack<Location>(); Stack<Location> required_blocks = new Stack<Location>(); new_columns.add(new Location(world, x, y, z)); int loop_count = 0; while (!new_columns.empty()) { loop_count++; if (room.blocks.size() > 10000 || loop_count > 5000) { System.out.println("Too many blocks in room."); return OUTSIDE; } // One of the horizontal neighbors of this is a ground-level block: empty on solid. // (or this is the starting spot) Location block = new_columns.pop(); type = BlockType.typeOf(block); Location block_above = block.above(); BlockType type_above = BlockType.typeOf(block_above); Location block_below = block.below(); BlockType type_below = BlockType.typeOf(block_below); //reportBlock("Visiting.", block); if (type_above.isSolidOrUnsafe()) { wall_columns.add(block_above); continue; } else if (!type.isSafe()) { wall_columns.add(block); continue; } else if (type.isSolid()) { if (!BlockType.typeOf(block.above(2)).isSolidOrUnsafe()) { block = block_above; type = type_above; } else { wall_columns.add(block); wall_columns.add(block.above(2)); continue; } } else if (!type_below.isSafe()) { reportBlock("Unsafe floor tile.", block); return DANGEROUS; } else if (!type_below.isSolid()) { if (type_below.isLadder() || BlockType.typeOf(block.below(2)).isSolidAndSafe()) { block = block_below; type = type_below; } else { Location safe_landing = null; for (int depth=2; depth<5; depth++) { block_below = block.below(depth); type_below = BlockType.typeOf(block_below); if (!type_below.isSafe()) { reportBlock("Drop into unsafe tile.", block_below); return DANGEROUS; } else if (type_below.isSolid()) { safe_landing = block_below; break; } } if (safe_landing == null) { reportBlock("Unsafe drop distance.", block_below); return DANGEROUS; } else { required_blocks.add(safe_landing); continue; } } } // block now contains the ground-level block. if (room.origin == null) { room.origin = block; } if (type.isLadder()) { //reportBlock("Ladder", block); boolean bottom_ok = false; for (int depth=1; depth <= block.y; depth++) { block_below = block.below(depth); type_below = BlockType.typeOf(block_below); room.blocks.put(block_below, type_below); if (type_below.isLadder()) { continue; } else if (type_below.isSolidAndSafe()) { if (type_below.isDoor()) { doors.add(block_below); } bottom_ok = true; break; } else { reportBlock("Unsafe block below ladder.", block_below); return DANGEROUS; } } if (!bottom_ok) { reportBlock("Ladder to the void.", block_below); return DANGEROUS; } Location ladder_bottom = block_below; BlockType ladder_bottom_type = type_below; boolean top_ok = false; for (int height=1; height + block.y < 255; height++) { block_above = block.above(height); type_above = BlockType.typeOf(block_above); room.blocks.put(block_above, type_above); if (type_above.isLadder()) { continue; } else if (!type_above.isSafe()) { reportBlock("Unsafe block above ladder.", block_above); return DANGEROUS; } else { room.blocks.put(block_above, type_above); if (type_above.isDoor()) { doors.add(block_above); } top_ok = true; break; } } if (!top_ok) { reportBlock("Ladder to space.", block_above); return SPACE; } Location ladder_top = block_above; BlockType ladder_top_type = type_above; boolean[] had_floor = new boolean[] {false, false, false, false}; for (y=ladder_bottom.y - 1; y < ladder_top.y; y++) { Location ladder = new Location(world, ladder_bottom.x, y, ladder_bottom.z); if (y >= ladder_bottom.y) { room.blocks.put(ladder, BlockType.LADDER_LIKE); } for (int dir=0; dir<4; dir++) { Location neighbor = ladder.step(dir); BlockType neighbor_type = room.blocks.get(neighbor); //reportBlock("Next to ladder.", neighbor); if (neighbor_type != null) { // We've already visited here, so just note down if it's a floor // and continue. had_floor[dir] = neighbor_type.isSolidAndSafe(); continue; } neighbor_type = BlockType.typeOf(neighbor); if (neighbor_type.isSolidAndSafe()) { had_floor[dir] = true; if (y > ladder_bottom.y) { //reportBlock("Ladder's wall.", neighbor); // Register it as a wall. room.blocks.put(neighbor, neighbor_type); // And a door, if applicable. if (neighbor_type.isDoor()) { doors.add(neighbor); } } continue; } else if (had_floor[dir] && neighbor_type.isSafe()) { if (!BlockType.typeOf(neighbor.above()).isSolidOrUnsafe()) { if (y == ladder_bottom.y && !BlockType.typeOf(neighbor.above(2)).isSolidOrUnsafe()) { had_floor[dir] = false; continue; } new_columns.add(neighbor); } } had_floor[dir] = false; } } if (ladder_top_type.isSolid() || BlockType.typeOf(ladder_top.above()).isSolid()) { continue; } block = ladder_top; } // Register the floor. block_below = block.below(); room.blocks.put(block_below, BlockType.typeOf(block_below)); if (BlockType.typeOf(block_below).isDoor()) { doors.add(block_below); } // Register what's above the floor, up to the ceiling. for (int height=0; height<8; height++) { // This will include block itself. block_above = block.above(height); type = BlockType.typeOf(block_above); room.blocks.put(block_above, type); if (type.isSolid()) { break; } } for (int dir=0; dir<4; dir++) { Location neighbor = block.step(dir); if (!room.blocks.containsKey(neighbor)) { //reportBlock("Adding at spot 2", neighbor); new_columns.add(neighbor); } } } // Register the walls for (Location wall_start : wall_columns) { for (int depth=0; depth <= wall_start.y; depth++) { Location wall = wall_start.below(depth); BlockType wall_type = room.blocks.get(wall); if (wall_type != null) { // Already registered; break; } wall_type = BlockType.typeOf(wall); if (!wall_type.isSolidOrUnsafe()) { break; } boolean found_room = false; for (int dir=0; dir<6; dir++) { Location neighbor = wall.step(dir); BlockType neighbor_type = room.blocks.get(neighbor); if (neighbor_type != null) { // In the room. if (!neighbor_type.isSolidOrUnsafe()) { // Empty block. found_room = true; } } } if (found_room) { room.blocks.put(wall, wall_type); if (wall_type.isDoor()) { doors.add(wall); } } } } // Add connections for doors. List<Location> unexplored_blocks = new ArrayList<Location>(); for (Location door : doors) { unexplored_blocks.clear(); for (int dir=0; dir<6; dir++) { Location neighbor = door.step(dir); BlockType neighbor_type = room.blocks.get(neighbor); if (neighbor_type == null) { // Not in the room. neighbor_type = BlockType.typeOf(neighbor); if (!neighbor_type.isSolidOrUnsafe()) { unexplored_blocks.add(neighbor); } } } if (unexplored_blocks.size() > 0) { for (Location connector : unexplored_blocks) { room.connections.put(connector, null); } } } // Ensure that anywhere you can safely fall to is still in the room. for (Location landing : required_blocks) { if (!room.containsBlock(landing)) { reportBlock("Drop to outside room.", landing); return NONCONTIGUOUS; } } return room; }
public static Room detectRoom(Location start) { Room room = new Room(); World world = start.world; int x = start.x; int y = start.y; int z = start.z; BlockType type; // Descend to the bottom of the first air pocket at or below start. boolean found_air = false; int min_y = Math.max(0, y-5); for (y = start.y; y >= 0; y--) { type = BlockType.typeOf(new Location(world, x, y, z)); if (type.isFlag()) { continue; } else if (type.isLadder() || !type.isSolidOrUnsafe()) { found_air = true; } else if (found_air) { y++; // Go back into the air. break; } else if (y < min_y) { break; } } if (!found_air || BlockType.typeOf(new Location(world, x, y+1, z)).isSolid()) { reportBlock("No air pocket found.", x, y, z); return OUTSIDE; } Stack<Location> new_columns = new Stack<Location>(); Stack<Location> wall_columns = new Stack<Location>(); Stack<Location> doors = new Stack<Location>(); Stack<Location> required_blocks = new Stack<Location>(); new_columns.add(new Location(world, x, y, z)); int loop_count = 0; while (!new_columns.empty()) { loop_count++; if (room.blocks.size() > 10000 || loop_count > 5000) { System.out.println("Too many blocks in room."); return OUTSIDE; } // One of the horizontal neighbors of this is a ground-level block: empty on solid. // (or this is the starting spot) Location block = new_columns.pop(); type = BlockType.typeOf(block); Location block_above = block.above(); BlockType type_above = BlockType.typeOf(block_above); Location block_below = block.below(); BlockType type_below = BlockType.typeOf(block_below); //reportBlock("Visiting.", block); if (type_above.isSolidOrUnsafe()) { wall_columns.add(block_above); continue; } else if (!type.isSafe()) { wall_columns.add(block); continue; } else if (type.isSolid()) { if (!BlockType.typeOf(block.above(2)).isSolidOrUnsafe()) { block = block_above; type = type_above; } else { wall_columns.add(block); wall_columns.add(block.above(2)); continue; } } else if (!type_below.isSafe()) { reportBlock("Unsafe floor tile.", block); return DANGEROUS; } else if (!type_below.isSolid()) { if (type_below.isLadder() || BlockType.typeOf(block.below(2)).isSolidAndSafe()) { block = block_below; type = type_below; } else { Location safe_landing = null; for (int depth=2; depth<5; depth++) { block_below = block.below(depth); type_below = BlockType.typeOf(block_below); if (!type_below.isSafe()) { reportBlock("Drop into unsafe tile.", block_below); return DANGEROUS; } else if (type_below.isSolid()) { safe_landing = block_below; break; } } if (safe_landing == null) { reportBlock("Unsafe drop distance.", block_below); return DANGEROUS; } else { required_blocks.add(safe_landing); continue; } } } // block now contains the ground-level block. if (room.origin == null) { room.origin = block; } if (type.isLadder()) { //reportBlock("Ladder", block); boolean bottom_ok = false; for (int depth=1; depth <= block.y; depth++) { block_below = block.below(depth); type_below = BlockType.typeOf(block_below); room.blocks.put(block_below, type_below); if (type_below.isLadder()) { continue; } else if (type_below.isSolidAndSafe()) { if (type_below.isDoor()) { doors.add(block_below); } bottom_ok = true; break; } else { reportBlock("Unsafe block below ladder.", block_below); return DANGEROUS; } } if (!bottom_ok) { reportBlock("Ladder to the void.", block_below); return DANGEROUS; } Location ladder_bottom = block_below; BlockType ladder_bottom_type = type_below; boolean top_ok = false; for (int height=1; height + block.y < 255; height++) { block_above = block.above(height); type_above = BlockType.typeOf(block_above); room.blocks.put(block_above, type_above); if (type_above.isLadder()) { continue; } else if (!type_above.isSafe()) { reportBlock("Unsafe block above ladder.", block_above); return DANGEROUS; } else { room.blocks.put(block_above, type_above); if (type_above.isDoor()) { doors.add(block_above); } top_ok = true; break; } } if (!top_ok) { reportBlock("Ladder to space.", block_above); return SPACE; } Location ladder_top = block_above; BlockType ladder_top_type = type_above; boolean[] had_floor = new boolean[] {false, false, false, false}; for (y=ladder_bottom.y - 1; y < ladder_top.y; y++) { Location ladder = new Location(world, ladder_bottom.x, y, ladder_bottom.z); if (y >= ladder_bottom.y) { room.blocks.put(ladder, BlockType.LADDER_LIKE); } for (int dir=0; dir<4; dir++) { Location neighbor = ladder.step(dir); BlockType neighbor_type = room.blocks.get(neighbor); //reportBlock("Next to ladder.", neighbor); if (neighbor_type != null) { // We've already visited here, so just note down if it's a floor // and continue. had_floor[dir] = neighbor_type.isSolidAndSafe(); continue; } neighbor_type = BlockType.typeOf(neighbor); if (neighbor_type.isSolidAndSafe()) { had_floor[dir] = true; if (y > ladder_bottom.y) { //reportBlock("Ladder's wall.", neighbor); // Register it as a wall. room.blocks.put(neighbor, neighbor_type); // And a door, if applicable. if (neighbor_type.isDoor()) { doors.add(neighbor); } } continue; } else if (had_floor[dir] && neighbor_type.isSafe()) { if (!BlockType.typeOf(neighbor.above()).isSolidOrUnsafe()) { if (y == ladder_bottom.y && !BlockType.typeOf(neighbor.above(2)).isSolidOrUnsafe()) { had_floor[dir] = false; continue; } new_columns.add(neighbor); } } had_floor[dir] = false; } } if (ladder_top_type.isSolid() || BlockType.typeOf(ladder_top.above()).isSolid()) { continue; } block = ladder_top; } // Register the floor. block_below = block.below(); room.blocks.put(block_below, BlockType.typeOf(block_below)); if (BlockType.typeOf(block_below).isDoor()) { doors.add(block_below); } // Register what's above the floor, up to the ceiling. for (int height=0; height<8; height++) { // This will include block itself. block_above = block.above(height); type = BlockType.typeOf(block_above); room.blocks.put(block_above, type); if (type.isSolid()) { break; } } for (int dir=0; dir<4; dir++) { Location neighbor = block.step(dir); if (!room.blocks.containsKey(neighbor)) { //reportBlock("Adding at spot 2", neighbor); new_columns.add(neighbor); } } } // Register the walls for (Location wall_start : wall_columns) { for (int depth=0; depth <= wall_start.y; depth++) { Location wall = wall_start.below(depth); BlockType wall_type = room.blocks.get(wall); if (wall_type != null) { // Already registered; break; } wall_type = BlockType.typeOf(wall); if (!wall_type.isSolidOrUnsafe()) { break; } boolean found_room = false; for (int dir=0; dir<6; dir++) { Location neighbor = wall.step(dir); BlockType neighbor_type = room.blocks.get(neighbor); if (neighbor_type != null) { // In the room. if (!neighbor_type.isSolidOrUnsafe()) { // Empty block. found_room = true; } } } if (found_room) { room.blocks.put(wall, wall_type); if (wall_type.isDoor()) { doors.add(wall); } } } } // Add connections for doors. List<Location> unexplored_blocks = new ArrayList<Location>(); for (Location door : doors) { unexplored_blocks.clear(); for (int dir=0; dir<6; dir++) { Location neighbor = door.step(dir); BlockType neighbor_type = room.blocks.get(neighbor); if (neighbor_type == null) { // Not in the room. neighbor_type = BlockType.typeOf(neighbor); if (!neighbor_type.isSolidOrUnsafe()) { unexplored_blocks.add(neighbor); } } } if (unexplored_blocks.size() > 0) { for (Location connector : unexplored_blocks) { room.connections.put(connector, null); } } } // Ensure that anywhere you can safely fall to is still in the room. for (Location landing : required_blocks) { if (!room.containsBlock(landing)) { reportBlock("Drop to outside room.", landing); return NONCONTIGUOUS; } } return room; }
diff --git a/webapp/src/main/java/org/vaadin/tori/component/NewThreadComponent.java b/webapp/src/main/java/org/vaadin/tori/component/NewThreadComponent.java index 96a241c0..ba9b1841 100644 --- a/webapp/src/main/java/org/vaadin/tori/component/NewThreadComponent.java +++ b/webapp/src/main/java/org/vaadin/tori/component/NewThreadComponent.java @@ -1,29 +1,29 @@ /* * Copyright 2012 Vaadin 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.vaadin.tori.component; @SuppressWarnings("serial") public class NewThreadComponent extends AuthoringComponent { public interface NewThreadListener extends AuthoringListener { } public NewThreadComponent(final NewThreadListener listener, final String formattingSyntaxXhtml) { - super(listener, formattingSyntaxXhtml, "Thread body"); + super(listener, formattingSyntaxXhtml, "Post body"); } }
true
true
public NewThreadComponent(final NewThreadListener listener, final String formattingSyntaxXhtml) { super(listener, formattingSyntaxXhtml, "Thread body"); }
public NewThreadComponent(final NewThreadListener listener, final String formattingSyntaxXhtml) { super(listener, formattingSyntaxXhtml, "Post body"); }
diff --git a/src/com/github/joakimpersson/tda367/controller/UpgradePlayerState.java b/src/com/github/joakimpersson/tda367/controller/UpgradePlayerState.java index 99ed1ba..7394e26 100644 --- a/src/com/github/joakimpersson/tda367/controller/UpgradePlayerState.java +++ b/src/com/github/joakimpersson/tda367/controller/UpgradePlayerState.java @@ -1,129 +1,129 @@ package com.github.joakimpersson.tda367.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import com.github.joakimpersson.tda367.controller.input.InputData; import com.github.joakimpersson.tda367.controller.input.InputManager; import com.github.joakimpersson.tda367.gui.IUpgradePlayerView; import com.github.joakimpersson.tda367.gui.UpgradePlayerView; import com.github.joakimpersson.tda367.model.BombermanModel; import com.github.joakimpersson.tda367.model.IBombermanModel; import com.github.joakimpersson.tda367.model.constants.Attribute; import com.github.joakimpersson.tda367.model.constants.PlayerAction; import com.github.joakimpersson.tda367.model.player.Player; /** * * @author joakimpersson * */ public class UpgradePlayerState extends BasicGameState { private int stateID = -1; private IUpgradePlayerView view = null; private IBombermanModel model = null; private Map<Player, Integer> playersIndex = null; private List<Attribute> attributes = null; private InputManager inputManager = null; public UpgradePlayerState(int stateID) { this.stateID = stateID; } @Override public void init(GameContainer container, StateBasedGame game) throws SlickException { view = new UpgradePlayerView(); model = BombermanModel.getInstance(); inputManager = InputManager.getInstance(); attributes = model.getPlayers().get(0).getPermanentAttributes(); playersIndex = new HashMap<Player, Integer>(); for (Player p : model.getPlayers()) { playersIndex.put(p, 0); } } @Override public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { view.render(container, g, playersIndex); } @Override public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { Input input = container.getInput(); // TODO jocke only used during development if (input.isKeyDown(Input.KEY_ESCAPE)) { container.exit(); } - if (inputManager.pressedProcced(input)) { + if (inputManager.pressedProceed(input)) { game.enterState(BombermanGame.GAMEPLAY_STATE); } // TODO change location List<PlayerAction> actions = new ArrayList<PlayerAction>(); actions.add(PlayerAction.MoveUp); actions.add(PlayerAction.MoveDown); // should be rename to action perhaps actions.add(PlayerAction.Action); List<InputData> data = inputManager.getData(input, actions); for (InputData d : data) { PlayerAction action = d.getAction(); Player p = d.getPlayer(); switch (action) { case MoveUp: moveIndex(p, -1); break; case MoveDown: moveIndex(p, 1); break; case Action: model.upgradePlayer(p, attributes.get(playersIndex.get(p))); break; default: break; } } // TODO really bad solution try { Thread.sleep(80); } catch (InterruptedException e) { e.printStackTrace(); } } private void moveIndex(Player p, int delta) { int currentIndex = playersIndex.get(p); int n = attributes.size(); int newIndex = (currentIndex + delta); int r = newIndex % n; if (r < 0) { r += n; } playersIndex.put(p, r); } @Override public int getID() { return stateID; } }
true
true
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { Input input = container.getInput(); // TODO jocke only used during development if (input.isKeyDown(Input.KEY_ESCAPE)) { container.exit(); } if (inputManager.pressedProcced(input)) { game.enterState(BombermanGame.GAMEPLAY_STATE); } // TODO change location List<PlayerAction> actions = new ArrayList<PlayerAction>(); actions.add(PlayerAction.MoveUp); actions.add(PlayerAction.MoveDown); // should be rename to action perhaps actions.add(PlayerAction.Action); List<InputData> data = inputManager.getData(input, actions); for (InputData d : data) { PlayerAction action = d.getAction(); Player p = d.getPlayer(); switch (action) { case MoveUp: moveIndex(p, -1); break; case MoveDown: moveIndex(p, 1); break; case Action: model.upgradePlayer(p, attributes.get(playersIndex.get(p))); break; default: break; } } // TODO really bad solution try { Thread.sleep(80); } catch (InterruptedException e) { e.printStackTrace(); } }
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { Input input = container.getInput(); // TODO jocke only used during development if (input.isKeyDown(Input.KEY_ESCAPE)) { container.exit(); } if (inputManager.pressedProceed(input)) { game.enterState(BombermanGame.GAMEPLAY_STATE); } // TODO change location List<PlayerAction> actions = new ArrayList<PlayerAction>(); actions.add(PlayerAction.MoveUp); actions.add(PlayerAction.MoveDown); // should be rename to action perhaps actions.add(PlayerAction.Action); List<InputData> data = inputManager.getData(input, actions); for (InputData d : data) { PlayerAction action = d.getAction(); Player p = d.getPlayer(); switch (action) { case MoveUp: moveIndex(p, -1); break; case MoveDown: moveIndex(p, 1); break; case Action: model.upgradePlayer(p, attributes.get(playersIndex.get(p))); break; default: break; } } // TODO really bad solution try { Thread.sleep(80); } catch (InterruptedException e) { e.printStackTrace(); } }
diff --git a/src/net/java/otr4j/session/SessionImpl.java b/src/net/java/otr4j/session/SessionImpl.java index 6a27d92f..12cbb381 100644 --- a/src/net/java/otr4j/session/SessionImpl.java +++ b/src/net/java/otr4j/session/SessionImpl.java @@ -1,771 +1,771 @@ /* * otr4j, the open source java otr library. * * Distributable under LGPL license. See terms of license at gnu.org. */ package net.java.otr4j.session; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.KeyPair; import java.security.PublicKey; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Vector; import java.util.logging.Logger; import javax.crypto.interfaces.DHPublicKey; import net.java.otr4j.OtrEngineHost; import net.java.otr4j.OtrEngineListener; import net.java.otr4j.OtrException; import net.java.otr4j.OtrPolicy; import net.java.otr4j.crypto.OtrCryptoEngine; import net.java.otr4j.crypto.OtrCryptoEngineImpl; import net.java.otr4j.crypto.OtrTlvHandler; import net.java.otr4j.io.OtrInputStream; import net.java.otr4j.io.OtrOutputStream; import net.java.otr4j.io.SerializationConstants; import net.java.otr4j.io.SerializationUtils; import net.java.otr4j.io.messages.AbstractEncodedMessage; import net.java.otr4j.io.messages.AbstractMessage; import net.java.otr4j.io.messages.DataMessage; import net.java.otr4j.io.messages.ErrorMessage; import net.java.otr4j.io.messages.MysteriousT; import net.java.otr4j.io.messages.PlainTextMessage; import net.java.otr4j.io.messages.QueryMessage; /** @author George Politis */ public class SessionImpl implements Session { private SessionID sessionID; private OtrEngineHost host; private SessionStatus sessionStatus; private AuthContext authContext; private SessionKeys[][] sessionKeys; private Vector<byte[]> oldMacKeys; private static Logger logger = Logger.getLogger(SessionImpl.class.getName()); private List<OtrTlvHandler> tlvHandlers = new ArrayList<OtrTlvHandler>(); private BigInteger ess; private String lastSentMessage; private boolean doTransmitLastMessage = false; private boolean isLastMessageRetransmit = false; private byte[] extraKey; public SessionImpl(SessionID sessionID, OtrEngineHost listener) { this.setSessionID(sessionID); this.setHost(listener); // client application calls OtrEngine.getSessionStatus() // -> create new session if it does not exist, end up here // -> setSessionStatus() fires statusChangedEvent // -> client application calls OtrEngine.getSessionStatus() this.sessionStatus = SessionStatus.PLAINTEXT; } @Override public void addTlvHandler(OtrTlvHandler handler) { tlvHandlers.add(handler); } @Override public void removeTlvHandler(OtrTlvHandler handler) { tlvHandlers.remove(handler); } public BigInteger getS() { return ess; } private SessionKeys getEncryptionSessionKeys() { logger.finest("Getting encryption keys"); return getSessionKeysByIndex(SessionKeys.Previous, SessionKeys.Current); } private SessionKeys getMostRecentSessionKeys() { logger.finest("Getting most recent keys."); return getSessionKeysByIndex(SessionKeys.Current, SessionKeys.Current); } private SessionKeys getSessionKeysByID(int localKeyID, int remoteKeyID) { logger.finest("Searching for session keys with (localKeyID, remoteKeyID) = (" + localKeyID + "," + remoteKeyID + ")"); for (int i = 0; i < getSessionKeys().length; i++) { for (int j = 0; j < getSessionKeys()[i].length; j++) { SessionKeys current = getSessionKeysByIndex(i, j); if (current.getLocalKeyID() == localKeyID && current.getRemoteKeyID() == remoteKeyID) { logger.finest("Matching keys found."); return current; } } } return null; } private SessionKeys getSessionKeysByIndex(int localKeyIndex, int remoteKeyIndex) { if (getSessionKeys()[localKeyIndex][remoteKeyIndex] == null) getSessionKeys()[localKeyIndex][remoteKeyIndex] = new SessionKeysImpl(localKeyIndex, remoteKeyIndex); return getSessionKeys()[localKeyIndex][remoteKeyIndex]; } private void rotateRemoteSessionKeys(DHPublicKey pubKey) throws OtrException { logger.finest("Rotating remote keys."); SessionKeys sess1 = getSessionKeysByIndex(SessionKeys.Current, SessionKeys.Previous); if (sess1.getIsUsedReceivingMACKey()) { logger.finest("Detected used Receiving MAC key. Adding to old MAC keys to reveal it."); getOldMacKeys().add(sess1.getReceivingMACKey()); } SessionKeys sess2 = getSessionKeysByIndex(SessionKeys.Previous, SessionKeys.Previous); if (sess2.getIsUsedReceivingMACKey()) { logger.finest("Detected used Receiving MAC key. Adding to old MAC keys to reveal it."); getOldMacKeys().add(sess2.getReceivingMACKey()); } SessionKeys sess3 = getSessionKeysByIndex(SessionKeys.Current, SessionKeys.Current); sess1.setRemoteDHPublicKey(sess3.getRemoteKey(), sess3.getRemoteKeyID()); SessionKeys sess4 = getSessionKeysByIndex(SessionKeys.Previous, SessionKeys.Current); sess2.setRemoteDHPublicKey(sess4.getRemoteKey(), sess4.getRemoteKeyID()); sess3.setRemoteDHPublicKey(pubKey, sess3.getRemoteKeyID() + 1); sess4.setRemoteDHPublicKey(pubKey, sess4.getRemoteKeyID() + 1); } private void rotateLocalSessionKeys() throws OtrException { logger.finest("Rotating local keys."); SessionKeys sess1 = getSessionKeysByIndex(SessionKeys.Previous, SessionKeys.Current); if (sess1.getIsUsedReceivingMACKey()) { logger.finest("Detected used Receiving MAC key. Adding to old MAC keys to reveal it."); getOldMacKeys().add(sess1.getReceivingMACKey()); } SessionKeys sess2 = getSessionKeysByIndex(SessionKeys.Previous, SessionKeys.Previous); if (sess2.getIsUsedReceivingMACKey()) { logger.finest("Detected used Receiving MAC key. Adding to old MAC keys to reveal it."); getOldMacKeys().add(sess2.getReceivingMACKey()); } SessionKeys sess3 = getSessionKeysByIndex(SessionKeys.Current, SessionKeys.Current); sess1.setLocalPair(sess3.getLocalPair(), sess3.getLocalKeyID()); SessionKeys sess4 = getSessionKeysByIndex(SessionKeys.Current, SessionKeys.Previous); sess2.setLocalPair(sess4.getLocalPair(), sess4.getLocalKeyID()); KeyPair newPair = new OtrCryptoEngineImpl().generateDHKeyPair(); sess3.setLocalPair(newPair, sess3.getLocalKeyID() + 1); sess4.setLocalPair(newPair, sess4.getLocalKeyID() + 1); } private byte[] collectOldMacKeys() { logger.finest("Collecting old MAC keys to be revealed."); int len = 0; for (int i = 0; i < getOldMacKeys().size(); i++) len += getOldMacKeys().get(i).length; ByteBuffer buff = ByteBuffer.allocate(len); for (int i = 0; i < getOldMacKeys().size(); i++) buff.put(getOldMacKeys().get(i)); getOldMacKeys().clear(); return buff.array(); } private void setSessionStatus(SessionStatus sessionStatus) throws OtrException { switch (sessionStatus) { case ENCRYPTED: AuthContext auth = this.getAuthContext(); ess = auth.getS(); logger.finest("Setting most recent session keys from auth."); for (int i = 0; i < this.getSessionKeys()[0].length; i++) { SessionKeys current = getSessionKeysByIndex(0, i); current.setLocalPair(auth.getLocalDHKeyPair(), 1); current.setRemoteDHPublicKey(auth.getRemoteDHPublicKey(), 1); current.setS(auth.getS()); } KeyPair nextDH = new OtrCryptoEngineImpl().generateDHKeyPair(); for (int i = 0; i < this.getSessionKeys()[1].length; i++) { SessionKeys current = getSessionKeysByIndex(1, i); current.setRemoteDHPublicKey(auth.getRemoteDHPublicKey(), 1); current.setLocalPair(nextDH, 2); } this.setRemotePublicKey(auth.getRemoteLongTermPublicKey()); auth.reset(); break; } SessionStatus oldSessionStatus = this.sessionStatus; // This must be set correctly for transformSending this.sessionStatus = sessionStatus; if (sessionStatus == SessionStatus.ENCRYPTED && doTransmitLastMessage && lastSentMessage != null) { String msg = this.transformSending((isLastMessageRetransmit ? "[resent] " : "") + lastSentMessage, null); getHost().injectMessage(getSessionID(), msg); } doTransmitLastMessage = false; isLastMessageRetransmit = false; lastSentMessage = null; if (sessionStatus != oldSessionStatus) { for (OtrEngineListener l : this.listeners) l.sessionStatusChanged(getSessionID()); } } /* * (non-Javadoc) * * @see net.java.otr4j.session.ISession#getSessionStatus() */ public SessionStatus getSessionStatus() { return sessionStatus; } private void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } /* * (non-Javadoc) * * @see net.java.otr4j.session.ISession#getSessionID() */ public SessionID getSessionID() { return sessionID; } private void setHost(OtrEngineHost host) { this.host = host; } private OtrEngineHost getHost() { return host; } private SessionKeys[][] getSessionKeys() { if (sessionKeys == null) sessionKeys = new SessionKeys[2][2]; return sessionKeys; } private AuthContext getAuthContext() { if (authContext == null) authContext = new AuthContextImpl(this); return authContext; } private Vector<byte[]> getOldMacKeys() { if (oldMacKeys == null) oldMacKeys = new Vector<byte[]>(); return oldMacKeys; } public String transformReceiving(String msgText) throws OtrException { return transformReceiving(msgText, null); } /* * (non-Javadoc) * * @see * net.java.otr4j.session.ISession#handleReceivingMessage(java.lang.String) */ public String transformReceiving(String msgText, List<TLV> tlvs) throws OtrException { OtrPolicy policy = getSessionPolicy(); if (!policy.getAllowV1() && !policy.getAllowV2()) { logger.finest("Policy does not allow neither V1 not V2, ignoring message."); return msgText; } AbstractMessage m; try { m = SerializationUtils.toMessage(msgText); } catch (IOException e) { throw new OtrException(e); } if (m == null) return msgText; // Propably null or empty. switch (m.messageType) { case AbstractEncodedMessage.MESSAGE_DATA: return handleDataMessage((DataMessage) m, tlvs); case AbstractMessage.MESSAGE_ERROR: handleErrorMessage((ErrorMessage) m); return null; case AbstractMessage.MESSAGE_PLAINTEXT: return handlePlainTextMessage((PlainTextMessage) m); case AbstractMessage.MESSAGE_QUERY: handleQueryMessage((QueryMessage) m); return null; case AbstractEncodedMessage.MESSAGE_DH_COMMIT: case AbstractEncodedMessage.MESSAGE_DHKEY: case AbstractEncodedMessage.MESSAGE_REVEALSIG: case AbstractEncodedMessage.MESSAGE_SIGNATURE: AuthContext auth = this.getAuthContext(); auth.handleReceivingMessage(m); if (auth.getIsSecure()) { this.setSessionStatus(SessionStatus.ENCRYPTED); logger.finest("Gone Secure."); } return null; default: throw new UnsupportedOperationException("Received an uknown message type."); } } private void handleQueryMessage(QueryMessage queryMessage) throws OtrException { logger.finest(getSessionID().getAccountID() + " received a query message from " + getSessionID().getUserID() + " throught " + getSessionID().getProtocolName() + "."); setSessionStatus(SessionStatus.PLAINTEXT); OtrPolicy policy = getSessionPolicy(); if (queryMessage.versions.contains(2) && policy.getAllowV2()) { logger.finest("Query message with V2 support found."); getAuthContext().respondV2Auth(); } else if (queryMessage.versions.contains(1) && policy.getAllowV1()) { throw new UnsupportedOperationException(); } } private void handleErrorMessage(ErrorMessage errorMessage) throws OtrException { logger.finest(getSessionID().getAccountID() + " received an error message from " + getSessionID().getUserID() + " throught " + getSessionID().getUserID() + "."); OtrPolicy policy = getSessionPolicy(); if (policy.getErrorStartAKE()) { showWarning(errorMessage.error + " Initiating encryption."); logger.finest("Error message starts AKE."); doTransmitLastMessage = true; isLastMessageRetransmit = true; Vector<Integer> versions = new Vector<Integer>(); if (policy.getAllowV1()) versions.add(1); if (policy.getAllowV2()) versions.add(2); logger.finest("Sending Query"); injectMessage(new QueryMessage(versions)); } else { showError(errorMessage.error); } } private String handleDataMessage(DataMessage data, List<TLV> tlvs) throws OtrException { logger.finest(getSessionID().getAccountID() + " received a data message from " + getSessionID().getUserID() + "."); switch (this.getSessionStatus()) { case ENCRYPTED: logger.finest("Message state is ENCRYPTED. Trying to decrypt message."); // Find matching session keys. int senderKeyID = data.senderKeyID; int receipientKeyID = data.recipientKeyID; SessionKeys matchingKeys = this.getSessionKeysByID(receipientKeyID, senderKeyID); if (matchingKeys == null) { throw new OtrException("no matching keys found"); } // Verify received MAC with a locally calculated MAC. logger.finest("Transforming T to byte[] to calculate it's HmacSHA1."); byte[] serializedT; try { serializedT = SerializationUtils.toByteArray(data.getT()); } catch (IOException e) { throw new OtrException(e); } OtrCryptoEngine otrCryptoEngine = new OtrCryptoEngineImpl(); byte[] computedMAC = otrCryptoEngine.sha1Hmac(serializedT, matchingKeys.getReceivingMACKey(), SerializationConstants.TYPE_LEN_MAC); if (!Arrays.equals(computedMAC, data.mac)) { throw new OtrException("MAC verification failed, ignoring message"); } logger.finest("Computed HmacSHA1 value matches sent one."); // Mark this MAC key as old to be revealed. matchingKeys.setIsUsedReceivingMACKey(true); matchingKeys.setReceivingCtr(data.ctr); byte[] dmc = otrCryptoEngine.aesDecrypt(matchingKeys.getReceivingAESKey(), matchingKeys.getReceivingCtr(), data.encryptedMessage); String decryptedMsgContent; try { // Expect bytes to be text encoded in UTF-8. decryptedMsgContent = new String(dmc, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new OtrException(e); } logger.finest("Decrypted message: \"" + decryptedMsgContent + "\""); - extraKey = authContext.getExtraSymmetricKey(); + // FIXME extraKey = authContext.getExtraSymmetricKey(); // Rotate keys if necessary. SessionKeys mostRecent = this.getMostRecentSessionKeys(); if (mostRecent.getLocalKeyID() == receipientKeyID) this.rotateLocalSessionKeys(); if (mostRecent.getRemoteKeyID() == senderKeyID) this.rotateRemoteSessionKeys(data.nextDH); // Handle TLVs if (tlvs == null) { tlvs = new ArrayList<TLV>(); } int tlvIndex = decryptedMsgContent.indexOf((char) 0x0); if (tlvIndex > -1) { decryptedMsgContent = decryptedMsgContent.substring(0, tlvIndex); tlvIndex++; byte[] tlvsb = new byte[dmc.length - tlvIndex]; System.arraycopy(dmc, tlvIndex, tlvsb, 0, tlvsb.length); ByteArrayInputStream tin = new ByteArrayInputStream(tlvsb); while (tin.available() > 0) { int type; byte[] tdata; OtrInputStream eois = new OtrInputStream(tin); try { type = eois.readShort(); tdata = eois.readTlvData(); eois.close(); } catch (IOException e) { throw new OtrException(e); } tlvs.add(new TLV(type, tdata)); } } if (tlvs.size() > 0) { for (TLV tlv : tlvs) { switch (tlv.getType()) { case TLV.DISCONNECTED: this.setSessionStatus(SessionStatus.FINISHED); return null; default: for (OtrTlvHandler handler : tlvHandlers) { handler.processTlv(tlv); } } } } return decryptedMsgContent; case FINISHED: case PLAINTEXT: showError("Unreadable encrypted message was received."); injectMessage(new ErrorMessage(AbstractMessage.MESSAGE_ERROR, "You sent me an unreadable encrypted message")); throw new OtrException("Unreadable encrypted message received"); } return null; } public void injectMessage(AbstractMessage m) throws OtrException { String msg; try { msg = SerializationUtils.toString(m); } catch (IOException e) { throw new OtrException(e); } getHost().injectMessage(getSessionID(), msg); } private String handlePlainTextMessage(PlainTextMessage plainTextMessage) throws OtrException { logger.finest(getSessionID().getAccountID() + " received a plaintext message from " + getSessionID().getUserID() + " throught " + getSessionID().getProtocolName() + "."); OtrPolicy policy = getSessionPolicy(); List<Integer> versions = plainTextMessage.versions; if (versions == null || versions.size() < 1) { logger.finest("Received plaintext message without the whitespace tag."); switch (this.getSessionStatus()) { case ENCRYPTED: case FINISHED: // Display the message to the user, but warn him that the // message was received unencrypted. showError("The message was received unencrypted."); return plainTextMessage.cleanText; case PLAINTEXT: // Simply display the message to the user. If // REQUIRE_ENCRYPTION // is set, warn him that the message was received // unencrypted. if (policy.getRequireEncryption()) { showError("The message was received unencrypted."); } return plainTextMessage.cleanText; } } else { logger.finest("Received plaintext message with the whitespace tag."); switch (this.getSessionStatus()) { case ENCRYPTED: case FINISHED: // Remove the whitespace tag and display the message to the // user, but warn him that the message was received // unencrypted. showError("The message was received unencrypted."); case PLAINTEXT: // Remove the whitespace tag and display the message to the // user. If REQUIRE_ENCRYPTION is set, warn him that the // message // was received unencrypted. if (policy.getRequireEncryption()) showError("The message was received unencrypted."); } if (policy.getWhitespaceStartAKE()) { logger.finest("WHITESPACE_START_AKE is set"); if (plainTextMessage.versions.contains(2) && policy.getAllowV2()) { logger.finest("V2 tag found."); getAuthContext().respondV2Auth(); } else if (plainTextMessage.versions.contains(1) && policy.getAllowV1()) { throw new UnsupportedOperationException(); } } } return plainTextMessage.cleanText; } // Retransmit last sent message. Spec document does not mention where or // when that should happen, must check libotr code. public String transformSending(String msgText, List<TLV> tlvs) throws OtrException { switch (this.getSessionStatus()) { case PLAINTEXT: if (getSessionPolicy().getRequireEncryption()) { lastSentMessage = msgText; doTransmitLastMessage = true; this.startSession(); return null; } else // TODO this does not precisly behave according to // specification. return msgText; case ENCRYPTED: this.lastSentMessage = msgText; logger.finest(getSessionID().getAccountID() + " sends an encrypted message to " + getSessionID().getUserID() + " through " + getSessionID().getProtocolName() + "."); // Get encryption keys. SessionKeys encryptionKeys = this.getEncryptionSessionKeys(); int senderKeyID = encryptionKeys.getLocalKeyID(); int receipientKeyID = encryptionKeys.getRemoteKeyID(); // Increment CTR. encryptionKeys.incrementSendingCtr(); byte[] ctr = encryptionKeys.getSendingCtr(); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (msgText != null && msgText.length() > 0) try { out.write(msgText.getBytes("UTF8")); } catch (IOException e) { throw new OtrException(e); } // Append tlvs if (tlvs != null && tlvs.size() > 0) { out.write((byte) 0x00); OtrOutputStream eoos = new OtrOutputStream(out); for (TLV tlv : tlvs) { try { eoos.writeShort(tlv.type); eoos.writeTlvData(tlv.value); } catch (IOException e) { throw new OtrException(e); } } } OtrCryptoEngine otrCryptoEngine = new OtrCryptoEngineImpl(); byte[] data = out.toByteArray(); // Encrypt message. logger.finest("Encrypting message with keyids (localKeyID, remoteKeyID) = (" + senderKeyID + ", " + receipientKeyID + ")"); byte[] encryptedMsg = otrCryptoEngine.aesEncrypt(encryptionKeys.getSendingAESKey(), ctr, data); // Get most recent keys to get the next D-H public key. SessionKeys mostRecentKeys = this.getMostRecentSessionKeys(); DHPublicKey nextDH = (DHPublicKey) mostRecentKeys.getLocalPair().getPublic(); // Calculate T. MysteriousT t = new MysteriousT(2, 0, senderKeyID, receipientKeyID, nextDH, ctr, encryptedMsg); // Calculate T hash. byte[] sendingMACKey = encryptionKeys.getSendingMACKey(); logger.finest("Transforming T to byte[] to calculate it's HmacSHA1."); byte[] serializedT; try { serializedT = SerializationUtils.toByteArray(t); } catch (IOException e) { throw new OtrException(e); } byte[] mac = otrCryptoEngine.sha1Hmac(serializedT, sendingMACKey, SerializationConstants.TYPE_LEN_MAC); // Get old MAC keys to be revealed. byte[] oldKeys = this.collectOldMacKeys(); DataMessage m = new DataMessage(t, mac, oldKeys); try { return SerializationUtils.toString(m); } catch (IOException e) { throw new OtrException(e); } case FINISHED: this.lastSentMessage = msgText; showError("Your message to " + sessionID.getUserID() + " was not sent. Either end your private conversation, or restart it."); return null; default: logger.finest("Uknown message state, not processing."); return msgText; } } /* * (non-Javadoc) * * @see net.java.otr4j.session.ISession#startSession() */ public void startSession() throws OtrException { if (this.getSessionStatus() == SessionStatus.ENCRYPTED) return; if (!getSessionPolicy().getAllowV2()) throw new UnsupportedOperationException(); this.getAuthContext().startV2Auth(); } /* * (non-Javadoc) * * @see net.java.otr4j.session.ISession#endSession() */ public void endSession() throws OtrException { SessionStatus status = this.getSessionStatus(); switch (status) { case ENCRYPTED: Vector<TLV> tlvs = new Vector<TLV>(); tlvs.add(new TLV(1, null)); String msg = this.transformSending(null, tlvs); getHost().injectMessage(getSessionID(), msg); this.setSessionStatus(SessionStatus.PLAINTEXT); break; case FINISHED: this.setSessionStatus(SessionStatus.PLAINTEXT); break; case PLAINTEXT: return; } } /* * (non-Javadoc) * * @see net.java.otr4j.session.ISession#refreshSession() */ public void refreshSession() throws OtrException { this.endSession(); this.startSession(); } private PublicKey remotePublicKey; private void setRemotePublicKey(PublicKey pubKey) { this.remotePublicKey = pubKey; } public PublicKey getRemotePublicKey() { return remotePublicKey; } private List<OtrEngineListener> listeners = new Vector<OtrEngineListener>(); public void addOtrEngineListener(OtrEngineListener l) { synchronized (listeners) { if (!listeners.contains(l)) listeners.add(l); } } public void removeOtrEngineListener(OtrEngineListener l) { synchronized (listeners) { listeners.remove(l); } } public OtrPolicy getSessionPolicy() { return getHost().getSessionPolicy(getSessionID()); } public KeyPair getLocalKeyPair() { return getHost().getKeyPair(this.getSessionID()); } public void showError(String warning) { getHost().showError(sessionID, warning); } public void showWarning(String warning) { getHost().showWarning(sessionID, warning); } public byte[] getExtraKey() { return extraKey; } }
true
true
private String handleDataMessage(DataMessage data, List<TLV> tlvs) throws OtrException { logger.finest(getSessionID().getAccountID() + " received a data message from " + getSessionID().getUserID() + "."); switch (this.getSessionStatus()) { case ENCRYPTED: logger.finest("Message state is ENCRYPTED. Trying to decrypt message."); // Find matching session keys. int senderKeyID = data.senderKeyID; int receipientKeyID = data.recipientKeyID; SessionKeys matchingKeys = this.getSessionKeysByID(receipientKeyID, senderKeyID); if (matchingKeys == null) { throw new OtrException("no matching keys found"); } // Verify received MAC with a locally calculated MAC. logger.finest("Transforming T to byte[] to calculate it's HmacSHA1."); byte[] serializedT; try { serializedT = SerializationUtils.toByteArray(data.getT()); } catch (IOException e) { throw new OtrException(e); } OtrCryptoEngine otrCryptoEngine = new OtrCryptoEngineImpl(); byte[] computedMAC = otrCryptoEngine.sha1Hmac(serializedT, matchingKeys.getReceivingMACKey(), SerializationConstants.TYPE_LEN_MAC); if (!Arrays.equals(computedMAC, data.mac)) { throw new OtrException("MAC verification failed, ignoring message"); } logger.finest("Computed HmacSHA1 value matches sent one."); // Mark this MAC key as old to be revealed. matchingKeys.setIsUsedReceivingMACKey(true); matchingKeys.setReceivingCtr(data.ctr); byte[] dmc = otrCryptoEngine.aesDecrypt(matchingKeys.getReceivingAESKey(), matchingKeys.getReceivingCtr(), data.encryptedMessage); String decryptedMsgContent; try { // Expect bytes to be text encoded in UTF-8. decryptedMsgContent = new String(dmc, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new OtrException(e); } logger.finest("Decrypted message: \"" + decryptedMsgContent + "\""); extraKey = authContext.getExtraSymmetricKey(); // Rotate keys if necessary. SessionKeys mostRecent = this.getMostRecentSessionKeys(); if (mostRecent.getLocalKeyID() == receipientKeyID) this.rotateLocalSessionKeys(); if (mostRecent.getRemoteKeyID() == senderKeyID) this.rotateRemoteSessionKeys(data.nextDH); // Handle TLVs if (tlvs == null) { tlvs = new ArrayList<TLV>(); } int tlvIndex = decryptedMsgContent.indexOf((char) 0x0); if (tlvIndex > -1) { decryptedMsgContent = decryptedMsgContent.substring(0, tlvIndex); tlvIndex++; byte[] tlvsb = new byte[dmc.length - tlvIndex]; System.arraycopy(dmc, tlvIndex, tlvsb, 0, tlvsb.length); ByteArrayInputStream tin = new ByteArrayInputStream(tlvsb); while (tin.available() > 0) { int type; byte[] tdata; OtrInputStream eois = new OtrInputStream(tin); try { type = eois.readShort(); tdata = eois.readTlvData(); eois.close(); } catch (IOException e) { throw new OtrException(e); } tlvs.add(new TLV(type, tdata)); } } if (tlvs.size() > 0) { for (TLV tlv : tlvs) { switch (tlv.getType()) { case TLV.DISCONNECTED: this.setSessionStatus(SessionStatus.FINISHED); return null; default: for (OtrTlvHandler handler : tlvHandlers) { handler.processTlv(tlv); } } } } return decryptedMsgContent; case FINISHED: case PLAINTEXT: showError("Unreadable encrypted message was received."); injectMessage(new ErrorMessage(AbstractMessage.MESSAGE_ERROR, "You sent me an unreadable encrypted message")); throw new OtrException("Unreadable encrypted message received"); } return null; }
private String handleDataMessage(DataMessage data, List<TLV> tlvs) throws OtrException { logger.finest(getSessionID().getAccountID() + " received a data message from " + getSessionID().getUserID() + "."); switch (this.getSessionStatus()) { case ENCRYPTED: logger.finest("Message state is ENCRYPTED. Trying to decrypt message."); // Find matching session keys. int senderKeyID = data.senderKeyID; int receipientKeyID = data.recipientKeyID; SessionKeys matchingKeys = this.getSessionKeysByID(receipientKeyID, senderKeyID); if (matchingKeys == null) { throw new OtrException("no matching keys found"); } // Verify received MAC with a locally calculated MAC. logger.finest("Transforming T to byte[] to calculate it's HmacSHA1."); byte[] serializedT; try { serializedT = SerializationUtils.toByteArray(data.getT()); } catch (IOException e) { throw new OtrException(e); } OtrCryptoEngine otrCryptoEngine = new OtrCryptoEngineImpl(); byte[] computedMAC = otrCryptoEngine.sha1Hmac(serializedT, matchingKeys.getReceivingMACKey(), SerializationConstants.TYPE_LEN_MAC); if (!Arrays.equals(computedMAC, data.mac)) { throw new OtrException("MAC verification failed, ignoring message"); } logger.finest("Computed HmacSHA1 value matches sent one."); // Mark this MAC key as old to be revealed. matchingKeys.setIsUsedReceivingMACKey(true); matchingKeys.setReceivingCtr(data.ctr); byte[] dmc = otrCryptoEngine.aesDecrypt(matchingKeys.getReceivingAESKey(), matchingKeys.getReceivingCtr(), data.encryptedMessage); String decryptedMsgContent; try { // Expect bytes to be text encoded in UTF-8. decryptedMsgContent = new String(dmc, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new OtrException(e); } logger.finest("Decrypted message: \"" + decryptedMsgContent + "\""); // FIXME extraKey = authContext.getExtraSymmetricKey(); // Rotate keys if necessary. SessionKeys mostRecent = this.getMostRecentSessionKeys(); if (mostRecent.getLocalKeyID() == receipientKeyID) this.rotateLocalSessionKeys(); if (mostRecent.getRemoteKeyID() == senderKeyID) this.rotateRemoteSessionKeys(data.nextDH); // Handle TLVs if (tlvs == null) { tlvs = new ArrayList<TLV>(); } int tlvIndex = decryptedMsgContent.indexOf((char) 0x0); if (tlvIndex > -1) { decryptedMsgContent = decryptedMsgContent.substring(0, tlvIndex); tlvIndex++; byte[] tlvsb = new byte[dmc.length - tlvIndex]; System.arraycopy(dmc, tlvIndex, tlvsb, 0, tlvsb.length); ByteArrayInputStream tin = new ByteArrayInputStream(tlvsb); while (tin.available() > 0) { int type; byte[] tdata; OtrInputStream eois = new OtrInputStream(tin); try { type = eois.readShort(); tdata = eois.readTlvData(); eois.close(); } catch (IOException e) { throw new OtrException(e); } tlvs.add(new TLV(type, tdata)); } } if (tlvs.size() > 0) { for (TLV tlv : tlvs) { switch (tlv.getType()) { case TLV.DISCONNECTED: this.setSessionStatus(SessionStatus.FINISHED); return null; default: for (OtrTlvHandler handler : tlvHandlers) { handler.processTlv(tlv); } } } } return decryptedMsgContent; case FINISHED: case PLAINTEXT: showError("Unreadable encrypted message was received."); injectMessage(new ErrorMessage(AbstractMessage.MESSAGE_ERROR, "You sent me an unreadable encrypted message")); throw new OtrException("Unreadable encrypted message received"); } return null; }
diff --git a/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/navigtor/RemoteCNavigatorRefactorActionProvider.java b/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/navigtor/RemoteCNavigatorRefactorActionProvider.java index 83d1f5008..fedbe2ab6 100644 --- a/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/navigtor/RemoteCNavigatorRefactorActionProvider.java +++ b/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/navigtor/RemoteCNavigatorRefactorActionProvider.java @@ -1,82 +1,84 @@ /******************************************************************************* * Copyright (c) 2006, 2009 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.ptp.internal.rdt.ui.navigtor; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.internal.ui.navigator.CNavigatorRefactorActionProvider; import org.eclipse.core.resources.IProject; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ptp.rdt.core.resources.RemoteNature; import org.eclipse.ui.IActionBars; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.navigator.CommonActionProvider; import org.eclipse.ui.navigator.ICommonActionExtensionSite; /** * A clone of org.eclipse.ui.internal.navigator.resources.actions.RefactorActionProvider. */ public class RemoteCNavigatorRefactorActionProvider extends CommonActionProvider { private CNavigatorRefactorActionProvider fCDTRefactorActionProvider; public RemoteCNavigatorRefactorActionProvider() { super(); fCDTRefactorActionProvider = new CNavigatorRefactorActionProvider(); } /* * @see org.eclipse.ui.navigator.CommonActionProvider#init(org.eclipse.ui.navigator.ICommonActionExtensionSite) */ @Override public void init(ICommonActionExtensionSite actionSite) { super.init(actionSite); fCDTRefactorActionProvider.init(actionSite); } @Override public void dispose() { fCDTRefactorActionProvider.dispose(); } @Override public void fillActionBars(IActionBars actionBars) { fCDTRefactorActionProvider.fillActionBars(actionBars); } @Override public void fillContextMenu(IMenuManager menu) { ActionContext context = getContext(); ISelection selection = context.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof StructuredSelection) { Object sel = ((StructuredSelection)selection).getFirstElement(); if (sel instanceof ICElement) { IProject project = ((ICElement)sel).getCProject().getProject(); if (!RemoteNature.hasRemoteNature(project)){ fCDTRefactorActionProvider.fillContextMenu(menu); } + } else { //other resources + fCDTRefactorActionProvider.fillContextMenu(menu); } } } @Override public void setContext(ActionContext context) { super.setContext(context); fCDTRefactorActionProvider.setContext(context); } @Override public void updateActionBars() { fCDTRefactorActionProvider.updateActionBars(); } }
true
true
public void fillContextMenu(IMenuManager menu) { ActionContext context = getContext(); ISelection selection = context.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof StructuredSelection) { Object sel = ((StructuredSelection)selection).getFirstElement(); if (sel instanceof ICElement) { IProject project = ((ICElement)sel).getCProject().getProject(); if (!RemoteNature.hasRemoteNature(project)){ fCDTRefactorActionProvider.fillContextMenu(menu); } } } }
public void fillContextMenu(IMenuManager menu) { ActionContext context = getContext(); ISelection selection = context.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof StructuredSelection) { Object sel = ((StructuredSelection)selection).getFirstElement(); if (sel instanceof ICElement) { IProject project = ((ICElement)sel).getCProject().getProject(); if (!RemoteNature.hasRemoteNature(project)){ fCDTRefactorActionProvider.fillContextMenu(menu); } } else { //other resources fCDTRefactorActionProvider.fillContextMenu(menu); } } }
diff --git a/src/main/java/org/codeforamerica/open311/facade/data/ServiceDiscoveryInfo.java b/src/main/java/org/codeforamerica/open311/facade/data/ServiceDiscoveryInfo.java index faf53643..11a1a76c 100644 --- a/src/main/java/org/codeforamerica/open311/facade/data/ServiceDiscoveryInfo.java +++ b/src/main/java/org/codeforamerica/open311/facade/data/ServiceDiscoveryInfo.java @@ -1,79 +1,79 @@ package org.codeforamerica.open311.facade.data; import java.io.Serializable; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.codeforamerica.open311.facade.EndpointType; /** * Contains information regarding to a city (endpoints, allowed formats...). * * @author Santiago Munín <[email protected]> * */ public class ServiceDiscoveryInfo implements Serializable { private static final long serialVersionUID = 5804902138488110319L; private final static String GEO_REPORT_V2_SPECIFICATION_URL = "http://wiki.open311.org/GeoReport_v2"; private Date changeset; private String contact; private String keyService; List<Endpoint> endpoints; public ServiceDiscoveryInfo(Date changeset, String contact, String keyService, List<Endpoint> endpoints) { super(); this.changeset = changeset; this.contact = contact; this.keyService = keyService; this.endpoints = endpoints; } public Date getChangeset() { return changeset; } public String getContact() { return contact; } public String getKeyService() { return keyService; } public List<Endpoint> getEndpoints() { return endpoints; } /** * Searches through the list of endpoints and tries to find a valid endpoint * of the given type. Tries to get the GeoReport latest version (currently * v2). * * @param endpointType * Type of the desired endpoint. * @return <code>null</code> if a suitable endpoint couldn't be found. */ public Endpoint getMoreSuitableEndpoint(EndpointType endpointType) { List<Endpoint> typeFilteredEndpoints = new LinkedList<Endpoint>(); for (Endpoint endpoint : endpoints) { if (endpoint.getType() == endpointType) { typeFilteredEndpoints.add(endpoint); } } Endpoint candidate = null; for (Endpoint endpoint : typeFilteredEndpoints) { - // Some endpoints doesn't follows the specification so it does this + // Some endpoints don't follows the specification so it does this // "double check", which has been proved working. if (endpoint.getSpecificationUrl().equals(GEO_REPORT_V2_SPECIFICATION_URL)) { if (endpoint.getUrl().contains("v2")) { return endpoint; } candidate = endpoint; } } return candidate; } }
true
true
public Endpoint getMoreSuitableEndpoint(EndpointType endpointType) { List<Endpoint> typeFilteredEndpoints = new LinkedList<Endpoint>(); for (Endpoint endpoint : endpoints) { if (endpoint.getType() == endpointType) { typeFilteredEndpoints.add(endpoint); } } Endpoint candidate = null; for (Endpoint endpoint : typeFilteredEndpoints) { // Some endpoints doesn't follows the specification so it does this // "double check", which has been proved working. if (endpoint.getSpecificationUrl().equals(GEO_REPORT_V2_SPECIFICATION_URL)) { if (endpoint.getUrl().contains("v2")) { return endpoint; } candidate = endpoint; } } return candidate; }
public Endpoint getMoreSuitableEndpoint(EndpointType endpointType) { List<Endpoint> typeFilteredEndpoints = new LinkedList<Endpoint>(); for (Endpoint endpoint : endpoints) { if (endpoint.getType() == endpointType) { typeFilteredEndpoints.add(endpoint); } } Endpoint candidate = null; for (Endpoint endpoint : typeFilteredEndpoints) { // Some endpoints don't follows the specification so it does this // "double check", which has been proved working. if (endpoint.getSpecificationUrl().equals(GEO_REPORT_V2_SPECIFICATION_URL)) { if (endpoint.getUrl().contains("v2")) { return endpoint; } candidate = endpoint; } } return candidate; }
diff --git a/engine/src/blender/com/jme3/scene/plugins/blender/constraints/ConstraintHelper.java b/engine/src/blender/com/jme3/scene/plugins/blender/constraints/ConstraintHelper.java index 0b496ed9c..b9737564a 100644 --- a/engine/src/blender/com/jme3/scene/plugins/blender/constraints/ConstraintHelper.java +++ b/engine/src/blender/com/jme3/scene/plugins/blender/constraints/ConstraintHelper.java @@ -1,140 +1,140 @@ package com.jme3.scene.plugins.blender.constraints; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import com.jme3.scene.plugins.blender.AbstractBlenderHelper; import com.jme3.scene.plugins.blender.DataRepository; import com.jme3.scene.plugins.blender.animations.Ipo; import com.jme3.scene.plugins.blender.animations.IpoHelper; import com.jme3.scene.plugins.blender.exceptions.BlenderFileException; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; /** * This class should be used for constraint calculations. * @author Marcin Roguski */ public class ConstraintHelper extends AbstractBlenderHelper { private static final Logger LOGGER = Logger.getLogger(ConstraintHelper.class.getName()); /** * Helper constructor. It's main task is to generate the affection functions. These functions are common to all * ConstraintHelper instances. Unfortunately this constructor might grow large. If it becomes too large - I shall * consider refactoring. The constructor parses the given blender version and stores the result. Some * functionalities may differ in different blender versions. * @param blenderVersion * the version read from the blend file */ public ConstraintHelper(String blenderVersion, DataRepository dataRepository) { super(blenderVersion); } /** * This method reads constraints for for the given structure. The constraints are loaded only once for object/bone. * @param ownerOMA * the owner's old memory address * @param objectStructure * the structure we read constraint's for * @param dataRepository * the data repository * @throws BlenderFileException */ public Map<Long, List<Constraint>> loadConstraints(Structure objectStructure, DataRepository dataRepository) throws BlenderFileException { - if (blenderVersion < 250) {//TODO + if (blenderVersion >= 250) {//TODO LOGGER.warning("Loading of constraints not yet implemented for version 2.5x !"); return new HashMap<Long, List<Constraint>>(0); } // reading influence ipos for the constraints IpoHelper ipoHelper = dataRepository.getHelper(IpoHelper.class); Map<String, Map<String, Ipo>> constraintsIpos = new HashMap<String, Map<String, Ipo>>(); Pointer pActions = (Pointer) objectStructure.getFieldValue("action"); if (pActions.isNotNull()) { List<Structure> actions = pActions.fetchData(dataRepository.getInputStream()); for (Structure action : actions) { Structure chanbase = (Structure) action.getFieldValue("chanbase"); List<Structure> actionChannels = chanbase.evaluateListBase(dataRepository); for (Structure actionChannel : actionChannels) { Map<String, Ipo> ipos = new HashMap<String, Ipo>(); Structure constChannels = (Structure) actionChannel.getFieldValue("constraintChannels"); List<Structure> constraintChannels = constChannels.evaluateListBase(dataRepository); for (Structure constraintChannel : constraintChannels) { Pointer pIpo = (Pointer) constraintChannel.getFieldValue("ipo"); if (pIpo.isNotNull()) { String constraintName = constraintChannel.getFieldValue("name").toString(); Ipo ipo = ipoHelper.createIpo(pIpo.fetchData(dataRepository.getInputStream()).get(0), dataRepository); ipos.put(constraintName, ipo); } } String actionName = actionChannel.getFieldValue("name").toString(); constraintsIpos.put(actionName, ipos); } } } Map<Long, List<Constraint>> result = new HashMap<Long, List<Constraint>>(); //loading constraints connected with the object's bones Pointer pPose = (Pointer) objectStructure.getFieldValue("pose");//TODO: what if the object has two armatures ???? if (pPose.isNotNull()) { List<Structure> poseChannels = ((Structure) pPose.fetchData(dataRepository.getInputStream()).get(0).getFieldValue("chanbase")).evaluateListBase(dataRepository); for (Structure poseChannel : poseChannels) { List<Constraint> constraintsList = new ArrayList<Constraint>(); Long boneOMA = Long.valueOf(((Pointer) poseChannel.getFieldValue("bone")).getOldMemoryAddress()); //the name is read directly from structure because bone might not yet be loaded String name = dataRepository.getFileBlock(boneOMA).getStructure(dataRepository).getFieldValue("name").toString(); List<Structure> constraints = ((Structure) poseChannel.getFieldValue("constraints")).evaluateListBase(dataRepository); for (Structure constraint : constraints) { String constraintName = constraint.getFieldValue("name").toString(); Map<String, Ipo> ipoMap = constraintsIpos.get(name); Ipo ipo = ipoMap==null ? null : ipoMap.get(constraintName); if (ipo == null) { float enforce = ((Number) constraint.getFieldValue("enforce")).floatValue(); ipo = ipoHelper.createIpo(enforce); } constraintsList.add(ConstraintFactory.createConstraint(constraint, boneOMA, ipo, dataRepository)); } result.put(boneOMA, constraintsList); dataRepository.addConstraints(boneOMA, constraintsList); } } // TODO: reading constraints for objects (implement when object's animation will be available) List<Structure> constraintChannels = ((Structure)objectStructure.getFieldValue("constraintChannels")).evaluateListBase(dataRepository); for(Structure constraintChannel : constraintChannels) { System.out.println(constraintChannel); } //loading constraints connected with the object itself (TODO: test this) if(!result.containsKey(objectStructure.getOldMemoryAddress())) { List<Structure> constraints = ((Structure)objectStructure.getFieldValue("constraints")).evaluateListBase(dataRepository); List<Constraint> constraintsList = new ArrayList<Constraint>(constraints.size()); for(Structure constraint : constraints) { String constraintName = constraint.getFieldValue("name").toString(); String objectName = objectStructure.getName(); Map<String, Ipo> objectConstraintsIpos = constraintsIpos.get(objectName); Ipo ipo = objectConstraintsIpos!=null ? objectConstraintsIpos.get(constraintName) : null; if (ipo == null) { float enforce = ((Number) constraint.getFieldValue("enforce")).floatValue(); ipo = ipoHelper.createIpo(enforce); } constraintsList.add(ConstraintFactory.createConstraint(constraint, null, ipo, dataRepository)); } result.put(objectStructure.getOldMemoryAddress(), constraintsList); dataRepository.addConstraints(objectStructure.getOldMemoryAddress(), constraintsList); } return result; } @Override public boolean shouldBeLoaded(Structure structure, DataRepository dataRepository) { return true; } }
true
true
public Map<Long, List<Constraint>> loadConstraints(Structure objectStructure, DataRepository dataRepository) throws BlenderFileException { if (blenderVersion < 250) {//TODO LOGGER.warning("Loading of constraints not yet implemented for version 2.5x !"); return new HashMap<Long, List<Constraint>>(0); } // reading influence ipos for the constraints IpoHelper ipoHelper = dataRepository.getHelper(IpoHelper.class); Map<String, Map<String, Ipo>> constraintsIpos = new HashMap<String, Map<String, Ipo>>(); Pointer pActions = (Pointer) objectStructure.getFieldValue("action"); if (pActions.isNotNull()) { List<Structure> actions = pActions.fetchData(dataRepository.getInputStream()); for (Structure action : actions) { Structure chanbase = (Structure) action.getFieldValue("chanbase"); List<Structure> actionChannels = chanbase.evaluateListBase(dataRepository); for (Structure actionChannel : actionChannels) { Map<String, Ipo> ipos = new HashMap<String, Ipo>(); Structure constChannels = (Structure) actionChannel.getFieldValue("constraintChannels"); List<Structure> constraintChannels = constChannels.evaluateListBase(dataRepository); for (Structure constraintChannel : constraintChannels) { Pointer pIpo = (Pointer) constraintChannel.getFieldValue("ipo"); if (pIpo.isNotNull()) { String constraintName = constraintChannel.getFieldValue("name").toString(); Ipo ipo = ipoHelper.createIpo(pIpo.fetchData(dataRepository.getInputStream()).get(0), dataRepository); ipos.put(constraintName, ipo); } } String actionName = actionChannel.getFieldValue("name").toString(); constraintsIpos.put(actionName, ipos); } } } Map<Long, List<Constraint>> result = new HashMap<Long, List<Constraint>>(); //loading constraints connected with the object's bones Pointer pPose = (Pointer) objectStructure.getFieldValue("pose");//TODO: what if the object has two armatures ???? if (pPose.isNotNull()) { List<Structure> poseChannels = ((Structure) pPose.fetchData(dataRepository.getInputStream()).get(0).getFieldValue("chanbase")).evaluateListBase(dataRepository); for (Structure poseChannel : poseChannels) { List<Constraint> constraintsList = new ArrayList<Constraint>(); Long boneOMA = Long.valueOf(((Pointer) poseChannel.getFieldValue("bone")).getOldMemoryAddress()); //the name is read directly from structure because bone might not yet be loaded String name = dataRepository.getFileBlock(boneOMA).getStructure(dataRepository).getFieldValue("name").toString(); List<Structure> constraints = ((Structure) poseChannel.getFieldValue("constraints")).evaluateListBase(dataRepository); for (Structure constraint : constraints) { String constraintName = constraint.getFieldValue("name").toString(); Map<String, Ipo> ipoMap = constraintsIpos.get(name); Ipo ipo = ipoMap==null ? null : ipoMap.get(constraintName); if (ipo == null) { float enforce = ((Number) constraint.getFieldValue("enforce")).floatValue(); ipo = ipoHelper.createIpo(enforce); } constraintsList.add(ConstraintFactory.createConstraint(constraint, boneOMA, ipo, dataRepository)); } result.put(boneOMA, constraintsList); dataRepository.addConstraints(boneOMA, constraintsList); } } // TODO: reading constraints for objects (implement when object's animation will be available) List<Structure> constraintChannels = ((Structure)objectStructure.getFieldValue("constraintChannels")).evaluateListBase(dataRepository); for(Structure constraintChannel : constraintChannels) { System.out.println(constraintChannel); } //loading constraints connected with the object itself (TODO: test this) if(!result.containsKey(objectStructure.getOldMemoryAddress())) { List<Structure> constraints = ((Structure)objectStructure.getFieldValue("constraints")).evaluateListBase(dataRepository); List<Constraint> constraintsList = new ArrayList<Constraint>(constraints.size()); for(Structure constraint : constraints) { String constraintName = constraint.getFieldValue("name").toString(); String objectName = objectStructure.getName(); Map<String, Ipo> objectConstraintsIpos = constraintsIpos.get(objectName); Ipo ipo = objectConstraintsIpos!=null ? objectConstraintsIpos.get(constraintName) : null; if (ipo == null) { float enforce = ((Number) constraint.getFieldValue("enforce")).floatValue(); ipo = ipoHelper.createIpo(enforce); } constraintsList.add(ConstraintFactory.createConstraint(constraint, null, ipo, dataRepository)); } result.put(objectStructure.getOldMemoryAddress(), constraintsList); dataRepository.addConstraints(objectStructure.getOldMemoryAddress(), constraintsList); } return result; }
public Map<Long, List<Constraint>> loadConstraints(Structure objectStructure, DataRepository dataRepository) throws BlenderFileException { if (blenderVersion >= 250) {//TODO LOGGER.warning("Loading of constraints not yet implemented for version 2.5x !"); return new HashMap<Long, List<Constraint>>(0); } // reading influence ipos for the constraints IpoHelper ipoHelper = dataRepository.getHelper(IpoHelper.class); Map<String, Map<String, Ipo>> constraintsIpos = new HashMap<String, Map<String, Ipo>>(); Pointer pActions = (Pointer) objectStructure.getFieldValue("action"); if (pActions.isNotNull()) { List<Structure> actions = pActions.fetchData(dataRepository.getInputStream()); for (Structure action : actions) { Structure chanbase = (Structure) action.getFieldValue("chanbase"); List<Structure> actionChannels = chanbase.evaluateListBase(dataRepository); for (Structure actionChannel : actionChannels) { Map<String, Ipo> ipos = new HashMap<String, Ipo>(); Structure constChannels = (Structure) actionChannel.getFieldValue("constraintChannels"); List<Structure> constraintChannels = constChannels.evaluateListBase(dataRepository); for (Structure constraintChannel : constraintChannels) { Pointer pIpo = (Pointer) constraintChannel.getFieldValue("ipo"); if (pIpo.isNotNull()) { String constraintName = constraintChannel.getFieldValue("name").toString(); Ipo ipo = ipoHelper.createIpo(pIpo.fetchData(dataRepository.getInputStream()).get(0), dataRepository); ipos.put(constraintName, ipo); } } String actionName = actionChannel.getFieldValue("name").toString(); constraintsIpos.put(actionName, ipos); } } } Map<Long, List<Constraint>> result = new HashMap<Long, List<Constraint>>(); //loading constraints connected with the object's bones Pointer pPose = (Pointer) objectStructure.getFieldValue("pose");//TODO: what if the object has two armatures ???? if (pPose.isNotNull()) { List<Structure> poseChannels = ((Structure) pPose.fetchData(dataRepository.getInputStream()).get(0).getFieldValue("chanbase")).evaluateListBase(dataRepository); for (Structure poseChannel : poseChannels) { List<Constraint> constraintsList = new ArrayList<Constraint>(); Long boneOMA = Long.valueOf(((Pointer) poseChannel.getFieldValue("bone")).getOldMemoryAddress()); //the name is read directly from structure because bone might not yet be loaded String name = dataRepository.getFileBlock(boneOMA).getStructure(dataRepository).getFieldValue("name").toString(); List<Structure> constraints = ((Structure) poseChannel.getFieldValue("constraints")).evaluateListBase(dataRepository); for (Structure constraint : constraints) { String constraintName = constraint.getFieldValue("name").toString(); Map<String, Ipo> ipoMap = constraintsIpos.get(name); Ipo ipo = ipoMap==null ? null : ipoMap.get(constraintName); if (ipo == null) { float enforce = ((Number) constraint.getFieldValue("enforce")).floatValue(); ipo = ipoHelper.createIpo(enforce); } constraintsList.add(ConstraintFactory.createConstraint(constraint, boneOMA, ipo, dataRepository)); } result.put(boneOMA, constraintsList); dataRepository.addConstraints(boneOMA, constraintsList); } } // TODO: reading constraints for objects (implement when object's animation will be available) List<Structure> constraintChannels = ((Structure)objectStructure.getFieldValue("constraintChannels")).evaluateListBase(dataRepository); for(Structure constraintChannel : constraintChannels) { System.out.println(constraintChannel); } //loading constraints connected with the object itself (TODO: test this) if(!result.containsKey(objectStructure.getOldMemoryAddress())) { List<Structure> constraints = ((Structure)objectStructure.getFieldValue("constraints")).evaluateListBase(dataRepository); List<Constraint> constraintsList = new ArrayList<Constraint>(constraints.size()); for(Structure constraint : constraints) { String constraintName = constraint.getFieldValue("name").toString(); String objectName = objectStructure.getName(); Map<String, Ipo> objectConstraintsIpos = constraintsIpos.get(objectName); Ipo ipo = objectConstraintsIpos!=null ? objectConstraintsIpos.get(constraintName) : null; if (ipo == null) { float enforce = ((Number) constraint.getFieldValue("enforce")).floatValue(); ipo = ipoHelper.createIpo(enforce); } constraintsList.add(ConstraintFactory.createConstraint(constraint, null, ipo, dataRepository)); } result.put(objectStructure.getOldMemoryAddress(), constraintsList); dataRepository.addConstraints(objectStructure.getOldMemoryAddress(), constraintsList); } return result; }
diff --git a/alchemy-midlet/src/alchemy/nec/NEL.java b/alchemy-midlet/src/alchemy/nec/NEL.java index 6b2dc71..4c96c21 100644 --- a/alchemy-midlet/src/alchemy/nec/NEL.java +++ b/alchemy-midlet/src/alchemy/nec/NEL.java @@ -1,499 +1,499 @@ /* * This file is a part of Alchemy OS project. * Copyright (C) 2011-2013, Sergey Basalaev <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package alchemy.nec; import alchemy.core.Context; import alchemy.core.types.Int; import alchemy.evm.ELibBuilder; import alchemy.evm.Opcodes; import alchemy.fs.FSManager; import alchemy.nlib.NativeApp; import alchemy.util.IO; import alchemy.util.Properties; import alchemy.util.UTFReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; /** * Native Ether linker. * // TODO: move to alchemy.nes.asm * @author Sergey Basalaev */ public class NEL extends NativeApp { /** Highest supported library file format version. * @see ELibBuilder#VERSION */ static private final int SUPPORTED = 0x0201; static private final String VERSION = "Native Ether linker version 1.3.1"; static private final String HELP = "Usage: el [options] <input>...\nOptions:\n" + "-o <output>\n write to this file\n" + "-l<lib>\n link with given library\n" + "-L<path>\n append path to LIBPATH\n" + "-s<soname>\n use this soname\n" + "-h\n print this help and exit\n" + "-v\n print version and exit"; public NEL() { } public int main(Context c, String[] args) { //parsing arguments String outname = "a.out"; String soname = null; Vector infiles = new Vector(); Vector linklibs = new Vector(); linklibs.addElement("libcore.so"); //always link with libcore linklibs.addElement("libcoree.so"); //always link with libcoree boolean wait_outname = false; for (int i=0; i<args.length; i++) { String arg = args[i]; if (arg.equals("-h")) { IO.println(c.stdout, HELP); return 0; } else if (arg.equals("-v")) { IO.println(c.stdout, VERSION); return 0; } else if (arg.equals("-o")) { wait_outname = true; } else if (arg.startsWith("-l") && arg.length() > 2) { if (arg.indexOf('/') < 0) { linklibs.addElement("lib"+arg.substring(2)+".so"); } else { linklibs.addElement(arg.substring(2)); } } else if (arg.startsWith("-L")) { - c.setEnv("LIBPATH", c.getEnv("LIBPATH")+':'+arg.substring(3)); + c.setEnv("LIBPATH", c.getEnv("LIBPATH")+':'+arg.substring(2)); } else if (arg.startsWith("-s") && arg.length() > 2) { soname = arg.substring(2); } else if (arg.charAt(0) == '-') { IO.println(c.stderr, "Unknown argument: "+arg); return 1; } else if (wait_outname) { outname = arg; wait_outname = false; } else { infiles.addElement(arg); } } if (infiles.isEmpty()) { IO.println(c.stderr, "No files to process"); return 1; } try { //loading symbols from libraries Hashtable symbols = new Hashtable(); Vector libinfos = new Vector(); for (int li=0; li < linklibs.size(); li++) { String libname = linklibs.elementAt(li).toString(); LibInfo info = loadLibInfo(c, libname); libinfos.addElement(info); for (Enumeration e = info.symbols.elements(); e.hasMoreElements();) { symbols.put(e.nextElement(), info); } } //processing objects Vector pool = new Vector(); char[] reloctable = new char[128]; int count = 0, offset; for (int fi=0; fi < infiles.size(); fi++) { offset = count; String infile = c.toFile(infiles.elementAt(fi).toString()); DataInputStream data = new DataInputStream(FSManager.fs().read(infile)); if (data.readInt() != 0xC0DE0201) throw new Exception("Unsupported object format in "+infile); int lflags = data.readUnsignedByte(); if (lflags != 0) throw new Exception("Relinkage of shared objects is not supported"); int poolsize = data.readUnsignedShort(); for (int oi = 0; oi < poolsize; oi++) { int type = data.readUnsignedByte(); Object obj; switch (type) { case '0': obj = null; break; case 'i': obj = Int.toInt(data.readInt()); break; case 'l': obj = new Long(data.readLong()); break; case 'f': obj = new Float(data.readFloat()); break; case 'd': obj = new Double(data.readDouble()); break; case 'S': obj = data.readUTF(); break; case 'U': { String id = data.readUTF(); LibInfo info = (LibInfo)symbols.get(id); if (info != null) { obj = new ExFunc(id, info); info.used = true; } else { obj = new NELFunc(id); } break; } case 'P': { String name = data.readUTF(); InFunc f = new InFunc(name); f.flags = data.readUnsignedByte(); f.stack = data.readUnsignedByte(); f.locals = data.readUnsignedByte(); f.code = new byte[data.readUnsignedShort()]; data.readFully(f.code); f.relocs = new int[data.readShort()]; for (int i=0; i<f.relocs.length; i++) { f.relocs[i] = data.readUnsignedShort(); } f.reloffset = offset; if ((f.flags & Opcodes.FFLAG_LNUM) != 0) { f.lnumtable = new char[data.readUnsignedShort()]; for (int j=0; j< f.lnumtable.length; j++) { f.lnumtable[j] = data.readChar(); } } if ((f.flags & Opcodes.FFLAG_ERRTBL) != 0) { f.errtable = new char[data.readUnsignedShort()]; for (int j=0; j< f.errtable.length; j++) { f.errtable[j] = data.readChar(); } } obj = f; break; } default: throw new Exception("Unknown object type: "+String.valueOf(type)); } int objindex = pool.indexOf(obj); if (objindex < 0) { objindex = pool.size(); pool.addElement(obj); } else if (obj instanceof NELFunc) { NELFunc old = (NELFunc)pool.elementAt(objindex); if (old instanceof ExFunc) { if (obj instanceof InFunc) { throw new Exception("Multiple definitions of "+obj); } else if (obj instanceof ExFunc) { //should be ok } } else if (old instanceof InFunc) { if (obj instanceof ExFunc || obj instanceof InFunc) { throw new Exception("Multiple definitions of "+obj); } } else { //old is unresolved, replace it without a doubt pool.setElementAt(obj, objindex); } } if (reloctable.length == count) { char[] newrelocs = new char[count << 1]; System.arraycopy(reloctable, 0, newrelocs, 0, count); reloctable = newrelocs; } reloctable[count] = (char)objindex; count++; } data.close(); } //relocating for (Enumeration e = pool.elements(); e.hasMoreElements(); ) { Object obj = e.nextElement(); if (obj instanceof InFunc) { // relocating code InFunc f = (InFunc)obj; for (int ri=f.relocs.length-1; ri >= 0; ri--) { int r = f.relocs[ri]; // address in code with number to fix int oldaddr = ((f.code[r] & 0xff) << 8) | (f.code[r+1] & 0xff); int newaddr = reloctable[oldaddr+f.reloffset]; f.code[r] = (byte)(newaddr >> 8); f.code[r+1] = (byte)newaddr; } // relocating source if (f.lnumtable != null) f.lnumtable[0] = reloctable[f.lnumtable[0] + f.reloffset]; } else if (obj.getClass() == NELFunc.class) { throw new Exception("Unresolved symbol: "+obj); } } //indexing libraries, throwing out unused int li = 0; while (li < libinfos.size()) { LibInfo info = (LibInfo)libinfos.elementAt(li); if (info.used) { info.index = li; li++; } else { libinfos.removeElementAt(li); } } //writing output String outfile = c.toFile(outname); DataOutputStream out = new DataOutputStream(FSManager.fs().write(outfile)); out.writeInt(0xC0DE0201); if (soname != null) { out.writeByte(Opcodes.LFLAG_SONAME | Opcodes.LFLAG_DEPS); out.writeUTF(soname); } else { out.writeByte(Opcodes.LFLAG_DEPS); } out.writeShort(libinfos.size()); for (int i=0; i < libinfos.size(); i++) { out.writeUTF(((LibInfo)libinfos.elementAt(i)).soname); } out.writeShort(pool.size()); for (Enumeration e = pool.elements(); e.hasMoreElements(); ) { Object obj = e.nextElement(); if (obj == null) { out.writeByte('0'); } else if (obj.getClass() == Int.class) { out.writeByte('i'); Int ival = (Int)obj; out.writeInt(ival.value); } else if (obj.getClass() == Long.class) { out.writeByte('l'); Long lval = (Long)obj; out.writeLong(lval.longValue()); } else if (obj.getClass() == Float.class) { out.writeByte('f'); Float fval = (Float)obj; out.writeFloat(fval.floatValue()); } else if (obj.getClass() == Double.class) { out.writeByte('d'); Double dval = (Double)obj; out.writeDouble(dval.doubleValue()); } else if (obj.getClass() == String.class) { out.writeByte('S'); out.writeUTF(obj.toString()); } else if (obj instanceof ExFunc) { out.writeByte('E'); ExFunc ef = (ExFunc)obj; out.writeShort(ef.info.index); out.writeUTF(ef.name); } else if (obj instanceof InFunc) { InFunc func = (InFunc)obj; out.writeByte('P'); out.writeUTF(func.name); out.writeByte(func.flags & ~Opcodes.FFLAG_RELOCS); out.writeByte(func.stack); out.writeByte(func.locals); out.writeShort(func.code.length); out.write(func.code); if ((func.flags & Opcodes.FFLAG_LNUM) != 0) { out.writeShort(func.lnumtable.length); for (int j=0; j<func.lnumtable.length; j++) { out.writeChar(func.lnumtable[j]); } } if ((func.flags & Opcodes.FFLAG_ERRTBL) != 0) { out.writeShort(func.errtable.length); for (int j=0; j<func.errtable.length; j++) { out.writeChar(func.errtable[j]); } } } } out.close(); FSManager.fs().setExec(outfile, true); } catch (Exception e) { IO.println(c.stderr, "Error: "+e); // e.printStackTrace(); return 1; } return 0; } private LibInfo loadLibInfo(Context c, String libname) throws Exception { String libfile = c.resolveFile(libname, c.getEnv("LIBPATH")); InputStream in = FSManager.fs().read(libfile); int magic = in.read() << 8 | in.read(); LibInfo info; if (magic < 0) { in.close(); throw new Exception("File is too short: "+libfile); } else if (magic == ('#'<<8|'=')) { byte[] buf = IO.readFully(in); in.close(); info = loadLibInfo(c, IO.utfDecode(buf).trim()); } else if (magic == 0xC0DE) { info = loadFromECode(in); } else if (magic == ('#'<<8|'@')) { info = loadFromNative(in); } else { throw new Exception("Unknown library format in "+libfile); } if (info.soname == null) info.soname = libname; return info; } private LibInfo loadFromECode(InputStream in) throws Exception { DataInputStream data = new DataInputStream(in); if (data.readUnsignedShort() > SUPPORTED) throw new Exception("Unsupported format version"); LibInfo info = new LibInfo(); Vector symbols = new Vector(); int lflags = data.readUnsignedByte(); if ((lflags & Opcodes.LFLAG_SONAME) != 0) { //has soname info.soname = data.readUTF(); } //skipping dependencies int depsize = data.readUnsignedShort(); for (int i=0; i<depsize; i++) { data.skipBytes(data.readUnsignedShort()); } //reading pool int poolsize = data.readUnsignedShort(); for (int i=0; i<poolsize; i++) { int ch = data.readUnsignedByte(); switch (ch) { case '0': break; case 'i': case 'f': data.skipBytes(4); break; case 'l': case 'd': data.skipBytes(8); break; case 'S': data.skipBytes(data.readUnsignedShort()); break; case 'E': data.skipBytes(2); data.skipBytes(data.readUnsignedShort()); break; case 'P': { String name = data.readUTF(); int flags = data.readUnsignedByte(); data.skipBytes(2); data.skipBytes(data.readUnsignedShort()); if ((flags & Opcodes.FFLAG_SHARED) != 0) { symbols.addElement(name); } if ((flags & Opcodes.FFLAG_LNUM) != 0) { data.skipBytes(data.readUnsignedShort()*2); } if ((flags & Opcodes.FFLAG_ERRTBL) != 0) { data.skipBytes(data.readUnsignedShort()*2); } break; } default: throw new Exception("Unknown object type: "+ch); } } in.close(); info.symbols = symbols; return info; } private LibInfo loadFromNative(InputStream in) throws IOException { UTFReader r = new UTFReader(in); r.readLine(); //skip classname Properties prop = Properties.readFrom(r); r.close(); LibInfo info = new LibInfo(); info.soname = prop.get("soname"); String symbolfile = prop.get("symbols"); if (symbolfile == null) { info.symbols = new Vector(); } else { Vector vsym = new Vector(); InputStream symstream = getClass().getResourceAsStream(symbolfile); byte[] buf = new byte[symstream.available()]; symstream.read(buf); symstream.close(); final String[] syms = IO.split(IO.utfDecode(buf), '\n'); for (int i=0; i < syms.length; i++) { vsym.addElement(syms[i]); } info.symbols = vsym; } return info; } } class LibInfo { /** Shared object name. */ String soname; /** Symbols that this library provides. */ Vector symbols; /** Index assigned to this library by linker. */ int index; /** Are symbols from this library actually used? */ boolean used; } /** Unknown function. */ class NELFunc { String name; public NELFunc(String name) { this.name = name; } public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof NELFunc)) return false; return ((NELFunc)o).name.equals(this.name); } public String toString() { return '\''+name+'\''; } } /** Internal function. */ class InFunc extends NELFunc { int stack; int locals; int flags; byte[] code; int[] relocs; int reloffset; char[] lnumtable; char[] errtable; public InFunc(String name) { super(name); } } /** External function. */ class ExFunc extends NELFunc { LibInfo info; public ExFunc(String name, LibInfo info) { super(name); this.info = info; } }
true
true
public int main(Context c, String[] args) { //parsing arguments String outname = "a.out"; String soname = null; Vector infiles = new Vector(); Vector linklibs = new Vector(); linklibs.addElement("libcore.so"); //always link with libcore linklibs.addElement("libcoree.so"); //always link with libcoree boolean wait_outname = false; for (int i=0; i<args.length; i++) { String arg = args[i]; if (arg.equals("-h")) { IO.println(c.stdout, HELP); return 0; } else if (arg.equals("-v")) { IO.println(c.stdout, VERSION); return 0; } else if (arg.equals("-o")) { wait_outname = true; } else if (arg.startsWith("-l") && arg.length() > 2) { if (arg.indexOf('/') < 0) { linklibs.addElement("lib"+arg.substring(2)+".so"); } else { linklibs.addElement(arg.substring(2)); } } else if (arg.startsWith("-L")) { c.setEnv("LIBPATH", c.getEnv("LIBPATH")+':'+arg.substring(3)); } else if (arg.startsWith("-s") && arg.length() > 2) { soname = arg.substring(2); } else if (arg.charAt(0) == '-') { IO.println(c.stderr, "Unknown argument: "+arg); return 1; } else if (wait_outname) { outname = arg; wait_outname = false; } else { infiles.addElement(arg); } } if (infiles.isEmpty()) { IO.println(c.stderr, "No files to process"); return 1; } try { //loading symbols from libraries Hashtable symbols = new Hashtable(); Vector libinfos = new Vector(); for (int li=0; li < linklibs.size(); li++) { String libname = linklibs.elementAt(li).toString(); LibInfo info = loadLibInfo(c, libname); libinfos.addElement(info); for (Enumeration e = info.symbols.elements(); e.hasMoreElements();) { symbols.put(e.nextElement(), info); } } //processing objects Vector pool = new Vector(); char[] reloctable = new char[128]; int count = 0, offset; for (int fi=0; fi < infiles.size(); fi++) { offset = count; String infile = c.toFile(infiles.elementAt(fi).toString()); DataInputStream data = new DataInputStream(FSManager.fs().read(infile)); if (data.readInt() != 0xC0DE0201) throw new Exception("Unsupported object format in "+infile); int lflags = data.readUnsignedByte(); if (lflags != 0) throw new Exception("Relinkage of shared objects is not supported"); int poolsize = data.readUnsignedShort(); for (int oi = 0; oi < poolsize; oi++) { int type = data.readUnsignedByte(); Object obj; switch (type) { case '0': obj = null; break; case 'i': obj = Int.toInt(data.readInt()); break; case 'l': obj = new Long(data.readLong()); break; case 'f': obj = new Float(data.readFloat()); break; case 'd': obj = new Double(data.readDouble()); break; case 'S': obj = data.readUTF(); break; case 'U': { String id = data.readUTF(); LibInfo info = (LibInfo)symbols.get(id); if (info != null) { obj = new ExFunc(id, info); info.used = true; } else { obj = new NELFunc(id); } break; } case 'P': { String name = data.readUTF(); InFunc f = new InFunc(name); f.flags = data.readUnsignedByte(); f.stack = data.readUnsignedByte(); f.locals = data.readUnsignedByte(); f.code = new byte[data.readUnsignedShort()]; data.readFully(f.code); f.relocs = new int[data.readShort()]; for (int i=0; i<f.relocs.length; i++) { f.relocs[i] = data.readUnsignedShort(); } f.reloffset = offset; if ((f.flags & Opcodes.FFLAG_LNUM) != 0) { f.lnumtable = new char[data.readUnsignedShort()]; for (int j=0; j< f.lnumtable.length; j++) { f.lnumtable[j] = data.readChar(); } } if ((f.flags & Opcodes.FFLAG_ERRTBL) != 0) { f.errtable = new char[data.readUnsignedShort()]; for (int j=0; j< f.errtable.length; j++) { f.errtable[j] = data.readChar(); } } obj = f; break; } default: throw new Exception("Unknown object type: "+String.valueOf(type)); } int objindex = pool.indexOf(obj); if (objindex < 0) { objindex = pool.size(); pool.addElement(obj); } else if (obj instanceof NELFunc) { NELFunc old = (NELFunc)pool.elementAt(objindex); if (old instanceof ExFunc) { if (obj instanceof InFunc) { throw new Exception("Multiple definitions of "+obj); } else if (obj instanceof ExFunc) { //should be ok } } else if (old instanceof InFunc) { if (obj instanceof ExFunc || obj instanceof InFunc) { throw new Exception("Multiple definitions of "+obj); } } else { //old is unresolved, replace it without a doubt pool.setElementAt(obj, objindex); } } if (reloctable.length == count) { char[] newrelocs = new char[count << 1]; System.arraycopy(reloctable, 0, newrelocs, 0, count); reloctable = newrelocs; } reloctable[count] = (char)objindex; count++; } data.close(); } //relocating for (Enumeration e = pool.elements(); e.hasMoreElements(); ) { Object obj = e.nextElement(); if (obj instanceof InFunc) { // relocating code InFunc f = (InFunc)obj; for (int ri=f.relocs.length-1; ri >= 0; ri--) { int r = f.relocs[ri]; // address in code with number to fix int oldaddr = ((f.code[r] & 0xff) << 8) | (f.code[r+1] & 0xff); int newaddr = reloctable[oldaddr+f.reloffset]; f.code[r] = (byte)(newaddr >> 8); f.code[r+1] = (byte)newaddr; } // relocating source if (f.lnumtable != null) f.lnumtable[0] = reloctable[f.lnumtable[0] + f.reloffset]; } else if (obj.getClass() == NELFunc.class) { throw new Exception("Unresolved symbol: "+obj); } } //indexing libraries, throwing out unused int li = 0; while (li < libinfos.size()) { LibInfo info = (LibInfo)libinfos.elementAt(li); if (info.used) { info.index = li; li++; } else { libinfos.removeElementAt(li); } } //writing output String outfile = c.toFile(outname); DataOutputStream out = new DataOutputStream(FSManager.fs().write(outfile)); out.writeInt(0xC0DE0201); if (soname != null) { out.writeByte(Opcodes.LFLAG_SONAME | Opcodes.LFLAG_DEPS); out.writeUTF(soname); } else { out.writeByte(Opcodes.LFLAG_DEPS); } out.writeShort(libinfos.size()); for (int i=0; i < libinfos.size(); i++) { out.writeUTF(((LibInfo)libinfos.elementAt(i)).soname); } out.writeShort(pool.size()); for (Enumeration e = pool.elements(); e.hasMoreElements(); ) { Object obj = e.nextElement(); if (obj == null) { out.writeByte('0'); } else if (obj.getClass() == Int.class) { out.writeByte('i'); Int ival = (Int)obj; out.writeInt(ival.value); } else if (obj.getClass() == Long.class) { out.writeByte('l'); Long lval = (Long)obj; out.writeLong(lval.longValue()); } else if (obj.getClass() == Float.class) { out.writeByte('f'); Float fval = (Float)obj; out.writeFloat(fval.floatValue()); } else if (obj.getClass() == Double.class) { out.writeByte('d'); Double dval = (Double)obj; out.writeDouble(dval.doubleValue()); } else if (obj.getClass() == String.class) { out.writeByte('S'); out.writeUTF(obj.toString()); } else if (obj instanceof ExFunc) { out.writeByte('E'); ExFunc ef = (ExFunc)obj; out.writeShort(ef.info.index); out.writeUTF(ef.name); } else if (obj instanceof InFunc) { InFunc func = (InFunc)obj; out.writeByte('P'); out.writeUTF(func.name); out.writeByte(func.flags & ~Opcodes.FFLAG_RELOCS); out.writeByte(func.stack); out.writeByte(func.locals); out.writeShort(func.code.length); out.write(func.code); if ((func.flags & Opcodes.FFLAG_LNUM) != 0) { out.writeShort(func.lnumtable.length); for (int j=0; j<func.lnumtable.length; j++) { out.writeChar(func.lnumtable[j]); } } if ((func.flags & Opcodes.FFLAG_ERRTBL) != 0) { out.writeShort(func.errtable.length); for (int j=0; j<func.errtable.length; j++) { out.writeChar(func.errtable[j]); } } } } out.close(); FSManager.fs().setExec(outfile, true); } catch (Exception e) { IO.println(c.stderr, "Error: "+e); // e.printStackTrace(); return 1; } return 0; }
public int main(Context c, String[] args) { //parsing arguments String outname = "a.out"; String soname = null; Vector infiles = new Vector(); Vector linklibs = new Vector(); linklibs.addElement("libcore.so"); //always link with libcore linklibs.addElement("libcoree.so"); //always link with libcoree boolean wait_outname = false; for (int i=0; i<args.length; i++) { String arg = args[i]; if (arg.equals("-h")) { IO.println(c.stdout, HELP); return 0; } else if (arg.equals("-v")) { IO.println(c.stdout, VERSION); return 0; } else if (arg.equals("-o")) { wait_outname = true; } else if (arg.startsWith("-l") && arg.length() > 2) { if (arg.indexOf('/') < 0) { linklibs.addElement("lib"+arg.substring(2)+".so"); } else { linklibs.addElement(arg.substring(2)); } } else if (arg.startsWith("-L")) { c.setEnv("LIBPATH", c.getEnv("LIBPATH")+':'+arg.substring(2)); } else if (arg.startsWith("-s") && arg.length() > 2) { soname = arg.substring(2); } else if (arg.charAt(0) == '-') { IO.println(c.stderr, "Unknown argument: "+arg); return 1; } else if (wait_outname) { outname = arg; wait_outname = false; } else { infiles.addElement(arg); } } if (infiles.isEmpty()) { IO.println(c.stderr, "No files to process"); return 1; } try { //loading symbols from libraries Hashtable symbols = new Hashtable(); Vector libinfos = new Vector(); for (int li=0; li < linklibs.size(); li++) { String libname = linklibs.elementAt(li).toString(); LibInfo info = loadLibInfo(c, libname); libinfos.addElement(info); for (Enumeration e = info.symbols.elements(); e.hasMoreElements();) { symbols.put(e.nextElement(), info); } } //processing objects Vector pool = new Vector(); char[] reloctable = new char[128]; int count = 0, offset; for (int fi=0; fi < infiles.size(); fi++) { offset = count; String infile = c.toFile(infiles.elementAt(fi).toString()); DataInputStream data = new DataInputStream(FSManager.fs().read(infile)); if (data.readInt() != 0xC0DE0201) throw new Exception("Unsupported object format in "+infile); int lflags = data.readUnsignedByte(); if (lflags != 0) throw new Exception("Relinkage of shared objects is not supported"); int poolsize = data.readUnsignedShort(); for (int oi = 0; oi < poolsize; oi++) { int type = data.readUnsignedByte(); Object obj; switch (type) { case '0': obj = null; break; case 'i': obj = Int.toInt(data.readInt()); break; case 'l': obj = new Long(data.readLong()); break; case 'f': obj = new Float(data.readFloat()); break; case 'd': obj = new Double(data.readDouble()); break; case 'S': obj = data.readUTF(); break; case 'U': { String id = data.readUTF(); LibInfo info = (LibInfo)symbols.get(id); if (info != null) { obj = new ExFunc(id, info); info.used = true; } else { obj = new NELFunc(id); } break; } case 'P': { String name = data.readUTF(); InFunc f = new InFunc(name); f.flags = data.readUnsignedByte(); f.stack = data.readUnsignedByte(); f.locals = data.readUnsignedByte(); f.code = new byte[data.readUnsignedShort()]; data.readFully(f.code); f.relocs = new int[data.readShort()]; for (int i=0; i<f.relocs.length; i++) { f.relocs[i] = data.readUnsignedShort(); } f.reloffset = offset; if ((f.flags & Opcodes.FFLAG_LNUM) != 0) { f.lnumtable = new char[data.readUnsignedShort()]; for (int j=0; j< f.lnumtable.length; j++) { f.lnumtable[j] = data.readChar(); } } if ((f.flags & Opcodes.FFLAG_ERRTBL) != 0) { f.errtable = new char[data.readUnsignedShort()]; for (int j=0; j< f.errtable.length; j++) { f.errtable[j] = data.readChar(); } } obj = f; break; } default: throw new Exception("Unknown object type: "+String.valueOf(type)); } int objindex = pool.indexOf(obj); if (objindex < 0) { objindex = pool.size(); pool.addElement(obj); } else if (obj instanceof NELFunc) { NELFunc old = (NELFunc)pool.elementAt(objindex); if (old instanceof ExFunc) { if (obj instanceof InFunc) { throw new Exception("Multiple definitions of "+obj); } else if (obj instanceof ExFunc) { //should be ok } } else if (old instanceof InFunc) { if (obj instanceof ExFunc || obj instanceof InFunc) { throw new Exception("Multiple definitions of "+obj); } } else { //old is unresolved, replace it without a doubt pool.setElementAt(obj, objindex); } } if (reloctable.length == count) { char[] newrelocs = new char[count << 1]; System.arraycopy(reloctable, 0, newrelocs, 0, count); reloctable = newrelocs; } reloctable[count] = (char)objindex; count++; } data.close(); } //relocating for (Enumeration e = pool.elements(); e.hasMoreElements(); ) { Object obj = e.nextElement(); if (obj instanceof InFunc) { // relocating code InFunc f = (InFunc)obj; for (int ri=f.relocs.length-1; ri >= 0; ri--) { int r = f.relocs[ri]; // address in code with number to fix int oldaddr = ((f.code[r] & 0xff) << 8) | (f.code[r+1] & 0xff); int newaddr = reloctable[oldaddr+f.reloffset]; f.code[r] = (byte)(newaddr >> 8); f.code[r+1] = (byte)newaddr; } // relocating source if (f.lnumtable != null) f.lnumtable[0] = reloctable[f.lnumtable[0] + f.reloffset]; } else if (obj.getClass() == NELFunc.class) { throw new Exception("Unresolved symbol: "+obj); } } //indexing libraries, throwing out unused int li = 0; while (li < libinfos.size()) { LibInfo info = (LibInfo)libinfos.elementAt(li); if (info.used) { info.index = li; li++; } else { libinfos.removeElementAt(li); } } //writing output String outfile = c.toFile(outname); DataOutputStream out = new DataOutputStream(FSManager.fs().write(outfile)); out.writeInt(0xC0DE0201); if (soname != null) { out.writeByte(Opcodes.LFLAG_SONAME | Opcodes.LFLAG_DEPS); out.writeUTF(soname); } else { out.writeByte(Opcodes.LFLAG_DEPS); } out.writeShort(libinfos.size()); for (int i=0; i < libinfos.size(); i++) { out.writeUTF(((LibInfo)libinfos.elementAt(i)).soname); } out.writeShort(pool.size()); for (Enumeration e = pool.elements(); e.hasMoreElements(); ) { Object obj = e.nextElement(); if (obj == null) { out.writeByte('0'); } else if (obj.getClass() == Int.class) { out.writeByte('i'); Int ival = (Int)obj; out.writeInt(ival.value); } else if (obj.getClass() == Long.class) { out.writeByte('l'); Long lval = (Long)obj; out.writeLong(lval.longValue()); } else if (obj.getClass() == Float.class) { out.writeByte('f'); Float fval = (Float)obj; out.writeFloat(fval.floatValue()); } else if (obj.getClass() == Double.class) { out.writeByte('d'); Double dval = (Double)obj; out.writeDouble(dval.doubleValue()); } else if (obj.getClass() == String.class) { out.writeByte('S'); out.writeUTF(obj.toString()); } else if (obj instanceof ExFunc) { out.writeByte('E'); ExFunc ef = (ExFunc)obj; out.writeShort(ef.info.index); out.writeUTF(ef.name); } else if (obj instanceof InFunc) { InFunc func = (InFunc)obj; out.writeByte('P'); out.writeUTF(func.name); out.writeByte(func.flags & ~Opcodes.FFLAG_RELOCS); out.writeByte(func.stack); out.writeByte(func.locals); out.writeShort(func.code.length); out.write(func.code); if ((func.flags & Opcodes.FFLAG_LNUM) != 0) { out.writeShort(func.lnumtable.length); for (int j=0; j<func.lnumtable.length; j++) { out.writeChar(func.lnumtable[j]); } } if ((func.flags & Opcodes.FFLAG_ERRTBL) != 0) { out.writeShort(func.errtable.length); for (int j=0; j<func.errtable.length; j++) { out.writeChar(func.errtable[j]); } } } } out.close(); FSManager.fs().setExec(outfile, true); } catch (Exception e) { IO.println(c.stderr, "Error: "+e); // e.printStackTrace(); return 1; } return 0; }
diff --git a/core/src/test/java/io/undertow/util/FileSystemWatcherTestCase.java b/core/src/test/java/io/undertow/util/FileSystemWatcherTestCase.java index ba8d4f10b..cb2293512 100644 --- a/core/src/test/java/io/undertow/util/FileSystemWatcherTestCase.java +++ b/core/src/test/java/io/undertow/util/FileSystemWatcherTestCase.java @@ -1,147 +1,151 @@ package io.undertow.util; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.xnio.IoUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; /** * Test file system watcher, both poll and non poll based * * @author Stuart Douglas */ @RunWith(Parameterized.class) public class FileSystemWatcherTestCase { public static final String DIR_NAME = "/fileSystemWatcherTest"; public static final String EXISTING_FILE_NAME = "a.txt"; public static final String EXISTING_DIR = "existingDir"; private final BlockingDeque<Collection<FileChangeEvent>> results = new LinkedBlockingDeque<Collection<FileChangeEvent>>(); File rootDir; File existingSubDir; private final boolean forcePoll; @Parameterized.Parameters public static List<Object[]> parameters() { final List<Object[]> params = new ArrayList<Object[]>(); params.add(new Boolean[]{true}); params.add(new Boolean[]{false}); return params; } public FileSystemWatcherTestCase(boolean forcePoll) { this.forcePoll = forcePoll; } @Before public void setup() throws Exception { rootDir = new File(System.getProperty("java.io.tmpdir") + DIR_NAME); FileUtils.deleteRecursive(rootDir); rootDir.mkdirs(); File existing = new File(rootDir, EXISTING_FILE_NAME); touchFile(existing); existingSubDir = new File(rootDir, EXISTING_DIR); existingSubDir.mkdir(); existing = new File(existingSubDir, EXISTING_FILE_NAME); touchFile(existing); } private static void touchFile(File existing) throws IOException { FileOutputStream out = new FileOutputStream(existing); try { out.write(("data" + System.currentTimeMillis()).getBytes()); out.flush(); } finally { IoUtils.safeClose(out); } } @After public void after() { FileUtils.deleteRecursive(rootDir); } @Test public void testFileSystemWatcher() throws Exception { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.setForcePoll(forcePoll); watcher.setPollInterval(10); try { watcher.start(); watcher.addPath(rootDir, new FileChangeCallback() { @Override public void handleChanges(Collection<FileChangeEvent> changes) { results.add(changes); } }); //first add a file File added = new File(rootDir, "newlyAddedFile.txt").getAbsoluteFile(); touchFile(added); checkResult(added, FileChangeEvent.Type.ADDED); added.setLastModified(500); checkResult(added, FileChangeEvent.Type.MODIFIED); added.delete(); + Thread.sleep(1); checkResult(added, FileChangeEvent.Type.REMOVED); added = new File(existingSubDir, "newSubDirFile.txt"); touchFile(added); checkResult(added, FileChangeEvent.Type.ADDED); added.setLastModified(500); checkResult(added, FileChangeEvent.Type.MODIFIED); added.delete(); + Thread.sleep(1); checkResult(added, FileChangeEvent.Type.REMOVED); File existing = new File(rootDir, EXISTING_FILE_NAME); existing.delete(); + Thread.sleep(1); checkResult(existing, FileChangeEvent.Type.REMOVED); File newDir = new File(rootDir, "newlyCreatedDirectory"); newDir.mkdir(); checkResult(newDir, FileChangeEvent.Type.ADDED); added = new File(newDir, "newlyAddedFileInNewlyAddedDirectory.txt").getAbsoluteFile(); touchFile(added); checkResult(added, FileChangeEvent.Type.ADDED); added.setLastModified(500); checkResult(added, FileChangeEvent.Type.MODIFIED); added.delete(); + Thread.sleep(1); checkResult(added, FileChangeEvent.Type.REMOVED); } finally { watcher.stop(); } } private void checkResult(File file, FileChangeEvent.Type type) throws InterruptedException { Collection<FileChangeEvent> results = this.results.poll(10, TimeUnit.SECONDS); Assert.assertNotNull(results); Assert.assertEquals(1, results.size()); FileChangeEvent res = results.iterator().next(); if (type == FileChangeEvent.Type.REMOVED && res.getType() == FileChangeEvent.Type.MODIFIED) { //sometime OS's will give a MODIFIED event before the REMOVED one results = this.results.poll(10, TimeUnit.SECONDS); Assert.assertNotNull(results); Assert.assertEquals(1, results.size()); res = results.iterator().next(); } Assert.assertEquals(file, res.getFile()); Assert.assertEquals(type, res.getType()); } }
false
true
public void testFileSystemWatcher() throws Exception { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.setForcePoll(forcePoll); watcher.setPollInterval(10); try { watcher.start(); watcher.addPath(rootDir, new FileChangeCallback() { @Override public void handleChanges(Collection<FileChangeEvent> changes) { results.add(changes); } }); //first add a file File added = new File(rootDir, "newlyAddedFile.txt").getAbsoluteFile(); touchFile(added); checkResult(added, FileChangeEvent.Type.ADDED); added.setLastModified(500); checkResult(added, FileChangeEvent.Type.MODIFIED); added.delete(); checkResult(added, FileChangeEvent.Type.REMOVED); added = new File(existingSubDir, "newSubDirFile.txt"); touchFile(added); checkResult(added, FileChangeEvent.Type.ADDED); added.setLastModified(500); checkResult(added, FileChangeEvent.Type.MODIFIED); added.delete(); checkResult(added, FileChangeEvent.Type.REMOVED); File existing = new File(rootDir, EXISTING_FILE_NAME); existing.delete(); checkResult(existing, FileChangeEvent.Type.REMOVED); File newDir = new File(rootDir, "newlyCreatedDirectory"); newDir.mkdir(); checkResult(newDir, FileChangeEvent.Type.ADDED); added = new File(newDir, "newlyAddedFileInNewlyAddedDirectory.txt").getAbsoluteFile(); touchFile(added); checkResult(added, FileChangeEvent.Type.ADDED); added.setLastModified(500); checkResult(added, FileChangeEvent.Type.MODIFIED); added.delete(); checkResult(added, FileChangeEvent.Type.REMOVED); } finally { watcher.stop(); } }
public void testFileSystemWatcher() throws Exception { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.setForcePoll(forcePoll); watcher.setPollInterval(10); try { watcher.start(); watcher.addPath(rootDir, new FileChangeCallback() { @Override public void handleChanges(Collection<FileChangeEvent> changes) { results.add(changes); } }); //first add a file File added = new File(rootDir, "newlyAddedFile.txt").getAbsoluteFile(); touchFile(added); checkResult(added, FileChangeEvent.Type.ADDED); added.setLastModified(500); checkResult(added, FileChangeEvent.Type.MODIFIED); added.delete(); Thread.sleep(1); checkResult(added, FileChangeEvent.Type.REMOVED); added = new File(existingSubDir, "newSubDirFile.txt"); touchFile(added); checkResult(added, FileChangeEvent.Type.ADDED); added.setLastModified(500); checkResult(added, FileChangeEvent.Type.MODIFIED); added.delete(); Thread.sleep(1); checkResult(added, FileChangeEvent.Type.REMOVED); File existing = new File(rootDir, EXISTING_FILE_NAME); existing.delete(); Thread.sleep(1); checkResult(existing, FileChangeEvent.Type.REMOVED); File newDir = new File(rootDir, "newlyCreatedDirectory"); newDir.mkdir(); checkResult(newDir, FileChangeEvent.Type.ADDED); added = new File(newDir, "newlyAddedFileInNewlyAddedDirectory.txt").getAbsoluteFile(); touchFile(added); checkResult(added, FileChangeEvent.Type.ADDED); added.setLastModified(500); checkResult(added, FileChangeEvent.Type.MODIFIED); added.delete(); Thread.sleep(1); checkResult(added, FileChangeEvent.Type.REMOVED); } finally { watcher.stop(); } }
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/services/AbstractCloudService.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/services/AbstractCloudService.java index 08bb74b8..05918fc3 100644 --- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/services/AbstractCloudService.java +++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/services/AbstractCloudService.java @@ -1,650 +1,652 @@ package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services; import com.j_spaces.kernel.PlatformVersion; import iTests.framework.tools.SGTestHelper; import iTests.framework.utils.AssertUtils; import iTests.framework.utils.AssertUtils.RepetitiveConditionProvider; import iTests.framework.utils.IOUtils; import iTests.framework.utils.LogUtils; import iTests.framework.utils.SSHUtils; import iTests.framework.utils.ScriptUtils; import iTests.framework.utils.WebUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.cloudifysource.domain.cloud.Cloud; import org.cloudifysource.dsl.internal.ServiceReader; import org.cloudifysource.quality.iTests.framework.utils.CloudBootstrapper; import org.cloudifysource.quality.iTests.test.cli.cloudify.util.CloudTestUtils; import org.cloudifysource.quality.iTests.test.cli.cloudify.CommandTestUtils; import org.cloudifysource.quality.iTests.test.cli.cloudify.security.SecurityConstants; import org.cloudifysource.restclient.GSRestClient; import org.openspaces.admin.Admin; import org.testng.Assert; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; public abstract class AbstractCloudService implements CloudService { private static final int MAX_HOSTNAME_LENGTH = 35; private static final int MAX_VOLUME_NAME_LENGTH = 45; protected static final String RELATIVE_ESC_PATH = "/clouds/"; protected static final String CREDENTIALS_FOLDER = System.getProperty("iTests.credentialsFolder", SGTestHelper.getSGTestRootDir() + "/src/main/resources/credentials"); protected static final boolean enableLogstash = Boolean.parseBoolean(System.getProperty("iTests.enableLogstash", "false")); private static File propsFile = new File(CREDENTIALS_FOLDER + "/logstash/logstash.properties"); protected String logstashHost; private static final int TEN_SECONDS_IN_MILLIS = 10000; private static final int MAX_SCAN_RETRY = 3; private int numberOfManagementMachines = 1; private URL[] webUIUrls; private String machinePrefix; private String volumePrefix; private Map<String, String> additionalPropsToReplace = new HashMap<String, String>(); private Cloud cloud; private Map<String, Object> properties = new HashMap<String, Object>(); private String cloudName; private String cloudFolderName; private String cloudUniqueName = this.getClass().getSimpleName(); private CloudBootstrapper bootstrapper = new CloudBootstrapper(); private File customCloudGroovy; public AbstractCloudService(String cloudName) { this.cloudName = cloudName; } public CloudBootstrapper getBootstrapper() { return bootstrapper; } public void setBootstrapper(CloudBootstrapper bootstrapper) { bootstrapper.provider(this.cloudFolderName); this.bootstrapper = bootstrapper; } @Override public void beforeBootstrap() throws Exception { } @Override public void afterTeardown() throws Exception { } public Map<String, Object> getProperties() { return properties; } public Cloud getCloud() { return cloud; } public int getNumberOfManagementMachines() { return numberOfManagementMachines; } public void setNumberOfManagementMachines(int numberOfManagementMachines) { this.numberOfManagementMachines = numberOfManagementMachines; } public Map<String, String> getAdditionalPropsToReplace() { return additionalPropsToReplace; } public String getMachinePrefix() { return machinePrefix; } public void setMachinePrefix(String machinePrefix) { if (machinePrefix.length() > MAX_HOSTNAME_LENGTH) { Random random = new Random(); String rand = Integer.toString(random.nextInt(99999)); String substring = machinePrefix.substring(0, MAX_HOSTNAME_LENGTH - 6); substring = substring + rand; LogUtils.log("machinePrefix " + machinePrefix + " is too long. using " + substring + " as actual machine prefix"); this.machinePrefix = substring; } else { this.machinePrefix = machinePrefix; } } public String getVolumePrefix() { return volumePrefix; } public void setVolumePrefix(String volumePrefix) { if (volumePrefix.length() > MAX_VOLUME_NAME_LENGTH) { Random random = new Random(); String rand = Integer.toString(random.nextInt(99999)); String substring = volumePrefix.substring(0, MAX_VOLUME_NAME_LENGTH - 6); substring = substring + rand; LogUtils.log("volumePrefix " + volumePrefix + " is too long. using " + substring + " as actual volume prefix"); this.volumePrefix = substring; } else { this.volumePrefix = volumePrefix; } } public void setCloudName(String cloudName) { this.cloudName = cloudName; } public abstract void injectCloudAuthenticationDetails() throws IOException; public abstract String getUser(); public abstract String getApiKey(); @Override public void init(final String uniqueName) throws Exception { this.cloudUniqueName = uniqueName.toLowerCase(); this.cloudFolderName = cloudName + "_" + cloudUniqueName; bootstrapper.provider(this.cloudFolderName); bootstrapper.setCloudService(this); deleteServiceFolders(); createCloudFolder(); if(enableLogstash){ prepareLogstash(uniqueName); } } private void prepareLogstash(String tagClassName) throws Exception { initLogstashHost(); String pathToLogstash = SGTestHelper.getSGTestRootDir() + "/src/main/resources/logstash"; String preBootstrapScriptPath = getPathToCloudFolder() + "/upload/pre-bootstrap.sh"; if(cloudName.equalsIgnoreCase("byon")){ IOUtils.copyFile(pathToLogstash + "/byon/pre-bootstrap.sh", preBootstrapScriptPath); } if(cloudName.equalsIgnoreCase("rackspace") || cloudName.equalsIgnoreCase("hp")){ IOUtils.copyFile(pathToLogstash + "/rackspace_and_hp/pre-bootstrap.sh", preBootstrapScriptPath); } else{ IOUtils.copyFile(pathToLogstash + "/pre-bootstrap.sh", preBootstrapScriptPath); } String confFilePath = pathToLogstash + "/logstash-shipper.conf"; String backupFilePath = IOUtils.backupFile(confFilePath); //TODO fix path to build String remoteBuildPath; if(cloudName.equalsIgnoreCase("byon")){ remoteBuildPath = "/tmp/tgrid/gigaspaces"; } if(cloudName.contains("ec2")){ remoteBuildPath = "/home/ec2-user/gigaspaces"; } else{ remoteBuildPath = "/root/gigaspaces"; } IOUtils.replaceTextInFile(confFilePath, "<path_to_build>", remoteBuildPath); IOUtils.replaceTextInFile(confFilePath, "<test_name>", tagClassName); IOUtils.replaceTextInFile(confFilePath, "<build_number>", System.getProperty("iTests.buildNumber")); IOUtils.replaceTextInFile(confFilePath, "<version>", System.getProperty("cloudifyVersion")); IOUtils.replaceTextInFile(confFilePath, "<suite_name>", System.getProperty("iTests.suiteName")); IOUtils.replaceTextInFile(confFilePath, "<host>", logstashHost); String logstashConfInBuildPath = getPathToCloudFolder() + "/upload/cloudify-overrides/config/logstash"; FileUtils.forceMkdir(new File(logstashConfInBuildPath)); LogUtils.log("copying shipper conf file to " + logstashConfInBuildPath); IOUtils.copyFile(confFilePath, logstashConfInBuildPath + "/logstash-shipper.conf"); IOUtils.replaceFileWithMove(new File(confFilePath), new File(backupFilePath)); } @Override public boolean scanLeakedAgentNodes() { return true; } @Override public String[] getWebuiUrls() { if (webUIUrls == null) { return null; } String[] result = new String[webUIUrls.length]; for (int i = 0; i < webUIUrls.length; i++) { result[i] = webUIUrls[i].toString(); } return result; } @Override public String[] getRestUrls() { URL[] restAdminUrls = getBootstrapper().getRestAdminUrls(); if (restAdminUrls == null) { return null; } String[] result = new String[restAdminUrls.length]; for (int i = 0; i < restAdminUrls.length; i++) { result[i] = restAdminUrls[i].toString(); } return result; } @Override public boolean scanLeakedAgentAndManagementNodes() { return true; } @Override public boolean scanLeakedManagementNodes() { return true; } @Override public String getCloudName() { return cloudName; } public String getPathToCloudGroovy() { return getPathToCloudFolder() + "/" + getCloudName() + "-cloud.groovy"; } public void setCloudGroovy(File cloudFile) throws IOException { this.customCloudGroovy = cloudFile; } public String getPathToCloudFolder() { return ScriptUtils.getBuildPath() + RELATIVE_ESC_PATH + cloudFolderName; } @Override public void teardownCloud() throws Exception { String[] restUrls = getRestUrls(); - for(String url : restUrls){ - LogUtils.log("rest url: " + url); + if (restUrls != null) { + for(String url : restUrls){ + LogUtils.log("rest url: " + url); + } } Set<String> privateUrls = new HashSet<String>(); if (restUrls != null) { for(String resturl : restUrls){ final GSRestClient client = new GSRestClient("", "", new URL(resturl), PlatformVersion.getVersionNumber()); String privateIpUrl = "ProcessingUnits/Names/rest/Instances/0/JVMDetails/EnvironmentVariables"; String privateIp = (String)client.getAdminData(privateIpUrl).get("GIGASPACES_AGENT_ENV_PRIVATE_IP"); LogUtils.log("adding private ip " + privateIp); privateUrls.add(privateIp); } } try { if (restUrls != null) { if(!enableLogstash){ CloudTestUtils.dumpMachinesNewRestAPI( restUrls[0], SecurityConstants.USER_PWD_ALL_ROLES, SecurityConstants.USER_PWD_ALL_ROLES); } } } finally { if (restUrls != null) { if (!bootstrapper.isForce()) { // this is to connect to the cloud before tearing down. bootstrapper.setRestUrl(restUrls[0]); } bootstrapper.teardown(); afterTeardown(); } if (!bootstrapper.isTeardownExpectedToFail()) { scanForLeakedAgentAndManagementNodes(); } else { // machines were not supposed to be terminated. } } if(enableLogstash){ LogUtils.log("cloud name: " + cloudName); if(cloudName.equalsIgnoreCase("byon")){ for(String restUrl : this.getRestUrls()){ LogUtils.log("mng url: " + restUrl); int startIndex; int endIndex; if(System.getProperty("iTests.suiteName").contains("ipv6")){ LogUtils.log("using ipv6 address"); startIndex = restUrl.indexOf("[") + 1; endIndex = restUrl.lastIndexOf("]"); } else{ startIndex = restUrl.indexOf(":") + 3; endIndex = restUrl.lastIndexOf(":"); } if(startIndex > 0 && endIndex > -1){ String hostIp = restUrl.substring(startIndex, endIndex); LogUtils.log("destroying logstash agent on " + hostIp); SSHUtils.runCommand(hostIp, SSHUtils.DEFAULT_TIMEOUT, "pkill -9 -f logstash", "tgrid", "tgrid"); } else{ throw new IllegalStateException("could not resolve host address from " + restUrl); } } } else{ // killing any remaining logstash agent connections Properties props; try { props = IOUtils.readPropertiesFromFile(propsFile); } catch (final Exception e) { throw new IllegalStateException("Failed reading properties file : " + e.getMessage()); } String logstashHost = props.getProperty("logstash_server_host"); File pemFile = new File(CREDENTIALS_FOLDER + "/cloud/ec2/ec2-sgtest-us-east-logstash.pem"); String redisSrcDir = "/home/ec2-user/redis-2.6.14/src"; String user = "ec2-user"; long timeoutMilli = 20 * 1000; String output = SSHUtils.runCommand(logstashHost, timeoutMilli, "cd " + redisSrcDir + "; ./redis-cli client list", user, pemFile); int ipAndPortStartIndex; int ipAndPortEndIndex; int currentIndex = 0; String ipAndPort; while(true){ ipAndPortStartIndex = output.indexOf("addr=", currentIndex) + 5; if(ipAndPortStartIndex == 4){ break; } ipAndPortEndIndex = output.indexOf(" ", ipAndPortStartIndex); ipAndPort = output.substring(ipAndPortStartIndex, ipAndPortEndIndex); currentIndex = ipAndPortEndIndex; if(restUrls != null){ for(String restUrl : restUrls){ int ipStartIndex = restUrl.indexOf(":") + 3; String ip = restUrl.substring(ipStartIndex, restUrl.indexOf(":", ipStartIndex)); if(ipAndPort.contains(ip)){ LogUtils.log("shutting down redis client on " + ipAndPort); SSHUtils.runCommand(logstashHost, timeoutMilli, "cd " + redisSrcDir + "; ./redis-cli client kill " + ipAndPort, user, pemFile); } } for(String privateRestUrl : privateUrls){ if(ipAndPort.contains(privateRestUrl)){ LogUtils.log("In private ip search. shutting down redis client on " + ipAndPort); SSHUtils.runCommand(logstashHost, timeoutMilli, "cd " + redisSrcDir + "; ./redis-cli client kill " + ipAndPort, user, pemFile); } } } else{ LogUtils.log("restUrls is null"); } } } } } @Override public void teardownCloud(Admin admin) throws IOException, InterruptedException { try { CommandTestUtils.runCommandAndWait("teardown-cloud -force --verbose " + this.cloudName + "_" + this.cloudUniqueName); } finally { scanForLeakedAgentAndManagementNodes(); } } @Override public String bootstrapCloud() throws Exception { String output = ""; overrideLogsFile(); if (customCloudGroovy != null) { // use a custom grooyv file if defined File originalCloudGroovy = new File(getPathToCloudGroovy()); IOUtils.replaceFile(originalCloudGroovy, customCloudGroovy); } injectCloudAuthenticationDetails(); replaceProps(); writePropertiesToCloudFolder(getProperties()); // Load updated configuration file into POJO this.cloud = ServiceReader.readCloud(new File(getPathToCloudGroovy())); if (bootstrapper.isScanForLeakedNodes()) { scanForLeakedAgentAndManagementNodes(); } beforeBootstrap(); printCloudConfigFile(); printPropertiesFile(); bootstrapper.setNumberOfManagementMachines(numberOfManagementMachines); if (bootstrapper.isNoWebServices()) { output = bootstrapper.bootstrap().getOutput(); } else { output = bootstrapper.bootstrap().getOutput(); if (bootstrapper.isBootstrapExpectedToFail()) { return output; } this.webUIUrls = CloudTestUtils.extractPublicWebuiUrls(output, numberOfManagementMachines); LogUtils.log("webuiUrls = " + StringUtils.join(webUIUrls, ",")); assertBootstrapServicesAreAvailable(); URL machinesURL; for (int i = 0; i < numberOfManagementMachines; i++) { machinesURL = getMachinesUrl(getBootstrapper().getRestAdminUrls()[i].toString()); LogUtils.log("Expecting " + numberOfManagementMachines + " machines"); if (bootstrapper.isSecured()) { LogUtils.log("Found " + CloudTestUtils.getNumberOfMachines(machinesURL, bootstrapper.getUser(), bootstrapper.getPassword()) + " machines"); } else { LogUtils.log("Found " + CloudTestUtils.getNumberOfMachines(machinesURL) + " machines"); } } } return output; } private void printPropertiesFile() throws IOException { LogUtils.log(FileUtils.readFileToString(new File(getPathToCloudFolder(), getCloudName() + "-cloud.properties"))); } private void scanForLeakedAgentAndManagementNodes() { if (cloud == null) { return; } // We will give a short timeout to give the ESM // time to recognize that he needs to shutdown the machine. try { Thread.sleep(TEN_SECONDS_IN_MILLIS); } catch (InterruptedException e) { } Throwable first = null; for (int i = 0; i < MAX_SCAN_RETRY; i++) { try { boolean leakedAgentAndManagementNodesScanResult = scanLeakedAgentAndManagementNodes(); if (leakedAgentAndManagementNodesScanResult == true) { return; } else { Assert.fail("Leaked nodes were found!"); } break; } catch (final Exception t) { first = t; LogUtils.log("Failed scaning for leaked nodes. attempt number " + (i + 1), t); } } if (first != null) { Assert.fail("Failed scanning for leaked nodes after " + MAX_SCAN_RETRY + " attempts. First exception was --> " + first.getMessage(), first); } } private void writePropertiesToCloudFolder(Map<String, Object> properties) throws IOException { // add a properties file to the cloud driver IOUtils.writePropertiesToFile(properties, new File(getPathToCloudFolder() + "/" + getCloudName() + "-cloud.properties")); } private File createCloudFolder() throws IOException { File originalCloudFolder = new File(ScriptUtils.getBuildPath() + RELATIVE_ESC_PATH + getCloudName()); File serviceCloudFolder = new File(originalCloudFolder.getParent(), cloudFolderName); try { if (serviceCloudFolder.isDirectory()) { FileUtils.deleteDirectory(serviceCloudFolder); } // create a new folder for the test to work on (if it's not created already) with the content of the // original folder LogUtils.log("copying " + originalCloudFolder + " to " + serviceCloudFolder); FileUtils.copyDirectory(originalCloudFolder, serviceCloudFolder); } catch (IOException e) { LogUtils.log("caught an exception while creating service folder " + serviceCloudFolder.getAbsolutePath(), e); throw e; } return serviceCloudFolder; } private void deleteServiceFolders() throws IOException { File serviceCloudFolder = new File(getPathToCloudFolder()); try { if (serviceCloudFolder.exists()) { FileUtils.deleteDirectory(serviceCloudFolder); } } catch (IOException e) { LogUtils.log("caught an exception while deleting service folder " + serviceCloudFolder.getAbsolutePath(), e); throw e; } } private void replaceProps() throws IOException { if (additionalPropsToReplace != null) { IOUtils.replaceTextInFile(getPathToCloudGroovy(), additionalPropsToReplace); } } private void printCloudConfigFile() throws IOException { String pathToCloudGroovy = getPathToCloudGroovy(); File cloudConfigFile = new File(pathToCloudGroovy); if (!cloudConfigFile.exists()) { LogUtils.log("Failed to print the cloud configuration file content"); return; } String cloudConfigFileAsString = FileUtils.readFileToString(cloudConfigFile); LogUtils.log("Cloud configuration file: " + cloudConfigFile.getAbsolutePath()); LogUtils.log(cloudConfigFileAsString); } private URL getMachinesUrl(String url) throws Exception { return new URL(stripSlash(url) + "/admin/machines"); } private void assertBootstrapServicesAreAvailable() throws MalformedURLException { LogUtils.log("Waiting for bootstrap web services to be available"); URL[] restAdminUrls = getBootstrapper().getRestAdminUrls(); for (int i = 0; i < restAdminUrls.length; i++) { // The rest home page is a JSP page, which will fail to compile if there is no JDK installed. So use // testrest instead assertWebServiceAvailable(new URL(restAdminUrls[i].toString() + "/service/testrest")); assertWebServiceAvailable(webUIUrls[i]); } } private static void assertWebServiceAvailable(final URL url) { AssertUtils.repetitiveAssertTrue(url + " is not up", new RepetitiveConditionProvider() { public boolean getCondition() { try { return WebUtils.isURLAvailable(url); } catch (final Exception e) { LogUtils.log(url + " is not available yet"); return false; } } }, CloudTestUtils.OPERATION_TIMEOUT); } private void overrideLogsFile() throws IOException { File logging = new File(SGTestHelper.getSGTestRootDir() + "/src/main/config/gs_logging.properties"); File uploadOverrides = new File(getPathToCloudFolder() + "/upload/cloudify-overrides/"); uploadOverrides.mkdir(); File uploadLoggsDir = new File(uploadOverrides.getAbsoluteFile() + "/config/"); uploadLoggsDir.mkdir(); FileUtils.copyFileToDirectory(logging, uploadLoggsDir); File originalGsLogging = new File(SGTestHelper.getBuildDir() + "/config/gs_logging.properties"); if (originalGsLogging.exists()) { originalGsLogging.delete(); } FileUtils.copyFile(logging, originalGsLogging); } private static String stripSlash(String str) { if (str == null || !str.endsWith("/")) { return str; } return str.substring(0, str.length() - 1); } protected Properties getCloudProperties(String propertiesFileName) { Properties properties = new Properties(); try { properties.load(new FileInputStream(propertiesFileName)); } catch (IOException e) { throw new RuntimeException("failed to read " + propertiesFileName + " file - " + e, e); } return properties; } private void initLogstashHost(){ if(logstashHost != null){ return; } Properties props; try { props = IOUtils.readPropertiesFromFile(propsFile); } catch (final Exception e) { throw new IllegalStateException("Failed reading properties file : " + e.getMessage()); } logstashHost = props.getProperty("logstash_server_host"); } }
true
true
public void teardownCloud() throws Exception { String[] restUrls = getRestUrls(); for(String url : restUrls){ LogUtils.log("rest url: " + url); } Set<String> privateUrls = new HashSet<String>(); if (restUrls != null) { for(String resturl : restUrls){ final GSRestClient client = new GSRestClient("", "", new URL(resturl), PlatformVersion.getVersionNumber()); String privateIpUrl = "ProcessingUnits/Names/rest/Instances/0/JVMDetails/EnvironmentVariables"; String privateIp = (String)client.getAdminData(privateIpUrl).get("GIGASPACES_AGENT_ENV_PRIVATE_IP"); LogUtils.log("adding private ip " + privateIp); privateUrls.add(privateIp); } } try { if (restUrls != null) { if(!enableLogstash){ CloudTestUtils.dumpMachinesNewRestAPI( restUrls[0], SecurityConstants.USER_PWD_ALL_ROLES, SecurityConstants.USER_PWD_ALL_ROLES); } } } finally { if (restUrls != null) { if (!bootstrapper.isForce()) { // this is to connect to the cloud before tearing down. bootstrapper.setRestUrl(restUrls[0]); } bootstrapper.teardown(); afterTeardown(); } if (!bootstrapper.isTeardownExpectedToFail()) { scanForLeakedAgentAndManagementNodes(); } else { // machines were not supposed to be terminated. } } if(enableLogstash){ LogUtils.log("cloud name: " + cloudName); if(cloudName.equalsIgnoreCase("byon")){ for(String restUrl : this.getRestUrls()){ LogUtils.log("mng url: " + restUrl); int startIndex; int endIndex; if(System.getProperty("iTests.suiteName").contains("ipv6")){ LogUtils.log("using ipv6 address"); startIndex = restUrl.indexOf("[") + 1; endIndex = restUrl.lastIndexOf("]"); } else{ startIndex = restUrl.indexOf(":") + 3; endIndex = restUrl.lastIndexOf(":"); } if(startIndex > 0 && endIndex > -1){ String hostIp = restUrl.substring(startIndex, endIndex); LogUtils.log("destroying logstash agent on " + hostIp); SSHUtils.runCommand(hostIp, SSHUtils.DEFAULT_TIMEOUT, "pkill -9 -f logstash", "tgrid", "tgrid"); } else{ throw new IllegalStateException("could not resolve host address from " + restUrl); } } } else{ // killing any remaining logstash agent connections Properties props; try { props = IOUtils.readPropertiesFromFile(propsFile); } catch (final Exception e) { throw new IllegalStateException("Failed reading properties file : " + e.getMessage()); } String logstashHost = props.getProperty("logstash_server_host"); File pemFile = new File(CREDENTIALS_FOLDER + "/cloud/ec2/ec2-sgtest-us-east-logstash.pem"); String redisSrcDir = "/home/ec2-user/redis-2.6.14/src"; String user = "ec2-user"; long timeoutMilli = 20 * 1000; String output = SSHUtils.runCommand(logstashHost, timeoutMilli, "cd " + redisSrcDir + "; ./redis-cli client list", user, pemFile); int ipAndPortStartIndex; int ipAndPortEndIndex; int currentIndex = 0; String ipAndPort; while(true){ ipAndPortStartIndex = output.indexOf("addr=", currentIndex) + 5; if(ipAndPortStartIndex == 4){ break; } ipAndPortEndIndex = output.indexOf(" ", ipAndPortStartIndex); ipAndPort = output.substring(ipAndPortStartIndex, ipAndPortEndIndex); currentIndex = ipAndPortEndIndex; if(restUrls != null){ for(String restUrl : restUrls){ int ipStartIndex = restUrl.indexOf(":") + 3; String ip = restUrl.substring(ipStartIndex, restUrl.indexOf(":", ipStartIndex)); if(ipAndPort.contains(ip)){ LogUtils.log("shutting down redis client on " + ipAndPort); SSHUtils.runCommand(logstashHost, timeoutMilli, "cd " + redisSrcDir + "; ./redis-cli client kill " + ipAndPort, user, pemFile); } } for(String privateRestUrl : privateUrls){ if(ipAndPort.contains(privateRestUrl)){ LogUtils.log("In private ip search. shutting down redis client on " + ipAndPort); SSHUtils.runCommand(logstashHost, timeoutMilli, "cd " + redisSrcDir + "; ./redis-cli client kill " + ipAndPort, user, pemFile); } } } else{ LogUtils.log("restUrls is null"); } } } } }
public void teardownCloud() throws Exception { String[] restUrls = getRestUrls(); if (restUrls != null) { for(String url : restUrls){ LogUtils.log("rest url: " + url); } } Set<String> privateUrls = new HashSet<String>(); if (restUrls != null) { for(String resturl : restUrls){ final GSRestClient client = new GSRestClient("", "", new URL(resturl), PlatformVersion.getVersionNumber()); String privateIpUrl = "ProcessingUnits/Names/rest/Instances/0/JVMDetails/EnvironmentVariables"; String privateIp = (String)client.getAdminData(privateIpUrl).get("GIGASPACES_AGENT_ENV_PRIVATE_IP"); LogUtils.log("adding private ip " + privateIp); privateUrls.add(privateIp); } } try { if (restUrls != null) { if(!enableLogstash){ CloudTestUtils.dumpMachinesNewRestAPI( restUrls[0], SecurityConstants.USER_PWD_ALL_ROLES, SecurityConstants.USER_PWD_ALL_ROLES); } } } finally { if (restUrls != null) { if (!bootstrapper.isForce()) { // this is to connect to the cloud before tearing down. bootstrapper.setRestUrl(restUrls[0]); } bootstrapper.teardown(); afterTeardown(); } if (!bootstrapper.isTeardownExpectedToFail()) { scanForLeakedAgentAndManagementNodes(); } else { // machines were not supposed to be terminated. } } if(enableLogstash){ LogUtils.log("cloud name: " + cloudName); if(cloudName.equalsIgnoreCase("byon")){ for(String restUrl : this.getRestUrls()){ LogUtils.log("mng url: " + restUrl); int startIndex; int endIndex; if(System.getProperty("iTests.suiteName").contains("ipv6")){ LogUtils.log("using ipv6 address"); startIndex = restUrl.indexOf("[") + 1; endIndex = restUrl.lastIndexOf("]"); } else{ startIndex = restUrl.indexOf(":") + 3; endIndex = restUrl.lastIndexOf(":"); } if(startIndex > 0 && endIndex > -1){ String hostIp = restUrl.substring(startIndex, endIndex); LogUtils.log("destroying logstash agent on " + hostIp); SSHUtils.runCommand(hostIp, SSHUtils.DEFAULT_TIMEOUT, "pkill -9 -f logstash", "tgrid", "tgrid"); } else{ throw new IllegalStateException("could not resolve host address from " + restUrl); } } } else{ // killing any remaining logstash agent connections Properties props; try { props = IOUtils.readPropertiesFromFile(propsFile); } catch (final Exception e) { throw new IllegalStateException("Failed reading properties file : " + e.getMessage()); } String logstashHost = props.getProperty("logstash_server_host"); File pemFile = new File(CREDENTIALS_FOLDER + "/cloud/ec2/ec2-sgtest-us-east-logstash.pem"); String redisSrcDir = "/home/ec2-user/redis-2.6.14/src"; String user = "ec2-user"; long timeoutMilli = 20 * 1000; String output = SSHUtils.runCommand(logstashHost, timeoutMilli, "cd " + redisSrcDir + "; ./redis-cli client list", user, pemFile); int ipAndPortStartIndex; int ipAndPortEndIndex; int currentIndex = 0; String ipAndPort; while(true){ ipAndPortStartIndex = output.indexOf("addr=", currentIndex) + 5; if(ipAndPortStartIndex == 4){ break; } ipAndPortEndIndex = output.indexOf(" ", ipAndPortStartIndex); ipAndPort = output.substring(ipAndPortStartIndex, ipAndPortEndIndex); currentIndex = ipAndPortEndIndex; if(restUrls != null){ for(String restUrl : restUrls){ int ipStartIndex = restUrl.indexOf(":") + 3; String ip = restUrl.substring(ipStartIndex, restUrl.indexOf(":", ipStartIndex)); if(ipAndPort.contains(ip)){ LogUtils.log("shutting down redis client on " + ipAndPort); SSHUtils.runCommand(logstashHost, timeoutMilli, "cd " + redisSrcDir + "; ./redis-cli client kill " + ipAndPort, user, pemFile); } } for(String privateRestUrl : privateUrls){ if(ipAndPort.contains(privateRestUrl)){ LogUtils.log("In private ip search. shutting down redis client on " + ipAndPort); SSHUtils.runCommand(logstashHost, timeoutMilli, "cd " + redisSrcDir + "; ./redis-cli client kill " + ipAndPort, user, pemFile); } } } else{ LogUtils.log("restUrls is null"); } } } } }
diff --git a/src/frontend/edu/brown/catalog/CatalogKey.java b/src/frontend/edu/brown/catalog/CatalogKey.java index 56670a95e..9ea73e7a8 100644 --- a/src/frontend/edu/brown/catalog/CatalogKey.java +++ b/src/frontend/edu/brown/catalog/CatalogKey.java @@ -1,234 +1,238 @@ package edu.brown.catalog; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.voltdb.catalog.*; import edu.brown.catalog.special.MultiAttributeCatalogType; import edu.brown.catalog.special.MultiColumn; import edu.brown.catalog.special.MultiProcParameter; import edu.brown.catalog.special.ReplicatedColumn; import edu.brown.utils.ClassUtil; public abstract class CatalogKey { public static final Logger LOG = Logger.getLogger(CatalogKey.class); private static final String PARENT_DELIMITER = "."; private static final String MULTIATTRIBUTE_DELIMITER = "#"; private static final Map<CatalogType, String> CACHE_CREATEKEY = new HashMap<CatalogType, String>(); private static final Map<Database, Map<String, CatalogType>> CACHE_GETFROMKEY = new HashMap<Database, Map<String,CatalogType>>(); /** * Returns a String key representation of the column as "Parent.Child" * @param catalog_col * @return */ @SuppressWarnings("unchecked") public static <T extends CatalogType> String createKey(T catalog_item) { // There is a 7x speed-up when we use the cache versus always constructing a new key String ret = CACHE_CREATEKEY.get(catalog_item); if (ret != null) return (ret); if (catalog_item == null) return (null); assert(catalog_item.getParent() != null) : catalog_item + " has null parent"; CatalogType parent = catalog_item.getParent(); ret = parent.getName() + PARENT_DELIMITER; // Special Case: MultiAttributeCatalogType if (catalog_item instanceof MultiAttributeCatalogType) { MultiAttributeCatalogType multicatalog = (MultiAttributeCatalogType)catalog_item; ret += multicatalog.getPrefix(); for (Object sub_item : multicatalog) { ret += MULTIATTRIBUTE_DELIMITER + ((CatalogType)sub_item).getName(); } // FOR } else { ret += catalog_item.getName(); // Special Case: StmtParameter // Since there may be Statement's with the same name but in different Procedures, // we also want to include the Procedure name if (catalog_item instanceof StmtParameter) { assert(parent.getParent() != null); ret = parent.getParent().getName() + PARENT_DELIMITER + ret; } } CACHE_CREATEKEY.put(catalog_item, ret); return (ret); } /** * Returns a String key representation of the column as "Parent.Child" * @param parent * @param child * @return */ public static String createKey(String parent, String child) { return (new StringBuilder().append(parent) .append(PARENT_DELIMITER) .append(child) .toString()); } public static Collection<String> createKeys(Iterable<? extends CatalogType> map) { Collection<String> keys = new ArrayList<String>(); for (CatalogType catalog_item : map) { keys.add(createKey(catalog_item)); } // FOR return (keys); } /** * Return the name of the catalog object from the key * @param catalog_key * @return */ public static String getNameFromKey(String catalog_key) { assert(catalog_key != null); return (catalog_key.substring(catalog_key.lastIndexOf(PARENT_DELIMITER) + 1)); } /** * Given a String key generated by createKey(), return the corresponding catalog * object for the given Database catalog. If the parent object does not exist, this function will * return null. If the parent exists but the child does not exist, then it trips an assert * @param catalog_db * @param key * @return */ @SuppressWarnings("unchecked") public static <T extends CatalogType> T getFromKey(Database catalog_db, String key, Class<T> catalog_class) { final boolean debug = LOG.isDebugEnabled(); if (debug) LOG.debug("Grabbing " + catalog_class + " object for '" + key + "'"); assert(catalog_db != null); assert(catalog_class != null); // Caching... Map<String, CatalogType> cache = CatalogKey.CACHE_GETFROMKEY.get(catalog_db); if (cache != null) { if (cache.containsKey(key)) return (T)cache.get(key); } else { cache = new HashMap<String, CatalogType>(); CatalogKey.CACHE_GETFROMKEY.put(catalog_db, cache); } T catalog_child = null; CatalogType catalog_parent = null; int idx = key.indexOf(PARENT_DELIMITER); assert (idx != -1) : "Invalid CatalogKey format '" + key + "'"; String parent_key = key.substring(0, idx); String child_key = key.substring(idx + 1); List<Class<?>> superclasses = ClassUtil.getSuperClasses(catalog_class); // Get the parent based on the type of the object they want back if (catalog_class.equals(Index.class) || catalog_class.equals(Constraint.class) || superclasses.contains(Column.class)) { catalog_parent = catalog_db.getTables().get(parent_key); } else if (catalog_class.equals(Statement.class) || superclasses.contains(ProcParameter.class)) { catalog_parent = catalog_db.getProcedures().get(parent_key); } else if (catalog_class.equals(Table.class) || catalog_class.equals(Procedure.class)) { catalog_parent = catalog_db; } else if (catalog_class.equals(Host.class)) { catalog_parent = (Cluster)catalog_db.getParent(); // Special Case: StmtParameter } else if (catalog_class.equals(StmtParameter.class)) { Procedure catalog_proc = catalog_db.getProcedures().get(parent_key); assert(catalog_proc != null); idx = child_key.indexOf('.'); parent_key = child_key.substring(0, idx); child_key = child_key.substring(idx + 1); catalog_parent = catalog_proc.getStatements().get(parent_key); } // Don't throw this error because it may be a dynamic catalog type that we use for the Markov stuff //} else { // assert(false) : "Unexpected Catalog key type '" + catalog_class + "'"; //} // It's ok for the parent to be missing, but it's *not* ok if the child is missing if (catalog_parent != null) { + if (debug) LOG.debug("Catalog Parent: " + CatalogUtil.getDisplayName(catalog_parent)); // COLUMN if (superclasses.contains(Column.class)) { // Special Case: Replicated Column if (child_key.equals(ReplicatedColumn.COLUMN_NAME)) { catalog_child = (T)ReplicatedColumn.get((Table)catalog_parent); // Special Case: MultiColumn } else if (child_key.startsWith(MultiColumn.PREFIX)) { int prefix_offset = MultiColumn.PREFIX.length() + MULTIATTRIBUTE_DELIMITER.length(); String names[] = child_key.substring(prefix_offset).split(MULTIATTRIBUTE_DELIMITER); assert(names.length > 1) : "Invalid MultiColumn Key: " + child_key; Column params[] = new Column[names.length]; for (int i = 0; i < names.length; i++) { params[i] = getFromKey(catalog_db, createKey(parent_key, names[i]), Column.class); } // FOR catalog_child = (T)MultiColumn.get(params); // Regular Columns } else { catalog_child = (T)((Table)catalog_parent).getColumns().get(child_key); } // INDEX } else if (superclasses.contains(Index.class)) { catalog_child = (T)((Table)catalog_parent).getIndexes().get(child_key); // CONSTRAINT } else if (superclasses.contains(Constraint.class)) { catalog_child = (T)((Table)catalog_parent).getConstraints().get(child_key); // PROCPARAMETER } else if (superclasses.contains(ProcParameter.class)) { // Special Case: MultiProcParameter if (child_key.startsWith(MultiProcParameter.PREFIX)) { int prefix_offset = MultiProcParameter.PREFIX.length() + MULTIATTRIBUTE_DELIMITER.length(); String names[] = child_key.substring(prefix_offset).split(MULTIATTRIBUTE_DELIMITER); assert(names.length > 1) : "Invalid MultiProcParameter Key: " + child_key.substring(prefix_offset); ProcParameter params[] = new ProcParameter[names.length]; for (int i = 0; i < names.length; i++) { params[i] = getFromKey(catalog_db, createKey(parent_key, names[i]), ProcParameter.class); } // FOR catalog_child = (T)MultiProcParameter.get(params); // Regular ProcParameter } else { catalog_child = (T)((Procedure)catalog_parent).getParameters().get(child_key); } // STATEMENT } else if (superclasses.contains(Statement.class)) { catalog_child = (T)((Procedure)catalog_parent).getStatements().get(child_key); // STMTPARAMETER } else if (superclasses.contains(StmtParameter.class)) { catalog_child = (T)((Statement)catalog_parent).getParameters().get(child_key); // TABLE } else if (superclasses.contains(Table.class)) { catalog_child = (T)((Database)catalog_parent).getTables().get(child_key); + if (catalog_child == null) { + LOG.debug("TABLES: " + CatalogUtil.debug(((Database)catalog_parent).getTables())); + } // PROCEDURE } else if (superclasses.contains(Procedure.class)) { catalog_child = (T)((Database)catalog_parent).getProcedures().get(child_key); // HOST } else if (superclasses.contains(Host.class)) { catalog_child = (T)((Cluster)catalog_parent).getHosts().get(child_key); // UNKNOWN! } else { LOG.fatal("Invalid child class '" + catalog_class + "' for catalog key " + key); assert (false); } // if (catalog_child == null) LOG.warn("The child catalog item is null for '" + key + "'"); - assert (catalog_child != null) : "The child catalog item is null for '" + key + "'"; + assert (catalog_child != null) : "The child catalog item is null for '" + key + "'\n" + superclasses; cache.put(key, catalog_child); return (catalog_child); } return (null); } public static <T extends CatalogType> Collection<T> getFromKeys(Database catalog_db, Collection<String> keys, Class<T> catalog_class) { List<T> items = new ArrayList<T>(); for (String key : keys) { items.add(CatalogKey.getFromKey(catalog_db, key, catalog_class)); } // FOR return (items); } }
false
true
public static <T extends CatalogType> T getFromKey(Database catalog_db, String key, Class<T> catalog_class) { final boolean debug = LOG.isDebugEnabled(); if (debug) LOG.debug("Grabbing " + catalog_class + " object for '" + key + "'"); assert(catalog_db != null); assert(catalog_class != null); // Caching... Map<String, CatalogType> cache = CatalogKey.CACHE_GETFROMKEY.get(catalog_db); if (cache != null) { if (cache.containsKey(key)) return (T)cache.get(key); } else { cache = new HashMap<String, CatalogType>(); CatalogKey.CACHE_GETFROMKEY.put(catalog_db, cache); } T catalog_child = null; CatalogType catalog_parent = null; int idx = key.indexOf(PARENT_DELIMITER); assert (idx != -1) : "Invalid CatalogKey format '" + key + "'"; String parent_key = key.substring(0, idx); String child_key = key.substring(idx + 1); List<Class<?>> superclasses = ClassUtil.getSuperClasses(catalog_class); // Get the parent based on the type of the object they want back if (catalog_class.equals(Index.class) || catalog_class.equals(Constraint.class) || superclasses.contains(Column.class)) { catalog_parent = catalog_db.getTables().get(parent_key); } else if (catalog_class.equals(Statement.class) || superclasses.contains(ProcParameter.class)) { catalog_parent = catalog_db.getProcedures().get(parent_key); } else if (catalog_class.equals(Table.class) || catalog_class.equals(Procedure.class)) { catalog_parent = catalog_db; } else if (catalog_class.equals(Host.class)) { catalog_parent = (Cluster)catalog_db.getParent(); // Special Case: StmtParameter } else if (catalog_class.equals(StmtParameter.class)) { Procedure catalog_proc = catalog_db.getProcedures().get(parent_key); assert(catalog_proc != null); idx = child_key.indexOf('.'); parent_key = child_key.substring(0, idx); child_key = child_key.substring(idx + 1); catalog_parent = catalog_proc.getStatements().get(parent_key); } // Don't throw this error because it may be a dynamic catalog type that we use for the Markov stuff //} else { // assert(false) : "Unexpected Catalog key type '" + catalog_class + "'"; //} // It's ok for the parent to be missing, but it's *not* ok if the child is missing if (catalog_parent != null) { // COLUMN if (superclasses.contains(Column.class)) { // Special Case: Replicated Column if (child_key.equals(ReplicatedColumn.COLUMN_NAME)) { catalog_child = (T)ReplicatedColumn.get((Table)catalog_parent); // Special Case: MultiColumn } else if (child_key.startsWith(MultiColumn.PREFIX)) { int prefix_offset = MultiColumn.PREFIX.length() + MULTIATTRIBUTE_DELIMITER.length(); String names[] = child_key.substring(prefix_offset).split(MULTIATTRIBUTE_DELIMITER); assert(names.length > 1) : "Invalid MultiColumn Key: " + child_key; Column params[] = new Column[names.length]; for (int i = 0; i < names.length; i++) { params[i] = getFromKey(catalog_db, createKey(parent_key, names[i]), Column.class); } // FOR catalog_child = (T)MultiColumn.get(params); // Regular Columns } else { catalog_child = (T)((Table)catalog_parent).getColumns().get(child_key); } // INDEX } else if (superclasses.contains(Index.class)) { catalog_child = (T)((Table)catalog_parent).getIndexes().get(child_key); // CONSTRAINT } else if (superclasses.contains(Constraint.class)) { catalog_child = (T)((Table)catalog_parent).getConstraints().get(child_key); // PROCPARAMETER } else if (superclasses.contains(ProcParameter.class)) { // Special Case: MultiProcParameter if (child_key.startsWith(MultiProcParameter.PREFIX)) { int prefix_offset = MultiProcParameter.PREFIX.length() + MULTIATTRIBUTE_DELIMITER.length(); String names[] = child_key.substring(prefix_offset).split(MULTIATTRIBUTE_DELIMITER); assert(names.length > 1) : "Invalid MultiProcParameter Key: " + child_key.substring(prefix_offset); ProcParameter params[] = new ProcParameter[names.length]; for (int i = 0; i < names.length; i++) { params[i] = getFromKey(catalog_db, createKey(parent_key, names[i]), ProcParameter.class); } // FOR catalog_child = (T)MultiProcParameter.get(params); // Regular ProcParameter } else { catalog_child = (T)((Procedure)catalog_parent).getParameters().get(child_key); } // STATEMENT } else if (superclasses.contains(Statement.class)) { catalog_child = (T)((Procedure)catalog_parent).getStatements().get(child_key); // STMTPARAMETER } else if (superclasses.contains(StmtParameter.class)) { catalog_child = (T)((Statement)catalog_parent).getParameters().get(child_key); // TABLE } else if (superclasses.contains(Table.class)) { catalog_child = (T)((Database)catalog_parent).getTables().get(child_key); // PROCEDURE } else if (superclasses.contains(Procedure.class)) { catalog_child = (T)((Database)catalog_parent).getProcedures().get(child_key); // HOST } else if (superclasses.contains(Host.class)) { catalog_child = (T)((Cluster)catalog_parent).getHosts().get(child_key); // UNKNOWN! } else { LOG.fatal("Invalid child class '" + catalog_class + "' for catalog key " + key); assert (false); } // if (catalog_child == null) LOG.warn("The child catalog item is null for '" + key + "'"); assert (catalog_child != null) : "The child catalog item is null for '" + key + "'"; cache.put(key, catalog_child); return (catalog_child); } return (null); }
public static <T extends CatalogType> T getFromKey(Database catalog_db, String key, Class<T> catalog_class) { final boolean debug = LOG.isDebugEnabled(); if (debug) LOG.debug("Grabbing " + catalog_class + " object for '" + key + "'"); assert(catalog_db != null); assert(catalog_class != null); // Caching... Map<String, CatalogType> cache = CatalogKey.CACHE_GETFROMKEY.get(catalog_db); if (cache != null) { if (cache.containsKey(key)) return (T)cache.get(key); } else { cache = new HashMap<String, CatalogType>(); CatalogKey.CACHE_GETFROMKEY.put(catalog_db, cache); } T catalog_child = null; CatalogType catalog_parent = null; int idx = key.indexOf(PARENT_DELIMITER); assert (idx != -1) : "Invalid CatalogKey format '" + key + "'"; String parent_key = key.substring(0, idx); String child_key = key.substring(idx + 1); List<Class<?>> superclasses = ClassUtil.getSuperClasses(catalog_class); // Get the parent based on the type of the object they want back if (catalog_class.equals(Index.class) || catalog_class.equals(Constraint.class) || superclasses.contains(Column.class)) { catalog_parent = catalog_db.getTables().get(parent_key); } else if (catalog_class.equals(Statement.class) || superclasses.contains(ProcParameter.class)) { catalog_parent = catalog_db.getProcedures().get(parent_key); } else if (catalog_class.equals(Table.class) || catalog_class.equals(Procedure.class)) { catalog_parent = catalog_db; } else if (catalog_class.equals(Host.class)) { catalog_parent = (Cluster)catalog_db.getParent(); // Special Case: StmtParameter } else if (catalog_class.equals(StmtParameter.class)) { Procedure catalog_proc = catalog_db.getProcedures().get(parent_key); assert(catalog_proc != null); idx = child_key.indexOf('.'); parent_key = child_key.substring(0, idx); child_key = child_key.substring(idx + 1); catalog_parent = catalog_proc.getStatements().get(parent_key); } // Don't throw this error because it may be a dynamic catalog type that we use for the Markov stuff //} else { // assert(false) : "Unexpected Catalog key type '" + catalog_class + "'"; //} // It's ok for the parent to be missing, but it's *not* ok if the child is missing if (catalog_parent != null) { if (debug) LOG.debug("Catalog Parent: " + CatalogUtil.getDisplayName(catalog_parent)); // COLUMN if (superclasses.contains(Column.class)) { // Special Case: Replicated Column if (child_key.equals(ReplicatedColumn.COLUMN_NAME)) { catalog_child = (T)ReplicatedColumn.get((Table)catalog_parent); // Special Case: MultiColumn } else if (child_key.startsWith(MultiColumn.PREFIX)) { int prefix_offset = MultiColumn.PREFIX.length() + MULTIATTRIBUTE_DELIMITER.length(); String names[] = child_key.substring(prefix_offset).split(MULTIATTRIBUTE_DELIMITER); assert(names.length > 1) : "Invalid MultiColumn Key: " + child_key; Column params[] = new Column[names.length]; for (int i = 0; i < names.length; i++) { params[i] = getFromKey(catalog_db, createKey(parent_key, names[i]), Column.class); } // FOR catalog_child = (T)MultiColumn.get(params); // Regular Columns } else { catalog_child = (T)((Table)catalog_parent).getColumns().get(child_key); } // INDEX } else if (superclasses.contains(Index.class)) { catalog_child = (T)((Table)catalog_parent).getIndexes().get(child_key); // CONSTRAINT } else if (superclasses.contains(Constraint.class)) { catalog_child = (T)((Table)catalog_parent).getConstraints().get(child_key); // PROCPARAMETER } else if (superclasses.contains(ProcParameter.class)) { // Special Case: MultiProcParameter if (child_key.startsWith(MultiProcParameter.PREFIX)) { int prefix_offset = MultiProcParameter.PREFIX.length() + MULTIATTRIBUTE_DELIMITER.length(); String names[] = child_key.substring(prefix_offset).split(MULTIATTRIBUTE_DELIMITER); assert(names.length > 1) : "Invalid MultiProcParameter Key: " + child_key.substring(prefix_offset); ProcParameter params[] = new ProcParameter[names.length]; for (int i = 0; i < names.length; i++) { params[i] = getFromKey(catalog_db, createKey(parent_key, names[i]), ProcParameter.class); } // FOR catalog_child = (T)MultiProcParameter.get(params); // Regular ProcParameter } else { catalog_child = (T)((Procedure)catalog_parent).getParameters().get(child_key); } // STATEMENT } else if (superclasses.contains(Statement.class)) { catalog_child = (T)((Procedure)catalog_parent).getStatements().get(child_key); // STMTPARAMETER } else if (superclasses.contains(StmtParameter.class)) { catalog_child = (T)((Statement)catalog_parent).getParameters().get(child_key); // TABLE } else if (superclasses.contains(Table.class)) { catalog_child = (T)((Database)catalog_parent).getTables().get(child_key); if (catalog_child == null) { LOG.debug("TABLES: " + CatalogUtil.debug(((Database)catalog_parent).getTables())); } // PROCEDURE } else if (superclasses.contains(Procedure.class)) { catalog_child = (T)((Database)catalog_parent).getProcedures().get(child_key); // HOST } else if (superclasses.contains(Host.class)) { catalog_child = (T)((Cluster)catalog_parent).getHosts().get(child_key); // UNKNOWN! } else { LOG.fatal("Invalid child class '" + catalog_class + "' for catalog key " + key); assert (false); } // if (catalog_child == null) LOG.warn("The child catalog item is null for '" + key + "'"); assert (catalog_child != null) : "The child catalog item is null for '" + key + "'\n" + superclasses; cache.put(key, catalog_child); return (catalog_child); } return (null); }
diff --git a/OnTime/src/java/managers/TimetableManager.java b/OnTime/src/java/managers/TimetableManager.java index 5e0e72c..6bc8da6 100644 --- a/OnTime/src/java/managers/TimetableManager.java +++ b/OnTime/src/java/managers/TimetableManager.java @@ -1,154 +1,154 @@ package managers; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import javafiles.Event; public class TimetableManager { public TimetableManager() { } /** * Outputs a timetable for a week for a given user * Times will be stored in the db as integers eg period 1,2,3 etc * @param user * @throws FileNotFoundException * @throws IOException */ public String outputTimetable(String user, Calendar cal) throws FileNotFoundException, IOException { DBManager db = new DBManager(); ArrayList<Event> events = db.getEventsForUser(user); String output = ""; output += ("<div id=\"calendar\">"); output += (" <div id=\"calcontainer\">"); output += (" <div id=\"calheader\">"); output += (" <h2>" + cal.MONTH + " " + cal.YEAR + "</h2>"); output += (" </div> "); output += (" <div id=\"daysweek\">"); output += (" <div class=\"dayweek\"><p>Monday</p></div>"); output += (" <div class=\"dayweek\"><p>Tuesday</p></div>"); output += (" <div class=\"dayweek\"><p>Wednesday</p></div>"); output += (" <div class=\"dayweek\"><p>Thursday</p></div>"); output += (" <div class=\"dayweek\"><p>Friday</p></div>"); output += (" <div class=\"dayweek\"><p>Saturday</p></div>"); output += (" <div class=\"dayweek brn\"><p>Sunday</p></div>"); output += (" </div>"); output += (" <div id=\"daysmonth\">"); int currentDay = 1;//first monday for(int i=0; i<5; i++) {//for 5 weeks output += "<div class= \"week\">"; for(int j = 0; j < 7; j++) { //7 days - ArrayList<Event> todaysEvents = null; + ArrayList<Event> todaysEvents = new ArrayList<Event>(); for(Event e : events) { if(e.getStartDateDay() == currentDay && e.getStartDateMonth() == cal.MONTH && e.getStartDateYear() == cal.YEAR) { todaysEvents.add(e); } } if(currentDay % 7 == 0) { output += outputDayBrn(currentDay, todaysEvents); } else { output += outputDay(currentDay, todaysEvents); } currentDay++; } output += (" </div>"); } output += (" </div>"); output += (" </div>"); output += (" <div id=\"calcat\">"); output += (" <div class=\"caldot blue\"></div><p>Lecture</p>"); output += (" <div class=\"caldot yellow\"></div><p>Tutorial</p>"); output += (" <div class=\"caldot green\"></div><p>Student Meeting</p>"); output += (" <div class=\"caldot red\"></div><p>Lecturer Meeting</p>"); output += (" </div>"); output += ("</div>"); output += ("</div>"); return output; } private String outputDay(int dayNumber, ArrayList<Event> eventsForToday ) { String output = ""; output += ("<div class=\"day\">"); output += (" <div class=\"daybar\"><p>" + dayNumber + "</p></div>"); output += (" <div class=\"dots\">"); output += (" <ul>"); //****************************************************************** //output += (" <li class=\"yellow\"></li>"); TODO: need to add entry to //output += (" <li class=\"green\"></li>"); db for types of events //***************************************************************88 output += (" </ul>"); output += (" </div> "); output += (" <!-- slide open -->"); output += (" <div class=\"open\">"); output += (" <ul>"); int currEventStart = 0; for(Event e: eventsForToday) { int duration = e.getEndTime() - e.getStartTime(); int startTime = e.getStartTime() - currEventStart - duration; output += (" <li class=\"yellow l" + duration + " a" + startTime + " \"><p>" + e.getStartTime() + ":00 " + e.getDescription() + "</p></li>"); currEventStart = e.getStartTime(); } output += (" </ul>"); output += (" </div> "); output += (" <!-- slide closed -->"); output += ("</div> "); return output; } private String outputDayBrn(int dayNumber, ArrayList<Event> eventsForToday) { String output = ""; output += ("<div class=\"day brn\">"); output += (" <div class=\"daybar\"><p>" + dayNumber + "</p></div>"); output += (" <div class=\"dots\">"); output += (" <ul>"); //****************************************************************** //output += (" <li class=\"yellow\"></li>"); TODO: need to add entry to //output += (" <li class=\"green\"></li>"); db for types of events //***************************************************************88 output += (" </ul>"); output += (" </div> "); output += (" <!-- slide open -->"); output += (" <div class=\"open\">"); output += (" <ul>"); int currEventStart = 0; for(Event e: eventsForToday) { int duration = e.getEndTime() - e.getStartTime(); int startTime = e.getStartTime() - currEventStart - duration; output += (" <li class=\"yellow l" + duration + " a" + startTime + " \"><p>" + e.getStartTime() + ":00 " + e.getName() + " - " + e.getDescription() + "</p></li>"); currEventStart = e.getStartTime(); } output += (" </ul>"); output += (" </div> "); output += (" <!-- slide closed -->"); output += ("</div> "); return output; } }
true
true
public String outputTimetable(String user, Calendar cal) throws FileNotFoundException, IOException { DBManager db = new DBManager(); ArrayList<Event> events = db.getEventsForUser(user); String output = ""; output += ("<div id=\"calendar\">"); output += (" <div id=\"calcontainer\">"); output += (" <div id=\"calheader\">"); output += (" <h2>" + cal.MONTH + " " + cal.YEAR + "</h2>"); output += (" </div> "); output += (" <div id=\"daysweek\">"); output += (" <div class=\"dayweek\"><p>Monday</p></div>"); output += (" <div class=\"dayweek\"><p>Tuesday</p></div>"); output += (" <div class=\"dayweek\"><p>Wednesday</p></div>"); output += (" <div class=\"dayweek\"><p>Thursday</p></div>"); output += (" <div class=\"dayweek\"><p>Friday</p></div>"); output += (" <div class=\"dayweek\"><p>Saturday</p></div>"); output += (" <div class=\"dayweek brn\"><p>Sunday</p></div>"); output += (" </div>"); output += (" <div id=\"daysmonth\">"); int currentDay = 1;//first monday for(int i=0; i<5; i++) {//for 5 weeks output += "<div class= \"week\">"; for(int j = 0; j < 7; j++) { //7 days ArrayList<Event> todaysEvents = null; for(Event e : events) { if(e.getStartDateDay() == currentDay && e.getStartDateMonth() == cal.MONTH && e.getStartDateYear() == cal.YEAR) { todaysEvents.add(e); } } if(currentDay % 7 == 0) { output += outputDayBrn(currentDay, todaysEvents); } else { output += outputDay(currentDay, todaysEvents); } currentDay++; } output += (" </div>"); } output += (" </div>"); output += (" </div>"); output += (" <div id=\"calcat\">"); output += (" <div class=\"caldot blue\"></div><p>Lecture</p>"); output += (" <div class=\"caldot yellow\"></div><p>Tutorial</p>"); output += (" <div class=\"caldot green\"></div><p>Student Meeting</p>"); output += (" <div class=\"caldot red\"></div><p>Lecturer Meeting</p>"); output += (" </div>"); output += ("</div>"); output += ("</div>"); return output; }
public String outputTimetable(String user, Calendar cal) throws FileNotFoundException, IOException { DBManager db = new DBManager(); ArrayList<Event> events = db.getEventsForUser(user); String output = ""; output += ("<div id=\"calendar\">"); output += (" <div id=\"calcontainer\">"); output += (" <div id=\"calheader\">"); output += (" <h2>" + cal.MONTH + " " + cal.YEAR + "</h2>"); output += (" </div> "); output += (" <div id=\"daysweek\">"); output += (" <div class=\"dayweek\"><p>Monday</p></div>"); output += (" <div class=\"dayweek\"><p>Tuesday</p></div>"); output += (" <div class=\"dayweek\"><p>Wednesday</p></div>"); output += (" <div class=\"dayweek\"><p>Thursday</p></div>"); output += (" <div class=\"dayweek\"><p>Friday</p></div>"); output += (" <div class=\"dayweek\"><p>Saturday</p></div>"); output += (" <div class=\"dayweek brn\"><p>Sunday</p></div>"); output += (" </div>"); output += (" <div id=\"daysmonth\">"); int currentDay = 1;//first monday for(int i=0; i<5; i++) {//for 5 weeks output += "<div class= \"week\">"; for(int j = 0; j < 7; j++) { //7 days ArrayList<Event> todaysEvents = new ArrayList<Event>(); for(Event e : events) { if(e.getStartDateDay() == currentDay && e.getStartDateMonth() == cal.MONTH && e.getStartDateYear() == cal.YEAR) { todaysEvents.add(e); } } if(currentDay % 7 == 0) { output += outputDayBrn(currentDay, todaysEvents); } else { output += outputDay(currentDay, todaysEvents); } currentDay++; } output += (" </div>"); } output += (" </div>"); output += (" </div>"); output += (" <div id=\"calcat\">"); output += (" <div class=\"caldot blue\"></div><p>Lecture</p>"); output += (" <div class=\"caldot yellow\"></div><p>Tutorial</p>"); output += (" <div class=\"caldot green\"></div><p>Student Meeting</p>"); output += (" <div class=\"caldot red\"></div><p>Lecturer Meeting</p>"); output += (" </div>"); output += ("</div>"); output += ("</div>"); return output; }
diff --git a/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java b/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java index 5c3058174..153b172de 100644 --- a/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java +++ b/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java @@ -1,643 +1,643 @@ package org.opentripplanner.api.ws; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.onebusaway.gtfs.model.AgencyAndId; import org.onebusaway.gtfs.model.Trip; import org.opentripplanner.api.model.Itinerary; import org.opentripplanner.api.model.Leg; import org.opentripplanner.api.model.Place; import org.opentripplanner.api.model.RelativeDirection; import org.opentripplanner.api.model.TripPlan; import org.opentripplanner.api.model.WalkStep; import org.opentripplanner.common.geometry.DirectionUtils; import org.opentripplanner.common.geometry.PackedCoordinateSequence; import org.opentripplanner.routing.core.Edge; import org.opentripplanner.routing.core.EdgeNarrative; import org.opentripplanner.routing.core.Graph; import org.opentripplanner.routing.core.RouteSpec; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.TraverseMode; import org.opentripplanner.routing.core.TraverseModeSet; import org.opentripplanner.routing.core.TraverseOptions; import org.opentripplanner.routing.core.Vertex; import org.opentripplanner.routing.edgetype.EdgeWithElevation; import org.opentripplanner.routing.edgetype.FreeEdge; import org.opentripplanner.routing.error.PathNotFoundException; import org.opentripplanner.routing.error.VertexNotFoundException; import org.opentripplanner.routing.services.FareService; import org.opentripplanner.routing.services.PathService; import org.opentripplanner.routing.services.PathServiceFactory; import org.opentripplanner.routing.spt.GraphPath; import org.opentripplanner.util.PolylineEncoder; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; public class PlanGenerator { private static final Logger LOGGER = Logger.getLogger(PlanGenerator.class.getCanonicalName()); Request request; private PathService pathService; private FareService fareService; public PlanGenerator(Request request, PathServiceFactory pathServiceFactory) { this.request = request; pathService = pathServiceFactory.getPathService(request.getRouterId()); Graph graph = pathService.getGraphService().getGraph(); fareService = graph.getService(FareService.class); } /** * Generates a TripPlan from a Request; * */ public TripPlan generate() { TraverseOptions options = getOptions(request); checkLocationsAccessible(request, options); /* try to plan the trip */ List<GraphPath> paths = null; boolean tooSloped = false; try { List<String> intermediates = request.getIntermediatePlaces(); if (intermediates.size() == 0) { paths = pathService.plan(request.getFrom(), request.getTo(), request.getDateTime(), options, request.getNumItineraries()); if (paths == null && request.getWheelchair()) { // There are no paths that meet the user's slope restrictions. // Try again without slope restrictions (and warn user). options.maxSlope = Double.MAX_VALUE; paths = pathService.plan(request.getFrom(), request.getTo(), request.getDateTime(), options, request.getNumItineraries()); tooSloped = true; } } else { paths = pathService.plan(request.getFrom(), request.getTo(), intermediates, request.getDateTime(), options); } } catch (VertexNotFoundException e) { LOGGER.log(Level.INFO, "Vertex not found: " + request.getFrom() + " : " + request.getTo(), e); throw e; } if (paths == null || paths.size() == 0) { LOGGER .log(Level.INFO, "Path not found: " + request.getFrom() + " : " + request.getTo()); throw new PathNotFoundException(); } TripPlan plan = generatePlan(paths, request); if (plan != null) { for (Itinerary i : plan.itinerary) { i.tooSloped = tooSloped; } } return plan; } /** * Generates a TripPlan from a set of paths */ public TripPlan generatePlan(List<GraphPath> paths, Request request) { GraphPath exemplar = paths.get(0); Vertex tripStartVertex = exemplar.getStartVertex(); Vertex tripEndVertex = exemplar.getEndVertex(); String startName = tripStartVertex.getName(); String endName = tripEndVertex.getName(); // Use vertex labels if they don't have names if (startName == null) { startName = tripStartVertex.getLabel(); } if (endName == null) { endName = tripEndVertex.getLabel(); } Place from = new Place(tripStartVertex.getX(), tripStartVertex.getY(), startName); Place to = new Place(tripEndVertex.getX(), tripEndVertex.getY(), endName); TripPlan plan = new TripPlan(from, to, request.getDateTime()); for (GraphPath path : paths) { Itinerary itinerary = generateItinerary(path, request.getShowIntermediateStops()); plan.addItinerary(itinerary); } return plan; } /** * Generate an itinerary from a @{link GraphPath}. The algorithm here is to walk over each edge * in the graph path, accumulating geometry, time, and length data. On mode change, a new leg is * generated. Street legs undergo an additional processing step to generate turn-by-turn * directions. * * @param path * @param showIntermediateStops * whether intermediate stops are included in the generated itinerary * @return itinerary */ private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) { Itinerary itinerary = makeEmptyItinerary(path); Leg leg = null; List<String> notesForNewLeg = new ArrayList<String>(); Edge edge = null; EdgeNarrative edgeNarrative = null; TraverseMode mode = null; TraverseMode previousMode = null; CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence(); State finalState = path.states.getLast(); double previousElevation = Double.MAX_VALUE; double edgeElapsedTime; GeometryFactory geometryFactory = new GeometryFactory(); int startWalk = -1; int i = -1; for (State currState : path.states) { i++; /* grab base edge and associated narrative information from SPT edge */ edge = currState.getBackEdge(); edgeNarrative = currState.getBackEdgeNarrative(); /* skip initial state, which has no back edges */ if (edge == null) continue; /* Add in notes */ Set<String> notes = edgeNarrative.getNotes(); if (notes != null) { if (leg == null) { notesForNewLeg.addAll(notes); } else { for (String note : notes) { leg.addNote(note); } } } /* ignore freeEdges */ if (edge instanceof FreeEdge && currState != finalState) { continue; } mode = edgeNarrative.getMode(); edgeElapsedTime = currState.getTime() - currState.getBackState().getTime(); boolean changingToInterlinedTrip = leg != null && leg.route != null && !leg.route.equals(edgeNarrative.getName()) && mode.isTransit() && previousMode != null && previousMode.isTransit(); if (mode != previousMode || changingToInterlinedTrip) { /* change in mode. make a new leg if we are entering walk or transit, * otherwise just update the general itinerary info and move to next edge. */ previousMode = mode; if (mode == TraverseMode.TRANSFER) { /* transferring mode */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += edgeNarrative.getDistance(); continue; } else if (mode == TraverseMode.BOARDING) { /* boarding mode */ itinerary.transfers++; itinerary.waitingTime += edgeElapsedTime; continue; } else if (mode == TraverseMode.ALIGHTING) { /* alighting mode */ itinerary.waitingTime += edgeElapsedTime; leg.to = makePlace(edgeNarrative.getToVertex()); leg.endTime = new Date(currState.getBackState().getTime()); continue; } else if (changingToInterlinedTrip) { /* finalize leg */ leg.to = makePlace(edgeNarrative.getFromVertex()); leg.endTime = new Date(currState.getBackState().getTime()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); leg.interlineWithPreviousLeg = true; /* reset coordinates */ coordinates = new CoordinateArrayListSequence(); /* initialize new leg */ leg = makeLeg(currState); for (String noteForNewLeg : notesForNewLeg) { leg.addNote(noteForNewLeg); } notesForNewLeg.clear(); leg.mode = mode.toString(); startWalk = -1; leg.route = edgeNarrative.getName(); itinerary.addLeg(leg); } else { /* entering transit or onStreet mode leg because traverseMode can only be: * transit, onStreetNonTransit, board, alight, or transfer. */ if (leg != null) { /* finalize prior leg if it exists */ if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i)); } if (leg.to == null) { /* this stuff is filled in in the alight case, but not in the walk case */ - leg.to = makePlace(edgeNarrative.getToVertex()); + leg.to = makePlace(edgeNarrative.getFromVertex()); leg.endTime = new Date(currState.getBackState().getTime()); } Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); /* reset coordinates */ coordinates = new CoordinateArrayListSequence(); } /* initialize new leg */ leg = makeLeg(currState); for (String noteForNewLeg : notesForNewLeg) { leg.addNote(noteForNewLeg); } notesForNewLeg.clear(); if (mode == null) { mode = currState.getBackState().getBackEdgeNarrative().getMode(); previousMode = mode; } leg.mode = mode.toString(); if (mode.isOnStreetNonTransit()) { /* on-street (walk/bike) leg * mark where in edge list on-street legs begin, * so step-by-step instructions can be generated for this sublist later */ startWalk = i; } else { /* transit leg */ startWalk = -1; leg.route = edgeNarrative.getName(); } itinerary.addLeg(leg); } } /* end handling mode changes */ /* either a new leg has been created, or a leg already existed, * and the current edge's mode is same as that leg. * if you fall through to here, a leg necessarily exists and leg != null. * accumulate current edge's distance onto this existing leg. */ leg.distance += edgeNarrative.getDistance(); /* for all edges with geometry, append their coordinates to the leg's. */ Geometry edgeGeometry = edgeNarrative.getGeometry(); if (edgeGeometry != null) { Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates(); if (coordinates.size() > 0 && coordinates.getCoordinate(coordinates.size() - 1).equals( edgeCoordinates[0])) { coordinates.extend(edgeCoordinates, 1); } else { coordinates.extend(edgeCoordinates); } } /* we are not boarding, alighting, etc. * so are we walking/biking/driving or using transit? */ if (mode.isOnStreetNonTransit()) { /* we are on the street (non-transit) */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += edgeNarrative.getDistance(); if (edge instanceof EdgeWithElevation) { PackedCoordinateSequence profile = ((EdgeWithElevation) edge) .getElevationProfile(); previousElevation = applyElevation(profile, itinerary, previousElevation); } } else if (mode.isTransit()) { /* we are on a transit trip */ itinerary.transitTime += edgeElapsedTime; if (showIntermediateStops) { /* add an intermediate stop to the current leg */ if (leg.stop == null) { /* first transit edge, just create the list (the initial stop is current * "from" vertex) */ leg.stop = new ArrayList<Place>(); } /* any further transit edge, add "from" vertex to intermediate stops */ Place stop = makePlace(currState); leg.stop.add(stop); } } } /* end loop over graphPath edge list */ if (leg != null) { /* finalize leg */ leg.to = makePlace(edgeNarrative.getToVertex()); leg.endTime = new Date(finalState.getTime()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i + 1)); } } if (itinerary.transfers == -1) { itinerary.transfers = 0; } itinerary.removeBogusLegs(); return itinerary; } /** * Adjusts an Itinerary's elevation fields from an elevation profile * * @return the elevation at the end of the profile */ private double applyElevation(PackedCoordinateSequence profile, Itinerary itinerary, double previousElevation) { if (profile != null) { for (Coordinate coordinate : profile.toCoordinateArray()) { if (previousElevation == Double.MAX_VALUE) { previousElevation = coordinate.y; continue; } double elevationChange = previousElevation - coordinate.y; if (elevationChange > 0) { itinerary.elevationGained += elevationChange; } else { itinerary.elevationLost -= elevationChange; } previousElevation = coordinate.y; } } return previousElevation; } /** * Makes a new empty leg from a starting edge */ private Leg makeLeg(State s) { Leg leg = new Leg(); leg.startTime = new Date(s.getBackState().getTime()); EdgeNarrative en = s.getBackEdgeNarrative(); leg.route = en.getName(); Trip trip = en.getTrip(); if (trip != null) { leg.headsign = trip.getTripHeadsign(); leg.agencyId = trip.getId().getAgencyId(); leg.tripShortName = trip.getTripShortName(); } leg.distance = 0.0; leg.from = makePlace(en.getFromVertex()); return leg; } /** * Makes a new empty Itinerary for a given path. * * @return */ private Itinerary makeEmptyItinerary(GraphPath path) { Itinerary itinerary = new Itinerary(); State startState = path.states.getFirst(); State endState = path.states.getLast(); itinerary.startTime = new Date(startState.getTime()); itinerary.endTime = new Date(endState.getTime()); itinerary.duration = endState.getTime() - startState.getTime(); if (fareService != null) { itinerary.fare = fareService.getCost(path); } itinerary.transfers = -1; return itinerary; } /** * Makes a new Place from a state. Contains information about time. * * @return */ private Place makePlace(State state) { Coordinate endCoord = state.getVertex().getCoordinate(); String name = state.getVertex().getName(); AgencyAndId stopId = state.getVertex().getStopId(); Date timeAtState = new Date(state.getTime()); Place place = new Place(endCoord.x, endCoord.y, name, stopId, timeAtState); return place; } /** * Makes a new Place from a vertex. * * @return */ private Place makePlace(Vertex vertex) { Coordinate endCoord = vertex.getCoordinate(); Place place = new Place(endCoord.x, endCoord.y, vertex.getName()); place.stopId = vertex.getStopId(); return place; } /** * Throw an exception if the start and end locations are not wheelchair accessible given the * user's specified maximum slope. */ private void checkLocationsAccessible(Request request, TraverseOptions options) { if (request.getWheelchair()) { // check if the start and end locations are accessible if (!pathService.isAccessible(request.getFrom(), options) || !pathService.isAccessible(request.getTo(), options)) { throw new LocationNotAccessible(); } } } /** * Get the traverse options for a request * * @param request * @return */ private TraverseOptions getOptions(Request request) { TraverseModeSet modeSet = request.getModeSet(); assert (modeSet.isValid()); TraverseOptions options = new TraverseOptions(modeSet); options.optimizeFor = request.getOptimize(); options.setArriveBy(request.isArriveBy()); options.wheelchairAccessible = request.getWheelchair(); if (request.getMaxSlope() > 0) { options.maxSlope = request.getMaxSlope(); } if (request.getMaxWalkDistance() > 0) { options.maxWalkDistance = request.getMaxWalkDistance(); } if (request.getMinTransferTime() != null) { options.minTransferTime = request.getMinTransferTime(); } if (request.getPreferredRoutes()!= null){ for(String element : request.getPreferredRoutes()){ String[] routeSpec = element.split("_", 2); if (routeSpec.length != 2) { throw new IllegalArgumentException("AgencyId or routeId not set in preferredRoutes list"); } options.preferredRoutes.add(new RouteSpec(routeSpec[0], routeSpec[1])); } } if (request.getUnpreferredRoutes()!= null){ for(String element : request.getUnpreferredRoutes()){ String[] routeSpec = element.split("_", 2); if (routeSpec.length != 2) { throw new IllegalArgumentException("AgencyId or routeId not set in unpreferredRoutes list"); } options.unpreferredRoutes.add(new RouteSpec(routeSpec[0], routeSpec[1])); } } if (request.getBannedRoutes()!= null){ for(String element : request.getBannedRoutes()){ String[] routeSpec = element.split("_", 2); if (routeSpec.length != 2) { throw new IllegalArgumentException("AgencyId or routeId not set in bannedRoutes list"); } options.bannedRoutes.add(new RouteSpec(routeSpec[0], routeSpec[1])); } } return options; } /** * Converts a list of street edges to a list of turn-by-turn directions. * * @param edges * : A list of street edges * @return */ private List<WalkStep> getWalkSteps(PathService pathService, List<State> states) { List<WalkStep> steps = new ArrayList<WalkStep>(); WalkStep step = null; double lastAngle = 0, distance = 0; // distance used for appending elevation profiles int roundaboutExit = 0; // track whether we are in a roundabout, and if so the exit number for (State currState : states) { Edge edge = currState.getBackEdge(); EdgeNarrative edgeResult = currState.getBackEdgeNarrative(); if (edge instanceof FreeEdge) { continue; } Geometry geom = edgeResult.getGeometry(); if (geom == null) { continue; } String streetName = edgeResult.getName(); if (step == null) { // first step step = createWalkStep(currState); steps.add(step); double thisAngle = DirectionUtils.getFirstAngle(geom); step.setAbsoluteDirection(thisAngle); // new step, set distance to length of first edge distance = edgeResult.getDistance(); } else if (step.streetName != streetName && (step.streetName != null && !step.streetName.equals(streetName))) { /* street name has changed */ if (roundaboutExit > 0) { // if we were just on a roundabout, // make note of which exit was taken in the existing step step.exit = Integer.toString(roundaboutExit); // ordinal numbers from localization roundaboutExit = 0; } /* start a new step */ step = createWalkStep(currState); steps.add(step); if (edgeResult.isRoundabout()) { // indicate that we are now on a roundabout // and use one-based exit numbering roundaboutExit = 1; } double thisAngle = DirectionUtils.getFirstAngle(geom); step.setDirections(lastAngle, thisAngle, edgeResult.isRoundabout()); step.becomes = !pathService.multipleOptionsBefore(edge); // new step, set distance to length of first edge distance = edgeResult.getDistance(); } else { /* street name has not changed */ double thisAngle = DirectionUtils.getFirstAngle(geom); RelativeDirection direction = WalkStep.getRelativeDirection(lastAngle, thisAngle, edgeResult.isRoundabout()); boolean optionsBefore = pathService.multipleOptionsBefore(edge); if (edgeResult.isRoundabout()) { // we are on a roundabout, and have already traversed at least one edge of it. if (optionsBefore) { // increment exit count if we passed one. roundaboutExit += 1; } } if (edgeResult.isRoundabout() || direction == RelativeDirection.CONTINUE) { // we are continuing almost straight, or continuing along a roundabout. // just append elevation info onto the existing step. if (step.elevation != null) { String s = encodeElevationProfile(edge, distance); if (step.elevation.length() > 0 && s != null && s.length() > 0) step.elevation += ","; step.elevation += s; } // extending a step, increment the existing distance distance += edgeResult.getDistance(); } else { // we are not on a roundabout, and not continuing straight through. // figure out if there were turn options at the last intersection. if (optionsBefore) { // turn to stay on same-named street step = createWalkStep(currState); steps.add(step); step.setDirections(lastAngle, thisAngle, false); step.stayOn = true; // new step, set distance to length of first edge distance = edgeResult.getDistance(); } } } // increment the total length for this step step.distance += edgeResult.getDistance(); lastAngle = DirectionUtils.getLastAngle(geom); } return steps; } private WalkStep createWalkStep(State s) { EdgeNarrative en = s.getBackEdgeNarrative(); WalkStep step; step = new WalkStep(); step.streetName = en.getName(); step.lon = en.getFromVertex().getX(); step.lat = en.getFromVertex().getY(); step.elevation = encodeElevationProfile(s.getBackEdge(), 0); return step; } private String encodeElevationProfile(Edge edge, double offset) { if (!(edge instanceof EdgeWithElevation)) { return ""; } EdgeWithElevation elevEdge = (EdgeWithElevation) edge; if (elevEdge.getElevationProfile() == null) { return ""; } String str = ""; Coordinate[] coordArr = elevEdge.getElevationProfile().toCoordinateArray(); for (int i = 0; i < coordArr.length; i++) { str += Math.round(coordArr[i].x + offset) + "," + Math.round(coordArr[i].y * 10.0) / 10.0 + (i < coordArr.length - 1 ? "," : ""); } return str; } }
true
true
private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) { Itinerary itinerary = makeEmptyItinerary(path); Leg leg = null; List<String> notesForNewLeg = new ArrayList<String>(); Edge edge = null; EdgeNarrative edgeNarrative = null; TraverseMode mode = null; TraverseMode previousMode = null; CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence(); State finalState = path.states.getLast(); double previousElevation = Double.MAX_VALUE; double edgeElapsedTime; GeometryFactory geometryFactory = new GeometryFactory(); int startWalk = -1; int i = -1; for (State currState : path.states) { i++; /* grab base edge and associated narrative information from SPT edge */ edge = currState.getBackEdge(); edgeNarrative = currState.getBackEdgeNarrative(); /* skip initial state, which has no back edges */ if (edge == null) continue; /* Add in notes */ Set<String> notes = edgeNarrative.getNotes(); if (notes != null) { if (leg == null) { notesForNewLeg.addAll(notes); } else { for (String note : notes) { leg.addNote(note); } } } /* ignore freeEdges */ if (edge instanceof FreeEdge && currState != finalState) { continue; } mode = edgeNarrative.getMode(); edgeElapsedTime = currState.getTime() - currState.getBackState().getTime(); boolean changingToInterlinedTrip = leg != null && leg.route != null && !leg.route.equals(edgeNarrative.getName()) && mode.isTransit() && previousMode != null && previousMode.isTransit(); if (mode != previousMode || changingToInterlinedTrip) { /* change in mode. make a new leg if we are entering walk or transit, * otherwise just update the general itinerary info and move to next edge. */ previousMode = mode; if (mode == TraverseMode.TRANSFER) { /* transferring mode */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += edgeNarrative.getDistance(); continue; } else if (mode == TraverseMode.BOARDING) { /* boarding mode */ itinerary.transfers++; itinerary.waitingTime += edgeElapsedTime; continue; } else if (mode == TraverseMode.ALIGHTING) { /* alighting mode */ itinerary.waitingTime += edgeElapsedTime; leg.to = makePlace(edgeNarrative.getToVertex()); leg.endTime = new Date(currState.getBackState().getTime()); continue; } else if (changingToInterlinedTrip) { /* finalize leg */ leg.to = makePlace(edgeNarrative.getFromVertex()); leg.endTime = new Date(currState.getBackState().getTime()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); leg.interlineWithPreviousLeg = true; /* reset coordinates */ coordinates = new CoordinateArrayListSequence(); /* initialize new leg */ leg = makeLeg(currState); for (String noteForNewLeg : notesForNewLeg) { leg.addNote(noteForNewLeg); } notesForNewLeg.clear(); leg.mode = mode.toString(); startWalk = -1; leg.route = edgeNarrative.getName(); itinerary.addLeg(leg); } else { /* entering transit or onStreet mode leg because traverseMode can only be: * transit, onStreetNonTransit, board, alight, or transfer. */ if (leg != null) { /* finalize prior leg if it exists */ if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i)); } if (leg.to == null) { /* this stuff is filled in in the alight case, but not in the walk case */ leg.to = makePlace(edgeNarrative.getToVertex()); leg.endTime = new Date(currState.getBackState().getTime()); } Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); /* reset coordinates */ coordinates = new CoordinateArrayListSequence(); } /* initialize new leg */ leg = makeLeg(currState); for (String noteForNewLeg : notesForNewLeg) { leg.addNote(noteForNewLeg); } notesForNewLeg.clear(); if (mode == null) { mode = currState.getBackState().getBackEdgeNarrative().getMode(); previousMode = mode; } leg.mode = mode.toString(); if (mode.isOnStreetNonTransit()) { /* on-street (walk/bike) leg * mark where in edge list on-street legs begin, * so step-by-step instructions can be generated for this sublist later */ startWalk = i; } else { /* transit leg */ startWalk = -1; leg.route = edgeNarrative.getName(); } itinerary.addLeg(leg); } } /* end handling mode changes */ /* either a new leg has been created, or a leg already existed, * and the current edge's mode is same as that leg. * if you fall through to here, a leg necessarily exists and leg != null. * accumulate current edge's distance onto this existing leg. */ leg.distance += edgeNarrative.getDistance(); /* for all edges with geometry, append their coordinates to the leg's. */ Geometry edgeGeometry = edgeNarrative.getGeometry(); if (edgeGeometry != null) { Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates(); if (coordinates.size() > 0 && coordinates.getCoordinate(coordinates.size() - 1).equals( edgeCoordinates[0])) { coordinates.extend(edgeCoordinates, 1); } else { coordinates.extend(edgeCoordinates); } } /* we are not boarding, alighting, etc. * so are we walking/biking/driving or using transit? */ if (mode.isOnStreetNonTransit()) { /* we are on the street (non-transit) */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += edgeNarrative.getDistance(); if (edge instanceof EdgeWithElevation) { PackedCoordinateSequence profile = ((EdgeWithElevation) edge) .getElevationProfile(); previousElevation = applyElevation(profile, itinerary, previousElevation); } } else if (mode.isTransit()) { /* we are on a transit trip */ itinerary.transitTime += edgeElapsedTime; if (showIntermediateStops) { /* add an intermediate stop to the current leg */ if (leg.stop == null) { /* first transit edge, just create the list (the initial stop is current * "from" vertex) */ leg.stop = new ArrayList<Place>(); } /* any further transit edge, add "from" vertex to intermediate stops */ Place stop = makePlace(currState); leg.stop.add(stop); } } } /* end loop over graphPath edge list */ if (leg != null) { /* finalize leg */ leg.to = makePlace(edgeNarrative.getToVertex()); leg.endTime = new Date(finalState.getTime()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i + 1)); } } if (itinerary.transfers == -1) { itinerary.transfers = 0; } itinerary.removeBogusLegs(); return itinerary; }
private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) { Itinerary itinerary = makeEmptyItinerary(path); Leg leg = null; List<String> notesForNewLeg = new ArrayList<String>(); Edge edge = null; EdgeNarrative edgeNarrative = null; TraverseMode mode = null; TraverseMode previousMode = null; CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence(); State finalState = path.states.getLast(); double previousElevation = Double.MAX_VALUE; double edgeElapsedTime; GeometryFactory geometryFactory = new GeometryFactory(); int startWalk = -1; int i = -1; for (State currState : path.states) { i++; /* grab base edge and associated narrative information from SPT edge */ edge = currState.getBackEdge(); edgeNarrative = currState.getBackEdgeNarrative(); /* skip initial state, which has no back edges */ if (edge == null) continue; /* Add in notes */ Set<String> notes = edgeNarrative.getNotes(); if (notes != null) { if (leg == null) { notesForNewLeg.addAll(notes); } else { for (String note : notes) { leg.addNote(note); } } } /* ignore freeEdges */ if (edge instanceof FreeEdge && currState != finalState) { continue; } mode = edgeNarrative.getMode(); edgeElapsedTime = currState.getTime() - currState.getBackState().getTime(); boolean changingToInterlinedTrip = leg != null && leg.route != null && !leg.route.equals(edgeNarrative.getName()) && mode.isTransit() && previousMode != null && previousMode.isTransit(); if (mode != previousMode || changingToInterlinedTrip) { /* change in mode. make a new leg if we are entering walk or transit, * otherwise just update the general itinerary info and move to next edge. */ previousMode = mode; if (mode == TraverseMode.TRANSFER) { /* transferring mode */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += edgeNarrative.getDistance(); continue; } else if (mode == TraverseMode.BOARDING) { /* boarding mode */ itinerary.transfers++; itinerary.waitingTime += edgeElapsedTime; continue; } else if (mode == TraverseMode.ALIGHTING) { /* alighting mode */ itinerary.waitingTime += edgeElapsedTime; leg.to = makePlace(edgeNarrative.getToVertex()); leg.endTime = new Date(currState.getBackState().getTime()); continue; } else if (changingToInterlinedTrip) { /* finalize leg */ leg.to = makePlace(edgeNarrative.getFromVertex()); leg.endTime = new Date(currState.getBackState().getTime()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); leg.interlineWithPreviousLeg = true; /* reset coordinates */ coordinates = new CoordinateArrayListSequence(); /* initialize new leg */ leg = makeLeg(currState); for (String noteForNewLeg : notesForNewLeg) { leg.addNote(noteForNewLeg); } notesForNewLeg.clear(); leg.mode = mode.toString(); startWalk = -1; leg.route = edgeNarrative.getName(); itinerary.addLeg(leg); } else { /* entering transit or onStreet mode leg because traverseMode can only be: * transit, onStreetNonTransit, board, alight, or transfer. */ if (leg != null) { /* finalize prior leg if it exists */ if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i)); } if (leg.to == null) { /* this stuff is filled in in the alight case, but not in the walk case */ leg.to = makePlace(edgeNarrative.getFromVertex()); leg.endTime = new Date(currState.getBackState().getTime()); } Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); /* reset coordinates */ coordinates = new CoordinateArrayListSequence(); } /* initialize new leg */ leg = makeLeg(currState); for (String noteForNewLeg : notesForNewLeg) { leg.addNote(noteForNewLeg); } notesForNewLeg.clear(); if (mode == null) { mode = currState.getBackState().getBackEdgeNarrative().getMode(); previousMode = mode; } leg.mode = mode.toString(); if (mode.isOnStreetNonTransit()) { /* on-street (walk/bike) leg * mark where in edge list on-street legs begin, * so step-by-step instructions can be generated for this sublist later */ startWalk = i; } else { /* transit leg */ startWalk = -1; leg.route = edgeNarrative.getName(); } itinerary.addLeg(leg); } } /* end handling mode changes */ /* either a new leg has been created, or a leg already existed, * and the current edge's mode is same as that leg. * if you fall through to here, a leg necessarily exists and leg != null. * accumulate current edge's distance onto this existing leg. */ leg.distance += edgeNarrative.getDistance(); /* for all edges with geometry, append their coordinates to the leg's. */ Geometry edgeGeometry = edgeNarrative.getGeometry(); if (edgeGeometry != null) { Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates(); if (coordinates.size() > 0 && coordinates.getCoordinate(coordinates.size() - 1).equals( edgeCoordinates[0])) { coordinates.extend(edgeCoordinates, 1); } else { coordinates.extend(edgeCoordinates); } } /* we are not boarding, alighting, etc. * so are we walking/biking/driving or using transit? */ if (mode.isOnStreetNonTransit()) { /* we are on the street (non-transit) */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += edgeNarrative.getDistance(); if (edge instanceof EdgeWithElevation) { PackedCoordinateSequence profile = ((EdgeWithElevation) edge) .getElevationProfile(); previousElevation = applyElevation(profile, itinerary, previousElevation); } } else if (mode.isTransit()) { /* we are on a transit trip */ itinerary.transitTime += edgeElapsedTime; if (showIntermediateStops) { /* add an intermediate stop to the current leg */ if (leg.stop == null) { /* first transit edge, just create the list (the initial stop is current * "from" vertex) */ leg.stop = new ArrayList<Place>(); } /* any further transit edge, add "from" vertex to intermediate stops */ Place stop = makePlace(currState); leg.stop.add(stop); } } } /* end loop over graphPath edge list */ if (leg != null) { /* finalize leg */ leg.to = makePlace(edgeNarrative.getToVertex()); leg.endTime = new Date(finalState.getTime()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i + 1)); } } if (itinerary.transfers == -1) { itinerary.transfers = 0; } itinerary.removeBogusLegs(); return itinerary; }
diff --git a/src/com/eteks/sweethome3d/model/Catalog.java b/src/com/eteks/sweethome3d/model/Catalog.java index 24306f77..d975440c 100644 --- a/src/com/eteks/sweethome3d/model/Catalog.java +++ b/src/com/eteks/sweethome3d/model/Catalog.java @@ -1,223 +1,224 @@ /* * Catalog.java 7 avr. 2006 * * Copyright (c) 2006 Emmanuel PUYBARET / eTeks <[email protected]>. All Rights * Reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA */ package com.eteks.sweethome3d.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Furniture catalog. * @author Emmanuel Puybaret */ public abstract class Catalog { private List<Category> categories = new ArrayList<Category>(); private boolean sorted; private List<CatalogPieceOfFurniture> selectedFurniture = Collections.emptyList(); private List<SelectionListener> selectionListeners = new ArrayList<SelectionListener>(); private List<FurnitureListener> furnitureListeners = new ArrayList<FurnitureListener>(); /** * Returns the catagories list sorted by name. * @return an unmodifiable list of catagories. */ public List<Category> getCategories() { checkCategoriesSorted(); return Collections.unmodifiableList(this.categories); } /** * Checks categories are sorted. */ private void checkCategoriesSorted() { if (!this.sorted) { Collections.sort(this.categories); this.sorted = true; } } /** * Returns the count of catagories in this catalog. */ public int getCategoriesCount() { return this.categories.size(); } /** * Returns the category at a given <code>index</code>. */ public Category getCategory(int index) { checkCategoriesSorted(); return this.categories.get(index); } /** * Adds the furniture <code>listener</code> in parameter to this home. */ public void addFurnitureListener(FurnitureListener listener) { this.furnitureListeners.add(listener); } /** * Removes the furniture <code>listener</code> in parameter from this home. */ public void removeFurnitureListener(FurnitureListener listener) { this.furnitureListeners.remove(listener); } /** * Adds a catagory. * @param category the category to add. * @throws IllegalArgumentException if a category with same name as the one in * parameter already exists in this catalog. */ private void add(Category category) { if (this.categories.contains(category)) { throw new IllegalArgumentException( category.getName() + " already exists in catalog"); } this.categories.add(category); this.sorted = false; } /** * Adds <code>piece</code> of a given <code>category</code> to this catalog. * Once the <code>piece</code> is added, furniture listeners added to this catalog will receive a * {@link FurnitureListener#pieceOfFurnitureChanged(FurnitureEvent) pieceOfFurnitureChanged} * notification. * @param category the category of the piece. * @param piece a piece of furniture. */ public void add(Category category, CatalogPieceOfFurniture piece) { int index = this.categories.indexOf(category); // If category doesn't exist yet, add it to catagories if (index == -1) { category = new Category(category.getName()); add(category); } else { category = this.categories.get(index); } // Add current piece of furniture to category list category.add(piece); firePieceOfFurnitureChanged(piece, Collections.binarySearch(category.getFurniture(), piece), FurnitureEvent.Type.ADD); } /** * Deletes the <code>piece</code> from this catalog. * If then piece category is empty, it will be removed from the categories of this catalog. * Once the <code>piece</code> is deleted, furniture listeners added to this home will receive a * {@link FurnitureListener#pieceOfFurnitureChanged(FurnitureEvent) pieceOfFurnitureChanged} * notification. * @param piece a piece of furniture in that category. */ public void delete(CatalogPieceOfFurniture piece) { + Category category = piece.getCategory(); // Remove piece from its category - for (Category category : this.categories) { + if (category != null) { int pieceIndex = Collections.binarySearch(category.getFurniture(), piece); if (pieceIndex >= 0) { // Ensure selectedFurniture don't keep a reference to piece deselectPieceOfFurniture(piece); category.delete(piece); if (category.getFurniture().size() == 0) { // Make a copy of the list to avoid conflicts in the list returned by getCategories this.categories = new ArrayList<Category>(this.categories); this.categories.remove(category); this.sorted = false; } firePieceOfFurnitureChanged(piece, pieceIndex, FurnitureEvent.Type.DELETE); return; } - } + } throw new IllegalArgumentException( "catalog doesn't contain piece " + piece.getName()); } private void firePieceOfFurnitureChanged(CatalogPieceOfFurniture piece, int index, FurnitureEvent.Type eventType) { if (!this.furnitureListeners.isEmpty()) { FurnitureEvent furnitureEvent = new FurnitureEvent(this, piece, index, eventType); // Work on a copy of furnitureListeners to ensure a listener // can modify safely listeners list FurnitureListener [] listeners = this.furnitureListeners. toArray(new FurnitureListener [this.furnitureListeners.size()]); for (FurnitureListener listener : listeners) { listener.pieceOfFurnitureChanged(furnitureEvent); } } } /** * Adds the selection <code>listener</code> in parameter to this home. */ public void addSelectionListener(SelectionListener listener) { this.selectionListeners.add(listener); } /** * Removes the selection <code>listener</code> in parameter from this home. */ public void removeSelectionListener(SelectionListener listener) { this.selectionListeners.remove(listener); } /** * Returns an unmodifiable list of the selected furniture in catalog. */ public List<CatalogPieceOfFurniture> getSelectedFurniture() { return Collections.unmodifiableList(this.selectedFurniture); } /** * Sets the selected items in home and notifies listeners selection change. */ public void setSelectedFurniture(List<CatalogPieceOfFurniture> selectedFurniture) { this.selectedFurniture = new ArrayList<CatalogPieceOfFurniture>(selectedFurniture); if (!this.selectionListeners.isEmpty()) { SelectionEvent selectionEvent = new SelectionEvent(this, getSelectedFurniture()); // Work on a copy of selectionListeners to ensure a listener // can modify safely listeners list SelectionListener [] listeners = this.selectionListeners. toArray(new SelectionListener [this.selectionListeners.size()]); for (SelectionListener listener : listeners) { listener.selectionChanged(selectionEvent); } } } /** * Removes <code>piece</code> from selected furniture. */ private void deselectPieceOfFurniture(CatalogPieceOfFurniture piece) { int pieceSelectionIndex = this.selectedFurniture.indexOf(piece); if (pieceSelectionIndex != -1) { List<CatalogPieceOfFurniture> selectedItems = new ArrayList<CatalogPieceOfFurniture>(getSelectedFurniture()); selectedItems.remove(pieceSelectionIndex); setSelectedFurniture(selectedItems); } } }
false
true
public void delete(CatalogPieceOfFurniture piece) { // Remove piece from its category for (Category category : this.categories) { int pieceIndex = Collections.binarySearch(category.getFurniture(), piece); if (pieceIndex >= 0) { // Ensure selectedFurniture don't keep a reference to piece deselectPieceOfFurniture(piece); category.delete(piece); if (category.getFurniture().size() == 0) { // Make a copy of the list to avoid conflicts in the list returned by getCategories this.categories = new ArrayList<Category>(this.categories); this.categories.remove(category); this.sorted = false; } firePieceOfFurnitureChanged(piece, pieceIndex, FurnitureEvent.Type.DELETE); return; } } throw new IllegalArgumentException( "catalog doesn't contain piece " + piece.getName()); }
public void delete(CatalogPieceOfFurniture piece) { Category category = piece.getCategory(); // Remove piece from its category if (category != null) { int pieceIndex = Collections.binarySearch(category.getFurniture(), piece); if (pieceIndex >= 0) { // Ensure selectedFurniture don't keep a reference to piece deselectPieceOfFurniture(piece); category.delete(piece); if (category.getFurniture().size() == 0) { // Make a copy of the list to avoid conflicts in the list returned by getCategories this.categories = new ArrayList<Category>(this.categories); this.categories.remove(category); this.sorted = false; } firePieceOfFurnitureChanged(piece, pieceIndex, FurnitureEvent.Type.DELETE); return; } } throw new IllegalArgumentException( "catalog doesn't contain piece " + piece.getName()); }
diff --git a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java index 1e3656495..9d1ded99f 100644 --- a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java +++ b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java @@ -1,456 +1,456 @@ package org.apache.solr.cloud; /** * 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 java.io.IOException; import java.net.MalformedURLException; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.request.AbstractUpdateRequest; import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.cloud.SafeStopThread; import org.apache.solr.common.cloud.ZkCoreNodeProps; import org.apache.solr.common.cloud.ZkNodeProps; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.CoreDescriptor; import org.apache.solr.core.RequestHandlers.LazyRequestHandlerWrapper; import org.apache.solr.core.SolrCore; import org.apache.solr.handler.ReplicationHandler; import org.apache.solr.request.LocalSolrQueryRequest; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrRequestHandler; import org.apache.solr.request.SolrRequestInfo; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.update.CommitUpdateCommand; import org.apache.solr.update.PeerSync; import org.apache.solr.update.UpdateLog; import org.apache.solr.update.UpdateLog.RecoveryInfo; import org.apache.solr.update.processor.DistributedUpdateProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RecoveryStrategy extends Thread implements SafeStopThread { private static final int MAX_RETRIES = 500; private static final int INTERRUPTED = MAX_RETRIES + 1; private static final int START_TIMEOUT = 100; private static final String REPLICATION_HANDLER = "/replication"; private static Logger log = LoggerFactory.getLogger(RecoveryStrategy.class); private volatile boolean close = false; private ZkController zkController; private String baseUrl; private String coreZkNodeName; private ZkStateReader zkStateReader; private volatile String coreName; private int retries; private boolean recoveringAfterStartup; private CoreContainer cc; public RecoveryStrategy(CoreContainer cc, String name) { this.cc = cc; this.coreName = name; setName("RecoveryThread"); zkController = cc.getZkController(); zkStateReader = zkController.getZkStateReader(); baseUrl = zkController.getBaseUrl(); coreZkNodeName = zkController.getNodeName() + "_" + coreName; } public void setRecoveringAfterStartup(boolean recoveringAfterStartup) { this.recoveringAfterStartup = recoveringAfterStartup; } // make sure any threads stop retrying public void close() { close = true; } private void recoveryFailed(final SolrCore core, final ZkController zkController, final String baseUrl, final String shardZkNodeName, final CoreDescriptor cd) { SolrException.log(log, "Recovery failed - I give up."); zkController.publishAsRecoveryFailed(baseUrl, cd, shardZkNodeName, core.getName()); close = true; } private void replicate(String nodeName, SolrCore core, ZkNodeProps leaderprops, String baseUrl) throws SolrServerException, IOException { String leaderBaseUrl = leaderprops.get(ZkStateReader.BASE_URL_PROP); ZkCoreNodeProps leaderCNodeProps = new ZkCoreNodeProps(leaderprops); String leaderUrl = leaderCNodeProps.getCoreUrl(); log.info("Attempting to replicate from " + leaderUrl); // if we are the leader, either we are trying to recover faster // then our ephemeral timed out or we are the only node if (!leaderBaseUrl.equals(baseUrl)) { // send commit commitOnLeader(leaderUrl); // use rep handler directly, so we can do this sync rather than async SolrRequestHandler handler = core.getRequestHandler(REPLICATION_HANDLER); if (handler instanceof LazyRequestHandlerWrapper) { handler = ((LazyRequestHandlerWrapper)handler).getWrappedHandler(); } ReplicationHandler replicationHandler = (ReplicationHandler) handler; if (replicationHandler == null) { throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "Skipping recovery, no " + REPLICATION_HANDLER + " handler found"); } ModifiableSolrParams solrParams = new ModifiableSolrParams(); solrParams.set(ReplicationHandler.MASTER_URL, leaderUrl + "replication"); if (close) retries = INTERRUPTED; boolean success = replicationHandler.doFetch(solrParams, true); // TODO: look into making sure force=true does not download files we already have if (!success) { throw new SolrException(ErrorCode.SERVER_ERROR, "Replication for recovery failed."); } // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() + " replicated " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits + " from " + leaderUrl + " gen:" + core.getDeletionPolicy().getLatestCommit().getGeneration() + " data:" + core.getDataDir()); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } } } private void commitOnLeader(String leaderUrl) throws MalformedURLException, SolrServerException, IOException { CommonsHttpSolrServer server = new CommonsHttpSolrServer(leaderUrl); server.setConnectionTimeout(30000); server.setSoTimeout(30000); UpdateRequest ureq = new UpdateRequest(); ureq.setParams(new ModifiableSolrParams()); ureq.getParams().set(DistributedUpdateProcessor.COMMIT_END_POINT, true); ureq.setAction(AbstractUpdateRequest.ACTION.COMMIT, false, true).process( server); server.commit(); server.shutdown(); } private void sendPrepRecoveryCmd(String leaderBaseUrl, String leaderCoreName) throws MalformedURLException, SolrServerException, IOException { CommonsHttpSolrServer server = new CommonsHttpSolrServer(leaderBaseUrl); server.setConnectionTimeout(45000); server.setSoTimeout(45000); WaitForState prepCmd = new WaitForState(); prepCmd.setCoreName(leaderCoreName); prepCmd.setNodeName(zkController.getNodeName()); prepCmd.setCoreNodeName(coreZkNodeName); prepCmd.setState(ZkStateReader.RECOVERING); prepCmd.setCheckLive(true); prepCmd.setPauseFor(6000); server.request(prepCmd); server.shutdown(); } @Override public void run() { SolrCore core = cc.getCore(coreName); if (core == null) { SolrException.log(log, "SolrCore not found - cannot recover:" + coreName); return; } // set request info for logging SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams()); SolrQueryResponse rsp = new SolrQueryResponse(); SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp)); try { doRecovery(core); } finally { SolrRequestInfo.clearRequestInfo(); } } public void doRecovery(SolrCore core) { boolean replayed = false; - boolean succesfulRecovery = false; + boolean successfulRecovery = false; UpdateLog ulog; try { ulog = core.getUpdateHandler().getUpdateLog(); if (ulog == null) { SolrException.log(log, "No UpdateLog found - cannot recover"); recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); return; } } finally { core.close(); } List<Long> startingRecentVersions; UpdateLog.RecentUpdates startingRecentUpdates = ulog.getRecentUpdates(); try { startingRecentVersions = startingRecentUpdates.getVersions(ulog.numRecordsToKeep); } finally { startingRecentUpdates.close(); } List<Long> reallyStartingVersions = ulog.getStartingVersions(); if (reallyStartingVersions != null && recoveringAfterStartup) { int oldIdx = 0; // index of the start of the old list in the current list long firstStartingVersion = reallyStartingVersions.size() > 0 ? reallyStartingVersions.get(0) : 0; for (; oldIdx<startingRecentVersions.size(); oldIdx++) { if (startingRecentVersions.get(oldIdx) == firstStartingVersion) break; } if (oldIdx > 0) { log.info("####### Found new versions added after startup: num=" + oldIdx); } // TODO: only log at debug level in the future (or move to oldIdx > 0 block) log.info("###### startupVersions=" + reallyStartingVersions); log.info("###### currentVersions=" + startingRecentVersions); } if (recoveringAfterStartup) { // if we're recovering after startup (i.e. we have been down), then we need to know what the last versions were // when we went down. startingRecentVersions = reallyStartingVersions; } boolean firstTime = true; - while (!succesfulRecovery && !close && !isInterrupted()) { // don't use interruption or it will close channels though + while (!successfulRecovery && !close && !isInterrupted()) { // don't use interruption or it will close channels though core = cc.getCore(coreName); if (core == null) { SolrException.log(log, "SolrCore not found - cannot recover:" + coreName); return; } try { // first thing we just try to sync zkController.publish(core.getCoreDescriptor(), ZkStateReader.RECOVERING); CloudDescriptor cloudDesc = core.getCoreDescriptor() .getCloudDescriptor(); ZkNodeProps leaderprops = zkStateReader.getLeaderProps( cloudDesc.getCollectionName(), cloudDesc.getShardId()); String leaderBaseUrl = leaderprops.get(ZkStateReader.BASE_URL_PROP); String leaderCoreName = leaderprops.get(ZkStateReader.CORE_NAME_PROP); String leaderUrl = ZkCoreNodeProps.getCoreUrl(leaderBaseUrl, leaderCoreName); sendPrepRecoveryCmd(leaderBaseUrl, leaderCoreName); // first thing we just try to sync if (firstTime) { firstTime = false; // only try sync the first time through the loop log.info("Attempting to PeerSync from " + leaderUrl + " recoveringAfterStartup="+recoveringAfterStartup); // System.out.println("Attempting to PeerSync from " + leaderUrl // + " i am:" + zkController.getNodeName()); PeerSync peerSync = new PeerSync(core, Collections.singletonList(leaderUrl), ulog.numRecordsToKeep); peerSync.setStartingVersions(startingRecentVersions); boolean syncSuccess = peerSync.sync(); if (syncSuccess) { SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams()); core.getUpdateHandler().commit(new CommitUpdateCommand(req, false)); - log.info("Sync Recovery was succesful - registering as Active"); + log.info("Sync Recovery was successful - registering as Active"); // System.out - // .println("Sync Recovery was succesful - registering as Active " + // .println("Sync Recovery was successful - registering as Active " // + zkController.getNodeName()); // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = // core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() // + " synched " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } // sync success - register as active and return zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); - succesfulRecovery = true; + successfulRecovery = true; close = true; return; } log.info("Sync Recovery was not successful - trying replication"); } //System.out.println("Sync Recovery was not successful - trying replication"); log.info("Begin buffering updates"); ulog.bufferUpdates(); replayed = false; try { replicate(zkController.getNodeName(), core, leaderprops, leaderUrl); replay(ulog); replayed = true; - log.info("Recovery was succesful - registering as Active"); + log.info("Recovery was successful - registering as Active"); // if there are pending recovery requests, don't advert as active zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); close = true; - succesfulRecovery = true; + successfulRecovery = true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (!replayed) { try { ulog.dropBufferedUpdates(); } catch (Throwable t) { SolrException.log(log, "", t); } } } } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (core != null) { core.close(); } } - if (!succesfulRecovery) { + if (!successfulRecovery) { // lets pause for a moment and we need to try again... // TODO: we don't want to retry for some problems? // Or do a fall off retry... try { SolrException.log(log, "Recovery failed - trying again..."); retries++; if (retries >= MAX_RETRIES) { if (retries == INTERRUPTED) { } else { // TODO: for now, give up after X tries - should we do more? core = cc.getCore(coreName); try { recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); } finally { if (core != null) { core.close(); } } } break; } } catch (Exception e) { SolrException.log(log, "", e); } try { Thread.sleep(Math.min(START_TIMEOUT * retries, 60000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } } log.info("Finished recovery process"); } } private Future<RecoveryInfo> replay(UpdateLog ulog) throws InterruptedException, ExecutionException, TimeoutException { Future<RecoveryInfo> future = ulog.applyBufferedUpdates(); if (future == null) { // no replay needed\ log.info("No replay needed"); } else { log.info("Replaying buffered documents"); // wait for replay future.get(); } // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() + " replayed " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } return future; } public boolean isClosed() { return close; } }
false
true
public void doRecovery(SolrCore core) { boolean replayed = false; boolean succesfulRecovery = false; UpdateLog ulog; try { ulog = core.getUpdateHandler().getUpdateLog(); if (ulog == null) { SolrException.log(log, "No UpdateLog found - cannot recover"); recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); return; } } finally { core.close(); } List<Long> startingRecentVersions; UpdateLog.RecentUpdates startingRecentUpdates = ulog.getRecentUpdates(); try { startingRecentVersions = startingRecentUpdates.getVersions(ulog.numRecordsToKeep); } finally { startingRecentUpdates.close(); } List<Long> reallyStartingVersions = ulog.getStartingVersions(); if (reallyStartingVersions != null && recoveringAfterStartup) { int oldIdx = 0; // index of the start of the old list in the current list long firstStartingVersion = reallyStartingVersions.size() > 0 ? reallyStartingVersions.get(0) : 0; for (; oldIdx<startingRecentVersions.size(); oldIdx++) { if (startingRecentVersions.get(oldIdx) == firstStartingVersion) break; } if (oldIdx > 0) { log.info("####### Found new versions added after startup: num=" + oldIdx); } // TODO: only log at debug level in the future (or move to oldIdx > 0 block) log.info("###### startupVersions=" + reallyStartingVersions); log.info("###### currentVersions=" + startingRecentVersions); } if (recoveringAfterStartup) { // if we're recovering after startup (i.e. we have been down), then we need to know what the last versions were // when we went down. startingRecentVersions = reallyStartingVersions; } boolean firstTime = true; while (!succesfulRecovery && !close && !isInterrupted()) { // don't use interruption or it will close channels though core = cc.getCore(coreName); if (core == null) { SolrException.log(log, "SolrCore not found - cannot recover:" + coreName); return; } try { // first thing we just try to sync zkController.publish(core.getCoreDescriptor(), ZkStateReader.RECOVERING); CloudDescriptor cloudDesc = core.getCoreDescriptor() .getCloudDescriptor(); ZkNodeProps leaderprops = zkStateReader.getLeaderProps( cloudDesc.getCollectionName(), cloudDesc.getShardId()); String leaderBaseUrl = leaderprops.get(ZkStateReader.BASE_URL_PROP); String leaderCoreName = leaderprops.get(ZkStateReader.CORE_NAME_PROP); String leaderUrl = ZkCoreNodeProps.getCoreUrl(leaderBaseUrl, leaderCoreName); sendPrepRecoveryCmd(leaderBaseUrl, leaderCoreName); // first thing we just try to sync if (firstTime) { firstTime = false; // only try sync the first time through the loop log.info("Attempting to PeerSync from " + leaderUrl + " recoveringAfterStartup="+recoveringAfterStartup); // System.out.println("Attempting to PeerSync from " + leaderUrl // + " i am:" + zkController.getNodeName()); PeerSync peerSync = new PeerSync(core, Collections.singletonList(leaderUrl), ulog.numRecordsToKeep); peerSync.setStartingVersions(startingRecentVersions); boolean syncSuccess = peerSync.sync(); if (syncSuccess) { SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams()); core.getUpdateHandler().commit(new CommitUpdateCommand(req, false)); log.info("Sync Recovery was succesful - registering as Active"); // System.out // .println("Sync Recovery was succesful - registering as Active " // + zkController.getNodeName()); // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = // core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() // + " synched " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } // sync success - register as active and return zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); succesfulRecovery = true; close = true; return; } log.info("Sync Recovery was not successful - trying replication"); } //System.out.println("Sync Recovery was not successful - trying replication"); log.info("Begin buffering updates"); ulog.bufferUpdates(); replayed = false; try { replicate(zkController.getNodeName(), core, leaderprops, leaderUrl); replay(ulog); replayed = true; log.info("Recovery was succesful - registering as Active"); // if there are pending recovery requests, don't advert as active zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); close = true; succesfulRecovery = true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (!replayed) { try { ulog.dropBufferedUpdates(); } catch (Throwable t) { SolrException.log(log, "", t); } } } } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (core != null) { core.close(); } } if (!succesfulRecovery) { // lets pause for a moment and we need to try again... // TODO: we don't want to retry for some problems? // Or do a fall off retry... try { SolrException.log(log, "Recovery failed - trying again..."); retries++; if (retries >= MAX_RETRIES) { if (retries == INTERRUPTED) { } else { // TODO: for now, give up after X tries - should we do more? core = cc.getCore(coreName); try { recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); } finally { if (core != null) { core.close(); } } } break; } } catch (Exception e) { SolrException.log(log, "", e); } try { Thread.sleep(Math.min(START_TIMEOUT * retries, 60000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } } log.info("Finished recovery process"); } }
public void doRecovery(SolrCore core) { boolean replayed = false; boolean successfulRecovery = false; UpdateLog ulog; try { ulog = core.getUpdateHandler().getUpdateLog(); if (ulog == null) { SolrException.log(log, "No UpdateLog found - cannot recover"); recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); return; } } finally { core.close(); } List<Long> startingRecentVersions; UpdateLog.RecentUpdates startingRecentUpdates = ulog.getRecentUpdates(); try { startingRecentVersions = startingRecentUpdates.getVersions(ulog.numRecordsToKeep); } finally { startingRecentUpdates.close(); } List<Long> reallyStartingVersions = ulog.getStartingVersions(); if (reallyStartingVersions != null && recoveringAfterStartup) { int oldIdx = 0; // index of the start of the old list in the current list long firstStartingVersion = reallyStartingVersions.size() > 0 ? reallyStartingVersions.get(0) : 0; for (; oldIdx<startingRecentVersions.size(); oldIdx++) { if (startingRecentVersions.get(oldIdx) == firstStartingVersion) break; } if (oldIdx > 0) { log.info("####### Found new versions added after startup: num=" + oldIdx); } // TODO: only log at debug level in the future (or move to oldIdx > 0 block) log.info("###### startupVersions=" + reallyStartingVersions); log.info("###### currentVersions=" + startingRecentVersions); } if (recoveringAfterStartup) { // if we're recovering after startup (i.e. we have been down), then we need to know what the last versions were // when we went down. startingRecentVersions = reallyStartingVersions; } boolean firstTime = true; while (!successfulRecovery && !close && !isInterrupted()) { // don't use interruption or it will close channels though core = cc.getCore(coreName); if (core == null) { SolrException.log(log, "SolrCore not found - cannot recover:" + coreName); return; } try { // first thing we just try to sync zkController.publish(core.getCoreDescriptor(), ZkStateReader.RECOVERING); CloudDescriptor cloudDesc = core.getCoreDescriptor() .getCloudDescriptor(); ZkNodeProps leaderprops = zkStateReader.getLeaderProps( cloudDesc.getCollectionName(), cloudDesc.getShardId()); String leaderBaseUrl = leaderprops.get(ZkStateReader.BASE_URL_PROP); String leaderCoreName = leaderprops.get(ZkStateReader.CORE_NAME_PROP); String leaderUrl = ZkCoreNodeProps.getCoreUrl(leaderBaseUrl, leaderCoreName); sendPrepRecoveryCmd(leaderBaseUrl, leaderCoreName); // first thing we just try to sync if (firstTime) { firstTime = false; // only try sync the first time through the loop log.info("Attempting to PeerSync from " + leaderUrl + " recoveringAfterStartup="+recoveringAfterStartup); // System.out.println("Attempting to PeerSync from " + leaderUrl // + " i am:" + zkController.getNodeName()); PeerSync peerSync = new PeerSync(core, Collections.singletonList(leaderUrl), ulog.numRecordsToKeep); peerSync.setStartingVersions(startingRecentVersions); boolean syncSuccess = peerSync.sync(); if (syncSuccess) { SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams()); core.getUpdateHandler().commit(new CommitUpdateCommand(req, false)); log.info("Sync Recovery was successful - registering as Active"); // System.out // .println("Sync Recovery was successful - registering as Active " // + zkController.getNodeName()); // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = // core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() // + " synched " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } // sync success - register as active and return zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); successfulRecovery = true; close = true; return; } log.info("Sync Recovery was not successful - trying replication"); } //System.out.println("Sync Recovery was not successful - trying replication"); log.info("Begin buffering updates"); ulog.bufferUpdates(); replayed = false; try { replicate(zkController.getNodeName(), core, leaderprops, leaderUrl); replay(ulog); replayed = true; log.info("Recovery was successful - registering as Active"); // if there are pending recovery requests, don't advert as active zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); close = true; successfulRecovery = true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (!replayed) { try { ulog.dropBufferedUpdates(); } catch (Throwable t) { SolrException.log(log, "", t); } } } } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (core != null) { core.close(); } } if (!successfulRecovery) { // lets pause for a moment and we need to try again... // TODO: we don't want to retry for some problems? // Or do a fall off retry... try { SolrException.log(log, "Recovery failed - trying again..."); retries++; if (retries >= MAX_RETRIES) { if (retries == INTERRUPTED) { } else { // TODO: for now, give up after X tries - should we do more? core = cc.getCore(coreName); try { recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); } finally { if (core != null) { core.close(); } } } break; } } catch (Exception e) { SolrException.log(log, "", e); } try { Thread.sleep(Math.min(START_TIMEOUT * retries, 60000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } } log.info("Finished recovery process"); } }
diff --git a/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/i18n/ExternalizeStringsWizardPage.java b/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/i18n/ExternalizeStringsWizardPage.java index c09a3882..81d04da1 100644 --- a/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/i18n/ExternalizeStringsWizardPage.java +++ b/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/i18n/ExternalizeStringsWizardPage.java @@ -1,808 +1,811 @@ /******************************************************************************* * Copyright (c) 2007-2010 Exadel, Inc. and 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: * Exadel, Inc. and Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.jst.jsp.i18n; import java.util.HashSet; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.DialogPage; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.wst.xml.core.internal.document.AttrImpl; import org.eclipse.wst.xml.core.internal.document.TextImpl; import org.jboss.tools.common.model.loaders.impl.EncodedProperties; import org.jboss.tools.common.model.ui.ModelUIImages; import org.jboss.tools.jst.jsp.JspEditorPlugin; import org.jboss.tools.jst.jsp.bundle.BundleMap; import org.jboss.tools.jst.jsp.bundle.BundleMap.BundleEntry; import org.jboss.tools.jst.jsp.messages.JstUIMessages; import org.jboss.tools.jst.jsp.util.Constants; import org.w3c.dom.Attr; public class ExternalizeStringsWizardPage extends WizardPage { public static final String PAGE_NAME = "ExternalizeStringsWizardBasicPage"; //$NON-NLS-1$ private final int DIALOG_WIDTH = 450; private final int DIALOG_HEIGHT = 650; private Text propsKey; private Text propsValue; private Button newFile; private Label propsFileLabel; private Text propsFile; private Label rbListLabel; private Combo rbCombo; private BundleMap bm; private Group propsFilesGroup; private Status propsKeyStatus; private Status propsValueStatus; private Status duplicateKeyStatus; private Status duplicateValueStatus; private Table tagsTable; private IDocument document; private ISelectionProvider selectionProvider; /** * Creates the wizard page * * @param pageName * the name of the page * @param editor * the source text editor * @param bm * bundle map, or not null */ public ExternalizeStringsWizardPage(String pageName, BundleMap bm, IDocument document, ISelectionProvider selectionProvider) { /* * Setting dialog Title, Description, Image. */ super(pageName, JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_TITLE, ModelUIImages.getImageDescriptor(ModelUIImages.WIZARD_DEFAULT)); setDescription(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_DESCRIPTION); setPageComplete(false); this.bm=bm; this.document = document; this.selectionProvider = selectionProvider; propsKeyStatus = new Status(IStatus.OK, JspEditorPlugin.PLUGIN_ID, Constants.EMPTY); propsValueStatus = new Status(IStatus.OK, JspEditorPlugin.PLUGIN_ID, Constants.EMPTY); duplicateKeyStatus = new Status(IStatus.OK, JspEditorPlugin.PLUGIN_ID, Constants.EMPTY); duplicateValueStatus = new Status(IStatus.OK, JspEditorPlugin.PLUGIN_ID, Constants.EMPTY); } public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.widthHint = DIALOG_WIDTH; gd.heightHint = DIALOG_HEIGHT; composite.setLayoutData(gd); /* * Create properties string group */ Group propsStringGroup = new Group(composite, SWT.SHADOW_ETCHED_IN); propsStringGroup.setLayout(new GridLayout(3, false)); propsStringGroup.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 1, 1)); propsStringGroup.setText(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_PROPS_STRINGS_GROUP); /* * Create Properties Key label */ Label propsKeyLabel = new Label(propsStringGroup, SWT.NONE); propsKeyLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.NONE, false, false, 1, 1)); propsKeyLabel.setText(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_PROPERTIES_KEY); /* * Create Properties Key value */ propsKey = new Text(propsStringGroup, SWT.BORDER); propsKey.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 2, 1)); propsKey.setText(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_DEFAULT_KEY); /* * Create Properties Value label */ Label propsValueLabel = new Label(propsStringGroup, SWT.NONE); propsValueLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.NONE, false, false, 1, 1)); propsValueLabel.setText(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_PROPERTIES_VALUE); /* * Create Properties Value value */ propsValue = new Text(propsStringGroup, SWT.BORDER); propsValue.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 2, 1)); propsValue.setText(Constants.EMPTY); /* * Create New File Checkbox */ newFile = new Button(composite, SWT.CHECK); newFile.setLayoutData(new GridData(SWT.LEFT, SWT.NONE, false, false, 1, 1)); newFile.setText(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_NEW_FILE); /* * Create properties string group */ propsFilesGroup = new Group(composite, SWT.SHADOW_ETCHED_IN); propsFilesGroup.setLayout(new GridLayout(3, false)); gd = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); gd.heightHint = 300; propsFilesGroup.setLayoutData(gd); propsFilesGroup.setText(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_PROPS_FILES_GROUP); /* * Create Resource Bundles List label */ rbListLabel = new Label(propsFilesGroup, SWT.NONE); rbListLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.NONE, false, false, 1, 1)); rbListLabel.setText(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_RESOURCE_BUNDLE_LIST); /* * Create Resource Bundles combobox */ rbCombo = new Combo(propsFilesGroup, SWT.NONE); rbCombo.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 2, 1)); /* * Create Properties File label */ propsFileLabel = new Label(propsFilesGroup, SWT.NONE); propsFileLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.NONE, false,false, 1, 1)); propsFileLabel.setText(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_PROPERTIES_FILE); /* * Create Properties File path field */ propsFile = new Text(propsFilesGroup, SWT.BORDER); propsFile.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true,false, 2, 1)); propsFile.setText(Constants.EMPTY); propsFile.setEditable(false); /* * Create properties file table of content */ tagsTable = ExternalizeStringsUtils.createPropertiesTable(propsFilesGroup, SWT.BORDER); /* * Initialize all fields with real values. */ initializeFieldsAndAddLIsteners(); /* * Wizard Page control should be initialized. */ setControl(composite); } /** * Gets the bundle prefix. * * @return the bundle prefix */ public String getBundlePrefix() { String bundlePrefix = Constants.EMPTY; if (!isNewFile()) { for (BundleEntry be : bm.getBundles()) { if (be.uri.equalsIgnoreCase(rbCombo.getText())) { bundlePrefix = be.prefix; } } } return bundlePrefix; } /** * Gets resource bundle's file * @return the file */ public IFile getBundleFile() { return bm.getBundleFile(rbCombo.getText()); } /** * Use existed key-value pair from the properties file * without writing any data to the file. * * @return */ public boolean isDuplicatedKeyAndValue() { boolean exists = false; if (isValueDuplicated(propsValue.getText()) && isKeyDuplicated(propsKey.getText())) { exists = true; } return exists; } /** * Gets <code>key=value</code> pair * * @return a pair <code>key=value</code> */ public String getKeyValuePair() { /* * While initializing 'propsValue' field \t\r\n were replaced by \\\\t, etc. * Now we should return escaped characters, and during saving tha properties * they will treated as escape symbols as well. * Otherwise \\\\t string will be put into the properties file. */ String value = propsValue.getText(); if (value != null) { value = value.replaceAll("\\\\t", "\t"); //$NON-NLS-1$ //$NON-NLS-2$ value = value.replaceAll("\\\\r", "\r"); //$NON-NLS-1$ //$NON-NLS-2$ value = value.replaceAll("\\\\n", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ } return propsKey.getText() + Constants.EQUAL + EncodedProperties.saveConvert(value, true); } /** * Gets the key. * * @return the key */ public String getKey() { return propsKey.getText(); } /** * Check if "Create new file.." option is enabled * * @return the status */ public boolean isNewFile() { return newFile.getSelection(); } /** * Replaces the text in the current file */ public void replaceText(String replacement) { IDocument doc = getDocument(); ISelection sel = getSelectionProvider().getSelection(); if (ExternalizeStringsUtils.isSelectionCorrect(sel)) { try { /* * Get source text and new text */ TextSelection textSel = (TextSelection) sel; IStructuredSelection structuredSelection = (IStructuredSelection) sel; Object firstElement = structuredSelection.getFirstElement(); int offset = 0; int length = 0; /* * When user selection is empty * underlying node will e automatically selected. * Thus we need to correct replacement offsets. */ if ((textSel.getLength() != 0)) { offset = textSel.getOffset(); length = textSel.getLength(); } else if (firstElement instanceof TextImpl) { TextImpl ti = (TextImpl) firstElement; offset = ti.getStartOffset(); length = ti.getLength(); } else if (firstElement instanceof AttrImpl) { AttrImpl ai = (AttrImpl) firstElement; /* * Get offset and length without quotes ".." */ offset = ai.getValueRegionStartOffset() + 1; length = ai.getValueRegionText().length() - 2; } /* * Replace text in the editor with "key.value" */ doc.replace(offset, length, replacement); } catch (BadLocationException ex) { JspEditorPlugin.getPluginLog().logError(ex); } } } @Override public boolean isPageComplete() { boolean isPageComplete = false; /* * The page is ready when there are no error messages * and the bundle is selected * and "key=value" exists. */ if ((getErrorMessage() == null) && !Constants.EMPTY.equalsIgnoreCase(propsKey.getText().trim()) && !Constants.EMPTY.equalsIgnoreCase(propsValue.getText().trim()) && ((rbCombo.getSelectionIndex() != -1) || isNewFile())) { isPageComplete = true; } return isPageComplete; } @Override public boolean canFlipToNextPage() { return isPageComplete() && (getNextPage() != null) && isNewFile(); } /** * Initialize dialog's controls. * Fill in appropriate text and make validation. */ private void initializeFieldsAndAddLIsteners() { ISelection sel = getSelectionProvider().getSelection(); if (ExternalizeStringsUtils.isSelectionCorrect(sel)) { String text = Constants.EMPTY; String stringToUpdate = Constants.EMPTY; TextSelection textSelection = null; IStructuredSelection structuredSelection = (IStructuredSelection) sel; textSelection = (TextSelection) sel; text = textSelection.getText(); Object selectedElement = structuredSelection.getFirstElement(); /* * When selected text is empty * parse selected element and find a string to replace.. */ if ((text.trim().length() == 0)) { if (selectedElement instanceof org.w3c.dom.Text) { /* * ..it could be a plain text */ org.w3c.dom.Text textNode = (org.w3c.dom.Text) selectedElement; if (textNode.getNodeValue().trim().length() > 0) { stringToUpdate = textNode.getNodeValue(); getSelectionProvider().setSelection(new StructuredSelection(stringToUpdate)); } } else if (selectedElement instanceof Attr) { /* * ..or an attribute's value */ Attr attrNode = (Attr) selectedElement; if (attrNode.getNodeValue().trim().length() > 0) { stringToUpdate = attrNode.getNodeValue(); getSelectionProvider().setSelection(new StructuredSelection(stringToUpdate)); } } if ((stringToUpdate.trim().length() > 0)) { text = stringToUpdate; } } /* * https://issues.jboss.org/browse/JBIDE-9203 * Replace special characters with their string representation. * Key should be generated first. */ propsKey.setText(ExternalizeStringsUtils.generatePropertyKey(text)); /* * Replaced escaped symbols by strings. */ String value = text; if (value != null) { value = value.replaceAll("\t", "\\\\t"); //$NON-NLS-1$ //$NON-NLS-2$ value = value.replaceAll("\r", "\\\\r"); //$NON-NLS-1$ //$NON-NLS-2$ value = value.replaceAll("\n", "\\\\n"); //$NON-NLS-1$ //$NON-NLS-2$ } propsValue.setText(value); /* * Initialize bundle messages field */ if (bm == null) { JspEditorPlugin.getDefault().logWarning( JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_RB_IS_MISSING); } else { BundleEntry[] bundles = bm.getBundles(); Set<String> uriSet = new HashSet<String>(); for (BundleEntry bundleEntry : bundles) { if (!uriSet.contains(bundleEntry.uri)) { uriSet.add(bundleEntry.uri); rbCombo.add(bundleEntry.uri); } } /* * Select the first bundle if there is any in the list */ if (rbCombo.getItemCount() > 0) { rbCombo.select(0); setResourceBundlePath(rbCombo.getText()); } else { /* * https://jira.jboss.org/browse/JBIDE-7247 * Select 'Create new file' checkbox and * disable bundle group if no bundles are found. */ newFile.setSelection(true); enableBundleGroup(false); } } /* * Check the initial value status * When the same value is already externalized -- * suggest to use already created key as well. */ updatePropertiesValueStatus(); updateDuplicateValueStatus(); /* * When selected text is fine perform further validation */ if (propsValueStatus.isOK()) { /* * Check the bundle for the value in it. * if so -- show the warning and set correct key. */ if (!duplicateValueStatus.isOK()) { /* * Set the same key value */ propsKey.setText(getValueForKey(propsValue.getText())); /* * Set the new warning message */ applyStatus(this, new IStatus[] {duplicateValueStatus}); } else { /* * Check the initial key status * If there is the error - add sequence number to the key */ updateDuplicateKeyStatus(); while (!duplicateKeyStatus.isOK()) { int index = propsKey.getText().lastIndexOf('_'); String newKey = Constants.EMPTY; if (index != -1) { /* * String sequence at the end should be checked. * If it is a sequence number - it should be increased by 1. * If not - new number should be added. */ String numberString = propsKey.getText().substring(index + 1); int number; try { number = Integer.parseInt(numberString); number++; newKey = propsKey.getText().substring(0, index + 1) + number; } catch (NumberFormatException e) { newKey = propsKey.getText() + "_1"; //$NON-NLS-1$ } } else { /* * If the string has no sequence number - add it. */ newKey = propsKey.getText() + "_1"; //$NON-NLS-1$ } /* * Set the new key text */ propsKey.setText(newKey); updateDuplicateKeyStatus(); } /* * https://jira.jboss.org/browse/JBIDE-6945 * Set the greeting message only. * All the validation will take place in the fields' listeners * after user enters some new values. */ setMessage(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_ENTER_KEY_NAME, IMessageProvider.INFORMATION); } } else { /* * Set the message about wrong selected text. */ applyStatus(this, new IStatus[] {propsValueStatus}); } /* * Update the Buttons state. * When all the fields are correct -- * then user should be able to press OK */ setPageComplete(isPageComplete()); /* * Add selection listeners to the fields */ propsKey.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateStatus(); } }); propsKey.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent e) { for (int i = 0; i < ExternalizeStringsUtils.REPLACED_CHARACTERS.length; i++) { /* * Entering of the forbidden characters will be prevented. + * https://issues.jboss.org/browse/JBIDE-11551 + * Dot(.) should be supported. */ - if (e.character == ExternalizeStringsUtils.REPLACED_CHARACTERS[i]) { + if ((e.character == ExternalizeStringsUtils.REPLACED_CHARACTERS[i]) + && (e.character != '.')) { e.doit = false; break; } } } }); propsValue.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateStatus(); } }); newFile.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean selected = ((Button)e.getSource()).getSelection(); if (selected) { enableBundleGroup(false); } else { enableBundleGroup(true); } updateStatus(); } }); rbCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setResourceBundlePath(rbCombo.getText()); updateDuplicateKeyStatus(); updateStatus(); } }); } else { JspEditorPlugin.getDefault().logWarning( JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_INITIALIZATION_ERROR); } } /** * Checks keys in the selected resource bundle. * * @param key the key name * @return <code>true</code> if there is a key with the specified name */ private boolean isKeyDuplicated(String key) { boolean isDuplicated = false; if ((tagsTable.getItemCount() > 0) && (null != key) && !isNewFile()) { TableItem[] items = tagsTable.getItems(); for (TableItem tableItem : items) { if (key.equalsIgnoreCase(tableItem.getText(0))) { isDuplicated = true; break; } } } return isDuplicated; } /** * Checks values in the selected resource bundle. * * @param value the text string to externalize * @return <code>true</code> if there is a key with the specified name */ private boolean isValueDuplicated(String value) { boolean isDuplicated = false; if ((tagsTable.getItemCount() > 0) && (null != value) && !isNewFile()) { TableItem[] items = tagsTable.getItems(); for (TableItem tableItem : items) { if (value.equalsIgnoreCase(tableItem.getText(1))) { isDuplicated = true; break; } } } return isDuplicated; } /** * Returns the key for the specified value * from the visual table. * * @param value - the value * @return the key or empty string */ private String getValueForKey(String value) { String key = Constants.EMPTY; if ((tagsTable.getItemCount() > 0) && (null != value) && !isNewFile()) { TableItem[] items = tagsTable.getItems(); for (TableItem tableItem : items) { if (value.equalsIgnoreCase(tableItem.getText(1))) { key = tableItem.getText(0); break; } } } return key; } /** * Enables or disables resource bundle information * * @param enabled shows the status */ private void enableBundleGroup(boolean enabled) { propsFilesGroup.setEnabled(enabled); propsFileLabel.setEnabled(enabled); propsFile.setEnabled(enabled); rbListLabel.setEnabled(enabled); rbCombo.setEnabled(enabled); tagsTable.setEnabled(enabled); } /** * Update duplicate key status. */ private void updateDuplicateKeyStatus() { if (isKeyDuplicated(propsKey.getText())) { duplicateKeyStatus = new Status( IStatus.ERROR, JspEditorPlugin.PLUGIN_ID, JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_KEY_ALREADY_EXISTS); } else { duplicateKeyStatus = new Status(IStatus.OK, JspEditorPlugin.PLUGIN_ID, Constants.EMPTY); } } /** * Update duplicate key status. */ private void updateDuplicateValueStatus() { if (isValueDuplicated(propsValue.getText())) { duplicateValueStatus = new Status( IStatus.WARNING, JspEditorPlugin.PLUGIN_ID, JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_VALUE_EXISTS); } else { duplicateValueStatus = new Status(IStatus.OK, JspEditorPlugin.PLUGIN_ID, Constants.EMPTY); } } private void updatePropertiesValueStatus() { String text = propsValue.getText(); if ((text == null) || (Constants.EMPTY.equalsIgnoreCase(text.trim())) || (text.indexOf(Constants.GT) != -1) || (text.indexOf(Constants.LT) != -1)) { propsValueStatus = new Status( IStatus.ERROR, JspEditorPlugin.PLUGIN_ID, JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_WRONG_SELECTED_TEXT); } else { propsValueStatus = new Status(IStatus.OK, JspEditorPlugin.PLUGIN_ID, Constants.EMPTY); } } /** * Update properties key status. */ private void updatePropertiesKeyStatus() { if ((propsKey.getText() == null) || (Constants.EMPTY.equalsIgnoreCase(propsKey.getText().trim()))) { propsKeyStatus = new Status( IStatus.ERROR, JspEditorPlugin.PLUGIN_ID, JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_KEY_MUST_BE_SET); } else { propsKeyStatus = new Status(IStatus.OK, JspEditorPlugin.PLUGIN_ID, Constants.EMPTY); } } /** * Update page status. */ private void updateStatus() { /* * Update all statuses */ updatePropertiesKeyStatus(); updatePropertiesValueStatus(); updateDuplicateKeyStatus(); updateDuplicateValueStatus(); /* * Apply status to the dialog */ if (!duplicateValueStatus.isOK() && getValueForKey(propsValue.getText()) .equalsIgnoreCase(propsKey.getText())) { applyStatus(this, new IStatus[] { propsKeyStatus, propsValueStatus, duplicateValueStatus}); } else { applyStatus(this, new IStatus[] { propsKeyStatus, propsValueStatus, duplicateKeyStatus}); } /* * Set page complete */ setPageComplete(isPageComplete()); } /** * Apply status to the dialog. * * @param page the page * @param statuses all the statuses */ private void applyStatus(DialogPage page, IStatus[] statuses) { IStatus severeStatus = statuses[0]; for (IStatus status : statuses) { severeStatus = severeStatus.getSeverity() >= status.getSeverity() ? severeStatus : status; } String message = severeStatus.getMessage(); switch (severeStatus.getSeverity()) { case IStatus.OK: page.setMessage(null, IMessageProvider.NONE); page.setErrorMessage(null); break; case IStatus.WARNING: page.setMessage(message, IMessageProvider.WARNING); page.setErrorMessage(null); break; case IStatus.INFO: page.setMessage(message, IMessageProvider.INFORMATION); page.setErrorMessage(null); break; default: if (message.length() == 0) { message = null; } page.setMessage(null); page.setErrorMessage(message); break; } } /** * Sets the resource bundle path according to the selection * from the bundles list. * * @param bundleName the resource bundle name */ private void setResourceBundlePath(String bundleName) { IFile bundleFile = bm.getBundleFile(bundleName); String bundlePath = Constants.EMPTY; if (bundleFile != null) { bundlePath = bundleFile.getFullPath().toString(); ExternalizeStringsUtils.populatePropertiesTable(tagsTable, bundleFile); } else { JspEditorPlugin.getDefault().logError( "Could not get Bundle File for resource '" //$NON-NLS-1$ + bundleName + "'"); //$NON-NLS-1$ } propsFile.setText(bundlePath); } private ISelectionProvider getSelectionProvider(){ return selectionProvider; } private IDocument getDocument(){ return document; } }
false
true
private void initializeFieldsAndAddLIsteners() { ISelection sel = getSelectionProvider().getSelection(); if (ExternalizeStringsUtils.isSelectionCorrect(sel)) { String text = Constants.EMPTY; String stringToUpdate = Constants.EMPTY; TextSelection textSelection = null; IStructuredSelection structuredSelection = (IStructuredSelection) sel; textSelection = (TextSelection) sel; text = textSelection.getText(); Object selectedElement = structuredSelection.getFirstElement(); /* * When selected text is empty * parse selected element and find a string to replace.. */ if ((text.trim().length() == 0)) { if (selectedElement instanceof org.w3c.dom.Text) { /* * ..it could be a plain text */ org.w3c.dom.Text textNode = (org.w3c.dom.Text) selectedElement; if (textNode.getNodeValue().trim().length() > 0) { stringToUpdate = textNode.getNodeValue(); getSelectionProvider().setSelection(new StructuredSelection(stringToUpdate)); } } else if (selectedElement instanceof Attr) { /* * ..or an attribute's value */ Attr attrNode = (Attr) selectedElement; if (attrNode.getNodeValue().trim().length() > 0) { stringToUpdate = attrNode.getNodeValue(); getSelectionProvider().setSelection(new StructuredSelection(stringToUpdate)); } } if ((stringToUpdate.trim().length() > 0)) { text = stringToUpdate; } } /* * https://issues.jboss.org/browse/JBIDE-9203 * Replace special characters with their string representation. * Key should be generated first. */ propsKey.setText(ExternalizeStringsUtils.generatePropertyKey(text)); /* * Replaced escaped symbols by strings. */ String value = text; if (value != null) { value = value.replaceAll("\t", "\\\\t"); //$NON-NLS-1$ //$NON-NLS-2$ value = value.replaceAll("\r", "\\\\r"); //$NON-NLS-1$ //$NON-NLS-2$ value = value.replaceAll("\n", "\\\\n"); //$NON-NLS-1$ //$NON-NLS-2$ } propsValue.setText(value); /* * Initialize bundle messages field */ if (bm == null) { JspEditorPlugin.getDefault().logWarning( JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_RB_IS_MISSING); } else { BundleEntry[] bundles = bm.getBundles(); Set<String> uriSet = new HashSet<String>(); for (BundleEntry bundleEntry : bundles) { if (!uriSet.contains(bundleEntry.uri)) { uriSet.add(bundleEntry.uri); rbCombo.add(bundleEntry.uri); } } /* * Select the first bundle if there is any in the list */ if (rbCombo.getItemCount() > 0) { rbCombo.select(0); setResourceBundlePath(rbCombo.getText()); } else { /* * https://jira.jboss.org/browse/JBIDE-7247 * Select 'Create new file' checkbox and * disable bundle group if no bundles are found. */ newFile.setSelection(true); enableBundleGroup(false); } } /* * Check the initial value status * When the same value is already externalized -- * suggest to use already created key as well. */ updatePropertiesValueStatus(); updateDuplicateValueStatus(); /* * When selected text is fine perform further validation */ if (propsValueStatus.isOK()) { /* * Check the bundle for the value in it. * if so -- show the warning and set correct key. */ if (!duplicateValueStatus.isOK()) { /* * Set the same key value */ propsKey.setText(getValueForKey(propsValue.getText())); /* * Set the new warning message */ applyStatus(this, new IStatus[] {duplicateValueStatus}); } else { /* * Check the initial key status * If there is the error - add sequence number to the key */ updateDuplicateKeyStatus(); while (!duplicateKeyStatus.isOK()) { int index = propsKey.getText().lastIndexOf('_'); String newKey = Constants.EMPTY; if (index != -1) { /* * String sequence at the end should be checked. * If it is a sequence number - it should be increased by 1. * If not - new number should be added. */ String numberString = propsKey.getText().substring(index + 1); int number; try { number = Integer.parseInt(numberString); number++; newKey = propsKey.getText().substring(0, index + 1) + number; } catch (NumberFormatException e) { newKey = propsKey.getText() + "_1"; //$NON-NLS-1$ } } else { /* * If the string has no sequence number - add it. */ newKey = propsKey.getText() + "_1"; //$NON-NLS-1$ } /* * Set the new key text */ propsKey.setText(newKey); updateDuplicateKeyStatus(); } /* * https://jira.jboss.org/browse/JBIDE-6945 * Set the greeting message only. * All the validation will take place in the fields' listeners * after user enters some new values. */ setMessage(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_ENTER_KEY_NAME, IMessageProvider.INFORMATION); } } else { /* * Set the message about wrong selected text. */ applyStatus(this, new IStatus[] {propsValueStatus}); } /* * Update the Buttons state. * When all the fields are correct -- * then user should be able to press OK */ setPageComplete(isPageComplete()); /* * Add selection listeners to the fields */ propsKey.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateStatus(); } }); propsKey.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent e) { for (int i = 0; i < ExternalizeStringsUtils.REPLACED_CHARACTERS.length; i++) { /* * Entering of the forbidden characters will be prevented. */ if (e.character == ExternalizeStringsUtils.REPLACED_CHARACTERS[i]) { e.doit = false; break; } } } }); propsValue.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateStatus(); } }); newFile.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean selected = ((Button)e.getSource()).getSelection(); if (selected) { enableBundleGroup(false); } else { enableBundleGroup(true); } updateStatus(); } }); rbCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setResourceBundlePath(rbCombo.getText()); updateDuplicateKeyStatus(); updateStatus(); } }); } else { JspEditorPlugin.getDefault().logWarning( JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_INITIALIZATION_ERROR); } }
private void initializeFieldsAndAddLIsteners() { ISelection sel = getSelectionProvider().getSelection(); if (ExternalizeStringsUtils.isSelectionCorrect(sel)) { String text = Constants.EMPTY; String stringToUpdate = Constants.EMPTY; TextSelection textSelection = null; IStructuredSelection structuredSelection = (IStructuredSelection) sel; textSelection = (TextSelection) sel; text = textSelection.getText(); Object selectedElement = structuredSelection.getFirstElement(); /* * When selected text is empty * parse selected element and find a string to replace.. */ if ((text.trim().length() == 0)) { if (selectedElement instanceof org.w3c.dom.Text) { /* * ..it could be a plain text */ org.w3c.dom.Text textNode = (org.w3c.dom.Text) selectedElement; if (textNode.getNodeValue().trim().length() > 0) { stringToUpdate = textNode.getNodeValue(); getSelectionProvider().setSelection(new StructuredSelection(stringToUpdate)); } } else if (selectedElement instanceof Attr) { /* * ..or an attribute's value */ Attr attrNode = (Attr) selectedElement; if (attrNode.getNodeValue().trim().length() > 0) { stringToUpdate = attrNode.getNodeValue(); getSelectionProvider().setSelection(new StructuredSelection(stringToUpdate)); } } if ((stringToUpdate.trim().length() > 0)) { text = stringToUpdate; } } /* * https://issues.jboss.org/browse/JBIDE-9203 * Replace special characters with their string representation. * Key should be generated first. */ propsKey.setText(ExternalizeStringsUtils.generatePropertyKey(text)); /* * Replaced escaped symbols by strings. */ String value = text; if (value != null) { value = value.replaceAll("\t", "\\\\t"); //$NON-NLS-1$ //$NON-NLS-2$ value = value.replaceAll("\r", "\\\\r"); //$NON-NLS-1$ //$NON-NLS-2$ value = value.replaceAll("\n", "\\\\n"); //$NON-NLS-1$ //$NON-NLS-2$ } propsValue.setText(value); /* * Initialize bundle messages field */ if (bm == null) { JspEditorPlugin.getDefault().logWarning( JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_RB_IS_MISSING); } else { BundleEntry[] bundles = bm.getBundles(); Set<String> uriSet = new HashSet<String>(); for (BundleEntry bundleEntry : bundles) { if (!uriSet.contains(bundleEntry.uri)) { uriSet.add(bundleEntry.uri); rbCombo.add(bundleEntry.uri); } } /* * Select the first bundle if there is any in the list */ if (rbCombo.getItemCount() > 0) { rbCombo.select(0); setResourceBundlePath(rbCombo.getText()); } else { /* * https://jira.jboss.org/browse/JBIDE-7247 * Select 'Create new file' checkbox and * disable bundle group if no bundles are found. */ newFile.setSelection(true); enableBundleGroup(false); } } /* * Check the initial value status * When the same value is already externalized -- * suggest to use already created key as well. */ updatePropertiesValueStatus(); updateDuplicateValueStatus(); /* * When selected text is fine perform further validation */ if (propsValueStatus.isOK()) { /* * Check the bundle for the value in it. * if so -- show the warning and set correct key. */ if (!duplicateValueStatus.isOK()) { /* * Set the same key value */ propsKey.setText(getValueForKey(propsValue.getText())); /* * Set the new warning message */ applyStatus(this, new IStatus[] {duplicateValueStatus}); } else { /* * Check the initial key status * If there is the error - add sequence number to the key */ updateDuplicateKeyStatus(); while (!duplicateKeyStatus.isOK()) { int index = propsKey.getText().lastIndexOf('_'); String newKey = Constants.EMPTY; if (index != -1) { /* * String sequence at the end should be checked. * If it is a sequence number - it should be increased by 1. * If not - new number should be added. */ String numberString = propsKey.getText().substring(index + 1); int number; try { number = Integer.parseInt(numberString); number++; newKey = propsKey.getText().substring(0, index + 1) + number; } catch (NumberFormatException e) { newKey = propsKey.getText() + "_1"; //$NON-NLS-1$ } } else { /* * If the string has no sequence number - add it. */ newKey = propsKey.getText() + "_1"; //$NON-NLS-1$ } /* * Set the new key text */ propsKey.setText(newKey); updateDuplicateKeyStatus(); } /* * https://jira.jboss.org/browse/JBIDE-6945 * Set the greeting message only. * All the validation will take place in the fields' listeners * after user enters some new values. */ setMessage(JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_ENTER_KEY_NAME, IMessageProvider.INFORMATION); } } else { /* * Set the message about wrong selected text. */ applyStatus(this, new IStatus[] {propsValueStatus}); } /* * Update the Buttons state. * When all the fields are correct -- * then user should be able to press OK */ setPageComplete(isPageComplete()); /* * Add selection listeners to the fields */ propsKey.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateStatus(); } }); propsKey.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent e) { for (int i = 0; i < ExternalizeStringsUtils.REPLACED_CHARACTERS.length; i++) { /* * Entering of the forbidden characters will be prevented. * https://issues.jboss.org/browse/JBIDE-11551 * Dot(.) should be supported. */ if ((e.character == ExternalizeStringsUtils.REPLACED_CHARACTERS[i]) && (e.character != '.')) { e.doit = false; break; } } } }); propsValue.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateStatus(); } }); newFile.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean selected = ((Button)e.getSource()).getSelection(); if (selected) { enableBundleGroup(false); } else { enableBundleGroup(true); } updateStatus(); } }); rbCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setResourceBundlePath(rbCombo.getText()); updateDuplicateKeyStatus(); updateStatus(); } }); } else { JspEditorPlugin.getDefault().logWarning( JstUIMessages.EXTERNALIZE_STRINGS_DIALOG_INITIALIZATION_ERROR); } }
diff --git a/TFC_Shared/src/TFC/Containers/ContainerTerraForge.java b/TFC_Shared/src/TFC/Containers/ContainerTerraForge.java index e35f9fd55..7d072aa05 100644 --- a/TFC_Shared/src/TFC/Containers/ContainerTerraForge.java +++ b/TFC_Shared/src/TFC/Containers/ContainerTerraForge.java @@ -1,239 +1,238 @@ package TFC.Containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import TFC.Core.HeatManager; import TFC.Items.ItemOre; import TFC.TileEntities.TileEntityForge; public class ContainerTerraForge extends ContainerTFC { private TileEntityForge forge; private int coolTime; private int freezeTime; private int itemFreezeTime; private float firetemp; public ContainerTerraForge(InventoryPlayer inventoryplayer, TileEntityForge tileentityforge, World world, int x, int y, int z) { forge = tileentityforge; coolTime = 0; freezeTime = 0; itemFreezeTime = 0; //Input slot addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 0, 44, 8)); addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 1, 62, 26)); addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 2, 80, 44)); addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 3, 98, 26)); addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 4, 116, 8)); //fuel stack addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 5, 44, 26)); addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 6, 62, 44)); addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 7, 80, 62)); addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 8, 98, 44)); addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 9, 116, 26)); //Storage slot addSlotToContainer(new Slot(tileentityforge, 10, 152, 8)); addSlotToContainer(new Slot(tileentityforge, 11, 152, 26)); addSlotToContainer(new Slot(tileentityforge, 12, 152, 44)); addSlotToContainer(new Slot(tileentityforge, 13, 152, 62)); for(int i = 0; i < 3; i++) { for(int k = 0; k < 9; k++) { addSlotToContainer(new Slot(inventoryplayer, k + i * 9 + 9, 8 + k * 18, 84 + i * 18)); } } for(int j = 0; j < 9; j++) { addSlotToContainer(new Slot(inventoryplayer, j, 8 + j * 18, 142)); } } @Override public boolean canInteractWith(EntityPlayer entityplayer) { return true; } @Override public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { Slot slot = (Slot)inventorySlots.get(i); Slot[] slotinput = {(Slot)inventorySlots.get(2), (Slot)inventorySlots.get(1), (Slot)inventorySlots.get(3), (Slot)inventorySlots.get(0), (Slot)inventorySlots.get(4)}; Slot[] slotstorage = {(Slot)inventorySlots.get(10), (Slot)inventorySlots.get(11), (Slot)inventorySlots.get(12), (Slot)inventorySlots.get(13)}; Slot[] slotfuel = {(Slot)inventorySlots.get(7), (Slot)inventorySlots.get(6), (Slot)inventorySlots.get(8), (Slot)inventorySlots.get(5), (Slot)inventorySlots.get(9)}; HeatManager manager = HeatManager.getInstance(); if(slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); if(i <= 13) { - if(!entityplayer.inventory.addItemStackToInventory(itemstack1.copy())) + if(!this.mergeItemStack(itemstack1, 14, this.inventorySlots.size(), true)) { return null; } - slot.putStack(null); } else { if(itemstack1.itemID == Item.coal.itemID) { int j = 0; while(j < 5) { if(slotfuel[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotfuel[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else if(!(itemstack1.getItem() instanceof ItemOre) && manager.findMatchingIndex(itemstack1) != null) { int j = 0; while(j < 5) { if(slotinput[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotinput[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else { int j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } if(itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } } return null; } @Override public void detectAndSendChanges() { for (int var1 = 0; var1 < this.inventorySlots.size(); ++var1) { ItemStack var2 = ((Slot)this.inventorySlots.get(var1)).getStack(); ItemStack var3 = (ItemStack)this.inventoryItemStacks.get(var1); if (!ItemStack.areItemStacksEqual(var3, var2)) { var3 = var2 == null ? null : var2.copy(); this.inventoryItemStacks.set(var1, var3); for (int var4 = 0; var4 < this.crafters.size(); ++var4) { ((ICrafting)this.crafters.get(var4)).sendSlotContents(this, var1, var3); } } } for (int var1 = 0; var1 < this.crafters.size(); ++var1) { ICrafting var2 = (ICrafting)this.crafters.get(var1); if (this.firetemp != this.forge.fireTemperature) { var2.sendProgressBarUpdate(this, 0, (int)this.forge.fireTemperature); } } firetemp = this.forge.fireTemperature; } @Override public void updateProgressBar(int par1, int par2) { if (par1 == 0) { this.forge.fireTemperature = par2; } } }
false
true
public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { Slot slot = (Slot)inventorySlots.get(i); Slot[] slotinput = {(Slot)inventorySlots.get(2), (Slot)inventorySlots.get(1), (Slot)inventorySlots.get(3), (Slot)inventorySlots.get(0), (Slot)inventorySlots.get(4)}; Slot[] slotstorage = {(Slot)inventorySlots.get(10), (Slot)inventorySlots.get(11), (Slot)inventorySlots.get(12), (Slot)inventorySlots.get(13)}; Slot[] slotfuel = {(Slot)inventorySlots.get(7), (Slot)inventorySlots.get(6), (Slot)inventorySlots.get(8), (Slot)inventorySlots.get(5), (Slot)inventorySlots.get(9)}; HeatManager manager = HeatManager.getInstance(); if(slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); if(i <= 13) { if(!entityplayer.inventory.addItemStackToInventory(itemstack1.copy())) { return null; } slot.putStack(null); } else { if(itemstack1.itemID == Item.coal.itemID) { int j = 0; while(j < 5) { if(slotfuel[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotfuel[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else if(!(itemstack1.getItem() instanceof ItemOre) && manager.findMatchingIndex(itemstack1) != null) { int j = 0; while(j < 5) { if(slotinput[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotinput[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else { int j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } if(itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } } return null; }
public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { Slot slot = (Slot)inventorySlots.get(i); Slot[] slotinput = {(Slot)inventorySlots.get(2), (Slot)inventorySlots.get(1), (Slot)inventorySlots.get(3), (Slot)inventorySlots.get(0), (Slot)inventorySlots.get(4)}; Slot[] slotstorage = {(Slot)inventorySlots.get(10), (Slot)inventorySlots.get(11), (Slot)inventorySlots.get(12), (Slot)inventorySlots.get(13)}; Slot[] slotfuel = {(Slot)inventorySlots.get(7), (Slot)inventorySlots.get(6), (Slot)inventorySlots.get(8), (Slot)inventorySlots.get(5), (Slot)inventorySlots.get(9)}; HeatManager manager = HeatManager.getInstance(); if(slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); if(i <= 13) { if(!this.mergeItemStack(itemstack1, 14, this.inventorySlots.size(), true)) { return null; } } else { if(itemstack1.itemID == Item.coal.itemID) { int j = 0; while(j < 5) { if(slotfuel[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotfuel[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else if(!(itemstack1.getItem() instanceof ItemOre) && manager.findMatchingIndex(itemstack1) != null) { int j = 0; while(j < 5) { if(slotinput[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotinput[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else { int j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } if(itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } } return null; }
diff --git a/src/main/java/org/spoutcraft/launcher/SpoutcraftBuild.java b/src/main/java/org/spoutcraft/launcher/SpoutcraftBuild.java index fde3754..f3fa1be 100644 --- a/src/main/java/org/spoutcraft/launcher/SpoutcraftBuild.java +++ b/src/main/java/org/spoutcraft/launcher/SpoutcraftBuild.java @@ -1,82 +1,82 @@ package org.spoutcraft.launcher; import java.util.Map; import org.bukkit.util.config.Configuration; import org.spoutcraft.launcher.async.DownloadListener; public class SpoutcraftBuild { private String minecraftVersion; private String latestVersion; private int build; private DownloadListener listener = null; public SpoutcraftBuild(String minecraft, String latest, int build) { this.minecraftVersion = minecraft; this.latestVersion = latest; this.build = build; } public int getBuild() { return build; } public String getMinecraftVersion() { return minecraftVersion; } public String getLatestMinecraftVersion() { return latestVersion; } public String getMinecraftURL(String user) { return "http://s3.amazonaws.com/MinecraftDownload/minecraft.jar?user=" + user + "&ticket=1"; } public String getSpoutcraftURL() { return MirrorUtils.getMirrorUrl("Spoutcraft/" + build + "/spoutcraft-dev-SNAPSHOT.jar", null, listener); } public void setDownloadListener(DownloadListener listener) { this.listener = listener; } public void install() { Configuration config = SpoutcraftYML.getSpoutcraftYML(); config.setProperty("current", getBuild()); } public int getInstalledBuild() { Configuration config = SpoutcraftYML.getSpoutcraftYML(); return config.getInt("current", -1); } public String getPatchURL() { String mirrorURL = "/Patches/Minecraft/minecraft_"; mirrorURL += getLatestMinecraftVersion(); mirrorURL += "-" + getMinecraftVersion() + ".patch"; String fallbackURL = "http://mirror3.getspout.org/Patches/Minecraft/minecraft_"; fallbackURL += getLatestMinecraftVersion(); fallbackURL += "-" + getMinecraftVersion() + ".patch"; return MirrorUtils.getMirrorUrl(mirrorURL, fallbackURL, null); } @SuppressWarnings("unchecked") public static SpoutcraftBuild getSpoutcraftBuild() { Configuration config = SpoutcraftYML.getSpoutcraftYML(); Map<Integer, Object> builds = (Map<Integer, Object>) config.getProperty("builds"); int latest = config.getInt("latest", -1); int recommended = config.getInt("recommended", -1); int selected = SettingsUtil.getSelectedBuild(); if (SettingsUtil.isRecommendedBuild()) { Map<String, Object> build = (Map<String, Object>) builds.get(recommended); return new SpoutcraftBuild((String)build.get("minecraft"), MinecraftYML.getLatestMinecraftVersion(), recommended); } else if (SettingsUtil.isDevelopmentBuild()) { - Map<String, Object> build = (Map<String, Object>) builds.get(recommended); + Map<String, Object> build = (Map<String, Object>) builds.get(latest); return new SpoutcraftBuild((String)build.get("minecraft"), MinecraftYML.getLatestMinecraftVersion(), latest); } - Map<String, Object> build = (Map<String, Object>) builds.get(recommended); + Map<String, Object> build = (Map<String, Object>) builds.get(selected); return new SpoutcraftBuild((String)build.get("minecraft"), MinecraftYML.getLatestMinecraftVersion(), selected); } }
false
true
public static SpoutcraftBuild getSpoutcraftBuild() { Configuration config = SpoutcraftYML.getSpoutcraftYML(); Map<Integer, Object> builds = (Map<Integer, Object>) config.getProperty("builds"); int latest = config.getInt("latest", -1); int recommended = config.getInt("recommended", -1); int selected = SettingsUtil.getSelectedBuild(); if (SettingsUtil.isRecommendedBuild()) { Map<String, Object> build = (Map<String, Object>) builds.get(recommended); return new SpoutcraftBuild((String)build.get("minecraft"), MinecraftYML.getLatestMinecraftVersion(), recommended); } else if (SettingsUtil.isDevelopmentBuild()) { Map<String, Object> build = (Map<String, Object>) builds.get(recommended); return new SpoutcraftBuild((String)build.get("minecraft"), MinecraftYML.getLatestMinecraftVersion(), latest); } Map<String, Object> build = (Map<String, Object>) builds.get(recommended); return new SpoutcraftBuild((String)build.get("minecraft"), MinecraftYML.getLatestMinecraftVersion(), selected); }
public static SpoutcraftBuild getSpoutcraftBuild() { Configuration config = SpoutcraftYML.getSpoutcraftYML(); Map<Integer, Object> builds = (Map<Integer, Object>) config.getProperty("builds"); int latest = config.getInt("latest", -1); int recommended = config.getInt("recommended", -1); int selected = SettingsUtil.getSelectedBuild(); if (SettingsUtil.isRecommendedBuild()) { Map<String, Object> build = (Map<String, Object>) builds.get(recommended); return new SpoutcraftBuild((String)build.get("minecraft"), MinecraftYML.getLatestMinecraftVersion(), recommended); } else if (SettingsUtil.isDevelopmentBuild()) { Map<String, Object> build = (Map<String, Object>) builds.get(latest); return new SpoutcraftBuild((String)build.get("minecraft"), MinecraftYML.getLatestMinecraftVersion(), latest); } Map<String, Object> build = (Map<String, Object>) builds.get(selected); return new SpoutcraftBuild((String)build.get("minecraft"), MinecraftYML.getLatestMinecraftVersion(), selected); }
diff --git a/src/org/apache/xerces/impl/v2/SchemaValidator.java b/src/org/apache/xerces/impl/v2/SchemaValidator.java index 539e1e05..eb543eca 100644 --- a/src/org/apache/xerces/impl/v2/SchemaValidator.java +++ b/src/org/apache/xerces/impl/v2/SchemaValidator.java @@ -1,2704 +1,2705 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999,2000,2001 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.impl.v2; import org.apache.xerces.impl.v2.datatypes.*; import org.apache.xerces.impl.v2.identity.*; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.msg.XMLMessageFormatter; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLInputSource; import java.io.IOException; import org.apache.xerces.util.NamespaceSupport; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLChar; import org.apache.xerces.util.IntStack; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLDTDHandler; import org.apache.xerces.xni.XMLDTDContentModelHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDocumentFilter; import java.util.Enumeration; import java.util.Hashtable; import java.util.Stack; import java.util.Vector; import java.util.StringTokenizer; /** * The DTD validator. The validator implements a document * filter: receiving document events from the scanner; validating * the content and structure; augmenting the InfoSet, if applicable; * and notifying the parser of the information resulting from the * validation process. * <p> * This component requires the following features and properties from the * component manager that uses it: * <ul> * <li>http://xml.org/sax/features/validation</li> * <li>http://apache.org/xml/properties/internal/symbol-table</li> * <li>http://apache.org/xml/properties/internal/error-reporter</li> * <li>http://apache.org/xml/properties/internal/entity-resolver</li> * </ul> * * @author Eric Ye, IBM * @author Stubs generated by DesignDoc on Mon Sep 11 11:10:57 PDT 2000 * @author Andy Clark, IBM * @author Jeffrey Rodriguez IBM * * @version $Id$ */ public class SchemaValidator implements XMLComponent, XMLDocumentFilter, FieldActivator // for identity constraints { // // Constants // private static final boolean DEBUG = false; // feature identifiers /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** Feature identifier: dynamic validation. */ protected static final String DYNAMIC_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE; // property identifiers /** Property identifier: symbol table. */ protected static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error reporter. */ protected static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: entiry resolver. */ protected static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; // REVISIT: this is just a temporary solution for entity resolver // while we are making a decision protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; // recognized features and properties /** Recognized features. */ protected static final String[] RECOGNIZED_FEATURES = { VALIDATION, DYNAMIC_VALIDATION, }; /** Recognized properties. */ protected static final String[] RECOGNIZED_PROPERTIES = { SYMBOL_TABLE, ERROR_REPORTER, ENTITY_RESOLVER, }; // // Data // // features /** Validation. */ protected boolean fValidation = false; protected boolean fDynamicValidation = false; protected boolean fDoValidation = false; // properties /** Symbol table. */ protected SymbolTable fSymbolTable; /** Error reporter. */ protected XMLErrorReporter fErrorReporter; /** Entity resolver */ protected XMLEntityResolver fEntityResolver; // handlers /** Document handler. */ protected XMLDocumentHandler fDocumentHandler; // // XMLComponent methods // /* * Resets the component. The component can query the component manager * about any features and properties that affect the operation of the * component. * * @param componentManager The component manager. * * @throws SAXException Thrown by component on finitialization error. * For example, if a feature or property is * required for the operation of the component, the * component manager may throw a * SAXNotRecognizedException or a * SAXNotSupportedException. */ public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { ownReset(componentManager); } // reset(XMLComponentManager) /** * Returns a list of feature identifiers that are recognized by * this component. This method may return null if no features * are recognized by this component. */ public String[] getRecognizedFeatures() { return RECOGNIZED_FEATURES; } // getRecognizedFeatures():String[] /** * Sets the state of a feature. This method is called by the component * manager any time after reset when a feature changes state. * <p> * <strong>Note:</strong> Components should silently ignore features * that do not affect the operation of the component. * * @param featureId The feature identifier. * @param state The state of the feature. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { if (featureId.equals(VALIDATION)) fValidation = state; else if (featureId.equals(DYNAMIC_VALIDATION)) fDynamicValidation = state; } // setFeature(String,boolean) /** * Returns a list of property identifiers that are recognized by * this component. This method may return null if no properties * are recognized by this component. */ public String[] getRecognizedProperties() { return RECOGNIZED_PROPERTIES; } // getRecognizedProperties():String[] /** * Sets the value of a property. This method is called by the component * manager any time after reset when a property changes value. * <p> * <strong>Note:</strong> Components should silently ignore properties * that do not affect the operation of the component. * * @param propertyId The property identifier. * @param value The value of the property. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { } // setProperty(String,Object) // // XMLDocumentSource methods // /** * Sets the document handler to receive information about the document. * * @param documentHandler The document handler. */ public void setDocumentHandler(XMLDocumentHandler documentHandler) { fDocumentHandler = documentHandler; } // setDocumentHandler(XMLDocumentHandler) // // XMLDocumentHandler methods // /** * The start of the document. * * @param systemId The system identifier of the entity if the entity * is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument(XMLLocator locator, String encoding) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.startDocument(locator, encoding); } if(fValidation) fValueStoreCache.startDocument(); } // startDocument(XMLLocator,String) /** * Notifies of the presence of an XMLDecl line in the document. If * present, this method will be called immediately following the * startDocument call. * * @param version The XML version. * @param encoding The IANA encoding name of the document, or null if * not specified. * @param standalone The standalone value, or null if not specified. * * @throws XNIException Thrown by handler to signal an error. */ public void xmlDecl(String version, String encoding, String standalone) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.xmlDecl(version, encoding, standalone); } } // xmlDecl(String,String,String) /** * Notifies of the presence of the DOCTYPE line in the document. * * @param rootElement The name of the root element. * @param publicId The public identifier if an external DTD or null * if the external DTD is specified using SYSTEM. * @param systemId The system identifier if an external DTD, null * otherwise. * * @throws XNIException Thrown by handler to signal an error. */ public void doctypeDecl(String rootElement, String publicId, String systemId) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.doctypeDecl(rootElement, publicId, systemId); } } // doctypeDecl(String,String,String) /** * The start of a namespace prefix mapping. This method will only be * called when namespace processing is enabled. * * @param prefix The namespace prefix. * @param uri The URI bound to the prefix. * * @throws XNIException Thrown by handler to signal an error. */ public void startPrefixMapping(String prefix, String uri) throws XNIException { handleStartPrefix(prefix, uri); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startPrefixMapping(prefix, uri); } } // startPrefixMapping(String,String) /** * The start of an element. * * @param element The name of the element. * @param attributes The element attributes. * * @throws XNIException Thrown by handler to signal an error. */ public void startElement(QName element, XMLAttributes attributes) throws XNIException { handleStartElement(element, attributes); if (fDocumentHandler != null) { fDocumentHandler.startElement(element, attributes); } } // startElement(QName,XMLAttributes) /** * An empty element. * * @param element The name of the element. * @param attributes The element attributes. * * @throws XNIException Thrown by handler to signal an error. */ public void emptyElement(QName element, XMLAttributes attributes) throws XNIException { handleStartElement(element, attributes); handleEndElement(element); if (fDocumentHandler != null) { fDocumentHandler.emptyElement(element, attributes); } } // emptyElement(QName,XMLAttributes) /** * Character content. * * @param text The content. * * @throws XNIException Thrown by handler to signal an error. */ public void characters(XMLString text) throws XNIException { if (fSkipValidationDepth >= 0) return; boolean allWhiteSpace = true; for (int i=text.offset; i< text.offset+text.length; i++) { if (!XMLChar.isSpace(text.ch[i])) { allWhiteSpace = false; break; } } fBuffer.append(text.toString()); if (!allWhiteSpace) { fSawCharacters = true; } // call handlers if (fDocumentHandler != null) { fDocumentHandler.characters(text); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.characters(text); } } // characters(XMLString) /** * Ignorable whitespace. For this method to be called, the document * source must have some way of determining that the text containing * only whitespace characters should be considered ignorable. For * example, the validator can determine if a length of whitespace * characters in the document are ignorable based on the element * content model. * * @param text The ignorable whitespace. * * @throws XNIException Thrown by handler to signal an error. */ public void ignorableWhitespace(XMLString text) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.ignorableWhitespace(text); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.characters(text); } } // ignorableWhitespace(XMLString) /** * The end of an element. * * @param element The name of the element. * * @throws XNIException Thrown by handler to signal an error. */ public void endElement(QName element) throws XNIException { handleEndElement(element); if (fDocumentHandler != null) { fDocumentHandler.endElement(element); } } // endElement(QName) /** * The end of a namespace prefix mapping. This method will only be * called when namespace processing is enabled. * * @param prefix The namespace prefix. * * @throws XNIException Thrown by handler to signal an error. */ public void endPrefixMapping(String prefix) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.endPrefixMapping(prefix); } } // endPrefixMapping(String) /** * The start of a CDATA section. * * @throws XNIException Thrown by handler to signal an error. */ public void startCDATA() throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.startCDATA(); } } // startCDATA() /** * The end of a CDATA section. * * @throws XNIException Thrown by handler to signal an error. */ public void endCDATA() throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.endCDATA(); } } // endCDATA() /** * The end of the document. * * @throws XNIException Thrown by handler to signal an error. */ public void endDocument() throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.endDocument(); } if(fValidation) fValueStoreCache.endDocument(); } // endDocument() // // XMLDocumentHandler and XMLDTDHandler methods // /** * This method notifies of the start of an entity. The DTD has the * pseudo-name of "[dtd]; parameter entity names start with '%'; and * general entity names are just the entity name. * <p> * <strong>Note:</strong> Since the DTD is an entity, the handler * will be notified of the start of the DTD entity by calling the * startEntity method with the entity name "[dtd]" <em>before</em> calling * the startDTD method. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * @param publicId The public identifier of the entity if the entity * is external, null otherwise. * @param systemId The system identifier of the entity if the entity * is external, null otherwise. * @param baseSystemId The base system identifier of the entity if * the entity is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal parameter entities). * * @throws XNIException Thrown by handler to signal an error. */ public void startEntity(String name, String publicId, String systemId, String baseSystemId, String encoding) throws XNIException { if (fDocumentHandler != null) { fDocumentHandler.startEntity(name, publicId, systemId, baseSystemId, encoding); } } // startEntity(String,String,String,String,String) /** * Notifies of the presence of a TextDecl line in an entity. If present, * this method will be called immediately following the startEntity call. * <p> * <strong>Note:</strong> This method will never be called for the * document entity; it is only called for external general entities * referenced in document content. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param version The XML version, or null if not specified. * @param encoding The IANA encoding name of the entity. * * @throws XNIException Thrown by handler to signal an error. */ public void textDecl(String version, String encoding) throws XNIException { if (fDocumentHandler != null) { fDocumentHandler.textDecl(version, encoding); } } // textDecl(String,String) /** * A comment. * * @param text The text in the comment. * * @throws XNIException Thrown by application to signal an error. */ public void comment(XMLString text) throws XNIException { if (fDocumentHandler != null) { fDocumentHandler.comment(text); } } // comment(XMLString) /** * A processing instruction. Processing instructions consist of a * target name and, optionally, text data. The data is only meaningful * to the application. * <p> * Typically, a processing instruction's data will contain a series * of pseudo-attributes. These pseudo-attributes follow the form of * element attributes but are <strong>not</strong> parsed or presented * to the application as anything other than text. The application is * responsible for parsing the data. * * @param target The target. * @param data The data or null if none specified. * * @throws XNIException Thrown by handler to signal an error. */ public void processingInstruction(String target, XMLString data) throws XNIException { if (fDocumentHandler != null) { fDocumentHandler.processingInstruction(target, data); } } // processingInstruction(String,XMLString) /** * This method notifies the end of an entity. The DTD has the pseudo-name * of "[dtd]; parameter entity names start with '%'; and general entity * names are just the entity name. * <p> * <strong>Note:</strong> Since the DTD is an entity, the handler * will be notified of the end of the DTD entity by calling the * endEntity method with the entity name "[dtd]" <em>after</em> calling * the endDTD method. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * * @throws XNIException Thrown by handler to signal an error. */ public void endEntity(String name) throws XNIException { if (fDocumentHandler != null) { fDocumentHandler.endEntity(name); } } // endEntity(String) // constants static final int INITIAL_STACK_SIZE = 8; static final int INC_STACK_SIZE = 8; // some constants that'll be added into the symbol table String XMLNS; String URI_XSI; String XSI_SCHEMALOCATION; String XSI_NONAMESPACESCHEMALOCATION; String XSI_TYPE; String XSI_NIL; String URI_SCHEMAFORSCHEMA; // // Data // /** Schema grammar resolver. */ final XSGrammarResolver fGrammarResolver; /** Schema handler */ final XSDHandler fSchemaHandler; /** Namespace support. */ final NamespaceSupport fNamespaceSupport = new NamespaceSupport(); /** this flag is used to indicate whether the next prefix binding * should start a new context (.pushContext) */ boolean fPushForNextBinding; /** the DV usd to convert xsi:type to a QName */ // REVISIT: in new simple type design, make things in DVs static, // so that we can QNameDV.getCompiledForm() final DatatypeValidator fQNameDV = (DatatypeValidator)SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_QNAME); /** used to build content models */ // REVISIT: create decl pool, and pass it to each traversers final CMBuilder fCMBuilder = new CMBuilder(new XSDeclarationPool()); // state /** Skip validation. */ int fSkipValidationDepth; /** Element depth. */ int fElementDepth; /** Child count. */ int fChildCount; /** Element decl stack. */ int[] fChildCountStack = new int[INITIAL_STACK_SIZE]; /** Current element declaration. */ XSElementDecl fCurrentElemDecl; /** Element decl stack. */ XSElementDecl[] fElemDeclStack = new XSElementDecl[INITIAL_STACK_SIZE]; /** nil value of the current element */ boolean fNil; /** nil value stack */ boolean[] fNilStack = new boolean[INITIAL_STACK_SIZE]; /** Current type. */ XSTypeDecl fCurrentType; /** type stack. */ XSTypeDecl[] fTypeStack = new XSTypeDecl[INITIAL_STACK_SIZE]; /** Current content model. */ XSCMValidator fCurrentCM; /** Content model stack. */ XSCMValidator[] fCMStack = new XSCMValidator[INITIAL_STACK_SIZE]; /** the current state of the current content model */ int[] fCurrCMState; /** stack to hold content model states */ int[][] fCMStateStack = new int[INITIAL_STACK_SIZE][]; /** Temporary string buffers. */ final StringBuffer fBuffer = new StringBuffer(); /** Did we see non-whitespace character data? */ boolean fSawCharacters = false; /** Stack to record if we saw character data outside of element content*/ boolean[] fStringContent = new boolean[INITIAL_STACK_SIZE]; /** * This table has to be own by instance of XMLValidator and shared * among ID, IDREF and IDREFS. * REVISIT: Should replace with a lighter structure. */ final Hashtable fTableOfIDs = new Hashtable(); final Hashtable fTableOfIDRefs = new Hashtable(); /** * temprory qname */ final QName fTempQName = new QName(); /** * temprory empty object, used to fill IDREF table */ static final Object fTempObject = new Object(); // identity constraint information /** * Stack of active XPath matchers for identity constraints. All * active XPath matchers are notified of startElement, characters * and endElement callbacks in order to perform their matches. * <p> * For each element with identity constraints, the selector of * each identity constraint is activated. When the selector matches * its XPath, then all the fields of the identity constraint are * activated. * <p> * <strong>Note:</strong> Once the activation scope is left, the * XPath matchers are automatically removed from the stack of * active matchers and no longer receive callbacks. */ protected XPathMatcherStack fMatcherStack = new XPathMatcherStack(); /** Cache of value stores for identity constraint fields. */ protected ValueStoreCache fValueStoreCache = new ValueStoreCache(); // // Constructors // /** Default constructor. */ public SchemaValidator() { fGrammarResolver = new XSGrammarResolver(); fSchemaHandler = new XSDHandler(fGrammarResolver); } // <init>() void ownReset(XMLComponentManager componentManager) throws XMLConfigurationException { // get error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // get symbol table. if it's a new one, add symbols to it. SymbolTable symbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE); if (symbolTable != fSymbolTable) { XMLNS = symbolTable.addSymbol(SchemaSymbols.O_XMLNS); URI_XSI = symbolTable.addSymbol(SchemaSymbols.URI_XSI); XSI_SCHEMALOCATION = symbolTable.addSymbol(SchemaSymbols.OXSI_SCHEMALOCATION); XSI_NONAMESPACESCHEMALOCATION = symbolTable.addSymbol(SchemaSymbols.OXSI_NONAMESPACESCHEMALOCATION); XSI_TYPE = symbolTable.addSymbol(SchemaSymbols.OXSI_TYPE); XSI_NIL = symbolTable.addSymbol(SchemaSymbols.OXSI_NIL); URI_SCHEMAFORSCHEMA = symbolTable.addSymbol(SchemaSymbols.OURI_SCHEMAFORSCHEMA); } fSymbolTable = symbolTable; // get entity resolver. if there is no one, create a default // REVISIT: use default entity resolution from ENTITY MANAGER - temporary solution fEntityResolver = (XMLEntityResolver)componentManager.getProperty(ENTITY_MANAGER); // initialize namespace support fNamespaceSupport.reset(fSymbolTable); fPushForNextBinding = true; // clear grammars, and put the one for schema namespace there fGrammarResolver.reset(); fGrammarResolver.putGrammar(URI_SCHEMAFORSCHEMA, SchemaGrammar.SG_SchemaNS); // reset schema handler and all traversal objects fSchemaHandler.reset(fErrorReporter, fEntityResolver, fSymbolTable); // initialize state fCurrentElemDecl = null; fNil = false; fCurrentType = null; fCurrentCM = null; fCurrCMState = null; fBuffer.setLength(0); fSawCharacters=false; fSkipValidationDepth = -1; fElementDepth = -1; fChildCount = 0; // clear values stored in id and idref table fTableOfIDs.clear(); fTableOfIDRefs.clear(); fMatcherStack.clear(); fValueStoreCache = new ValueStoreCache(); } // reset(XMLComponentManager) /** ensure element stack capacity */ void ensureStackCapacity() { if (fElementDepth == fElemDeclStack.length) { int newSize = fElementDepth + INC_STACK_SIZE; int[] newArrayI = new int[newSize]; System.arraycopy(fChildCountStack, 0, newArrayI, 0, newSize); fChildCountStack = newArrayI; XSElementDecl[] newArrayE = new XSElementDecl[newSize]; System.arraycopy(fElemDeclStack, 0, newArrayE, 0, newSize); fElemDeclStack = newArrayE; XSTypeDecl[] newArrayT = new XSTypeDecl[newSize]; System.arraycopy(fTypeStack, 0, newArrayT, 0, newSize); fTypeStack = newArrayT; XSCMValidator[] newArrayC = new XSCMValidator[newSize]; System.arraycopy(fCMStack, 0, newArrayC, 0, newSize); fCMStack = newArrayC; boolean[] newArrayD = new boolean[newSize]; System.arraycopy(fStringContent, 0, newArrayD, 0, newSize); fStringContent = newArrayD; int[][] newArrayIA = new int[newSize][]; System.arraycopy(fCMStateStack, 0, newArrayIA, 0, newSize); fCMStateStack = newArrayIA; } } // ensureStackCapacity // // FieldActivator methods // /** * Start the value scope for the specified identity constraint. This * method is called when the selector matches in order to initialize * the value store. * * @param identityConstraint The identity constraint. */ public void startValueScopeFor(IdentityConstraint identityConstraint) throws XNIException { for(int i=0; i<identityConstraint.getFieldCount(); i++) { Field field = identityConstraint.getFieldAt(i); ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(field); valueStore.startValueScope(); } } // startValueScopeFor(IdentityConstraint identityConstraint) /** * Request to activate the specified field. This method returns the * matcher for the field. * * @param field The field to activate. */ public XPathMatcher activateField(Field field) throws XNIException { ValueStore valueStore = fValueStoreCache.getValueStoreFor(field); field.setMayMatch(true); XPathMatcher matcher = field.createMatcher(valueStore); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(fSymbolTable); return matcher; } // activateField(Field):XPathMatcher /** * Ends the value scope for the specified identity constraint. * * @param identityConstraint The identity constraint. */ public void endValueScopeFor(IdentityConstraint identityConstraint) throws XNIException { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint); valueStore.endValueScope(); } // endValueScopeFor(IdentityConstraint) // a utility method for Idnetity constraints private void activateSelectorFor(IdentityConstraint ic) throws XNIException { Selector selector = ic.getSelector(); FieldActivator activator = this; if(selector == null) return; XPathMatcher matcher = selector.createMatcher(activator); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(fSymbolTable); } // // Protected methods // /** Handle element. */ void handleStartElement(QName element, XMLAttributes attributes) { if (DEBUG) { System.out.println("handleStartElement: " +element); } // we receive prefix binding events before this one, // so at this point, the prefix bindings for this element is done, // and we need to push context when we receive another prefix binding. // but if fPushForNextBinding is still true, that means there has // been no prefix binding for this element. we still need to push // context, because the context is always popped in end element. if (fPushForNextBinding) fNamespaceSupport.pushContext(); else fPushForNextBinding = true; // whether to do validation // REVISIT: consider DynamicValidation if (fElementDepth == -1) { fDoValidation = fValidation; } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; return; } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fChildCountStack[fElementDepth] = fChildCount+1; fChildCount = 0; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fTypeStack[fElementDepth] = fCurrentType; fCMStack[fElementDepth] = fCurrentCM; fStringContent[fElementDepth] = fSawCharacters; } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars // REVISIT: we'll defer this operation until there is a reference to // a component from that namespace String sLocation = attributes.getValue(URI_XSI, XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(URI_XSI, XSI_NONAMESPACESCHEMALOCATION); if (sLocation != null) { StringTokenizer t = new StringTokenizer(sLocation, " \n\t\r"); String namespace, location; while (t.hasMoreTokens()) { namespace = t.nextToken (); if (!t.hasMoreTokens()) { // REVISIT: report error for wrong number of uris break; } location = t.nextToken(); if (fGrammarResolver.getGrammar(namespace) == null) fSchemaHandler.parseSchema(namespace, location); } } if (nsLocation != null) { if (fGrammarResolver.getGrammar(fSchemaHandler.EMPTY_STRING) == null) fSchemaHandler.parseSchema(fSchemaHandler.EMPTY_STRING, nsLocation); } // get the element decl for this element fCurrentElemDecl = null; fNil = false; XSWildcardDecl wildcard = null; // if there is a content model, then get the decl from that if (fCurrentCM != null) { Object decl = fCurrentCM.oneTransition(element, fCurrCMState); // it could be an element decl or a wildcard decl // REVISIT: is there a more efficient way than 'instanceof' if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl)decl; } else if (decl instanceof XSWildcardDecl) { wildcard = (XSWildcardDecl)decl; } else if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR && fDoValidation) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; //REVISIT: is it the only case we will have particle = null? // if (ctype.fParticle != null) { reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname, ctype.fParticle.toString()}); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname,"mixed with no element content"}); } fCurrCMState[0] = XSCMValidator.SUBSEQUENT_ERROR; } else if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl)decl; } else if (decl instanceof XSWildcardDecl) { wildcard = (XSWildcardDecl)decl; } } // save the current content model state in the stack if (fElementDepth != -1) fCMStateStack[fElementDepth] = fCurrCMState; // increase the element depth after we've saved all states for the // parent element fElementDepth++; // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.WILDCARD_SKIP) { fSkipValidationDepth = fElementDepth; return; } // try again to get the element decl if (fCurrentElemDecl == null) { SchemaGrammar sGrammar = fGrammarResolver.getGrammar(element.uri); if (sGrammar != null) fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.isAbstract()) reportSchemaError("cvc-elt.2", new Object[]{element.rawname}); // get the type for the current element fCurrentType = null; if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } // get type from xsi:type String xsiType = attributes.getValue(URI_XSI, XSI_TYPE); if (xsiType != null) getAndCheckXsiType(element, xsiType); // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType != null) { if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; if (ctype.isAbstractType()) { reportSchemaError("cvc-type.2", new Object[]{"Element " + element.rawname + " is declared with a type that is abstract. Use xsi:type to specify a non-abstract type"}); } } } // if the element decl is not found if (fCurrentType == null && fDoValidation) { // if this is the root element, or wildcard = strict, report error if (fElementDepth == 0) { // report error, because it's root element reportSchemaError("cvc-elt.1", new Object[]{element.rawname}); } else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.WILDCARD_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[]{element.rawname}); } // no element decl found, have to skip this element fSkipValidationDepth = fElementDepth; return; } // then try to get the content model fCurrentCM = null; if (fCurrentType != null) { if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0) { fCurrentCM = ((XSComplexTypeDecl)fCurrentType).getContentModel(fCMBuilder); } } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // and the buffer to hold the value of the element fBuffer.setLength(0); fSawCharacters = false; // get information about xsi:nil String xsiNil = attributes.getValue(URI_XSI, XSI_NIL); if (xsiNil != null) getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; attrGrp = ctype.fAttrGrp; } processAttributes(element, attributes, attrGrp); // activate identity constraints if (fValidation ) { fValueStoreCache.startElement(); fMatcherStack.pushContext(); if (fCurrentElemDecl != null) { fValueStoreCache.initValueStoresFor(fCurrentElemDecl); int icCount = fCurrentElemDecl.fIDCPos; int uniqueOrKey = 0; for (;uniqueOrKey < icCount; uniqueOrKey++) { if(fCurrentElemDecl.fIDConstraints[uniqueOrKey].getType() != IdentityConstraint.KEYREF ) { activateSelectorFor(fCurrentElemDecl.fIDConstraints[uniqueOrKey]); } else break; } for (int keyref = uniqueOrKey; keyref < icCount; keyref++) { activateSelectorFor((IdentityConstraint)fCurrentElemDecl.fIDConstraints[keyref]); } } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement(element, attributes, fGrammarResolver.getGrammar(element.uri)); } } } // handleStartElement(QName,XMLAttributes,boolean) /** Handle end element. */ void handleEndElement(QName element) { // need to pop context so that the bindings for this element is // discarded. fNamespaceSupport.popContext(); // if we are skipping, return if (fSkipValidationDepth >= 0) { // but if this is the top element that we are skipping, // restore the states. if (fSkipValidationDepth == fElementDepth && fSkipValidationDepth > 0) { fSkipValidationDepth = -1; fElementDepth--; fChildCount = fChildCountStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; } else { fElementDepth--; } return; } // now validate the content of the element processElementContent(element); // Element Locally Valid (Element) // 6 The element information item must be �valid� with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (�3.11.4). // call matchers and de-activate context int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.endElement(element, fCurrentElemDecl, fGrammarResolver.getGrammar(element.uri)); } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); IdentityConstraint id; if((id = matcher.getIDConstraint()) != null && id.getType() != IdentityConstraint.KEYREF) { matcher.endDocumentFragment(); fValueStoreCache.transplant(id); } else if (id == null) matcher.endDocumentFragment(); } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); IdentityConstraint id; if((id = matcher.getIDConstraint()) != null && id.getType() == IdentityConstraint.KEYREF) { ValueStoreBase values = fValueStoreCache.getValueStoreFor(id); if(values != null) // nothing to do if nothing matched! values.endDocumentFragment(); matcher.endDocumentFragment(); } } fValueStoreCache.endElement(); // decrease element depth and restore states fElementDepth--; if (fElementDepth == -1) { if (fDoValidation) { try { // 7 If the element information item is the �validation root�, it must be �valid� per Validation Root Valid (ID/IDREF) (�3.3.4). // REVISIT: how to do it? new simpletype design? IDREFDatatypeValidator.checkIdRefs(fTableOfIDs, fTableOfIDRefs); } catch (InvalidDatatypeValueException ex) { // REVISIT: put idref value in ex reportSchemaError("cvc-id.1", new Object[]{ex.getLocalizedMessage()}); } } } else { // get the states for the parent element. fChildCount = fChildCountStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; } } // handleEndElement(QName,boolean)*/ void handleStartPrefix(String prefix, String uri) { // push namespace context if necessary if (fPushForNextBinding) { fNamespaceSupport.pushContext(); fPushForNextBinding = false; } // add prefix declaration to the namespace support // REVISIT: should it be null or "" fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null); } void getAndCheckXsiType(QName element, String xsiType) { // Element Locally Valid (Element) // 4 If there is an attribute information item among the element information item's [attributes] whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is type, then all of the following must be true: // 4.1 The �normalized value� of that attribute information item must be �valid� with respect to the built-in QName simple type, as defined by String Valid (�3.14.4); QName typeName = null; try { // REVISIT: have QNameDV to return QName //typeName = fQNameDV.validate(xsiType, fNamespaceSupport); fQNameDV.validate(xsiType, fNamespaceSupport); String prefix = fSchemaHandler.EMPTY_STRING; String localpart = xsiType; int colonptr = xsiType.indexOf(":"); if (colonptr > 0) { prefix = fSymbolTable.addSymbol(xsiType.substring(0,colonptr)); localpart = xsiType.substring(colonptr+1); } // REVISIT: if we take the null approach (instead of ""), // we need to chech the retrned value from getURI // to see whether a binding is found. String uri = fNamespaceSupport.getURI(prefix); typeName = new QName(prefix, localpart, xsiType, uri); } catch (InvalidDatatypeValueException e) { reportSchemaError("cvc-elt.4.1", new Object[]{element.rawname, URI_XSI+","+XSI_TYPE, xsiType}); return; } // 4.2 The �local name� and �namespace name� (as defined in QName Interpretation (�3.15.3)), of the �actual value� of that attribute information item must resolve to a type definition, as defined in QName resolution (Instance) (�3.15.4) XSTypeDecl type = null; SchemaGrammar grammar = fGrammarResolver.getGrammar(typeName.uri); if (grammar != null) type = grammar.getGlobalTypeDecl(typeName.localpart); if (type == null) { reportSchemaError("cvc-elt.4.2", new Object[]{element.rawname, xsiType}); return; } // if there is no current type, set this one as current. // and we don't need to do extra checking if (fCurrentType != null) { // 4.3 The �local type definition� must be validly derived from the {type definition} given the union of the {disallowed substitutions} and the {type definition}'s {prohibited substitutions}, as defined in Type Derivation OK (Complex) (�3.4.6) (if it is a complex type definition), or given {disallowed substitutions} as defined in Type Derivation OK (Simple) (�3.14.6) (if it is a simple type definition). int block = fCurrentElemDecl.fBlock; if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0) block |= ((XSComplexTypeDecl)fCurrentType).fBlock; if (!XSConstraints.checkTypeDerivationOk(type, fCurrentType, block)) reportSchemaError("cvc-elt.4.3", new Object[]{element.rawname, xsiType}); } fCurrentType = type; } void getXsiNil(QName element, String xsiNil) { // Element Locally Valid (Element) // 3 The appropriate case among the following must be true: // 3.1 If {nillable} is false, then there must be no attribute information item among the element information item's [attributes] whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is nil. if (fCurrentElemDecl != null && !fCurrentElemDecl.isNillable()) reportSchemaError("cvc-elt.3.1", new Object[]{element.rawname, URI_XSI+","+XSI_NIL}); // 3.2 If {nillable} is true and there is such an attribute information item and its �actual value� is true , then all of the following must be true: // 3.2.2 There must be no fixed {value constraint}. if (xsiNil.equals(SchemaSymbols.ATTVAL_TRUE) || xsiNil.equals(SchemaSymbols.ATTVAL_TRUE_1)) { fNil = true; if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSElementDecl.FIXED_VALUE) { reportSchemaError("cvc-elt.3.2.2", new Object[]{element.rawname, URI_XSI+","+XSI_NIL}); } } } void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // if we don't do validation, we don't need to validate the attributes if (!fDoValidation) return; // Element Locally Valid (Type) // 3.1.1 The element information item's [attributes] must be empty, excepting those whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation. if (fCurrentType == null || (fCurrentType.getXSType()&XSTypeDecl.SIMPLE_TYPE) != 0) { int attCount = attributes.getLength(); for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); if (fTempQName.uri == URI_XSI) { if (fTempQName.localpart != XSI_SCHEMALOCATION && fTempQName.localpart != XSI_NONAMESPACESCHEMALOCATION && fTempQName.localpart != XSI_NIL && fTempQName.localpart != XSI_TYPE) { reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname}); } } else if (fTempQName.rawname != XMLNS && !fTempQName.rawname.startsWith("xmlns:")) { reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname}); } } return; } XSAttributeUse attrUses[] = attrGrp.getAttributeUses(); int useCount = attrUses.length; XSWildcardDecl attrWildcard = attrGrp.fAttributeWC; // whether we have seen a Wildcard ID. String wildcardIDName = null; // for each present attribute int attCount = attributes.getLength(); // Element Locally Valid (Complex Type) // 3 For each attribute information item in the element information item's [attributes] excepting those whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation, the appropriate case among the following must be true: // get the corresponding attribute decl for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); // if it's from xsi namespace, it must be one of the four if (fTempQName.uri == URI_XSI) { if (fTempQName.localpart == XSI_SCHEMALOCATION || fTempQName.localpart == XSI_NONAMESPACESCHEMALOCATION || fTempQName.localpart == XSI_NIL || fTempQName.localpart == XSI_TYPE) { continue; } } else if (fTempQName.rawname == XMLNS || fTempQName.rawname.startsWith("xmlns:")) { continue; } // it's not xmlns, and not xsi, then we need to find a decl for it XSAttributeUse currUse = null; for (int i = 0; i < useCount; i++) { if (attrUses[i].fAttrDecl.fName == fTempQName.localpart && attrUses[i].fAttrDecl.fTargetNamespace == fTempQName.uri) { currUse = attrUses[i]; break; } } // 3.2 otherwise all of the following must be true: // 3.2.1 There must be an {attribute wildcard}. // 3.2.2 The attribute information item must be �valid� with respect to it as defined in Item Valid (Wildcard) (�3.10.4). // if failed, get it from wildcard if (currUse == null) { //if (attrWildcard == null) // reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname}); if (attrWildcard == null || !attrWildcard.allowNamespace(fTempQName.uri)) { // so this attribute is not allowed reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); continue; } } XSAttributeDecl currDecl = null; if (currUse != null) { currDecl = currUse.fAttrDecl; } else { // which means it matches a wildcard // skip it if it's skip if (attrWildcard.fType == XSWildcardDecl.WILDCARD_SKIP) continue; // now get the grammar and attribute decl SchemaGrammar grammar = fGrammarResolver.getGrammar(fTempQName.uri); if (grammar != null) currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart); // if can't find if (currDecl == null) { // if strict, report error if (attrWildcard.fType == XSWildcardDecl.WILDCARD_STRICT) reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); // then continue to the next attribute continue; } else { // 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose �validation� resulted in a �context-determined declaration� of mustFind or no �context-determined declaration� at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (�3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true: // 5.1 There must be no more than one item in �wild IDs�. if (currDecl.fType instanceof IDDatatypeValidator) { if (wildcardIDName != null) reportSchemaError("cvc-complex-type.5.1", new Object[]{element.rawname, currDecl.fName, wildcardIDName}); else wildcardIDName = currDecl.fName; } } } // Attribute Locally Valid // For an attribute information item to be locally �valid� with respect to an attribute declaration all of the following must be true: // 1 The declaration must not be �absent� (see Missing Sub-components (�5.3) for how this can fail to be the case). // 2 Its {type definition} must not be absent. // 3 The item's �normalized value� must be locally �valid� with respect to that {type definition} as per String Valid (�3.14.4). // get simple type DatatypeValidator attDV = currDecl.fType; // get attribute value String attrValue = attributes.getValue(index); // normalize it // REVISIT: or should the normalize() be called within validate()? attrValue = XSAttributeChecker.normalize(attrValue, attDV.getWSFacet()); Object actualValue = null; try { // REVISIT: use XSSimpleTypeDecl.ValidateContext to replace null // actualValue = attDV.validate(attrValue, null); attDV.validate(attrValue, null); } catch (InvalidDatatypeValueException idve) { reportSchemaError("cvc-attribute.3", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } // get the value constraint from use or decl // 4 The item's �actual value� must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType if (currDecl.fConstraintType == XSAttributeDecl.FIXED_VALUE) { // REVISIT: compare should be equal, and takes object, instead of string // do it in the new datatype design //if (attDV.compare((String)actualValue, (String)currDecl.fDefault) != 0) if (attDV.compare(attrValue, (String)currDecl.fDefault) != 0) reportSchemaError("cvc-attribute.4", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } // 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an �absent� {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be �valid� with respect to that attribute use as per Attribute Locally Valid (Use) (�3.5.4). In this case the {attribute declaration} of that attribute use is the �context-determined declaration� for the attribute information item with respect to Schema-Validity Assessment (Attribute) (�3.2.4) and Assessment Outcome (Attribute) (�3.2.5). if (currUse != null && currUse.fConstraintType == XSAttributeDecl.FIXED_VALUE) { // REVISIT: compare should be equal, and takes object, instead of string // do it in the new datatype design - if (attDV.compare((String)actualValue, (String)currUse.fDefault) != 0) + //if (attDV.compare((String)actualValue, (String)currUse.fDefault) != 0) + if (attDV.compare(attrValue, (String)currUse.fDefault) != 0) reportSchemaError("cvc-complex-type.3.1", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } } // end of for (all attributes) // 5.2 If �wild IDs� is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID. if (attrGrp.fIDAttrName != null && wildcardIDName != null) reportSchemaError("cvc-complex-type.5.2", new Object[]{element.rawname, wildcardIDName, attrGrp.fIDAttrName}); } //processAttributes void addDefaultAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // REVISIT: should we check prohibited attributes? // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) add default attrs (FIXED and NOT_FIXED) // if (DEBUG) { System.out.println("addDefaultAttributes: " + element); } XSAttributeUse attrUses[] = attrGrp.getAttributeUses(); int useCount = attrUses.length; XSAttributeUse currUse; XSAttributeDecl currDecl; short constType; Object defaultValue; boolean isSpecified; QName attName; // for each attribute use for (int i = 0; i < useCount; i++) { currUse = attrUses[i]; currDecl = currUse.fAttrDecl; // get value constraint constType = currUse.fConstraintType; defaultValue = currUse.fDefault; if (constType == XSAttributeDecl.NO_CONSTRAINT) { constType = currDecl.fConstraintType; defaultValue = currDecl.fDefault; } // whether this attribute is specified isSpecified = attributes.getValue(currDecl.fTargetNamespace, currDecl.fName) != null; // Element Locally Valid (Complex Type) // 4 The {attribute declaration} of each attribute use in the {attribute uses} whose {required} is true matches one of the attribute information items in the element information item's [attributes] as per clause 3.1 above. if (currUse.fUse == SchemaSymbols.USE_REQUIRED) { if (!isSpecified) reportSchemaError("cvc-complex-type.4", new Object[]{element.rawname, currDecl.fName}); } // if the attribute is not specified, then apply the value constraint if (!isSpecified && constType != XSAttributeDecl.NO_CONSTRAINT) { attName = new QName(null, currDecl.fName, currDecl.fName, currDecl.fTargetNamespace); //REVISIT: what's the proper attrType? attributes.addAttribute(attName, null, (defaultValue !=null)?defaultValue.toString():""); } } // for } // addDefaultAttributes void processElementContent(QName element) { // fCurrentElemDecl: default value; ... if(fCurrentElemDecl != null) { if(fCurrentElemDecl.fDefault != null) { if(fBuffer.toString().trim().length() == 0) { int bufLen = fCurrentElemDecl.fDefault.toString().length(); char [] chars = new char[bufLen]; fCurrentElemDecl.fDefault.toString().getChars(0, bufLen, chars, 0); XMLString text = new XMLString(chars, 0, bufLen); if(fDocumentHandler != null) { fDocumentHandler.characters(text); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.characters(text); } } } } // fixed values are handled later, after xsi:type determined. if (DEBUG) { System.out.println("processElementContent:" +element); } if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSElementDecl.DEFAULT_VALUE) { } if (fDoValidation) { String content = fBuffer.toString(); // Element Locally Valid (Element) // 3.2.1 The element information item must have no character or element information item [children]. if (fNil) { if (fChildCount != 0 || content.length() != 0) reportSchemaError("cvc-elt.3.2.1", new Object[]{element.rawname, URI_XSI+","+XSI_NIL}); } // 5 The appropriate case among the following must be true: // 5.1 If the declaration has a {value constraint}, the item has neither element nor character [children] and clause 3.2 has not applied, then all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() != XSElementDecl.NO_CONSTRAINT && fChildCount == 0 && content.length() == 0 && !fNil) { // 5.1.1 If the �actual type definition� is a �local type definition� then the canonical lexical representation of the {value constraint} value must be a valid default for the �actual type definition� as defined in Element Default Valid (Immediate) (�3.3.6). if (fCurrentType != fCurrentElemDecl.fType) { if (!XSConstraints.ElementDefaultValidImmediate(fCurrentType, fCurrentElemDecl.fDefault.toString())) reportSchemaError("cvc-elt.5.1.1", new Object[]{element.rawname, fCurrentType.getXSTypeName(), fCurrentElemDecl.fDefault.toString()}); } // 5.1.2 The element information item with the canonical lexical representation of the {value constraint} value used as its �normalized value� must be �valid� with respect to the �actual type definition� as defined by Element Locally Valid (Type) (�3.3.4). elementLocallyValidType(element, fCurrentElemDecl.fDefault.toString()); } else { // 5.2 If the declaration has no {value constraint} or the item has either element or character [children] or clause 3.2 has applied, then all of the following must be true: // 5.2.1 The element information item must be �valid� with respect to the �actual type definition� as defined by Element Locally Valid (Type) (�3.3.4). Object actualValue = elementLocallyValidType(element, content); // 5.2.2 If there is a fixed {value constraint} and clause 3.2 has not applied, all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSElementDecl.FIXED_VALUE && !fNil) { // 5.2.2.1 The element information item must have no element information item [children]. if (fChildCount != 0) reportSchemaError("cvc-elt.5.2.2.1", new Object[]{element.rawname}); // 5.2.2.2 The appropriate case among the following must be true: if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; // 5.2.2.2.1 If the {content type} of the �actual type definition� is mixed, then the �initial value� of the item must match the canonical lexical representation of the {value constraint} value. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // REVISIT: how to get the initial value, does whiteSpace count? if (!fCurrentElemDecl.fDefault.toString().equals(content)) reportSchemaError("cvc-elt.5.2.2.2.1", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.toString()}); } // 5.2.2.2.2 If the {content type} of the �actual type definition� is a simple type definition, then the �actual value� of the item must match the canonical lexical representation of the {value constraint} value. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { // REVISIT: compare should be equal, and takes object, instead of string // do it in the new datatype design if (ctype.fDatatypeValidator.compare((String)actualValue, (String)fCurrentElemDecl.fDefault) != 0) reportSchemaError("cvc-elt.5.2.2.2.2", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.toString()}); } } else if ((fCurrentType.getXSType() & XSTypeDecl.SIMPLE_TYPE) != 0) { DatatypeValidator sType = (DatatypeValidator)fCurrentType; // REVISIT: compare should be equal, and takes object, instead of string // do it in the new datatype design if (sType.compare((String)actualValue, (String)fCurrentElemDecl.fDefault) != 0) reportSchemaError("cvc-elt.5.2.2.2.2", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.toString()}); } } } } // if fDoValidation } // processElementContent Object elementLocallyValidType(QName element, String textContent) { if (fCurrentType == null) return null; Object retValue = null; // Element Locally Valid (Type) // 3 The appropriate case among the following must be true: // 3.1 If the type definition is a simple type definition, then all of the following must be true: if ((fCurrentType.getXSType() & XSTypeDecl.SIMPLE_TYPE) != 0) { // 3.1.2 The element information item must have no element information item [children]. if (fChildCount != 0) reportSchemaError("cvc-type.3.1.2", new Object[]{element.rawname}); // 3.1.3 If clause 3.2 of Element Locally Valid (Element) (�3.3.4) did not apply, then the �normalized value� must be �valid� with respect to the type definition as defined by String Valid (�3.14.4). if (!fNil) { DatatypeValidator dv = (DatatypeValidator)fCurrentType; // REVISIT: or should the normalize() be called within validate()? String content = XSAttributeChecker.normalize(textContent, dv.getWSFacet()); try { // REVISIT: use XSSimpleTypeDecl.ValidateContext to replace null // retValue = dv.validate(content, null); // make sure we return something... - NG retValue = content; dv.validate(content, null); } catch (InvalidDatatypeValueException e) { reportSchemaError("cvc-type.3.1.3", new Object[]{element.rawname, content}); } } } else { // 3.2 If the type definition is a complex type definition, then the element information item must be �valid� with respect to the type definition as per Element Locally Valid (Complex Type) (�3.4.4); elementLocallyValidComplexType(element, textContent); } return retValue; } // elementLocallyValidType void elementLocallyValidComplexType(QName element, String textContent) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; // Element Locally Valid (Complex Type) // For an element information item to be locally �valid� with respect to a complex type definition all of the following must be true: // 1 {abstract} is false. // 2 If clause 3.2 of Element Locally Valid (Element) (�3.3.4) did not apply, then the appropriate case among the following must be true: if (!fNil) { // 2.1 If the {content type} is empty, then the element information item has no character or element information item [children]. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY && (fChildCount != 0 || textContent.length() != 0)) { reportSchemaError("cvc-complex-type.2.1", new Object[]{element.rawname}); } // 2.2 If the {content type} is a simple type definition, then the element information item has no element information item [children], and the �normalized value� of the element information item is �valid� with respect to that simple type definition as defined by String Valid (�3.14.4). if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (fChildCount != 0) reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname}); DatatypeValidator dv = ctype.fDatatypeValidator; // REVISIT: or should the normalize() be called within validate()? String content = XSAttributeChecker.normalize(textContent, dv.getWSFacet()); try { // REVISIT: use XSSimpleTypeDecl.ValidateContext to replace null dv.validate(content, null); } catch (InvalidDatatypeValueException e) { reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname}); } } // 2.3 If the {content type} is element-only, then the element information item has no character information item [children] other than those whose [character code] is defined as a white space in [XML 1.0 (Second Edition)]. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { // REVISIT: how to check whether there is any text content? if (fSawCharacters) { reportSchemaError("cvc-complex-type.2.3", new Object[]{element.rawname}); } } // 2.4 If the {content type} is element-only or mixed, then the sequence of the element information item's element information item [children], if any, taken in order, is �valid� with respect to the {content type}'s particle, as defined in Element Sequence Locally Valid (Particle) (�3.9.4). if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT || ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // if the current state is a valid state, check whether // it's one of the final states. if (DEBUG) { System.out.println(fCurrCMState); } if (fCurrCMState[0] >= 0 && !fCurrentCM.endContentModel(fCurrCMState)) { reportSchemaError("cvc-complex-type.2.4.b", new Object[]{element.rawname, ctype.fParticle.toString()}); } } } } // elementLocallyValidComplexType void reportSchemaError(String key, Object[] arguments) { if (fDoValidation) fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, arguments, XMLErrorReporter.SEVERITY_ERROR); } /**********************************/ // xpath matcher information /** * Stack of XPath matchers for identity constraints. * * @author Andy Clark, IBM */ protected static class XPathMatcherStack { // // Data // /** Active matchers. */ protected XPathMatcher[] fMatchers = new XPathMatcher[4]; /** Count of active matchers. */ protected int fMatchersCount; /** Offset stack for contexts. */ protected IntStack fContextStack = new IntStack(); // // Constructors // public XPathMatcherStack() { } // <init>() // // Public methods // /** Resets the XPath matcher stack. */ public void clear() { for (int i = 0; i < fMatchersCount; i++) { fMatchers[i] = null; } fMatchersCount = 0; fContextStack.clear(); } // clear() /** Returns the size of the stack. */ public int size() { return fContextStack.size(); } // size():int /** Returns the count of XPath matchers. */ public int getMatcherCount() { return fMatchersCount; } // getMatcherCount():int /** Adds a matcher. */ public void addMatcher(XPathMatcher matcher) { ensureMatcherCapacity(); fMatchers[fMatchersCount++] = matcher; } // addMatcher(XPathMatcher) /** Returns the XPath matcher at the specified index. */ public XPathMatcher getMatcherAt(int index) { return fMatchers[index]; } // getMatcherAt(index):XPathMatcher /** Pushes a new context onto the stack. */ public void pushContext() { fContextStack.push(fMatchersCount); } // pushContext() /** Pops a context off of the stack. */ public void popContext() { fMatchersCount = fContextStack.pop(); } // popContext() // // Private methods // /** Ensures the size of the matchers array. */ private void ensureMatcherCapacity() { if (fMatchersCount == fMatchers.length) { XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2]; System.arraycopy(fMatchers, 0, array, 0, fMatchers.length); fMatchers = array; } } // ensureMatcherCapacity() } // class XPathMatcherStack // value store implementations /** * Value store implementation base class. There are specific subclasses * for handling unique, key, and keyref. * * @author Andy Clark, IBM */ protected abstract class ValueStoreBase implements ValueStore { // // Constants // /** Not a value (Unicode: #FFFF). */ protected IDValue NOT_AN_IDVALUE = new IDValue("\uFFFF", null); // // Data // /** Identity constraint. */ protected IdentityConstraint fIdentityConstraint; /** Current data values. */ protected final OrderedHashtable fValues = new OrderedHashtable(); /** Current data value count. */ protected int fValuesCount; /** Data value tuples. */ protected final Vector fValueTuples = new Vector(); // // Constructors // /** Constructs a value store for the specified identity constraint. */ protected ValueStoreBase(IdentityConstraint identityConstraint) { fIdentityConstraint = identityConstraint; } // <init>(IdentityConstraint) // // Public methods // // destroys this ValueStore; useful when, for instance, a // locally-scoped ID constraint is involved. public void destroy() { fValuesCount = 0; fValues.clear(); fValueTuples.removeAllElements(); } // end destroy():void // appends the contents of one ValueStore to those of us. public void append(ValueStoreBase newVal) { for (int i = 0; i < newVal.fValueTuples.size(); i++) { OrderedHashtable o = (OrderedHashtable)newVal.fValueTuples.elementAt(i); if (!contains(o)) fValueTuples.addElement(o); } } // append(ValueStoreBase) /** Start scope for value store. */ public void startValueScope() throws XNIException { fValuesCount = 0; int count = fIdentityConstraint.getFieldCount(); for (int i = 0; i < count; i++) { fValues.put(fIdentityConstraint.getFieldAt(i), NOT_AN_IDVALUE); } } // startValueScope() /** Ends scope for value store. */ public void endValueScope() throws XNIException { // is there anything to do? // REVISIT: This check solves the problem with field matchers // that get activated because they are at the same // level as the declaring element (e.g. selector xpath // is ".") but never match. // However, this doesn't help us catch the problem // when we expect a field value but never see it. A // better solution has to be found. -Ac // REVISIT: Is this a problem? -Ac // Yes - NG if (fValuesCount == 0) { if(fIdentityConstraint.getType() == IdentityConstraint.KEY) { String code = "AbsentKeyValue"; String eName = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{eName}); } return; } // do we have enough values? if (fValuesCount != fIdentityConstraint.getFieldCount()) { switch (fIdentityConstraint.getType()) { case IdentityConstraint.UNIQUE: { String code = "UniqueNotEnoughValues"; String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{ename}); break; } case IdentityConstraint.KEY: { String code = "KeyNotEnoughValues"; UniqueOrKey key = (UniqueOrKey)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = key.getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } case IdentityConstraint.KEYREF: { String code = "KeyRefNotEnoughValues"; KeyRef keyref = (KeyRef)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = (keyref.getKey()).getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } } return; } } // endValueScope() // This is needed to allow keyref's to look for matched keys // in the correct scope. Unique and Key may also need to // override this method for purposes of their own. // This method is called whenever the DocumentFragment // of an ID Constraint goes out of scope. public void endDocumentFragment() throws XNIException { } // endDocumentFragment():void /** * Signals the end of the document. This is where the specific * instances of value stores can verify the integrity of the * identity constraints. */ public void endDocument() throws XNIException { } // endDocument() // // ValueStore methods // /* reports an error if an element is matched * has nillable true and is matched by a key. */ public void reportNilError(IdentityConstraint id) { if(id.getType() == IdentityConstraint.KEY) { String code = "KeyMatchesNillable"; reportSchemaError(code, new Object[]{id.getElementName()}); } } // reportNilError /** * Adds the specified value to the value store. * * @param value The value to add. * @param field The field associated to the value. This reference * is used to ensure that each field only adds a value * once within a selection scope. */ public void addValue(Field field, IDValue value) { if(!field.mayMatch()) { String code = "FieldMultipleMatch"; reportSchemaError(code, new Object[]{field.toString()}); } // do we even know this field? int index = fValues.indexOf(field); if (index == -1) { String code = "UnknownField"; reportSchemaError(code, new Object[]{field.toString()}); return; } // store value IDValue storedValue = fValues.valueAt(index); if (storedValue.isDuplicateOf(NOT_AN_IDVALUE)) { fValuesCount++; } fValues.put(field, value); if (fValuesCount == fValues.size()) { // is this value as a group duplicated? if (contains(fValues)) { duplicateValue(fValues); } // store values OrderedHashtable values = (OrderedHashtable)fValues.clone(); fValueTuples.addElement(values); } } // addValue(String,Field) /** * Returns true if this value store contains the specified * values tuple. */ public boolean contains(OrderedHashtable tuple) { // do sizes match? int tcount = tuple.size(); // iterate over tuples to find it int count = fValueTuples.size(); LOOP: for (int i = 0; i < count; i++) { OrderedHashtable vtuple = (OrderedHashtable)fValueTuples.elementAt(i); // compare values for (int j = 0; j < tcount; j++) { IDValue value1 = vtuple.valueAt(j); IDValue value2 = tuple.valueAt(j); if(!(value1.isDuplicateOf(value2))) { continue LOOP; } } // found it return true; } // didn't find it return false; } // contains(Hashtable):boolean // // Protected methods // /** * Called when a duplicate value is added. Subclasses should override * this method to perform error checking. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws XNIException { // no-op } // duplicateValue(Hashtable) /** Returns a string of the specified values. */ protected String toString(OrderedHashtable tuple) { // no values int size = tuple.size(); if (size == 0) { return ""; } // construct value string StringBuffer str = new StringBuffer(); for (int i = 0; i < size; i++) { if (i > 0) { str.append(','); } str.append(tuple.valueAt(i)); } return str.toString(); } // toString(OrderedHashtable):String // // Object methods // /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { s = s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { s = s.substring(index2 + 1); } return s + '[' + fIdentityConstraint + ']'; } // toString():String } // class ValueStoreBase /** * Unique value store. * * @author Andy Clark, IBM */ protected class UniqueValueStore extends ValueStoreBase { // // Constructors // /** Constructs a unique value store. */ public UniqueValueStore(UniqueOrKey unique) { super(unique); } // <init>(Unique) // // ValueStoreBase protected methods // /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws XNIException { String code = "DuplicateUnique"; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class UniqueValueStore /** * Key value store. * * @author Andy Clark, IBM */ protected class KeyValueStore extends ValueStoreBase { // REVISIT: Implement a more efficient storage mechanism. -Ac // // Constructors // /** Constructs a key value store. */ public KeyValueStore(UniqueOrKey key) { super(key); } // <init>(Key) // // ValueStoreBase protected methods // /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws XNIException { String code = "DuplicateKey"; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class KeyValueStore /** * Key reference value store. * * @author Andy Clark, IBM */ protected class KeyRefValueStore extends ValueStoreBase { // // Data // /** Key value store. */ protected ValueStoreBase fKeyValueStore; // // Constructors // /** Constructs a key value store. */ public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore) { super(keyRef); fKeyValueStore = keyValueStore; } // <init>(KeyRef) // // ValueStoreBase methods // // end the value Scope; here's where we have to tie // up keyRef loose ends. public void endDocumentFragment () throws XNIException { // do all the necessary management... super.endDocumentFragment (); // verify references // get the key store corresponding (if it exists): fKeyValueStore = (ValueStoreBase)fValueStoreCache.fGlobalIDConstraintMap.get(((KeyRef)fIdentityConstraint).getKey()); if(fKeyValueStore == null) { // report error String code = "KeyRefOutOfScope"; String value = fIdentityConstraint.toString(); reportSchemaError(code, new Object[]{value}); return; } int count = fValueTuples.size(); for (int i = 0; i < count; i++) { OrderedHashtable values = (OrderedHashtable)fValueTuples.elementAt(i); if (!fKeyValueStore.contains(values)) { String code = "KeyNotFound"; String value = toString(values); String element = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,element}); } } } // endDocumentFragment() /** End document. */ public void endDocument() throws XNIException { super.endDocument(); } // endDocument() } // class KeyRefValueStore // value store management /** * Value store cache. This class is used to store the values for * identity constraints. * * @author Andy Clark, IBM */ protected class ValueStoreCache { // // Data // // values stores /** stores all global Values stores. */ protected final Vector fValueStores = new Vector(); /** Values stores associated to specific identity constraints. */ protected final Hashtable fIdentityConstraint2ValueStoreMap = new Hashtable(); // sketch of algorithm: // - when a constraint is first encountered, its // values are stored in the (local) fIdentityConstraint2ValueStoreMap; // - Once it is validated (i.e., wen it goes out of scope), // its values are merged into the fGlobalIDConstraintMap; // - as we encounter keyref's, we look at the global table to // validate them. // the fGlobalIDMapStack has the following structure: // - validation always occurs against the fGlobalIDConstraintMap // (which comprises all the "eligible" id constraints); // When an endelement is found, this Hashtable is merged with the one // below in the stack. // When a start tag is encountered, we create a new // fGlobalIDConstraintMap. // i.e., the top of the fGlobalIDMapStack always contains // the preceding siblings' eligible id constraints; // the fGlobalIDConstraintMap contains descendants+self. // keyrefs can only match descendants+self. protected final Stack fGlobalMapStack = new Stack(); protected final Hashtable fGlobalIDConstraintMap = new Hashtable(); // // Constructors // /** Default constructor. */ public ValueStoreCache() { } // <init>() // // Public methods // /** Resets the identity constraint cache. */ public void startDocument() throws XNIException { fValueStores.removeAllElements(); fIdentityConstraint2ValueStoreMap.clear(); fGlobalIDConstraintMap.clear(); fGlobalMapStack.removeAllElements(); } // startDocument() // startElement: pushes the current fGlobalIDConstraintMap // onto fGlobalMapStack and clears fGlobalIDConstraint map. public void startElement() { fGlobalMapStack.push(fGlobalIDConstraintMap.clone()); fGlobalIDConstraintMap.clear(); } // startElement(void) // endElement(): merges contents of fGlobalIDConstraintMap with the // top of fGlobalMapStack into fGlobalIDConstraintMap. public void endElement() { if (fGlobalMapStack.isEmpty()) return; // must be an invalid doc! Hashtable oldMap = (Hashtable)fGlobalMapStack.pop(); Enumeration keys = oldMap.keys(); while(keys.hasMoreElements()) { IdentityConstraint id = (IdentityConstraint)keys.nextElement(); ValueStoreBase oldVal = (ValueStoreBase)oldMap.get(id); if(oldVal != null) { ValueStoreBase currVal = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVal == null) fGlobalIDConstraintMap.put(id, oldVal); else { currVal.append(oldVal); fGlobalIDConstraintMap.put(id, currVal); } } } } // endElement() /** * Initializes the value stores for the specified element * declaration. */ public void initValueStoresFor(XSElementDecl eDecl) throws XNIException { // initialize value stores for unique fields IdentityConstraint [] icArray = eDecl.fIDConstraints; int icCount = eDecl.fIDCPos; for (int i = 0; i < icCount; i++) { switch (icArray[i].getType()) { case (IdentityConstraint.UNIQUE): // initialize value stores for unique fields UniqueOrKey unique = (UniqueOrKey)icArray[i]; UniqueValueStore uniqueValueStore = (UniqueValueStore)fIdentityConstraint2ValueStoreMap.get(unique); if (uniqueValueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } uniqueValueStore = new UniqueValueStore(unique); fValueStores.addElement(uniqueValueStore); fIdentityConstraint2ValueStoreMap.put(unique, uniqueValueStore); break; case (IdentityConstraint.KEY): // initialize value stores for key fields UniqueOrKey key = (UniqueOrKey)icArray[i]; KeyValueStore keyValueStore = (KeyValueStore)fIdentityConstraint2ValueStoreMap.get(key); if (keyValueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } keyValueStore = new KeyValueStore(key); fValueStores.addElement(keyValueStore); fIdentityConstraint2ValueStoreMap.put(key, keyValueStore); break; case (IdentityConstraint.KEYREF): // initialize value stores for key reference fields KeyRef keyRef = (KeyRef)icArray[i]; KeyRefValueStore keyRefValueStore = (KeyRefValueStore)fIdentityConstraint2ValueStoreMap.get(keyRef); if (keyRefValueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } keyRefValueStore = new KeyRefValueStore(keyRef, null); fValueStores.addElement(keyRefValueStore); fIdentityConstraint2ValueStoreMap.put(keyRef, keyRefValueStore); break; } } } // initValueStoresFor(XSElementDecl) /** Returns the value store associated to the specified field. */ public ValueStoreBase getValueStoreFor(Field field) { IdentityConstraint identityConstraint = field.getIdentityConstraint(); return (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(identityConstraint); } // getValueStoreFor(Field):ValueStoreBase /** Returns the value store associated to the specified IdentityConstraint. */ public ValueStoreBase getValueStoreFor(IdentityConstraint id) { return (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase /** Returns the global value store associated to the specified IdentityConstraint. */ public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) { return (ValueStoreBase)fGlobalIDConstraintMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase // This method takes the contents of the (local) ValueStore // associated with id and moves them into the global // hashtable, if id is a <unique> or a <key>. // If it's a <keyRef>, then we leave it for later. public void transplant(IdentityConstraint id) { if (id.getType() == IdentityConstraint.KEYREF ) return; ValueStoreBase newVals = (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id); fIdentityConstraint2ValueStoreMap.remove(id); ValueStoreBase currVals = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVals != null) { currVals.append(newVals); fGlobalIDConstraintMap.put(id, currVals); } else fGlobalIDConstraintMap.put(id, newVals); } // transplant(id) /** Check identity constraints. */ public void endDocument() throws XNIException { int count = fValueStores.size(); for (int i = 0; i < count; i++) { ValueStoreBase valueStore = (ValueStoreBase)fValueStores.elementAt(i); valueStore.endDocument(); } } // endDocument() // // Object methods // /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { return s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { return s.substring(index2 + 1); } return s; } // toString():String } // class ValueStoreCache // utility classes /** * Ordered hashtable. This class acts as a hashtable with * <code>put()</code> and <code>get()</code> operations but also * allows values to be queried via the order that they were * added to the hashtable. * <p> * <strong>Note:</strong> This class does not perform any error * checking. * <p> * <strong>Note:</strong> This class is <em>not</em> efficient but * is assumed to be used for a very small set of values. * * @author Andy Clark, IBM */ static final class OrderedHashtable implements Cloneable { // // Data // /** Size. */ private int fSize; /** Hashtable entries. */ private Entry[] fEntries = null; // // Public methods // /** Returns the number of entries in the hashtable. */ public int size() { return fSize; } // size():int /** Puts an entry into the hashtable. */ public void put(Field key, IDValue value) { int index = indexOf(key); if (index == -1) { ensureCapacity(fSize); index = fSize++; fEntries[index].key = key; } fEntries[index].value = value; } // put(Field,String) /** Returns the value associated to the specified key. */ public IDValue get(Field key) { return fEntries[indexOf(key)].value; } // get(Field):String /** Returns the index of the entry with the specified key. */ public int indexOf(Field key) { for (int i = 0; i < fSize; i++) { // NOTE: Only way to be sure that the keys are the // same is by using a reference comparison. In // order to rely on the equals method, each // field would have to take into account its // position in the identity constraint, the // identity constraint, the declaring element, // and the grammar that it is defined in. // Otherwise, you have the possibility that // the equals method would return true for two // fields that look *very* similar. // The reference compare isn't bad, actually, // because the field objects are cacheable. -Ac if (fEntries[i].key == key) { return i; } } return -1; } // indexOf(Field):int /** Returns the key at the specified index. */ public Field keyAt(int index) { return fEntries[index].key; } // keyAt(int):Field /** Returns the value at the specified index. */ public IDValue valueAt(int index) { return fEntries[index].value; } // valueAt(int):String /** Removes all of the entries from the hashtable. */ public void clear() { fSize = 0; } // clear() // // Private methods // /** Ensures the capacity of the entries array. */ private void ensureCapacity(int size) { // sizes int osize = -1; int nsize = -1; // create array if (fEntries == null) { osize = 0; nsize = 2; fEntries = new Entry[nsize]; } // resize array else if (fEntries.length <= size) { osize = fEntries.length; nsize = 2 * osize; Entry[] array = new Entry[nsize]; System.arraycopy(fEntries, 0, array, 0, osize); fEntries = array; } // create new entries for (int i = osize; i < nsize; i++) { fEntries[i] = new Entry(); } } // ensureCapacity(int) // // Cloneable methods // /** Clones this object. */ public Object clone() { OrderedHashtable hashtable = new OrderedHashtable(); for (int i = 0; i < fSize; i++) { hashtable.put(fEntries[i].key, fEntries[i].value); } return hashtable; } // clone():Object // // Object methods // /** Returns a string representation of this object. */ public String toString() { if (fSize == 0) { return "[]"; } StringBuffer str = new StringBuffer(); str.append('['); for (int i = 0; i < fSize; i++) { if (i > 0) { str.append(','); } str.append('{'); str.append(fEntries[i].key); str.append(','); str.append(fEntries[i].value); str.append('}'); } str.append(']'); return str.toString(); } // toString():String // // Classes // /** * Hashtable entry. */ public static final class Entry { // // Data // /** Key. */ public Field key; /** Value. */ public IDValue value; } // class Entry } // class OrderedHashtable } // class SchemaValidator
true
true
void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // if we don't do validation, we don't need to validate the attributes if (!fDoValidation) return; // Element Locally Valid (Type) // 3.1.1 The element information item's [attributes] must be empty, excepting those whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation. if (fCurrentType == null || (fCurrentType.getXSType()&XSTypeDecl.SIMPLE_TYPE) != 0) { int attCount = attributes.getLength(); for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); if (fTempQName.uri == URI_XSI) { if (fTempQName.localpart != XSI_SCHEMALOCATION && fTempQName.localpart != XSI_NONAMESPACESCHEMALOCATION && fTempQName.localpart != XSI_NIL && fTempQName.localpart != XSI_TYPE) { reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname}); } } else if (fTempQName.rawname != XMLNS && !fTempQName.rawname.startsWith("xmlns:")) { reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname}); } } return; } XSAttributeUse attrUses[] = attrGrp.getAttributeUses(); int useCount = attrUses.length; XSWildcardDecl attrWildcard = attrGrp.fAttributeWC; // whether we have seen a Wildcard ID. String wildcardIDName = null; // for each present attribute int attCount = attributes.getLength(); // Element Locally Valid (Complex Type) // 3 For each attribute information item in the element information item's [attributes] excepting those whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation, the appropriate case among the following must be true: // get the corresponding attribute decl for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); // if it's from xsi namespace, it must be one of the four if (fTempQName.uri == URI_XSI) { if (fTempQName.localpart == XSI_SCHEMALOCATION || fTempQName.localpart == XSI_NONAMESPACESCHEMALOCATION || fTempQName.localpart == XSI_NIL || fTempQName.localpart == XSI_TYPE) { continue; } } else if (fTempQName.rawname == XMLNS || fTempQName.rawname.startsWith("xmlns:")) { continue; } // it's not xmlns, and not xsi, then we need to find a decl for it XSAttributeUse currUse = null; for (int i = 0; i < useCount; i++) { if (attrUses[i].fAttrDecl.fName == fTempQName.localpart && attrUses[i].fAttrDecl.fTargetNamespace == fTempQName.uri) { currUse = attrUses[i]; break; } } // 3.2 otherwise all of the following must be true: // 3.2.1 There must be an {attribute wildcard}. // 3.2.2 The attribute information item must be �valid� with respect to it as defined in Item Valid (Wildcard) (�3.10.4). // if failed, get it from wildcard if (currUse == null) { //if (attrWildcard == null) // reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname}); if (attrWildcard == null || !attrWildcard.allowNamespace(fTempQName.uri)) { // so this attribute is not allowed reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); continue; } } XSAttributeDecl currDecl = null; if (currUse != null) { currDecl = currUse.fAttrDecl; } else { // which means it matches a wildcard // skip it if it's skip if (attrWildcard.fType == XSWildcardDecl.WILDCARD_SKIP) continue; // now get the grammar and attribute decl SchemaGrammar grammar = fGrammarResolver.getGrammar(fTempQName.uri); if (grammar != null) currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart); // if can't find if (currDecl == null) { // if strict, report error if (attrWildcard.fType == XSWildcardDecl.WILDCARD_STRICT) reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); // then continue to the next attribute continue; } else { // 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose �validation� resulted in a �context-determined declaration� of mustFind or no �context-determined declaration� at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (�3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true: // 5.1 There must be no more than one item in �wild IDs�. if (currDecl.fType instanceof IDDatatypeValidator) { if (wildcardIDName != null) reportSchemaError("cvc-complex-type.5.1", new Object[]{element.rawname, currDecl.fName, wildcardIDName}); else wildcardIDName = currDecl.fName; } } } // Attribute Locally Valid // For an attribute information item to be locally �valid� with respect to an attribute declaration all of the following must be true: // 1 The declaration must not be �absent� (see Missing Sub-components (�5.3) for how this can fail to be the case). // 2 Its {type definition} must not be absent. // 3 The item's �normalized value� must be locally �valid� with respect to that {type definition} as per String Valid (�3.14.4). // get simple type DatatypeValidator attDV = currDecl.fType; // get attribute value String attrValue = attributes.getValue(index); // normalize it // REVISIT: or should the normalize() be called within validate()? attrValue = XSAttributeChecker.normalize(attrValue, attDV.getWSFacet()); Object actualValue = null; try { // REVISIT: use XSSimpleTypeDecl.ValidateContext to replace null // actualValue = attDV.validate(attrValue, null); attDV.validate(attrValue, null); } catch (InvalidDatatypeValueException idve) { reportSchemaError("cvc-attribute.3", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } // get the value constraint from use or decl // 4 The item's �actual value� must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType if (currDecl.fConstraintType == XSAttributeDecl.FIXED_VALUE) { // REVISIT: compare should be equal, and takes object, instead of string // do it in the new datatype design //if (attDV.compare((String)actualValue, (String)currDecl.fDefault) != 0) if (attDV.compare(attrValue, (String)currDecl.fDefault) != 0) reportSchemaError("cvc-attribute.4", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } // 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an �absent� {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be �valid� with respect to that attribute use as per Attribute Locally Valid (Use) (�3.5.4). In this case the {attribute declaration} of that attribute use is the �context-determined declaration� for the attribute information item with respect to Schema-Validity Assessment (Attribute) (�3.2.4) and Assessment Outcome (Attribute) (�3.2.5). if (currUse != null && currUse.fConstraintType == XSAttributeDecl.FIXED_VALUE) { // REVISIT: compare should be equal, and takes object, instead of string // do it in the new datatype design if (attDV.compare((String)actualValue, (String)currUse.fDefault) != 0) reportSchemaError("cvc-complex-type.3.1", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } } // end of for (all attributes) // 5.2 If �wild IDs� is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID. if (attrGrp.fIDAttrName != null && wildcardIDName != null) reportSchemaError("cvc-complex-type.5.2", new Object[]{element.rawname, wildcardIDName, attrGrp.fIDAttrName}); } //processAttributes
void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // if we don't do validation, we don't need to validate the attributes if (!fDoValidation) return; // Element Locally Valid (Type) // 3.1.1 The element information item's [attributes] must be empty, excepting those whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation. if (fCurrentType == null || (fCurrentType.getXSType()&XSTypeDecl.SIMPLE_TYPE) != 0) { int attCount = attributes.getLength(); for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); if (fTempQName.uri == URI_XSI) { if (fTempQName.localpart != XSI_SCHEMALOCATION && fTempQName.localpart != XSI_NONAMESPACESCHEMALOCATION && fTempQName.localpart != XSI_NIL && fTempQName.localpart != XSI_TYPE) { reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname}); } } else if (fTempQName.rawname != XMLNS && !fTempQName.rawname.startsWith("xmlns:")) { reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname}); } } return; } XSAttributeUse attrUses[] = attrGrp.getAttributeUses(); int useCount = attrUses.length; XSWildcardDecl attrWildcard = attrGrp.fAttributeWC; // whether we have seen a Wildcard ID. String wildcardIDName = null; // for each present attribute int attCount = attributes.getLength(); // Element Locally Valid (Complex Type) // 3 For each attribute information item in the element information item's [attributes] excepting those whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation, the appropriate case among the following must be true: // get the corresponding attribute decl for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); // if it's from xsi namespace, it must be one of the four if (fTempQName.uri == URI_XSI) { if (fTempQName.localpart == XSI_SCHEMALOCATION || fTempQName.localpart == XSI_NONAMESPACESCHEMALOCATION || fTempQName.localpart == XSI_NIL || fTempQName.localpart == XSI_TYPE) { continue; } } else if (fTempQName.rawname == XMLNS || fTempQName.rawname.startsWith("xmlns:")) { continue; } // it's not xmlns, and not xsi, then we need to find a decl for it XSAttributeUse currUse = null; for (int i = 0; i < useCount; i++) { if (attrUses[i].fAttrDecl.fName == fTempQName.localpart && attrUses[i].fAttrDecl.fTargetNamespace == fTempQName.uri) { currUse = attrUses[i]; break; } } // 3.2 otherwise all of the following must be true: // 3.2.1 There must be an {attribute wildcard}. // 3.2.2 The attribute information item must be �valid� with respect to it as defined in Item Valid (Wildcard) (�3.10.4). // if failed, get it from wildcard if (currUse == null) { //if (attrWildcard == null) // reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname}); if (attrWildcard == null || !attrWildcard.allowNamespace(fTempQName.uri)) { // so this attribute is not allowed reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); continue; } } XSAttributeDecl currDecl = null; if (currUse != null) { currDecl = currUse.fAttrDecl; } else { // which means it matches a wildcard // skip it if it's skip if (attrWildcard.fType == XSWildcardDecl.WILDCARD_SKIP) continue; // now get the grammar and attribute decl SchemaGrammar grammar = fGrammarResolver.getGrammar(fTempQName.uri); if (grammar != null) currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart); // if can't find if (currDecl == null) { // if strict, report error if (attrWildcard.fType == XSWildcardDecl.WILDCARD_STRICT) reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); // then continue to the next attribute continue; } else { // 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose �validation� resulted in a �context-determined declaration� of mustFind or no �context-determined declaration� at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (�3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true: // 5.1 There must be no more than one item in �wild IDs�. if (currDecl.fType instanceof IDDatatypeValidator) { if (wildcardIDName != null) reportSchemaError("cvc-complex-type.5.1", new Object[]{element.rawname, currDecl.fName, wildcardIDName}); else wildcardIDName = currDecl.fName; } } } // Attribute Locally Valid // For an attribute information item to be locally �valid� with respect to an attribute declaration all of the following must be true: // 1 The declaration must not be �absent� (see Missing Sub-components (�5.3) for how this can fail to be the case). // 2 Its {type definition} must not be absent. // 3 The item's �normalized value� must be locally �valid� with respect to that {type definition} as per String Valid (�3.14.4). // get simple type DatatypeValidator attDV = currDecl.fType; // get attribute value String attrValue = attributes.getValue(index); // normalize it // REVISIT: or should the normalize() be called within validate()? attrValue = XSAttributeChecker.normalize(attrValue, attDV.getWSFacet()); Object actualValue = null; try { // REVISIT: use XSSimpleTypeDecl.ValidateContext to replace null // actualValue = attDV.validate(attrValue, null); attDV.validate(attrValue, null); } catch (InvalidDatatypeValueException idve) { reportSchemaError("cvc-attribute.3", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } // get the value constraint from use or decl // 4 The item's �actual value� must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType if (currDecl.fConstraintType == XSAttributeDecl.FIXED_VALUE) { // REVISIT: compare should be equal, and takes object, instead of string // do it in the new datatype design //if (attDV.compare((String)actualValue, (String)currDecl.fDefault) != 0) if (attDV.compare(attrValue, (String)currDecl.fDefault) != 0) reportSchemaError("cvc-attribute.4", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } // 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an �absent� {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be �valid� with respect to that attribute use as per Attribute Locally Valid (Use) (�3.5.4). In this case the {attribute declaration} of that attribute use is the �context-determined declaration� for the attribute information item with respect to Schema-Validity Assessment (Attribute) (�3.2.4) and Assessment Outcome (Attribute) (�3.2.5). if (currUse != null && currUse.fConstraintType == XSAttributeDecl.FIXED_VALUE) { // REVISIT: compare should be equal, and takes object, instead of string // do it in the new datatype design //if (attDV.compare((String)actualValue, (String)currUse.fDefault) != 0) if (attDV.compare(attrValue, (String)currUse.fDefault) != 0) reportSchemaError("cvc-complex-type.3.1", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } } // end of for (all attributes) // 5.2 If �wild IDs� is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID. if (attrGrp.fIDAttrName != null && wildcardIDName != null) reportSchemaError("cvc-complex-type.5.2", new Object[]{element.rawname, wildcardIDName, attrGrp.fIDAttrName}); } //processAttributes
diff --git a/uberfire-security/uberfire-security-server/src/main/java/org/uberfire/security/server/auth/HttpAuthenticationManager.java b/uberfire-security/uberfire-security-server/src/main/java/org/uberfire/security/server/auth/HttpAuthenticationManager.java index 5c4bf3572..c6f72fad9 100644 --- a/uberfire-security/uberfire-security-server/src/main/java/org/uberfire/security/server/auth/HttpAuthenticationManager.java +++ b/uberfire-security/uberfire-security-server/src/main/java/org/uberfire/security/server/auth/HttpAuthenticationManager.java @@ -1,191 +1,193 @@ /* * Copyright 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.security.server.auth; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import org.uberfire.security.ResourceManager; import org.uberfire.security.Role; import org.uberfire.security.SecurityContext; import org.uberfire.security.Subject; import org.uberfire.security.auth.AuthenticatedStorageProvider; import org.uberfire.security.auth.AuthenticationException; import org.uberfire.security.auth.AuthenticationManager; import org.uberfire.security.auth.AuthenticationProvider; import org.uberfire.security.auth.AuthenticationResult; import org.uberfire.security.auth.AuthenticationScheme; import org.uberfire.security.auth.Credential; import org.uberfire.security.auth.Principal; import org.uberfire.security.auth.RoleProvider; import org.uberfire.security.auth.SubjectPropertiesProvider; import org.uberfire.security.impl.IdentityImpl; import org.uberfire.security.impl.RoleImpl; import org.uberfire.security.server.HttpSecurityContext; import org.uberfire.security.server.cdi.SecurityFactory; import static org.kie.commons.validation.PortablePreconditions.checkNotEmpty; import static org.kie.commons.validation.PortablePreconditions.checkNotNull; import static org.kie.commons.validation.Preconditions.*; import static org.uberfire.security.Role.*; import static org.uberfire.security.auth.AuthenticationStatus.*; //TODO {porcelli} support for jaas! public class HttpAuthenticationManager implements AuthenticationManager { private final List<AuthenticationScheme> authSchemes; private final List<AuthenticationProvider> authProviders; private final List<RoleProvider> roleProviders; private final List<SubjectPropertiesProvider> subjectPropertiesProviders; private final List<AuthenticatedStorageProvider> authStorageProviders; private final ResourceManager resourceManager; private final Map<String, String> requestCache = new HashMap<String, String>(); //if System.getProperty("java.security.auth.login.config") != null => create a JAASProvider public HttpAuthenticationManager( final List<AuthenticationScheme> authScheme, final List<AuthenticationProvider> authProviders, final List<RoleProvider> roleProviders, final List<SubjectPropertiesProvider> subjectPropertiesProviders, final List<AuthenticatedStorageProvider> authStorageProviders, final ResourceManager resourceManager ) { this.authSchemes = checkNotEmpty( "authScheme", authScheme ); this.authProviders = checkNotEmpty( "authProviders", authProviders ); this.roleProviders = checkNotEmpty( "roleProviders", roleProviders ); this.subjectPropertiesProviders = checkNotNull( "subjectPropertiesProviders", subjectPropertiesProviders ); this.authStorageProviders = checkNotEmpty( "authStorageProviders", authStorageProviders ); this.resourceManager = checkNotNull( "resourceManager", resourceManager ); } @Override public Subject authenticate( final SecurityContext context ) throws AuthenticationException { final HttpSecurityContext httpContext = checkInstanceOf( "context", context, HttpSecurityContext.class ); Principal principal = null; for ( final AuthenticatedStorageProvider storeProvider : authStorageProviders ) { principal = storeProvider.load( httpContext ); if ( principal != null ) { break; } } if ( principal != null && principal instanceof Subject ) { return (Subject) principal; } boolean isRememberOp = principal != null; final boolean requiresAuthentication = resourceManager.requiresAuthentication( httpContext.getResource() ); if ( principal == null ) { for ( final AuthenticationScheme authScheme : authSchemes ) { if ( authScheme.isAuthenticationRequest( httpContext ) ) { break; } else if ( requiresAuthentication ) { - requestCache.put( httpContext.getRequest().getSession().getId(), httpContext.getRequest().getRequestURI() + "?" + httpContext.getRequest().getQueryString() ); + if ( !requestCache.containsKey( httpContext.getRequest().getSession().getId() ) ) { + requestCache.put( httpContext.getRequest().getSession().getId(), httpContext.getRequest().getRequestURI() + "?" + httpContext.getRequest().getQueryString() ); + } authScheme.challengeClient( httpContext ); } } if ( !requiresAuthentication ) { return null; } all_auth: for ( final AuthenticationScheme authScheme : authSchemes ) { final Credential credential = authScheme.buildCredential( httpContext ); if ( credential == null ) { continue; } for ( final AuthenticationProvider authProvider : authProviders ) { final AuthenticationResult result = authProvider.authenticate( credential ); if ( result.getStatus().equals( FAILED ) ) { throw new AuthenticationException( "Invalid credentials." ); } else if ( result.getStatus().equals( SUCCESS ) ) { principal = result.getPrincipal(); break all_auth; } } } } if ( principal == null ) { throw new AuthenticationException( "Invalid credentials." ); } final List<Role> roles = new ArrayList<Role>(); if ( isRememberOp ) { roles.add( new RoleImpl( ROLE_REMEMBER_ME ) ); } for ( final RoleProvider roleProvider : roleProviders ) { roles.addAll( roleProvider.loadRoles( principal ) ); } final Map<String, String> properties = new HashMap<String, String>(); for ( final SubjectPropertiesProvider propertiesProvider : subjectPropertiesProviders ) { properties.putAll( propertiesProvider.loadProperties( principal ) ); } final String name = principal.getName(); final Subject result = new IdentityImpl( name, roles, properties ); for ( final AuthenticatedStorageProvider storeProvider : authStorageProviders ) { storeProvider.store( httpContext, result ); } final String originalRequest = requestCache.remove( httpContext.getRequest().getSession().getId() ); if ( originalRequest != null && !originalRequest.isEmpty() && !httpContext.getResponse().isCommitted() ) { try { if ( useRedirect( originalRequest ) ) { httpContext.getResponse().sendRedirect( originalRequest ); } else { // subject must be already set here since we forwarding SecurityFactory.setSubject( result ); RequestDispatcher rd = httpContext.getRequest().getRequestDispatcher( originalRequest.replaceFirst( httpContext.getRequest().getContextPath(), "" ) ); // forward instead of sendRedirect as sendRedirect will always use GET method which // means it can change http method if non GET was used for instance POST rd.forward( httpContext.getRequest(), httpContext.getResponse() ); } } catch ( Exception e ) { throw new RuntimeException( "Unable to redirect." ); } } return result; } @Override public void logout( final SecurityContext context ) throws AuthenticationException { for ( final AuthenticatedStorageProvider storeProvider : authStorageProviders ) { storeProvider.cleanup( context ); } final HttpSecurityContext httpContext = checkInstanceOf( "context", context, HttpSecurityContext.class ); httpContext.getRequest().getSession().invalidate(); } private boolean useRedirect( String originalRequest ) { // hack for gwt hosted mode return originalRequest.contains( "gwt.codesvr" ); } }
true
true
public Subject authenticate( final SecurityContext context ) throws AuthenticationException { final HttpSecurityContext httpContext = checkInstanceOf( "context", context, HttpSecurityContext.class ); Principal principal = null; for ( final AuthenticatedStorageProvider storeProvider : authStorageProviders ) { principal = storeProvider.load( httpContext ); if ( principal != null ) { break; } } if ( principal != null && principal instanceof Subject ) { return (Subject) principal; } boolean isRememberOp = principal != null; final boolean requiresAuthentication = resourceManager.requiresAuthentication( httpContext.getResource() ); if ( principal == null ) { for ( final AuthenticationScheme authScheme : authSchemes ) { if ( authScheme.isAuthenticationRequest( httpContext ) ) { break; } else if ( requiresAuthentication ) { requestCache.put( httpContext.getRequest().getSession().getId(), httpContext.getRequest().getRequestURI() + "?" + httpContext.getRequest().getQueryString() ); authScheme.challengeClient( httpContext ); } } if ( !requiresAuthentication ) { return null; } all_auth: for ( final AuthenticationScheme authScheme : authSchemes ) { final Credential credential = authScheme.buildCredential( httpContext ); if ( credential == null ) { continue; } for ( final AuthenticationProvider authProvider : authProviders ) { final AuthenticationResult result = authProvider.authenticate( credential ); if ( result.getStatus().equals( FAILED ) ) { throw new AuthenticationException( "Invalid credentials." ); } else if ( result.getStatus().equals( SUCCESS ) ) { principal = result.getPrincipal(); break all_auth; } } } } if ( principal == null ) { throw new AuthenticationException( "Invalid credentials." ); } final List<Role> roles = new ArrayList<Role>(); if ( isRememberOp ) { roles.add( new RoleImpl( ROLE_REMEMBER_ME ) ); } for ( final RoleProvider roleProvider : roleProviders ) { roles.addAll( roleProvider.loadRoles( principal ) ); } final Map<String, String> properties = new HashMap<String, String>(); for ( final SubjectPropertiesProvider propertiesProvider : subjectPropertiesProviders ) { properties.putAll( propertiesProvider.loadProperties( principal ) ); } final String name = principal.getName(); final Subject result = new IdentityImpl( name, roles, properties ); for ( final AuthenticatedStorageProvider storeProvider : authStorageProviders ) { storeProvider.store( httpContext, result ); } final String originalRequest = requestCache.remove( httpContext.getRequest().getSession().getId() ); if ( originalRequest != null && !originalRequest.isEmpty() && !httpContext.getResponse().isCommitted() ) { try { if ( useRedirect( originalRequest ) ) { httpContext.getResponse().sendRedirect( originalRequest ); } else { // subject must be already set here since we forwarding SecurityFactory.setSubject( result ); RequestDispatcher rd = httpContext.getRequest().getRequestDispatcher( originalRequest.replaceFirst( httpContext.getRequest().getContextPath(), "" ) ); // forward instead of sendRedirect as sendRedirect will always use GET method which // means it can change http method if non GET was used for instance POST rd.forward( httpContext.getRequest(), httpContext.getResponse() ); } } catch ( Exception e ) { throw new RuntimeException( "Unable to redirect." ); } } return result; }
public Subject authenticate( final SecurityContext context ) throws AuthenticationException { final HttpSecurityContext httpContext = checkInstanceOf( "context", context, HttpSecurityContext.class ); Principal principal = null; for ( final AuthenticatedStorageProvider storeProvider : authStorageProviders ) { principal = storeProvider.load( httpContext ); if ( principal != null ) { break; } } if ( principal != null && principal instanceof Subject ) { return (Subject) principal; } boolean isRememberOp = principal != null; final boolean requiresAuthentication = resourceManager.requiresAuthentication( httpContext.getResource() ); if ( principal == null ) { for ( final AuthenticationScheme authScheme : authSchemes ) { if ( authScheme.isAuthenticationRequest( httpContext ) ) { break; } else if ( requiresAuthentication ) { if ( !requestCache.containsKey( httpContext.getRequest().getSession().getId() ) ) { requestCache.put( httpContext.getRequest().getSession().getId(), httpContext.getRequest().getRequestURI() + "?" + httpContext.getRequest().getQueryString() ); } authScheme.challengeClient( httpContext ); } } if ( !requiresAuthentication ) { return null; } all_auth: for ( final AuthenticationScheme authScheme : authSchemes ) { final Credential credential = authScheme.buildCredential( httpContext ); if ( credential == null ) { continue; } for ( final AuthenticationProvider authProvider : authProviders ) { final AuthenticationResult result = authProvider.authenticate( credential ); if ( result.getStatus().equals( FAILED ) ) { throw new AuthenticationException( "Invalid credentials." ); } else if ( result.getStatus().equals( SUCCESS ) ) { principal = result.getPrincipal(); break all_auth; } } } } if ( principal == null ) { throw new AuthenticationException( "Invalid credentials." ); } final List<Role> roles = new ArrayList<Role>(); if ( isRememberOp ) { roles.add( new RoleImpl( ROLE_REMEMBER_ME ) ); } for ( final RoleProvider roleProvider : roleProviders ) { roles.addAll( roleProvider.loadRoles( principal ) ); } final Map<String, String> properties = new HashMap<String, String>(); for ( final SubjectPropertiesProvider propertiesProvider : subjectPropertiesProviders ) { properties.putAll( propertiesProvider.loadProperties( principal ) ); } final String name = principal.getName(); final Subject result = new IdentityImpl( name, roles, properties ); for ( final AuthenticatedStorageProvider storeProvider : authStorageProviders ) { storeProvider.store( httpContext, result ); } final String originalRequest = requestCache.remove( httpContext.getRequest().getSession().getId() ); if ( originalRequest != null && !originalRequest.isEmpty() && !httpContext.getResponse().isCommitted() ) { try { if ( useRedirect( originalRequest ) ) { httpContext.getResponse().sendRedirect( originalRequest ); } else { // subject must be already set here since we forwarding SecurityFactory.setSubject( result ); RequestDispatcher rd = httpContext.getRequest().getRequestDispatcher( originalRequest.replaceFirst( httpContext.getRequest().getContextPath(), "" ) ); // forward instead of sendRedirect as sendRedirect will always use GET method which // means it can change http method if non GET was used for instance POST rd.forward( httpContext.getRequest(), httpContext.getResponse() ); } } catch ( Exception e ) { throw new RuntimeException( "Unable to redirect." ); } } return result; }
diff --git a/src/main/com/trendrr/oss/networking/http/Http.java b/src/main/com/trendrr/oss/networking/http/Http.java index 64759b6..996a238 100644 --- a/src/main/com/trendrr/oss/networking/http/Http.java +++ b/src/main/com/trendrr/oss/networking/http/Http.java @@ -1,300 +1,300 @@ /** * */ package com.trendrr.oss.networking.http; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URL; import java.net.URLConnection; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.trendrr.oss.DynMap; import com.trendrr.oss.Regex; import com.trendrr.oss.StringHelper; import com.trendrr.oss.TypeCast; import com.trendrr.oss.exceptions.TrendrrException; import com.trendrr.oss.exceptions.TrendrrIOException; import com.trendrr.oss.exceptions.TrendrrNetworkingException; import com.trendrr.oss.exceptions.TrendrrParseException; import com.trendrr.oss.networking.SocketChannelWrapper; /** * Simple http class. * * This makes it much easier to deal with headers, and funky requests. Apache httpclient is unusable... * * * @author Dustin Norlander * @created Jun 13, 2012 * */ public class Http { protected static Log log = LogFactory.getLog(Http.class); public static void main(String ...strings) throws Exception { // String test = "11\n{ \"status\":\"OK\" }\n0"; // byte[] a = readLine('\n',new ByteArrayInputStream(test.getBytes())); // System.out.println("a is: "+a.toString()+" of length "+ a.length); HttpRequest request = new HttpRequest(); request.setUrl("http://www.google.com/#hl=en&output=search&sclient=psy-ab&q=test&oq=test&aq=f&aqi=g4"); request.setMethod("GET"); // request.setUrl("https://tools.questionmarket.com/verveindex/trendrr_ping.pl"); // request.setMethod("POST"); // request.setContent("application/json", "this is a test".getBytes()); HttpResponse response = request(request); System.out.println(new String(response.getContent())); } public static HttpResponse request(HttpRequest request) throws TrendrrException { String host = request.getHost(); int port = 80; if (host.contains(":")) { String tmp[] = host.split("\\:"); host = tmp[0]; port = TypeCast.cast(Integer.class, tmp[1]); } Socket socket = null; try { if (request.isSSL()) { System.out.println("SSL!"); //uhh, what the hell do we do here? if (port == 80) { port = 443; } SocketFactory socketFactory = SSLSocketFactory.getDefault(); socket = socketFactory.createSocket(host, port); return doRequest(request, socket); } else { socket = new Socket(host, port); return doRequest(request, socket); } } catch (IOException x) { throw new TrendrrIOException(x); } catch (Exception x) { throw new TrendrrException(x); } finally { try { if (socket != null) { socket.close(); } } catch (Exception x) {} } } private static HttpResponse doRequest(HttpRequest request, Socket socket) throws IOException, TrendrrParseException { //TODO: socket timeouts // Create streams to securely send and receive data to the server InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); out.write(request.toByteArray()); // Read from in and write to out... String t; ByteArrayOutputStream contentoutput = new ByteArrayOutputStream(); // s.getInputStream().r StringBuilder headerBuilder = new StringBuilder(); while(!(t = readLine(in)).isEmpty()) { System.out.println("t is--"+t+"--end"); System.out.println("t.length="+t.length()); headerBuilder.append(t).append("\r\n"); } String headers = headerBuilder.toString(); System.out.println("headers="+headers+"--end"); HttpResponse response = HttpResponse.parse(headers); byte[] content = null; if (response.getHeader("Content-Length") != null) { content = new byte[getContentLength(response)]; in.read(content); contentoutput.write(content, 0, content.length); } else { String chunked = response.getHeader("Transfer-Encoding"); if (chunked != null && chunked.equalsIgnoreCase("chunked")) { int length = 1; String lengthstr = ""; while((lengthstr = readLine(in)) != null){ System.out.println("line:"+lengthstr); if(lengthstr.isEmpty()){ System.out.println("lengthstr is empty, skipping"); continue; }else { length = Integer.parseInt(lengthstr,16); System.out.println("length: "+length); if(length==0){ System.out.println("last chunk has been read"); break; } content = new byte[length]; int numread; int total=0; while(total < length && - (numread = in.read(content,0,length)) != -1){ + (numread = in.read(content,0,content.length-total)) != -1){ System.out.println("written: "+numread); // System.out.println("content: "+new String(content)); contentoutput.write(content, 0, numread); total+=numread; } } } } } contentoutput.close(); in.close(); out.close(); response.setContent(contentoutput.toByteArray()); return response; } /** * Method reads string until occurrence of "\r\n" or "\n", consistent with HTTP protocol * @param in stream to read in from * @return String consists of characters upto and excluding the newline characters */ private static String readLine(InputStream in) throws IOException{ byte current = 'a'; byte[] temp = new byte[1000];//is this large enough to handle any header content? int offset=-1; while((char)current != '\n'){ offset++; in.read(temp, offset, 1); // System.out.println("result at: "+offset+"="+(char)temp[offset]); current = temp[offset]; } int resultlen = 0; if(offset > 0){ if((char)temp[offset-1]=='\r'){//in case of "\r\n" termination, we ignore the \r resultlen = offset-1; }else{ resultlen = offset;//in case of lone "\n" termination } } byte[] result = new byte[resultlen]; for(int i=0; i<result.length; i++){ result[i]=temp[i]; } return new String(result); } private static int getContentLength(HttpResponse response) { int length = TypeCast.cast(Integer.class, response.getHeader("Content-Length"), 0); return length; } public static String get(String url) throws TrendrrNetworkingException { return get(url, null); } /** * Shortcut to do a simple GET request. returns the content on 200, else throws an exception * @param url * @param params * @return * @throws TrendrrNetworkingException */ public static String get(String url, DynMap params) throws TrendrrNetworkingException { try { if (!url.contains("?")) { url += "?"; } if (params != null) { url += params.toURLString(); } HttpRequest request = new HttpRequest(); request.setUrl(url); request.setMethod("GET"); HttpResponse response = request(request); if (response.getStatusCode() == 200) { return new String(response.getContent(), "utf8"); } //TODO: some kind of http exception. throw new TrendrrNetworkingException("Error from response") { }; } catch (TrendrrNetworkingException e) { throw e; }catch (Exception x) { throw new TrendrrIOException(x); } } public static String post(String url, DynMap params) throws TrendrrNetworkingException { try { //TODO: update for using request. URL u = new URL(url); URLConnection c = u.openConnection(); c.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(c.getOutputStream()); wr.write(params.toURLString()); wr.flush(); BufferedReader in = new BufferedReader( new InputStreamReader( c.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } catch (Exception x) { throw new TrendrrIOException(x); } } }
true
true
private static HttpResponse doRequest(HttpRequest request, Socket socket) throws IOException, TrendrrParseException { //TODO: socket timeouts // Create streams to securely send and receive data to the server InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); out.write(request.toByteArray()); // Read from in and write to out... String t; ByteArrayOutputStream contentoutput = new ByteArrayOutputStream(); // s.getInputStream().r StringBuilder headerBuilder = new StringBuilder(); while(!(t = readLine(in)).isEmpty()) { System.out.println("t is--"+t+"--end"); System.out.println("t.length="+t.length()); headerBuilder.append(t).append("\r\n"); } String headers = headerBuilder.toString(); System.out.println("headers="+headers+"--end"); HttpResponse response = HttpResponse.parse(headers); byte[] content = null; if (response.getHeader("Content-Length") != null) { content = new byte[getContentLength(response)]; in.read(content); contentoutput.write(content, 0, content.length); } else { String chunked = response.getHeader("Transfer-Encoding"); if (chunked != null && chunked.equalsIgnoreCase("chunked")) { int length = 1; String lengthstr = ""; while((lengthstr = readLine(in)) != null){ System.out.println("line:"+lengthstr); if(lengthstr.isEmpty()){ System.out.println("lengthstr is empty, skipping"); continue; }else { length = Integer.parseInt(lengthstr,16); System.out.println("length: "+length); if(length==0){ System.out.println("last chunk has been read"); break; } content = new byte[length]; int numread; int total=0; while(total < length && (numread = in.read(content,0,length)) != -1){ System.out.println("written: "+numread); // System.out.println("content: "+new String(content)); contentoutput.write(content, 0, numread); total+=numread; } } } } } contentoutput.close(); in.close(); out.close(); response.setContent(contentoutput.toByteArray()); return response; }
private static HttpResponse doRequest(HttpRequest request, Socket socket) throws IOException, TrendrrParseException { //TODO: socket timeouts // Create streams to securely send and receive data to the server InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); out.write(request.toByteArray()); // Read from in and write to out... String t; ByteArrayOutputStream contentoutput = new ByteArrayOutputStream(); // s.getInputStream().r StringBuilder headerBuilder = new StringBuilder(); while(!(t = readLine(in)).isEmpty()) { System.out.println("t is--"+t+"--end"); System.out.println("t.length="+t.length()); headerBuilder.append(t).append("\r\n"); } String headers = headerBuilder.toString(); System.out.println("headers="+headers+"--end"); HttpResponse response = HttpResponse.parse(headers); byte[] content = null; if (response.getHeader("Content-Length") != null) { content = new byte[getContentLength(response)]; in.read(content); contentoutput.write(content, 0, content.length); } else { String chunked = response.getHeader("Transfer-Encoding"); if (chunked != null && chunked.equalsIgnoreCase("chunked")) { int length = 1; String lengthstr = ""; while((lengthstr = readLine(in)) != null){ System.out.println("line:"+lengthstr); if(lengthstr.isEmpty()){ System.out.println("lengthstr is empty, skipping"); continue; }else { length = Integer.parseInt(lengthstr,16); System.out.println("length: "+length); if(length==0){ System.out.println("last chunk has been read"); break; } content = new byte[length]; int numread; int total=0; while(total < length && (numread = in.read(content,0,content.length-total)) != -1){ System.out.println("written: "+numread); // System.out.println("content: "+new String(content)); contentoutput.write(content, 0, numread); total+=numread; } } } } } contentoutput.close(); in.close(); out.close(); response.setContent(contentoutput.toByteArray()); return response; }
diff --git a/exo.core.component.database/src/main/java/org/exoplatform/services/database/impl/HibernateServiceImpl.java b/exo.core.component.database/src/main/java/org/exoplatform/services/database/impl/HibernateServiceImpl.java index d923b449..7273b7fe 100644 --- a/exo.core.component.database/src/main/java/org/exoplatform/services/database/impl/HibernateServiceImpl.java +++ b/exo.core.component.database/src/main/java/org/exoplatform/services/database/impl/HibernateServiceImpl.java @@ -1,454 +1,454 @@ /* * 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.database.impl; import org.exoplatform.commons.exception.ObjectNotFoundException; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.container.component.ComponentRequestLifecycle; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.PropertiesParam; import org.exoplatform.container.xml.Property; import org.exoplatform.services.cache.CacheService; import org.exoplatform.services.database.HibernateService; import org.exoplatform.services.database.ObjectQuery; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.resolver.DialectFactory; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import java.io.Serializable; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; /** * Created by The eXo Platform SAS . * * @author Tuan Nguyen [email protected] Date: Jun 14, 2003 * @author dhodnett $Id: HibernateServiceImpl.java,v 1.3 2004/10/30 02:27:52 * tuan08 Exp $ */ public class HibernateServiceImpl implements HibernateService, ComponentRequestLifecycle { public static final String AUTO_DIALECT = "AUTO"; private ThreadLocal<Session> threadLocal_; private static Log log_ = ExoLogger.getLogger(HibernateServiceImpl.class); private HibernateConfigurationImpl conf_; private SessionFactory sessionFactory_; private HashSet<String> mappings_ = new HashSet<String>(); @SuppressWarnings("unchecked") public HibernateServiceImpl(InitParams initParams, CacheService cacheService) { threadLocal_ = new ThreadLocal<Session>(); PropertiesParam param = initParams.getPropertiesParam("hibernate.properties"); HibernateSettingsFactory settingsFactory = new HibernateSettingsFactory(new ExoCacheProvider(cacheService)); conf_ = new HibernateConfigurationImpl(settingsFactory); Iterator properties = param.getPropertyIterator(); while (properties.hasNext()) { Property p = (Property)properties.next(); // String name = p.getName(); String value = p.getValue(); // Julien: Don't remove that unless you know what you are doing if (name.equals("hibernate.dialect") && !value.equalsIgnoreCase(AUTO_DIALECT)) { Package pkg = Dialect.class.getPackage(); String dialect = value.substring(22); value = pkg.getName() + "." + dialect; // 22 is the length of // "org.hibernate.dialect" log_.info("Using dialect " + dialect); } // conf_.setProperty(name, value); } // Replace the potential "java.io.tmpdir" variable in the connection URL String connectionURL = conf_.getProperty("hibernate.connection.url"); if (connectionURL != null) { connectionURL = connectionURL.replace("${java.io.tmpdir}", System.getProperty("java.io.tmpdir")); conf_.setProperty("hibernate.connection.url", connectionURL); } // Auto-detect dialect if "hibernate.dialect" is set as AUTO or is not set. String dialect = conf_.getProperty("hibernate.dialect"); - if (dialect != null && dialect.equalsIgnoreCase(AUTO_DIALECT)) + if (dialect == null || dialect.equalsIgnoreCase(AUTO_DIALECT)) { // detect dialect and replace parameter Connection connection = null; try { // check is there is datasource String dataSourceName = conf_.getProperty("hibernate.connection.datasource"); if (dataSourceName != null) { //detect with datasource DataSource dataSource; try { dataSource = (DataSource)new InitialContext().lookup(dataSourceName); if (dataSource == null) { log_.error("DataSource is configured but not finded.", new Exception()); } connection = dataSource.getConnection(); Dialect d = DialectFactory.buildDialect(new Properties(), connection); conf_.setProperty("hibernate.dialect", d.getClass().getName()); } catch (NamingException e) { log_.error(e.getMessage(), e); } } else { String url = conf_.getProperty("hibernate.connection.url"); if (url != null) { //detect with url //get driver class try { Class.forName(conf_.getProperty("hibernate.connection.driver_class")).newInstance(); } catch (InstantiationException e) { log_.error(e.getMessage(), e); } catch (IllegalAccessException e) { log_.error(e.getMessage(), e); } catch (ClassNotFoundException e) { log_.error(e.getMessage(), e); } String dbUserName = conf_.getProperty("hibernate.connection.username"); String dbPassword = conf_.getProperty("hibernate.connection.password"); connection = dbUserName != null ? DriverManager.getConnection(url, dbUserName, dbPassword) : DriverManager .getConnection(url); Dialect d = DialectFactory.buildDialect(new Properties(), connection); conf_.setProperty("hibernate.dialect", d.getClass().getName()); } else { Exception e = new Exception("Any data source is not configured!"); log_.error(e.getMessage(), e); } } } catch (SQLException e) { log_.error(e.getMessage(), e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { log_.error(e.getMessage(), e); } } } } } public void addPlugin(ComponentPlugin plugin) { if (plugin instanceof AddHibernateMappingPlugin) { AddHibernateMappingPlugin impl = (AddHibernateMappingPlugin)plugin; try { List path = impl.getMapping(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (path != null) { for (int i = 0; i < path.size(); i++) { String relativePath = (String)path.get(i); if (!mappings_.contains(relativePath)) { mappings_.add(relativePath); URL url = cl.getResource(relativePath); log_.info("Adding Hibernate Mapping: " + relativePath); conf_.addURL(url); } } } // Annotations List<String> annotations = impl.getAnnotations(); if (annotations != null) { for (String annotation : annotations) { Class clazz = cl.loadClass(annotation); conf_.addAnnotatedClass(clazz); } } } catch (Exception ex) { ex.printStackTrace(); } } } public ComponentPlugin removePlugin(String name) { return null; } public Collection getPlugins() { return null; } public Configuration getHibernateConfiguration() { return conf_; } /** * @return the SessionFactory */ public SessionFactory getSessionFactory() { if (sessionFactory_ == null) { sessionFactory_ = conf_.buildSessionFactory(); new SchemaUpdate(conf_).execute(false, true); } return sessionFactory_; } public Session openSession() { Session currentSession = threadLocal_.get(); if (currentSession == null) { if (log_.isDebugEnabled()) log_.debug("open new hibernate session in openSession()"); currentSession = getSessionFactory().openSession(); threadLocal_.set(currentSession); } return currentSession; } public Session openNewSession() { Session currentSession = threadLocal_.get(); if (currentSession != null) { closeSession(currentSession); } currentSession = getSessionFactory().openSession(); threadLocal_.set(currentSession); return currentSession; } public void closeSession(Session session) { if (session == null) return; try { session.close(); if (log_.isDebugEnabled()) log_.debug("close hibernate session in openSession(Session session)"); } catch (Throwable t) { log_.error("Error closing hibernate session : " + t.getMessage(), t); } threadLocal_.set(null); } final public void closeSession() { Session s = threadLocal_.get(); if (s != null) s.close(); threadLocal_.set(null); } public Object findExactOne(Session session, String query, String id) throws Exception { Object res = session.createQuery(query).setString(0, id).uniqueResult(); if (res == null) { throw new ObjectNotFoundException("Cannot find the object with id: " + id); } return res; } public Object findOne(Session session, String query, String id) throws Exception { List l = session.createQuery(query).setString(0, id).list(); if (l.size() == 0) { return null; } else if (l.size() > 1) { throw new Exception("Expect only one object but found" + l.size()); } else { return l.get(0); } } public Object findOne(Class clazz, Serializable id) throws Exception { Session session = openSession(); Object obj = session.get(clazz, id); return obj; } public Object findOne(ObjectQuery q) throws Exception { Session session = openSession(); List l = session.createQuery(q.getHibernateQuery()).list(); if (l.size() == 0) { return null; } else if (l.size() > 1) { throw new Exception("Expect only one object but found" + l.size()); } else { return l.get(0); } } public Object create(Object obj) throws Exception { Session session = openSession(); session.save(obj); session.flush(); return obj; } public Object update(Object obj) throws Exception { Session session = openSession(); session.update(obj); session.flush(); return obj; } public Object save(Object obj) throws Exception { Session session = openSession(); session.merge(obj); session.flush(); return obj; } public Object remove(Object obj) throws Exception { Session session = openSession(); session.delete(obj); session.flush(); return obj; } public Object remove(Class clazz, Serializable id) throws Exception { Session session = openSession(); Object obj = session.get(clazz, id); session.delete(obj); session.flush(); return obj; } public Object remove(Session session, Class clazz, Serializable id) throws Exception { Object obj = session.get(clazz, id); session.delete(obj); return obj; } public void startRequest(ExoContainer container) { } public void endRequest(ExoContainer container) { closeSession(); } }
true
true
public HibernateServiceImpl(InitParams initParams, CacheService cacheService) { threadLocal_ = new ThreadLocal<Session>(); PropertiesParam param = initParams.getPropertiesParam("hibernate.properties"); HibernateSettingsFactory settingsFactory = new HibernateSettingsFactory(new ExoCacheProvider(cacheService)); conf_ = new HibernateConfigurationImpl(settingsFactory); Iterator properties = param.getPropertyIterator(); while (properties.hasNext()) { Property p = (Property)properties.next(); // String name = p.getName(); String value = p.getValue(); // Julien: Don't remove that unless you know what you are doing if (name.equals("hibernate.dialect") && !value.equalsIgnoreCase(AUTO_DIALECT)) { Package pkg = Dialect.class.getPackage(); String dialect = value.substring(22); value = pkg.getName() + "." + dialect; // 22 is the length of // "org.hibernate.dialect" log_.info("Using dialect " + dialect); } // conf_.setProperty(name, value); } // Replace the potential "java.io.tmpdir" variable in the connection URL String connectionURL = conf_.getProperty("hibernate.connection.url"); if (connectionURL != null) { connectionURL = connectionURL.replace("${java.io.tmpdir}", System.getProperty("java.io.tmpdir")); conf_.setProperty("hibernate.connection.url", connectionURL); } // Auto-detect dialect if "hibernate.dialect" is set as AUTO or is not set. String dialect = conf_.getProperty("hibernate.dialect"); if (dialect != null && dialect.equalsIgnoreCase(AUTO_DIALECT)) { // detect dialect and replace parameter Connection connection = null; try { // check is there is datasource String dataSourceName = conf_.getProperty("hibernate.connection.datasource"); if (dataSourceName != null) { //detect with datasource DataSource dataSource; try { dataSource = (DataSource)new InitialContext().lookup(dataSourceName); if (dataSource == null) { log_.error("DataSource is configured but not finded.", new Exception()); } connection = dataSource.getConnection(); Dialect d = DialectFactory.buildDialect(new Properties(), connection); conf_.setProperty("hibernate.dialect", d.getClass().getName()); } catch (NamingException e) { log_.error(e.getMessage(), e); } } else { String url = conf_.getProperty("hibernate.connection.url"); if (url != null) { //detect with url //get driver class try { Class.forName(conf_.getProperty("hibernate.connection.driver_class")).newInstance(); } catch (InstantiationException e) { log_.error(e.getMessage(), e); } catch (IllegalAccessException e) { log_.error(e.getMessage(), e); } catch (ClassNotFoundException e) { log_.error(e.getMessage(), e); } String dbUserName = conf_.getProperty("hibernate.connection.username"); String dbPassword = conf_.getProperty("hibernate.connection.password"); connection = dbUserName != null ? DriverManager.getConnection(url, dbUserName, dbPassword) : DriverManager .getConnection(url); Dialect d = DialectFactory.buildDialect(new Properties(), connection); conf_.setProperty("hibernate.dialect", d.getClass().getName()); } else { Exception e = new Exception("Any data source is not configured!"); log_.error(e.getMessage(), e); } } } catch (SQLException e) { log_.error(e.getMessage(), e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { log_.error(e.getMessage(), e); } } } } }
public HibernateServiceImpl(InitParams initParams, CacheService cacheService) { threadLocal_ = new ThreadLocal<Session>(); PropertiesParam param = initParams.getPropertiesParam("hibernate.properties"); HibernateSettingsFactory settingsFactory = new HibernateSettingsFactory(new ExoCacheProvider(cacheService)); conf_ = new HibernateConfigurationImpl(settingsFactory); Iterator properties = param.getPropertyIterator(); while (properties.hasNext()) { Property p = (Property)properties.next(); // String name = p.getName(); String value = p.getValue(); // Julien: Don't remove that unless you know what you are doing if (name.equals("hibernate.dialect") && !value.equalsIgnoreCase(AUTO_DIALECT)) { Package pkg = Dialect.class.getPackage(); String dialect = value.substring(22); value = pkg.getName() + "." + dialect; // 22 is the length of // "org.hibernate.dialect" log_.info("Using dialect " + dialect); } // conf_.setProperty(name, value); } // Replace the potential "java.io.tmpdir" variable in the connection URL String connectionURL = conf_.getProperty("hibernate.connection.url"); if (connectionURL != null) { connectionURL = connectionURL.replace("${java.io.tmpdir}", System.getProperty("java.io.tmpdir")); conf_.setProperty("hibernate.connection.url", connectionURL); } // Auto-detect dialect if "hibernate.dialect" is set as AUTO or is not set. String dialect = conf_.getProperty("hibernate.dialect"); if (dialect == null || dialect.equalsIgnoreCase(AUTO_DIALECT)) { // detect dialect and replace parameter Connection connection = null; try { // check is there is datasource String dataSourceName = conf_.getProperty("hibernate.connection.datasource"); if (dataSourceName != null) { //detect with datasource DataSource dataSource; try { dataSource = (DataSource)new InitialContext().lookup(dataSourceName); if (dataSource == null) { log_.error("DataSource is configured but not finded.", new Exception()); } connection = dataSource.getConnection(); Dialect d = DialectFactory.buildDialect(new Properties(), connection); conf_.setProperty("hibernate.dialect", d.getClass().getName()); } catch (NamingException e) { log_.error(e.getMessage(), e); } } else { String url = conf_.getProperty("hibernate.connection.url"); if (url != null) { //detect with url //get driver class try { Class.forName(conf_.getProperty("hibernate.connection.driver_class")).newInstance(); } catch (InstantiationException e) { log_.error(e.getMessage(), e); } catch (IllegalAccessException e) { log_.error(e.getMessage(), e); } catch (ClassNotFoundException e) { log_.error(e.getMessage(), e); } String dbUserName = conf_.getProperty("hibernate.connection.username"); String dbPassword = conf_.getProperty("hibernate.connection.password"); connection = dbUserName != null ? DriverManager.getConnection(url, dbUserName, dbPassword) : DriverManager .getConnection(url); Dialect d = DialectFactory.buildDialect(new Properties(), connection); conf_.setProperty("hibernate.dialect", d.getClass().getName()); } else { Exception e = new Exception("Any data source is not configured!"); log_.error(e.getMessage(), e); } } } catch (SQLException e) { log_.error(e.getMessage(), e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { log_.error(e.getMessage(), e); } } } } }
diff --git a/src/main/java/net/intelie/lognit/cli/http/BayeuxFactory.java b/src/main/java/net/intelie/lognit/cli/http/BayeuxFactory.java index 30cf854..1e0528a 100644 --- a/src/main/java/net/intelie/lognit/cli/http/BayeuxFactory.java +++ b/src/main/java/net/intelie/lognit/cli/http/BayeuxFactory.java @@ -1,15 +1,13 @@ package net.intelie.lognit.cli.http; import org.cometd.client.BayeuxClient; import org.cometd.client.transport.LongPollingTransport; import org.eclipse.jetty.client.HttpClient; import java.util.HashMap; public class BayeuxFactory { public BayeuxClient create(String uri) { - HttpClient client = new HttpClient(); - client.setTimeout(1000); - return new BayeuxClient(uri, LongPollingTransport.create(null, client)); + return new BayeuxClient(uri, LongPollingTransport.create(null)); } }
true
true
public BayeuxClient create(String uri) { HttpClient client = new HttpClient(); client.setTimeout(1000); return new BayeuxClient(uri, LongPollingTransport.create(null, client)); }
public BayeuxClient create(String uri) { return new BayeuxClient(uri, LongPollingTransport.create(null)); }
diff --git a/src/core/org/apache/hadoop/ipc/Client.java b/src/core/org/apache/hadoop/ipc/Client.java index 05081b876..98dafbce6 100644 --- a/src/core/org/apache/hadoop/ipc/Client.java +++ b/src/core/org/apache/hadoop/ipc/Client.java @@ -1,1065 +1,1070 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.ipc; import java.net.Socket; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.net.ConnectException; import java.io.IOException; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FilterInputStream; import java.io.InputStream; import java.io.OutputStream; import java.security.PrivilegedExceptionAction; import java.util.Hashtable; import java.util.Iterator; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import javax.net.SocketFactory; import org.apache.commons.logging.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.KerberosInfo; import org.apache.hadoop.security.SaslRpcClient; import org.apache.hadoop.security.SaslRpcServer.AuthMethod; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.security.token.TokenSelector; import org.apache.hadoop.security.token.TokenInfo; import org.apache.hadoop.util.ReflectionUtils; /** A client for an IPC service. IPC calls take a single {@link Writable} as a * parameter, and return a {@link Writable} as their value. A service runs on * a port and is defined by a parameter class and a value class. * * @see Server */ public class Client { public static final Log LOG = LogFactory.getLog(Client.class); private Hashtable<ConnectionId, Connection> connections = new Hashtable<ConnectionId, Connection>(); private Class<? extends Writable> valueClass; // class of call values private int counter; // counter for call ids private AtomicBoolean running = new AtomicBoolean(true); // if client runs final private Configuration conf; final private int maxIdleTime; //connections will be culled if it was idle for //maxIdleTime msecs final private int maxRetries; //the max. no. of retries for socket connections private boolean tcpNoDelay; // if T then disable Nagle's Algorithm private int pingInterval; // how often sends ping to the server in msecs private SocketFactory socketFactory; // how to create sockets private int refCount = 1; final private static String PING_INTERVAL_NAME = "ipc.ping.interval"; final static int DEFAULT_PING_INTERVAL = 60000; // 1 min final static int PING_CALL_ID = -1; /** * set the ping interval value in configuration * * @param conf Configuration * @param pingInterval the ping interval */ final public static void setPingInterval(Configuration conf, int pingInterval) { conf.setInt(PING_INTERVAL_NAME, pingInterval); } /** * Get the ping interval from configuration; * If not set in the configuration, return the default value. * * @param conf Configuration * @return the ping interval */ final static int getPingInterval(Configuration conf) { return conf.getInt(PING_INTERVAL_NAME, DEFAULT_PING_INTERVAL); } /** * Increment this client's reference count * */ synchronized void incCount() { refCount++; } /** * Decrement this client's reference count * */ synchronized void decCount() { refCount--; } /** * Return if this client has no reference * * @return true if this client has no reference; false otherwise */ synchronized boolean isZeroReference() { return refCount==0; } /** A call waiting for a value. */ private class Call { int id; // call id Writable param; // parameter Writable value; // value, null if error IOException error; // exception, null if value boolean done; // true when call is done protected Call(Writable param) { this.param = param; synchronized (Client.this) { this.id = counter++; } } /** Indicate when the call is complete and the * value or error are available. Notifies by default. */ protected synchronized void callComplete() { this.done = true; notify(); // notify caller } /** Set the exception when there is an error. * Notify the caller the call is done. * * @param error exception thrown by the call; either local or remote */ public synchronized void setException(IOException error) { this.error = error; callComplete(); } /** Set the return value when there is no error. * Notify the caller the call is done. * * @param value return value of the call. */ public synchronized void setValue(Writable value) { this.value = value; callComplete(); } } /** Thread that reads responses and notifies callers. Each connection owns a * socket connected to a remote address. Calls are multiplexed through this * socket: responses may be delivered out of order. */ private class Connection extends Thread { private InetSocketAddress server; // server ip:port private String serverPrincipal; // server's krb5 principal name private ConnectionHeader header; // connection header private final ConnectionId remoteId; // connection id private AuthMethod authMethod; // authentication method private boolean useSasl; private Token<? extends TokenIdentifier> token; private SaslRpcClient saslRpcClient; private Socket socket = null; // connected socket private DataInputStream in; private DataOutputStream out; // currently active calls private Hashtable<Integer, Call> calls = new Hashtable<Integer, Call>(); private AtomicLong lastActivity = new AtomicLong();// last I/O activity time private AtomicBoolean shouldCloseConnection = new AtomicBoolean(); // indicate if the connection is closed private IOException closeException; // close reason public Connection(ConnectionId remoteId) throws IOException { this.remoteId = remoteId; this.server = remoteId.getAddress(); if (server.isUnresolved()) { throw new UnknownHostException("unknown host: " + remoteId.getAddress().getHostName()); } UserGroupInformation ticket = remoteId.getTicket(); Class<?> protocol = remoteId.getProtocol(); this.useSasl = UserGroupInformation.isSecurityEnabled(); if (useSasl && protocol != null) { TokenInfo tokenInfo = protocol.getAnnotation(TokenInfo.class); if (tokenInfo != null) { TokenSelector<? extends TokenIdentifier> tokenSelector = null; try { tokenSelector = tokenInfo.value().newInstance(); } catch (InstantiationException e) { throw new IOException(e.toString()); } catch (IllegalAccessException e) { throw new IOException(e.toString()); } InetSocketAddress addr = remoteId.getAddress(); token = tokenSelector.selectToken(new Text(addr.getAddress() .getHostAddress() + ":" + addr.getPort()), ticket.getTokens()); } KerberosInfo krbInfo = protocol.getAnnotation(KerberosInfo.class); if (krbInfo != null) { String serverKey = krbInfo.serverPrincipal(); if (serverKey == null) { throw new IOException( "Can't obtain server Kerberos config key from KerberosInfo"); } serverPrincipal = SecurityUtil.getServerPrincipal( conf.get(serverKey), server.getAddress().getCanonicalHostName()); if (LOG.isDebugEnabled()) { LOG.debug("RPC Server Kerberos principal name for protocol=" + protocol.getCanonicalName() + " is " + serverPrincipal); } } } if (!useSasl) { authMethod = AuthMethod.SIMPLE; } else if (token != null) { authMethod = AuthMethod.DIGEST; } else { authMethod = AuthMethod.KERBEROS; } header = new ConnectionHeader(protocol == null ? null : protocol .getName(), ticket, authMethod); if (LOG.isDebugEnabled()) LOG.debug("Use " + authMethod + " authentication for protocol " + protocol.getSimpleName()); this.setName("IPC Client (" + socketFactory.hashCode() +") connection to " + remoteId.getAddress().toString() + " from " + ((ticket==null)?"an unknown user":ticket.getUserName())); this.setDaemon(true); } /** Update lastActivity with the current time. */ private void touch() { lastActivity.set(System.currentTimeMillis()); } /** * Add a call to this connection's call queue and notify * a listener; synchronized. * Returns false if called during shutdown. * @param call to add * @return true if the call was added. */ private synchronized boolean addCall(Call call) { if (shouldCloseConnection.get()) return false; calls.put(call.id, call); notify(); return true; } /** This class sends a ping to the remote side when timeout on * reading. If no failure is detected, it retries until at least * a byte is read. */ private class PingInputStream extends FilterInputStream { /* constructor */ protected PingInputStream(InputStream in) { super(in); } /* Process timeout exception * if the connection is not going to be closed, send a ping. * otherwise, throw the timeout exception. */ private void handleTimeout(SocketTimeoutException e) throws IOException { if (shouldCloseConnection.get() || !running.get()) { throw e; } else { sendPing(); } } /** Read a byte from the stream. * Send a ping if timeout on read. Retries if no failure is detected * until a byte is read. * @throws IOException for any IO problem other than socket timeout */ public int read() throws IOException { do { try { return super.read(); } catch (SocketTimeoutException e) { handleTimeout(e); } } while (true); } /** Read bytes into a buffer starting from offset <code>off</code> * Send a ping if timeout on read. Retries if no failure is detected * until a byte is read. * * @return the total number of bytes read; -1 if the connection is closed. */ public int read(byte[] buf, int off, int len) throws IOException { do { try { return super.read(buf, off, len); } catch (SocketTimeoutException e) { handleTimeout(e); } } while (true); } } private synchronized void disposeSasl() { if (saslRpcClient != null) { try { saslRpcClient.dispose(); } catch (IOException ignored) { } } } private synchronized boolean setupSaslConnection(final InputStream in2, final OutputStream out2) throws IOException { try { saslRpcClient = new SaslRpcClient(authMethod, token, serverPrincipal); return saslRpcClient.saslConnect(in2, out2); } catch (Exception e) { LOG.warn("Exception encountered while connecting to the server : " + e.getMessage() + ". Will attempt a relogin"); /* * Catch all exceptions here. Most likely we would have hit one of * the kerberos exceptions. Just attempt to relogin and try to * connect to the server */ UserGroupInformation loginUser = UserGroupInformation.getLoginUser(); UserGroupInformation currentUser = UserGroupInformation.getCurrentUser(); UserGroupInformation realUser = currentUser.getRealUser(); if (authMethod == AuthMethod.KERBEROS && // relogin only in case it is the login user (e.g. JT) // or superuser (like oozie). (currentUser.equals(loginUser) || loginUser.equals(realUser))) { //try setting up the connection again try { //try re-login if (UserGroupInformation.isLoginKeytabBased()) { loginUser.reloginFromKeytab(); } else { loginUser.reloginFromTicketCache(); } disposeSasl(); saslRpcClient = new SaslRpcClient(authMethod, token, serverPrincipal); return saslRpcClient.saslConnect(in2, out2); } catch (Exception ex) { String msg = "Couldn't setup connection for " + loginUser.getUserName() + " to " + serverPrincipal + " even after relogin."; LOG.warn(msg); throw (IOException) new IOException(msg).initCause(ex); } } if (e instanceof RemoteException) throw (RemoteException)e; throw new IOException(e); } } /** Connect to the server and set up the I/O streams. It then sends * a header to the server and starts * the connection thread that waits for responses. */ private synchronized void setupIOstreams() throws InterruptedException { if (socket != null || shouldCloseConnection.get()) { return; } short ioFailures = 0; short timeoutFailures = 0; try { if (LOG.isDebugEnabled()) { LOG.debug("Connecting to "+server); } while (true) { try { this.socket = socketFactory.createSocket(); this.socket.setTcpNoDelay(tcpNoDelay); // connection time out is 20s NetUtils.connect(this.socket, remoteId.getAddress(), 20000); this.socket.setSoTimeout(pingInterval); break; } catch (SocketTimeoutException toe) { /* The max number of retries is 45, * which amounts to 20s*45 = 15 minutes retries. */ handleConnectionFailure(timeoutFailures++, 45, toe); } catch (IOException ie) { handleConnectionFailure(ioFailures++, maxRetries, ie); } } InputStream inStream = NetUtils.getInputStream(socket); OutputStream outStream = NetUtils.getOutputStream(socket); writeRpcHeader(outStream); if (useSasl) { final InputStream in2 = inStream; final OutputStream out2 = outStream; UserGroupInformation ticket = remoteId.getTicket(); if (authMethod == AuthMethod.KERBEROS) { if (ticket.getRealUser() != null) { ticket = ticket.getRealUser(); } } if (ticket.doAs(new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws IOException { - return setupSaslConnection(in2, out2); + try { + return setupSaslConnection(in2, out2); + } catch (IOException ie) { + handleConnectionFailure(1, 1, ie); + throw ie; + } } })) { // Sasl connect is successful. Let's set up Sasl i/o streams. inStream = saslRpcClient.getInputStream(inStream); outStream = saslRpcClient.getOutputStream(outStream); } else { // fall back to simple auth because server told us so. authMethod = AuthMethod.SIMPLE; header = new ConnectionHeader(header.getProtocol(), header.getUgi(), authMethod); useSasl = false; } } this.in = new DataInputStream(new BufferedInputStream (new PingInputStream(inStream))); this.out = new DataOutputStream (new BufferedOutputStream(outStream)); writeHeader(); // update last activity time touch(); // start the receiver thread after the socket connection has been set up start(); } catch (IOException e) { markClosed(e); close(); } } /* Handle connection failures * * If the current number of retries is equal to the max number of retries, * stop retrying and throw the exception; Otherwise backoff 1 second and * try connecting again. * * This Method is only called from inside setupIOstreams(), which is * synchronized. Hence the sleep is synchronized; the locks will be retained. * * @param curRetries current number of retries * @param maxRetries max number of retries allowed * @param ioe failure reason * @throws IOException if max number of retries is reached */ private void handleConnectionFailure( int curRetries, int maxRetries, IOException ioe) throws IOException { // close the current connection try { socket.close(); } catch (IOException e) { LOG.warn("Not able to close a socket", e); } // set socket to null so that the next call to setupIOstreams // can start the process of connect all over again. socket = null; // throw the exception if the maximum number of retries is reached if (curRetries >= maxRetries) { throw ioe; } // otherwise back off and retry try { Thread.sleep(1000); } catch (InterruptedException ignored) {} LOG.info("Retrying connect to server: " + server + ". Already tried " + curRetries + " time(s)."); } /* Write the RPC header */ private void writeRpcHeader(OutputStream outStream) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(outStream)); // Write out the header, version and authentication method out.write(Server.HEADER.array()); out.write(Server.CURRENT_VERSION); authMethod.write(out); out.flush(); } /* Write the protocol header for each connection * Out is not synchronized because only the first thread does this. */ private void writeHeader() throws IOException { // Write out the ConnectionHeader DataOutputBuffer buf = new DataOutputBuffer(); header.write(buf); // Write out the payload length int bufLen = buf.getLength(); out.writeInt(bufLen); out.write(buf.getData(), 0, bufLen); } /* wait till someone signals us to start reading RPC response or * it is idle too long, it is marked as to be closed, * or the client is marked as not running. * * Return true if it is time to read a response; false otherwise. */ private synchronized boolean waitForWork() { if (calls.isEmpty() && !shouldCloseConnection.get() && running.get()) { long timeout = maxIdleTime- (System.currentTimeMillis()-lastActivity.get()); if (timeout>0) { try { wait(timeout); } catch (InterruptedException e) {} } } if (!calls.isEmpty() && !shouldCloseConnection.get() && running.get()) { return true; } else if (shouldCloseConnection.get()) { return false; } else if (calls.isEmpty()) { // idle connection closed or stopped markClosed(null); return false; } else { // get stopped but there are still pending requests markClosed((IOException)new IOException().initCause( new InterruptedException())); return false; } } public InetSocketAddress getRemoteAddress() { return server; } /* Send a ping to the server if the time elapsed * since last I/O activity is equal to or greater than the ping interval */ private synchronized void sendPing() throws IOException { long curTime = System.currentTimeMillis(); if ( curTime - lastActivity.get() >= pingInterval) { lastActivity.set(curTime); synchronized (out) { out.writeInt(PING_CALL_ID); out.flush(); } } } public void run() { if (LOG.isDebugEnabled()) LOG.debug(getName() + ": starting, having connections " + connections.size()); while (waitForWork()) {//wait here for work - read or close connection receiveResponse(); } close(); if (LOG.isDebugEnabled()) LOG.debug(getName() + ": stopped, remaining connections " + connections.size()); } /** Initiates a call by sending the parameter to the remote server. * Note: this is not called from the Connection thread, but by other * threads. */ public void sendParam(Call call) { if (shouldCloseConnection.get()) { return; } DataOutputBuffer d=null; try { synchronized (this.out) { if (LOG.isDebugEnabled()) LOG.debug(getName() + " sending #" + call.id); //for serializing the //data to be written d = new DataOutputBuffer(); d.writeInt(call.id); call.param.write(d); byte[] data = d.getData(); int dataLength = d.getLength(); out.writeInt(dataLength); //first put the data length out.write(data, 0, dataLength);//write the data out.flush(); } } catch(IOException e) { markClosed(e); } finally { //the buffer is just an in-memory buffer, but it is still polite to // close early IOUtils.closeStream(d); } } /* Receive a response. * Because only one receiver, so no synchronization on in. */ private void receiveResponse() { if (shouldCloseConnection.get()) { return; } touch(); try { int id = in.readInt(); // try to read an id if (LOG.isDebugEnabled()) LOG.debug(getName() + " got value #" + id); Call call = calls.get(id); int state = in.readInt(); // read call status if (state == Status.SUCCESS.state) { Writable value = ReflectionUtils.newInstance(valueClass, conf); value.readFields(in); // read value call.setValue(value); calls.remove(id); } else if (state == Status.ERROR.state) { call.setException(new RemoteException(WritableUtils.readString(in), WritableUtils.readString(in))); } else if (state == Status.FATAL.state) { // Close the connection markClosed(new RemoteException(WritableUtils.readString(in), WritableUtils.readString(in))); } } catch (IOException e) { markClosed(e); } } private synchronized void markClosed(IOException e) { if (shouldCloseConnection.compareAndSet(false, true)) { closeException = e; notifyAll(); } } /** Close the connection. */ private synchronized void close() { if (!shouldCloseConnection.get()) { LOG.error("The connection is not in the closed state"); return; } // release the resources // first thing to do;take the connection out of the connection list synchronized (connections) { if (connections.get(remoteId) == this) { connections.remove(remoteId); } } // close the streams and therefore the socket IOUtils.closeStream(out); IOUtils.closeStream(in); disposeSasl(); // clean up all calls if (closeException == null) { if (!calls.isEmpty()) { LOG.warn( "A connection is closed for no cause and calls are not empty"); // clean up calls anyway closeException = new IOException("Unexpected closed connection"); cleanupCalls(); } } else { // log the info if (LOG.isDebugEnabled()) { LOG.debug("closing ipc connection to " + server + ": " + closeException.getMessage(),closeException); } // cleanup calls cleanupCalls(); } if (LOG.isDebugEnabled()) LOG.debug(getName() + ": closed"); } /* Cleanup all calls and mark them as done */ private void cleanupCalls() { Iterator<Entry<Integer, Call>> itor = calls.entrySet().iterator() ; while (itor.hasNext()) { Call c = itor.next().getValue(); c.setException(closeException); // local exception itor.remove(); } } } /** Call implementation used for parallel calls. */ private class ParallelCall extends Call { private ParallelResults results; private int index; public ParallelCall(Writable param, ParallelResults results, int index) { super(param); this.results = results; this.index = index; } /** Deliver result to result collector. */ protected void callComplete() { results.callComplete(this); } } /** Result collector for parallel calls. */ private static class ParallelResults { private Writable[] values; private int size; private int count; public ParallelResults(int size) { this.values = new Writable[size]; this.size = size; } /** Collect a result. */ public synchronized void callComplete(ParallelCall call) { values[call.index] = call.value; // store the value count++; // count it if (count == size) // if all values are in notify(); // then notify waiting caller } } /** Construct an IPC client whose values are of the given {@link Writable} * class. */ public Client(Class<? extends Writable> valueClass, Configuration conf, SocketFactory factory) { this.valueClass = valueClass; this.maxIdleTime = conf.getInt("ipc.client.connection.maxidletime", 10000); //10s this.maxRetries = conf.getInt("ipc.client.connect.max.retries", 10); this.tcpNoDelay = conf.getBoolean("ipc.client.tcpnodelay", false); this.pingInterval = getPingInterval(conf); if (LOG.isDebugEnabled()) { LOG.debug("The ping interval is" + this.pingInterval + "ms."); } this.conf = conf; this.socketFactory = factory; } /** * Construct an IPC client with the default SocketFactory * @param valueClass * @param conf */ public Client(Class<? extends Writable> valueClass, Configuration conf) { this(valueClass, conf, NetUtils.getDefaultSocketFactory(conf)); } /** Return the socket factory of this client * * @return this client's socket factory */ SocketFactory getSocketFactory() { return socketFactory; } /** Stop all threads related to this client. No further calls may be made * using this client. */ public void stop() { if (LOG.isDebugEnabled()) { LOG.debug("Stopping client"); } if (!running.compareAndSet(true, false)) { return; } // wake up all connections synchronized (connections) { for (Connection conn : connections.values()) { conn.interrupt(); } } // wait until all connections are closed while (!connections.isEmpty()) { try { Thread.sleep(100); } catch (InterruptedException e) { } } } /** Make a call, passing <code>param</code>, to the IPC server running at * <code>address</code>, returning the value. Throws exceptions if there are * network problems or if the remote code threw an exception. * @deprecated Use {@link #call(Writable, InetSocketAddress, Class, UserGroupInformation)} instead */ @Deprecated public Writable call(Writable param, InetSocketAddress address) throws InterruptedException, IOException { return call(param, address, null); } /** Make a call, passing <code>param</code>, to the IPC server running at * <code>address</code> with the <code>ticket</code> credentials, returning * the value. * Throws exceptions if there are network problems or if the remote code * threw an exception. * @deprecated Use {@link #call(Writable, InetSocketAddress, Class, UserGroupInformation)} instead */ @Deprecated public Writable call(Writable param, InetSocketAddress addr, UserGroupInformation ticket) throws InterruptedException, IOException { return call(param, addr, null, ticket); } /** Make a call, passing <code>param</code>, to the IPC server running at * <code>address</code> which is servicing the <code>protocol</code> protocol, * with the <code>ticket</code> credentials, returning the value. * Throws exceptions if there are network problems or if the remote code * threw an exception. */ public Writable call(Writable param, InetSocketAddress addr, Class<?> protocol, UserGroupInformation ticket) throws InterruptedException, IOException { Call call = new Call(param); Connection connection = getConnection(addr, protocol, ticket, call); connection.sendParam(call); // send the parameter boolean interrupted = false; synchronized (call) { while (!call.done) { try { call.wait(); // wait for the result } catch (InterruptedException ie) { // save the fact that we were interrupted interrupted = true; } } if (interrupted) { // set the interrupt flag now that we are done waiting Thread.currentThread().interrupt(); } if (call.error != null) { if (call.error instanceof RemoteException) { call.error.fillInStackTrace(); throw call.error; } else { // local exception throw wrapException(addr, call.error); } } else { return call.value; } } } /** * Take an IOException and the address we were trying to connect to * and return an IOException with the input exception as the cause. * The new exception provides the stack trace of the place where * the exception is thrown and some extra diagnostics information. * If the exception is ConnectException or SocketTimeoutException, * return a new one of the same type; Otherwise return an IOException. * * @param addr target address * @param exception the relevant exception * @return an exception to throw */ private IOException wrapException(InetSocketAddress addr, IOException exception) { if (exception instanceof ConnectException) { //connection refused; include the host:port in the error return (ConnectException)new ConnectException( "Call to " + addr + " failed on connection exception: " + exception) .initCause(exception); } else if (exception instanceof SocketTimeoutException) { return (SocketTimeoutException)new SocketTimeoutException( "Call to " + addr + " failed on socket timeout exception: " + exception).initCause(exception); } else { return (IOException)new IOException( "Call to " + addr + " failed on local exception: " + exception) .initCause(exception); } } /** * Makes a set of calls in parallel. Each parameter is sent to the * corresponding address. When all values are available, or have timed out * or errored, the collected results are returned in an array. The array * contains nulls for calls that timed out or errored. * @deprecated Use {@link #call(Writable[], InetSocketAddress[], Class, UserGroupInformation)} instead */ @Deprecated public Writable[] call(Writable[] params, InetSocketAddress[] addresses) throws IOException, InterruptedException { return call(params, addresses, null, null); } /** Makes a set of calls in parallel. Each parameter is sent to the * corresponding address. When all values are available, or have timed out * or errored, the collected results are returned in an array. The array * contains nulls for calls that timed out or errored. */ public Writable[] call(Writable[] params, InetSocketAddress[] addresses, Class<?> protocol, UserGroupInformation ticket) throws IOException, InterruptedException { if (addresses.length == 0) return new Writable[0]; ParallelResults results = new ParallelResults(params.length); synchronized (results) { for (int i = 0; i < params.length; i++) { ParallelCall call = new ParallelCall(params[i], results, i); try { Connection connection = getConnection(addresses[i], protocol, ticket, call); connection.sendParam(call); // send each parameter } catch (IOException e) { // log errors LOG.info("Calling "+addresses[i]+" caught: " + e.getMessage(),e); results.size--; // wait for one fewer result } } while (results.count != results.size) { try { results.wait(); // wait for all results } catch (InterruptedException e) {} } return results.values; } } /** Get a connection from the pool, or create a new one and add it to the * pool. Connections to a given host/port are reused. */ private Connection getConnection(InetSocketAddress addr, Class<?> protocol, UserGroupInformation ticket, Call call) throws IOException, InterruptedException { if (!running.get()) { // the client is stopped throw new IOException("The client is stopped"); } Connection connection; /* we could avoid this allocation for each RPC by having a * connectionsId object and with set() method. We need to manage the * refs for keys in HashMap properly. For now its ok. */ ConnectionId remoteId = new ConnectionId(addr, protocol, ticket); do { synchronized (connections) { connection = connections.get(remoteId); if (connection == null) { connection = new Connection(remoteId); connections.put(remoteId, connection); } } } while (!connection.addCall(call)); //we don't invoke the method below inside "synchronized (connections)" //block above. The reason for that is if the server happens to be slow, //it will take longer to establish a connection and that will slow the //entire system down. connection.setupIOstreams(); return connection; } /** * This class holds the address and the user ticket. The client connections * to servers are uniquely identified by <remoteAddress, protocol, ticket> */ private static class ConnectionId { InetSocketAddress address; UserGroupInformation ticket; Class<?> protocol; private static final int PRIME = 16777619; ConnectionId(InetSocketAddress address, Class<?> protocol, UserGroupInformation ticket) { this.protocol = protocol; this.address = address; this.ticket = ticket; } InetSocketAddress getAddress() { return address; } Class<?> getProtocol() { return protocol; } UserGroupInformation getTicket() { return ticket; } @Override public boolean equals(Object obj) { if (obj instanceof ConnectionId) { ConnectionId id = (ConnectionId) obj; return address.equals(id.address) && protocol == id.protocol && ((ticket != null && ticket.equals(id.ticket)) || (ticket == id.ticket)); } return false; } @Override public int hashCode() { return (address.hashCode() + PRIME * System.identityHashCode(protocol)) ^ (ticket == null ? 0 : ticket.hashCode()); } } }
true
true
private synchronized void setupIOstreams() throws InterruptedException { if (socket != null || shouldCloseConnection.get()) { return; } short ioFailures = 0; short timeoutFailures = 0; try { if (LOG.isDebugEnabled()) { LOG.debug("Connecting to "+server); } while (true) { try { this.socket = socketFactory.createSocket(); this.socket.setTcpNoDelay(tcpNoDelay); // connection time out is 20s NetUtils.connect(this.socket, remoteId.getAddress(), 20000); this.socket.setSoTimeout(pingInterval); break; } catch (SocketTimeoutException toe) { /* The max number of retries is 45, * which amounts to 20s*45 = 15 minutes retries. */ handleConnectionFailure(timeoutFailures++, 45, toe); } catch (IOException ie) { handleConnectionFailure(ioFailures++, maxRetries, ie); } } InputStream inStream = NetUtils.getInputStream(socket); OutputStream outStream = NetUtils.getOutputStream(socket); writeRpcHeader(outStream); if (useSasl) { final InputStream in2 = inStream; final OutputStream out2 = outStream; UserGroupInformation ticket = remoteId.getTicket(); if (authMethod == AuthMethod.KERBEROS) { if (ticket.getRealUser() != null) { ticket = ticket.getRealUser(); } } if (ticket.doAs(new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws IOException { return setupSaslConnection(in2, out2); } })) { // Sasl connect is successful. Let's set up Sasl i/o streams. inStream = saslRpcClient.getInputStream(inStream); outStream = saslRpcClient.getOutputStream(outStream); } else { // fall back to simple auth because server told us so. authMethod = AuthMethod.SIMPLE; header = new ConnectionHeader(header.getProtocol(), header.getUgi(), authMethod); useSasl = false; } } this.in = new DataInputStream(new BufferedInputStream (new PingInputStream(inStream))); this.out = new DataOutputStream (new BufferedOutputStream(outStream)); writeHeader(); // update last activity time touch(); // start the receiver thread after the socket connection has been set up start(); } catch (IOException e) { markClosed(e); close(); } }
private synchronized void setupIOstreams() throws InterruptedException { if (socket != null || shouldCloseConnection.get()) { return; } short ioFailures = 0; short timeoutFailures = 0; try { if (LOG.isDebugEnabled()) { LOG.debug("Connecting to "+server); } while (true) { try { this.socket = socketFactory.createSocket(); this.socket.setTcpNoDelay(tcpNoDelay); // connection time out is 20s NetUtils.connect(this.socket, remoteId.getAddress(), 20000); this.socket.setSoTimeout(pingInterval); break; } catch (SocketTimeoutException toe) { /* The max number of retries is 45, * which amounts to 20s*45 = 15 minutes retries. */ handleConnectionFailure(timeoutFailures++, 45, toe); } catch (IOException ie) { handleConnectionFailure(ioFailures++, maxRetries, ie); } } InputStream inStream = NetUtils.getInputStream(socket); OutputStream outStream = NetUtils.getOutputStream(socket); writeRpcHeader(outStream); if (useSasl) { final InputStream in2 = inStream; final OutputStream out2 = outStream; UserGroupInformation ticket = remoteId.getTicket(); if (authMethod == AuthMethod.KERBEROS) { if (ticket.getRealUser() != null) { ticket = ticket.getRealUser(); } } if (ticket.doAs(new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws IOException { try { return setupSaslConnection(in2, out2); } catch (IOException ie) { handleConnectionFailure(1, 1, ie); throw ie; } } })) { // Sasl connect is successful. Let's set up Sasl i/o streams. inStream = saslRpcClient.getInputStream(inStream); outStream = saslRpcClient.getOutputStream(outStream); } else { // fall back to simple auth because server told us so. authMethod = AuthMethod.SIMPLE; header = new ConnectionHeader(header.getProtocol(), header.getUgi(), authMethod); useSasl = false; } } this.in = new DataInputStream(new BufferedInputStream (new PingInputStream(inStream))); this.out = new DataOutputStream (new BufferedOutputStream(outStream)); writeHeader(); // update last activity time touch(); // start the receiver thread after the socket connection has been set up start(); } catch (IOException e) { markClosed(e); close(); } }
diff --git a/compiler/src/gen/utils/VisitorUtils.java b/compiler/src/gen/utils/VisitorUtils.java index 93bc07c..99d96c8 100644 --- a/compiler/src/gen/utils/VisitorUtils.java +++ b/compiler/src/gen/utils/VisitorUtils.java @@ -1,102 +1,102 @@ package gen.utils; import gen.*; import gen.visitor.*; import parser.*; public final class VisitorUtils { /** * Visits node and apply visitor to all childs. * * @param <T> * @param builder * @param node * @param visitor */ public static <T extends AsnParserVisitor & ContentProvider> void visitNodeAndAccept( CodeBuilder builder, SimpleNode node, T visitor) { node.jjtAccept(visitor, null); if (visitor.hasValuableContent()) { builder.append(visitor.getContent()); } } /** * Visits childs nodes of the node and apply visitor to all of them. * * @param <T> * @param builder * @param node * @param visitor */ public static <T extends AsnParserVisitor & ContentProvider> boolean visitChildsAndAccept( CodeBuilder builder, SimpleNode node, T visitor) { node.childrenAccept(visitor, null); if (visitor.hasValuableContent()) { builder.append(visitor.getContent()); return true; } return false; } public static <T extends AsnParserVisitor & ContentProvider> boolean visitChildsAndAccept( CodeBuilder builder, SimpleNode node, T... visitors) { boolean hasValuableContent = false; for (T visitor : visitors) { if (visitChildsAndAccept(builder, node, visitor)) { hasValuableContent = true; } } return hasValuableContent; } public static CodeBuilder generateCodeAsForTypeAssignment(final SimpleNode node, final String typeName, final GeneratorContext context) { final CodeBuilder builder = new CodeBuilder(); final ASTTypeAssignment newType = new ASTTypeAssignment(0); newType.setFirstToken(new Token(0, typeName)); - if (node instanceof ASTTaggedType) { + if (node instanceof ASTTaggedType || node instanceof ASTSetOrSequenceOfType) { for (int i = 0, j = 0; i < node.jjtGetNumChildren(); ++i, ++j) { if (!(node.jjtGetChild(i) instanceof ASTBuiltinType)) { --j; continue; } newType.jjtAddChild(node.jjtGetChild(i), j); } } else { for (int i = 0; i < node.jjtGetNumChildren(); ++i) { newType.jjtAddChild(node.jjtGetChild(i), i); } } final TypeGenerator gen = new TypeGenerator(newType); gen.generate(context); builder.append(gen.getContent()); return builder; } public static String queueGeneratedCode(final SimpleNode node, final GeneratorContext context) { final CodeBuilder uniqueName = new CodeBuilder(); VisitorUtils.visitChildsAndAccept(uniqueName, node, new UniqueNameProducer()); if (!context.hasExternalized(uniqueName.toString())) { /* indicate that generator know this type */ context.addExternalTypeName(uniqueName.toString()); /* generate code for a new type */ context.addExternalContent(VisitorUtils.generateCodeAsForTypeAssignment(node, uniqueName.toString(), context)); } return uniqueName.toString(); } /* * Do not allow instantiation. */ private VisitorUtils() { } }
true
true
public static CodeBuilder generateCodeAsForTypeAssignment(final SimpleNode node, final String typeName, final GeneratorContext context) { final CodeBuilder builder = new CodeBuilder(); final ASTTypeAssignment newType = new ASTTypeAssignment(0); newType.setFirstToken(new Token(0, typeName)); if (node instanceof ASTTaggedType) { for (int i = 0, j = 0; i < node.jjtGetNumChildren(); ++i, ++j) { if (!(node.jjtGetChild(i) instanceof ASTBuiltinType)) { --j; continue; } newType.jjtAddChild(node.jjtGetChild(i), j); } } else { for (int i = 0; i < node.jjtGetNumChildren(); ++i) { newType.jjtAddChild(node.jjtGetChild(i), i); } } final TypeGenerator gen = new TypeGenerator(newType); gen.generate(context); builder.append(gen.getContent()); return builder; }
public static CodeBuilder generateCodeAsForTypeAssignment(final SimpleNode node, final String typeName, final GeneratorContext context) { final CodeBuilder builder = new CodeBuilder(); final ASTTypeAssignment newType = new ASTTypeAssignment(0); newType.setFirstToken(new Token(0, typeName)); if (node instanceof ASTTaggedType || node instanceof ASTSetOrSequenceOfType) { for (int i = 0, j = 0; i < node.jjtGetNumChildren(); ++i, ++j) { if (!(node.jjtGetChild(i) instanceof ASTBuiltinType)) { --j; continue; } newType.jjtAddChild(node.jjtGetChild(i), j); } } else { for (int i = 0; i < node.jjtGetNumChildren(); ++i) { newType.jjtAddChild(node.jjtGetChild(i), i); } } final TypeGenerator gen = new TypeGenerator(newType); gen.generate(context); builder.append(gen.getContent()); return builder; }
diff --git a/com/mewin/WGRegionEffects/WGRegionEffectsPlugin.java b/com/mewin/WGRegionEffects/WGRegionEffectsPlugin.java index cd8e40a..d2cfacf 100644 --- a/com/mewin/WGRegionEffects/WGRegionEffectsPlugin.java +++ b/com/mewin/WGRegionEffects/WGRegionEffectsPlugin.java @@ -1,235 +1,235 @@ /* * Copyright (C) 2012 mewin <[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.mewin.WGRegionEffects; import com.mewin.WGCustomFlags.WGCustomFlagsPlugin; import com.mewin.WGCustomFlags.flags.CustomSetFlag; import com.mewin.WGRegionEffects.flags.PotionEffectDesc; import com.mewin.WGRegionEffects.flags.PotionEffectFlag; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.flags.RegionGroup; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; /** * * @author mewin <[email protected]> */ public class WGRegionEffectsPlugin extends JavaPlugin { public static final CustomSetFlag EFFECT_FLAG = new CustomSetFlag("effects", new PotionEffectFlag("effect", RegionGroup.ALL)); private WGCustomFlagsPlugin custPlugin; private WorldGuardPlugin wgPlugin; private WGRegionEffectsListener listener; private File confFile; private int tickDelay = 20; public static final Map<Player, List<PotionEffectDesc>> playerEffects = new HashMap<Player, List<PotionEffectDesc>>(); public static List<Player> ignoredPlayers = new ArrayList<Player>(); @Override public void onEnable() { Plugin plug = getServer().getPluginManager().getPlugin("WGCustomFlags"); confFile = new File(this.getDataFolder(), "config.yml"); if (plug == null || !(plug instanceof WGCustomFlagsPlugin) || !plug.isEnabled()) { getLogger().warning("Could not load WorldGuard Custom Flags Plugin, disabling"); getServer().getPluginManager().disablePlugin(this); return; } else { custPlugin = (WGCustomFlagsPlugin) plug; } plug = getServer().getPluginManager().getPlugin("WorldGuard"); if (plug == null || !(plug instanceof WorldGuardPlugin) || !plug.isEnabled()) { getLogger().warning("Could not load WorldGuard Plugin, disabling"); getServer().getPluginManager().disablePlugin(this); return; } else { wgPlugin = (WorldGuardPlugin) plug; } loadConfig(); listener = new WGRegionEffectsListener(wgPlugin, this); getServer().getPluginManager().registerEvents(listener, plug); custPlugin.addCustomFlag(EFFECT_FLAG); scheduleTask(); } private void loadConfig() { confFile.getParentFile().mkdirs(); getConfig().set("effect-duration", 2000); getConfig().set("effect-tick-delay", 1000); if (!confFile.exists()) { try { if (!confFile.createNewFile()) { throw new IOException("Could not create configuration file."); } getLogger().log(Level.INFO, "Configuration does not exist. Creating default config.yml."); getConfig().save(confFile); } catch(IOException ex) { getLogger().log(Level.WARNING, "Could not write default configuration: ", ex); } } else { try { getConfig().load(confFile); } catch(Exception ex) { getLogger().log(Level.WARNING, "Could not load configuration:", ex); } } PotionEffectDesc.defaultLength = getConfig().getInt("effect-duration", 2000) / 50; tickDelay = getConfig().getInt("effect-tick-delay", 1000) / 50; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("toggleeffects") || cmd.getName().equalsIgnoreCase("te")) { if (sender instanceof Player) { Player player = (Player) sender; if (!player.hasPermission("effects.toggle")) { player.sendMessage(ChatColor.RED + "You don't have permission for that."); } else if (WGRegionEffectsPlugin.ignoredPlayers.contains(player)) { WGRegionEffectsPlugin.ignoredPlayers.remove(player); player.sendMessage(ChatColor.GOLD + "Region effects toggled on."); } else { WGRegionEffectsPlugin.ignoredPlayers.add(player); player.sendMessage(ChatColor.GOLD + "Region effects toggled off."); } } else { sender.sendMessage("How could a console be affected by effects?"); } return true; } return false; } private void scheduleTask() { getServer().getScheduler().scheduleSyncRepeatingTask(wgPlugin, new Runnable() { @Override public synchronized void run() { for(Player p : getServer().getOnlinePlayers()) { if (ignoredPlayers.contains(p)) { continue; } List<PotionEffectDesc> effects; try { effects = new ArrayList<PotionEffectDesc>(playerEffects.get(p)); } catch(NullPointerException ex) { continue; } if (effects == null) { continue; } Iterator<PotionEffectDesc> itr = effects.iterator(); { CUR_POTION: while(itr.hasNext()) { PotionEffect effect = itr.next().createEffect(); Iterator<PotionEffect> itr2 = p.getActivePotionEffects().iterator(); while(itr2.hasNext()) { PotionEffect pe = itr2.next(); if ((pe.getType().equals(PotionEffectType.POISON) || pe.getType().equals(PotionEffectType.WITHER)) && effect.getType().equals(pe.getType()) && pe.getDuration() > 40) { continue CUR_POTION; } if (pe.getType() == effect.getType() && pe.getDuration() > effect.getDuration()) { continue CUR_POTION; } } if (effect.getAmplifier() != -1) { p.addPotionEffect(effect, true); } else { p.removePotionEffect(effect.getType()); } } } } } - }, tickDelay, 5L); + }, 5L, tickDelay); } }
true
true
private void scheduleTask() { getServer().getScheduler().scheduleSyncRepeatingTask(wgPlugin, new Runnable() { @Override public synchronized void run() { for(Player p : getServer().getOnlinePlayers()) { if (ignoredPlayers.contains(p)) { continue; } List<PotionEffectDesc> effects; try { effects = new ArrayList<PotionEffectDesc>(playerEffects.get(p)); } catch(NullPointerException ex) { continue; } if (effects == null) { continue; } Iterator<PotionEffectDesc> itr = effects.iterator(); { CUR_POTION: while(itr.hasNext()) { PotionEffect effect = itr.next().createEffect(); Iterator<PotionEffect> itr2 = p.getActivePotionEffects().iterator(); while(itr2.hasNext()) { PotionEffect pe = itr2.next(); if ((pe.getType().equals(PotionEffectType.POISON) || pe.getType().equals(PotionEffectType.WITHER)) && effect.getType().equals(pe.getType()) && pe.getDuration() > 40) { continue CUR_POTION; } if (pe.getType() == effect.getType() && pe.getDuration() > effect.getDuration()) { continue CUR_POTION; } } if (effect.getAmplifier() != -1) { p.addPotionEffect(effect, true); } else { p.removePotionEffect(effect.getType()); } } } } } }, tickDelay, 5L); }
private void scheduleTask() { getServer().getScheduler().scheduleSyncRepeatingTask(wgPlugin, new Runnable() { @Override public synchronized void run() { for(Player p : getServer().getOnlinePlayers()) { if (ignoredPlayers.contains(p)) { continue; } List<PotionEffectDesc> effects; try { effects = new ArrayList<PotionEffectDesc>(playerEffects.get(p)); } catch(NullPointerException ex) { continue; } if (effects == null) { continue; } Iterator<PotionEffectDesc> itr = effects.iterator(); { CUR_POTION: while(itr.hasNext()) { PotionEffect effect = itr.next().createEffect(); Iterator<PotionEffect> itr2 = p.getActivePotionEffects().iterator(); while(itr2.hasNext()) { PotionEffect pe = itr2.next(); if ((pe.getType().equals(PotionEffectType.POISON) || pe.getType().equals(PotionEffectType.WITHER)) && effect.getType().equals(pe.getType()) && pe.getDuration() > 40) { continue CUR_POTION; } if (pe.getType() == effect.getType() && pe.getDuration() > effect.getDuration()) { continue CUR_POTION; } } if (effect.getAmplifier() != -1) { p.addPotionEffect(effect, true); } else { p.removePotionEffect(effect.getType()); } } } } } }, 5L, tickDelay); }
diff --git a/chapter9-bookstore/src/main/java/com/apress/prospringmvc/bookstore/web/controller/LoginController.java b/chapter9-bookstore/src/main/java/com/apress/prospringmvc/bookstore/web/controller/LoginController.java index b5b255a..90f3f14 100644 --- a/chapter9-bookstore/src/main/java/com/apress/prospringmvc/bookstore/web/controller/LoginController.java +++ b/chapter9-bookstore/src/main/java/com/apress/prospringmvc/bookstore/web/controller/LoginController.java @@ -1,49 +1,50 @@ package com.apress.prospringmvc.bookstore.web.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; 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.util.WebUtils; import com.apress.prospringmvc.bookstore.domain.Account; import com.apress.prospringmvc.bookstore.service.AccountService; import com.apress.prospringmvc.bookstore.service.AuthenticationException; import com.apress.prospringmvc.bookstore.web.interceptor.SecurityHandlerInterceptor; @Controller public class LoginController { @Autowired private AccountService accountService; @RequestMapping(value = "/login", method = RequestMethod.GET) public void login() { } @RequestMapping(value = "/login", method = RequestMethod.POST) - public String handleLogin(@RequestParam("username") String username, @RequestParam("password")String password, HttpServletRequest request) - throws AuthenticationException { + public String handleLogin(@RequestParam + String username, @RequestParam + String password, HttpServletRequest request) throws AuthenticationException { Account account = this.accountService.login(username, password); WebUtils.setSessionAttribute(request, SecurityHandlerInterceptor.ACCOUNT_ATTRIBUTE, account); String url = (String) WebUtils.getSessionAttribute(request, SecurityHandlerInterceptor.REQUESTED_URL); WebUtils.setSessionAttribute(request, SecurityHandlerInterceptor.REQUESTED_URL, null); // Remove the attribute if (StringUtils.hasText(url) && !url.contains("login")) { // Prevent loops for the login page. return "redirect:" + url; } else { return "redirect:/index.htm"; } } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(HttpSession session) { session.invalidate(); return "redirect:/index.htm"; } }
true
true
public String handleLogin(@RequestParam("username") String username, @RequestParam("password")String password, HttpServletRequest request) throws AuthenticationException { Account account = this.accountService.login(username, password); WebUtils.setSessionAttribute(request, SecurityHandlerInterceptor.ACCOUNT_ATTRIBUTE, account); String url = (String) WebUtils.getSessionAttribute(request, SecurityHandlerInterceptor.REQUESTED_URL); WebUtils.setSessionAttribute(request, SecurityHandlerInterceptor.REQUESTED_URL, null); // Remove the attribute if (StringUtils.hasText(url) && !url.contains("login")) { // Prevent loops for the login page. return "redirect:" + url; } else { return "redirect:/index.htm"; } }
public String handleLogin(@RequestParam String username, @RequestParam String password, HttpServletRequest request) throws AuthenticationException { Account account = this.accountService.login(username, password); WebUtils.setSessionAttribute(request, SecurityHandlerInterceptor.ACCOUNT_ATTRIBUTE, account); String url = (String) WebUtils.getSessionAttribute(request, SecurityHandlerInterceptor.REQUESTED_URL); WebUtils.setSessionAttribute(request, SecurityHandlerInterceptor.REQUESTED_URL, null); // Remove the attribute if (StringUtils.hasText(url) && !url.contains("login")) { // Prevent loops for the login page. return "redirect:" + url; } else { return "redirect:/index.htm"; } }
diff --git a/src/main/java/uk/co/drnaylor/mcmmopartyadmin/commands/PartyAdminCommand.java b/src/main/java/uk/co/drnaylor/mcmmopartyadmin/commands/PartyAdminCommand.java index 9488a63..1cb55e9 100644 --- a/src/main/java/uk/co/drnaylor/mcmmopartyadmin/commands/PartyAdminCommand.java +++ b/src/main/java/uk/co/drnaylor/mcmmopartyadmin/commands/PartyAdminCommand.java @@ -1,330 +1,333 @@ /* * Copyright (C) 2013 Dr Daniel R. Naylor * * This file is part of mcMMO Party Admin. * * mcMMO Party Admin 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. * * mcMMO Party Admin 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 mcMMO Party Admin. If not, see <http://www.gnu.org/licenses/>. * **/ package uk.co.drnaylor.mcmmopartyadmin.commands; import com.gmail.nossr50.api.ChatAPI; import com.gmail.nossr50.api.PartyAPI; import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.events.party.McMMOPartyChangeEvent; import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.util.player.UserManager; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import uk.co.drnaylor.mcmmopartyadmin.PartyAdmin; import uk.co.drnaylor.mcmmopartyadmin.Util; import uk.co.drnaylor.mcmmopartyadmin.locales.L10n; import uk.co.drnaylor.mcmmopartyadmin.permissions.PermissionHandler; public class PartyAdminCommand implements CommandExecutor { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null || PermissionHandler.isAdmin(player)) { if (args.length > 2 && (args[0].equalsIgnoreCase("pc") || args[0].equalsIgnoreCase("chat"))) { StringBuilder a = new StringBuilder(); for (int i = 2; i < args.length; i++) { a.append(args[i]); + if (i != args.length - 1) { + a.append(" "); + } } partyChat(sender, args[1], a.toString()); return true; } switch (args.length) { case 1: if (args[0].equalsIgnoreCase("list")) { listParties(sender); return true; } listCommands(sender); return true; case 2: if (args[0].equalsIgnoreCase("removeparty") || args[0].equalsIgnoreCase("remparty") || args[0].equalsIgnoreCase("delparty") || args[0].equalsIgnoreCase("rp")) { disbandParty(sender, args[1]); return true; } else if (args[0].equalsIgnoreCase("removeplayer") || args[0].equalsIgnoreCase("rpl") || args[0].equalsIgnoreCase("kickplayer")) { removePlayerFromParty(sender, args[1]); return true; } else { listCommands(sender); return true; } case 3: if (args[0].equalsIgnoreCase("addplayer") || args[0].equalsIgnoreCase("apl")) { addPlayerToParty(sender, args[1], args[2]); return true; } else if (args[0].equalsIgnoreCase("changeowner") || args[0].equalsIgnoreCase("chown")) { changePartyOwner(sender, args[1], args[2]); return true; } else if ((args[0].equalsIgnoreCase("pc") || args[0].equalsIgnoreCase("chat"))) { partyChat(sender, args[1], args[2]); } else { listCommands(sender); return true; } default: listCommands(sender); return true; } } else { // No perms! Leave us be! player.sendMessage(L10n.getString("Commands.NoPermission")); } return true; } /** * Sends a list of all parties and it's members to the requester. * * @param sender Requester to send the list to. */ private void listParties(CommandSender sender) { // Get ALL the parties! List<Party> parties = PartyAPI.getParties(); // No parties? That's a shame... if (parties.isEmpty()) { sender.sendMessage(L10n.getString("Commands.List.NoParties")); } else { // Header sender.sendMessage(L10n.getString("Commands.List.PartyListHeader")); sender.sendMessage(ChatColor.DARK_AQUA + "==============="); // This next bit has no need for localisation // Over each party... for (Party a : parties) { // Get Party Leader String leader = PartyAPI.getPartyLeader(a.getName()); // Start building new string StringBuilder tempList = new StringBuilder(); tempList.append(ChatColor.DARK_AQUA); tempList.append(a.getName()); tempList.append(":"); // Over all players for (OfflinePlayer otherPlayerName : a.getMembers()) { tempList.append(" "); if (leader.equals(otherPlayerName.getName())) { // Leader in Gold tempList.append(ChatColor.GOLD); } else if (otherPlayerName.isOnline()) { // Online players in White tempList.append(ChatColor.WHITE); } else { // Offline players in Grey tempList.append(ChatColor.GRAY); } // Add name and space tempList.append(otherPlayerName.getName()); } // Send the message sender.sendMessage(tempList.toString()); } } } /** * Disbands an mcMMO party. * * @param sender Player or console who requested the disband * @param party Party to disband */ private void disbandParty(CommandSender sender, String party) { Party target = Util.getPartyFromList(party); if (target == null) { sender.sendMessage(L10n.getString("Party.DoesNotExist", party)); return; } // From Party Disband command for (Player member : target.getOnlineMembers()) { if (!PartyManager.handlePartyChangeEvent(member, target.getName(), null, McMMOPartyChangeEvent.EventReason.KICKED_FROM_PARTY)) { sender.sendMessage(L10n.getString("Commands.Disband.Fail", party)); return; } member.sendMessage(L10n.getString("Commands.Disband.ByAdmin")); } //It would be nice to get API to do this. PartyManager.disbandParty(target); sender.sendMessage(L10n.getString("Commands.Disband.Success", party)); } /** * Removes a player from their party. * * @param sender Player requesting removal * @param player Name of player to remove */ private void removePlayerFromParty(CommandSender sender, String player) { Player targetPlayer = PartyAdmin.plugin.getServer().getPlayer(player); // If the player is online if (targetPlayer != null) { // Is the player in a party? if (PartyAPI.inParty(targetPlayer)) { // Remove from the party! PartyAPI.removeFromParty(targetPlayer); // Tell them, and the sender targetPlayer.sendMessage(L10n.getString("Command.Kicked.ByAdmin")); sender.sendMessage(L10n.getString("Command.Kicked.Success", targetPlayer.getName())); } else { // Tell the sender that the can't do that! sender.sendMessage(L10n.getString("Player.NotInParty", targetPlayer.getName())); } } else { sender.sendMessage(L10n.getString("Player.NotOnline", player)); } } /** * Adds a player to a party. * * @param sender Player requesting the addition * @param player Player to add to party * @param partyName Party to add player to */ private void addPlayerToParty(CommandSender sender, String player, String partyName) { // Get the OfflinePlayer Player targetPlayer = PartyAdmin.plugin.getServer().getPlayerExact(player); Party party = Util.getPartyFromList(partyName); // No party! if (party == null) { sender.sendMessage(L10n.getString("Party.DoesNotExist", partyName)); return; } else if (targetPlayer == null) { sender.sendMessage(L10n.getString("Player.NotOnline", player)); return; } if (PartyAPI.inParty(targetPlayer)) { PartyAPI.removeFromParty(targetPlayer); } // If the player is online, we can add them to the party using the API PartyAPI.addToParty(targetPlayer, partyName); // Check to see that it happened and the event wasn't cancelled. if (PartyAPI.getPartyName(targetPlayer).equals(partyName)) { sender.sendMessage(L10n.getString("Commands.Added.Success", targetPlayer.getName(), partyName)); } else { sender.sendMessage(L10n.getString("Commands.Added.Failed", targetPlayer.getName(), partyName)); } } /** * Change the owner of a party. * * @param sender Player requesting the change * @param player Player to make the owner * @param partyName Party to make them the owner of */ private void changePartyOwner(CommandSender sender, String player, String partyName) { OfflinePlayer targetPlayer = PartyAdmin.plugin.getServer().getOfflinePlayer(player); if (targetPlayer == null) { // Player doesn't exist sender.sendMessage(L10n.getString("Player.NotFound", player)); return; } McMMOPlayer mcplayer = UserManager.getPlayer(targetPlayer); Party party = mcplayer.getParty(); if (party.getName().equals(partyName)) { PartyAPI.setPartyLeader(targetPlayer.getName(), partyName); sender.sendMessage(L10n.getString("Commands.ChangeOwner.Success", player, party)); sender.sendMessage(L10n.getString("Commands.ChangeOwner.Owner", player, party)); } else { sender.sendMessage(L10n.getString("Commands.ChangeOwner.NotInParty", player, party)); } } /** * Send a message to the specified party. * * @param sender Player sending the message * @param args */ private void partyChat(CommandSender sender, String party, String message) { if (Util.getPartyFromList(party) == null) { sender.sendMessage(L10n.getString("Party.DoesNotExist",party)); return; } if (!(sender instanceof Player)) { ChatAPI.sendPartyChat(PartyAdmin.plugin,L10n.getString("Console.Name"), party, message); } else { ChatAPI.sendPartyChat(PartyAdmin.plugin,sender.getName(), party, message); } if (sender instanceof Player) { Player send = (Player) sender; if (!PartyAdmin.plugin.getPartySpyHandler().isSpy(send)) { sender.sendMessage(L10n.getString("PartySpy.Off")); String p2 = ChatColor.GRAY + "[" + party + "] " + ChatColor.GREEN + " (" + ChatColor.WHITE + sender.getName() + ChatColor.GREEN + ") "; sender.sendMessage(p2 + message); } } } /** * Send a list of the permissible commands to the sender. * * @param player CommandSender to send the messages to. */ private void listCommands(CommandSender player) { player.sendMessage(ChatColor.DARK_AQUA + "mcMMO Party Admin v" + PartyAdmin.plugin.getDescription().getVersion()); //No need to localise this line player.sendMessage(ChatColor.DARK_AQUA + "================="); player.sendMessage(ChatColor.YELLOW + "/partyadmin list " + ChatColor.WHITE + "- " + L10n.getString("Description.List")); player.sendMessage(ChatColor.YELLOW + "/partyadmin rp <party> " + ChatColor.WHITE + "- " + L10n.getString("Description.Disband")); player.sendMessage(ChatColor.YELLOW + "/partyadmin apl <player> <party> " + ChatColor.WHITE + "- " + L10n.getString("Description.Add")); player.sendMessage(ChatColor.YELLOW + "/partyadmin rpl <player> " + ChatColor.WHITE + "- " + L10n.getString("Description.Remove")); player.sendMessage(ChatColor.YELLOW + "/partyadmin chown <player> <party> " + ChatColor.WHITE + "- " + L10n.getString("Description.ChangeOwner")); player.sendMessage(ChatColor.YELLOW + "/partyadmin pc <party> " + ChatColor.WHITE + "- " + L10n.getString("Description.PartyChat")); } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null || PermissionHandler.isAdmin(player)) { if (args.length > 2 && (args[0].equalsIgnoreCase("pc") || args[0].equalsIgnoreCase("chat"))) { StringBuilder a = new StringBuilder(); for (int i = 2; i < args.length; i++) { a.append(args[i]); } partyChat(sender, args[1], a.toString()); return true; } switch (args.length) { case 1: if (args[0].equalsIgnoreCase("list")) { listParties(sender); return true; } listCommands(sender); return true; case 2: if (args[0].equalsIgnoreCase("removeparty") || args[0].equalsIgnoreCase("remparty") || args[0].equalsIgnoreCase("delparty") || args[0].equalsIgnoreCase("rp")) { disbandParty(sender, args[1]); return true; } else if (args[0].equalsIgnoreCase("removeplayer") || args[0].equalsIgnoreCase("rpl") || args[0].equalsIgnoreCase("kickplayer")) { removePlayerFromParty(sender, args[1]); return true; } else { listCommands(sender); return true; } case 3: if (args[0].equalsIgnoreCase("addplayer") || args[0].equalsIgnoreCase("apl")) { addPlayerToParty(sender, args[1], args[2]); return true; } else if (args[0].equalsIgnoreCase("changeowner") || args[0].equalsIgnoreCase("chown")) { changePartyOwner(sender, args[1], args[2]); return true; } else if ((args[0].equalsIgnoreCase("pc") || args[0].equalsIgnoreCase("chat"))) { partyChat(sender, args[1], args[2]); } else { listCommands(sender); return true; } default: listCommands(sender); return true; } } else { // No perms! Leave us be! player.sendMessage(L10n.getString("Commands.NoPermission")); } return true; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null || PermissionHandler.isAdmin(player)) { if (args.length > 2 && (args[0].equalsIgnoreCase("pc") || args[0].equalsIgnoreCase("chat"))) { StringBuilder a = new StringBuilder(); for (int i = 2; i < args.length; i++) { a.append(args[i]); if (i != args.length - 1) { a.append(" "); } } partyChat(sender, args[1], a.toString()); return true; } switch (args.length) { case 1: if (args[0].equalsIgnoreCase("list")) { listParties(sender); return true; } listCommands(sender); return true; case 2: if (args[0].equalsIgnoreCase("removeparty") || args[0].equalsIgnoreCase("remparty") || args[0].equalsIgnoreCase("delparty") || args[0].equalsIgnoreCase("rp")) { disbandParty(sender, args[1]); return true; } else if (args[0].equalsIgnoreCase("removeplayer") || args[0].equalsIgnoreCase("rpl") || args[0].equalsIgnoreCase("kickplayer")) { removePlayerFromParty(sender, args[1]); return true; } else { listCommands(sender); return true; } case 3: if (args[0].equalsIgnoreCase("addplayer") || args[0].equalsIgnoreCase("apl")) { addPlayerToParty(sender, args[1], args[2]); return true; } else if (args[0].equalsIgnoreCase("changeowner") || args[0].equalsIgnoreCase("chown")) { changePartyOwner(sender, args[1], args[2]); return true; } else if ((args[0].equalsIgnoreCase("pc") || args[0].equalsIgnoreCase("chat"))) { partyChat(sender, args[1], args[2]); } else { listCommands(sender); return true; } default: listCommands(sender); return true; } } else { // No perms! Leave us be! player.sendMessage(L10n.getString("Commands.NoPermission")); } return true; }
diff --git a/cometd-java/cometd-java-benchmark/cometd-java-benchmark-common/src/main/java/org/cometd/benchmark/MonitoringQueuedThreadPool.java b/cometd-java/cometd-java-benchmark/cometd-java-benchmark-common/src/main/java/org/cometd/benchmark/MonitoringQueuedThreadPool.java index b6f17fb03..79df5f0bd 100644 --- a/cometd-java/cometd-java-benchmark/cometd-java-benchmark-common/src/main/java/org/cometd/benchmark/MonitoringQueuedThreadPool.java +++ b/cometd-java/cometd-java-benchmark/cometd-java-benchmark-common/src/main/java/org/cometd/benchmark/MonitoringQueuedThreadPool.java @@ -1,172 +1,172 @@ /* * Copyright (c) 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cometd.benchmark; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.eclipse.jetty.util.BlockingArrayQueue; import org.eclipse.jetty.util.thread.QueuedThreadPool; public class MonitoringQueuedThreadPool extends QueuedThreadPool { private final AtomicLong tasks = new AtomicLong(); private final AtomicLong maxLatency = new AtomicLong(); private final AtomicLong totalLatency = new AtomicLong(); private final AtomicInteger threads = new AtomicInteger(); private final AtomicInteger maxThreads = new AtomicInteger(); private final MonitoringBlockingArrayQueue queue; public MonitoringQueuedThreadPool(int maxThreads) { // Use a very long idle timeout to avoid creation/destruction of threads super(maxThreads, maxThreads, 24 * 3600 * 1000, new MonitoringBlockingArrayQueue(maxThreads, maxThreads)); queue = (MonitoringBlockingArrayQueue)getQueue(); setStopTimeout(2000); } @Override - public boolean dispatch(final Runnable job) + public void execute(final Runnable job) { final long begin = System.nanoTime(); - return super.dispatch(new Runnable() + super.execute(new Runnable() { public void run() { long latency = System.nanoTime() - begin; Atomics.updateMax(maxLatency, latency); totalLatency.addAndGet(latency); tasks.incrementAndGet(); Atomics.updateMax(maxThreads, threads.incrementAndGet()); try { job.run(); } finally { threads.decrementAndGet(); } } }); } public void reset() { queue.reset(); tasks.set(0); maxLatency.set(0); totalLatency.set(0); threads.set(0); maxThreads.set(0); } public long getTasks() { return tasks.get(); } public int getMaxActiveThreads() { return maxThreads.get(); } public int getMaxQueueSize() { return queue.maxSize.get(); } public long getAverageQueueLatency() { long count = tasks.get(); return count == 0 ? -1 : totalLatency.get() / count; } public long getMaxQueueLatency() { return maxLatency.get(); } public static class MonitoringBlockingArrayQueue extends BlockingArrayQueue<Runnable> { private final AtomicInteger size = new AtomicInteger(); private final AtomicInteger maxSize = new AtomicInteger(); public MonitoringBlockingArrayQueue(int capacity, int growBy) { super(capacity, growBy); } public void reset() { size.set(0); maxSize.set(0); } @Override public void clear() { reset(); super.clear(); } @Override public boolean offer(Runnable job) { boolean added = super.offer(job); if (added) increment(); return added; } private void increment() { Atomics.updateMax(maxSize, size.incrementAndGet()); } @Override public Runnable poll() { Runnable job = super.poll(); if (job != null) decrement(); return job; } @Override public Runnable poll(long time, TimeUnit unit) throws InterruptedException { Runnable job = super.poll(time, unit); if (job != null) decrement(); return job; } @Override public Runnable take() throws InterruptedException { Runnable job = super.take(); decrement(); return job; } private void decrement() { size.decrementAndGet(); } } }
false
true
public boolean dispatch(final Runnable job) { final long begin = System.nanoTime(); return super.dispatch(new Runnable() { public void run() { long latency = System.nanoTime() - begin; Atomics.updateMax(maxLatency, latency); totalLatency.addAndGet(latency); tasks.incrementAndGet(); Atomics.updateMax(maxThreads, threads.incrementAndGet()); try { job.run(); } finally { threads.decrementAndGet(); } } }); }
public void execute(final Runnable job) { final long begin = System.nanoTime(); super.execute(new Runnable() { public void run() { long latency = System.nanoTime() - begin; Atomics.updateMax(maxLatency, latency); totalLatency.addAndGet(latency); tasks.incrementAndGet(); Atomics.updateMax(maxThreads, threads.incrementAndGet()); try { job.run(); } finally { threads.decrementAndGet(); } } }); }
diff --git a/src/test/java/hudson/plugins/git/GitPublisherTest.java b/src/test/java/hudson/plugins/git/GitPublisherTest.java index c08e233..d8b5e3e 100644 --- a/src/test/java/hudson/plugins/git/GitPublisherTest.java +++ b/src/test/java/hudson/plugins/git/GitPublisherTest.java @@ -1,97 +1,97 @@ /* * The MIT License * * Copyright (c) 2004-2011, Oracle Corporation, Andrew Bayer, Anton Kozak, Nikita Levyankov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.plugins.git; import hudson.Launcher; import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.Hudson; import hudson.plugins.git.GitPublisher.BranchToPush; import hudson.plugins.git.GitPublisher.TagToPush; import hudson.scm.NullSCM; import hudson.tasks.BuildStepDescriptor; import java.util.Collections; import org.jvnet.hudson.test.Bug; /** * Tests for {@link GitPublisher} * * @author Kohsuke Kawaguchi */ public class GitPublisherTest extends AbstractGitTestCase { @Bug(5005) public void testMatrixBuild() throws Exception { final int[] run = new int[1]; // count the number of times the perform is called commit("a", johnDoe, "commit #1"); MatrixProject mp = createMatrixProject("xyz"); mp.setAxes(new AxisList(new Axis("VAR", "a", "b"))); mp.setScm(new GitSCM(workDir.getAbsolutePath())); - mp.getPublishersList().add(new GitPublisher( + mp.addPublisher(new GitPublisher( Collections.singletonList(new TagToPush("origin", "foo", true)), Collections.<BranchToPush>emptyList(), true, true) { @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException { run[0]++; try { return super.perform(build, launcher, listener); } finally { // until the 3rd one (which is the last one), we shouldn't create a tag if (run[0] < 3) { assertFalse(existsTag("foo")); } } } @Override public BuildStepDescriptor getDescriptor() { return (BuildStepDescriptor) Hudson.getInstance().getDescriptorOrDie(GitPublisher.class); // fake } private Object writeReplace() { return new NullSCM(); } }); MatrixBuild b = assertBuildStatusSuccess(mp.scheduleBuild2(0).get()); System.out.println(b.getLog()); assertTrue(existsTag("foo")); // twice for MatrixRun, which is to be ignored, then once for matrix completion assertEquals(3, run[0]); } private boolean existsTag(String tag) { String tags = git.launchCommand("tag"); System.out.println(tags); return tags.contains(tag); } }
true
true
public void testMatrixBuild() throws Exception { final int[] run = new int[1]; // count the number of times the perform is called commit("a", johnDoe, "commit #1"); MatrixProject mp = createMatrixProject("xyz"); mp.setAxes(new AxisList(new Axis("VAR", "a", "b"))); mp.setScm(new GitSCM(workDir.getAbsolutePath())); mp.getPublishersList().add(new GitPublisher( Collections.singletonList(new TagToPush("origin", "foo", true)), Collections.<BranchToPush>emptyList(), true, true) { @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException { run[0]++; try { return super.perform(build, launcher, listener); } finally { // until the 3rd one (which is the last one), we shouldn't create a tag if (run[0] < 3) { assertFalse(existsTag("foo")); } } } @Override public BuildStepDescriptor getDescriptor() { return (BuildStepDescriptor) Hudson.getInstance().getDescriptorOrDie(GitPublisher.class); // fake } private Object writeReplace() { return new NullSCM(); } }); MatrixBuild b = assertBuildStatusSuccess(mp.scheduleBuild2(0).get()); System.out.println(b.getLog()); assertTrue(existsTag("foo")); // twice for MatrixRun, which is to be ignored, then once for matrix completion assertEquals(3, run[0]); }
public void testMatrixBuild() throws Exception { final int[] run = new int[1]; // count the number of times the perform is called commit("a", johnDoe, "commit #1"); MatrixProject mp = createMatrixProject("xyz"); mp.setAxes(new AxisList(new Axis("VAR", "a", "b"))); mp.setScm(new GitSCM(workDir.getAbsolutePath())); mp.addPublisher(new GitPublisher( Collections.singletonList(new TagToPush("origin", "foo", true)), Collections.<BranchToPush>emptyList(), true, true) { @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException { run[0]++; try { return super.perform(build, launcher, listener); } finally { // until the 3rd one (which is the last one), we shouldn't create a tag if (run[0] < 3) { assertFalse(existsTag("foo")); } } } @Override public BuildStepDescriptor getDescriptor() { return (BuildStepDescriptor) Hudson.getInstance().getDescriptorOrDie(GitPublisher.class); // fake } private Object writeReplace() { return new NullSCM(); } }); MatrixBuild b = assertBuildStatusSuccess(mp.scheduleBuild2(0).get()); System.out.println(b.getLog()); assertTrue(existsTag("foo")); // twice for MatrixRun, which is to be ignored, then once for matrix completion assertEquals(3, run[0]); }
diff --git a/src/main/java/servlet/TestLampServlet.java b/src/main/java/servlet/TestLampServlet.java index dfa3b27..a946961 100644 --- a/src/main/java/servlet/TestLampServlet.java +++ b/src/main/java/servlet/TestLampServlet.java @@ -1,101 +1,101 @@ package main.java.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.net.URI; import java.net.URISyntaxException; import java.sql.*; public class TestLampServlet extends HttpServlet { // Database Connection private static Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; // Hardcoded dbUrl: // String dbUrl = "jdbc:postgres://ixhixpfgeanclh:p1uyfk5c9yLh1VEWoCOGb4FIEX@ec2-54-225-112-205.compute-1.amazonaws.com:5432/d3lbshfcpi0soa"; // Heroku dbUrl: String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } private static String convertIntToStatus(int data_value_int) { // Convert int to string String status_str = "on"; if (data_value_int == 0) { status_str = "off"; } return status_str; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Connection connection = getConnection(); // Return the latest status of the test lamp Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1"); rs.next(); request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1))); request.setAttribute("lampStatusTime", rs.getString(2)); } catch (SQLException e) { request.setAttribute("SQLException", e.getMessage()); } catch (URISyntaxException e) { request.setAttribute("URISyntaxException", e.getMessage()); } request.getRequestDispatcher("/testlamp-get.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data_value_str = request.getParameter("data_value"); data_value_str = data_value_str.toLowerCase(); // Convert string to corresponding int 0-off 1-on int data_value_int; if (data_value_str == "off") { data_value_int = 0; } else { data_value_int = 1; } try { Connection connection = getConnection(); // Insert latest test lamp change Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO test_lamp VALUES (" + data_value_int + ", now())"); - stmt.executeUpdate("INSERT INTO testing VALUES (" + data_value_str); + stmt.executeUpdate("INSERT INTO testing VALUES (" + data_value_str + ")"); // Return the latest status of the test lamp ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1"); rs.next(); request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1))); request.setAttribute("lampStatusTime", rs.getString(2)); } catch (SQLException e) { request.setAttribute("SQLException", e.getMessage()); } catch (URISyntaxException e) { request.setAttribute("URISyntaxException", e.getMessage()); } request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response); } };
true
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data_value_str = request.getParameter("data_value"); data_value_str = data_value_str.toLowerCase(); // Convert string to corresponding int 0-off 1-on int data_value_int; if (data_value_str == "off") { data_value_int = 0; } else { data_value_int = 1; } try { Connection connection = getConnection(); // Insert latest test lamp change Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO test_lamp VALUES (" + data_value_int + ", now())"); stmt.executeUpdate("INSERT INTO testing VALUES (" + data_value_str); // Return the latest status of the test lamp ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1"); rs.next(); request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1))); request.setAttribute("lampStatusTime", rs.getString(2)); } catch (SQLException e) { request.setAttribute("SQLException", e.getMessage()); } catch (URISyntaxException e) { request.setAttribute("URISyntaxException", e.getMessage()); } request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data_value_str = request.getParameter("data_value"); data_value_str = data_value_str.toLowerCase(); // Convert string to corresponding int 0-off 1-on int data_value_int; if (data_value_str == "off") { data_value_int = 0; } else { data_value_int = 1; } try { Connection connection = getConnection(); // Insert latest test lamp change Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO test_lamp VALUES (" + data_value_int + ", now())"); stmt.executeUpdate("INSERT INTO testing VALUES (" + data_value_str + ")"); // Return the latest status of the test lamp ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1"); rs.next(); request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1))); request.setAttribute("lampStatusTime", rs.getString(2)); } catch (SQLException e) { request.setAttribute("SQLException", e.getMessage()); } catch (URISyntaxException e) { request.setAttribute("URISyntaxException", e.getMessage()); } request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response); }
diff --git a/SevenZip/src/org/sleuthkit/autopsy/sevenzip/SevenZipIngestModule.java b/SevenZip/src/org/sleuthkit/autopsy/sevenzip/SevenZipIngestModule.java index 55350d84a..cc4ea7012 100644 --- a/SevenZip/src/org/sleuthkit/autopsy/sevenzip/SevenZipIngestModule.java +++ b/SevenZip/src/org/sleuthkit/autopsy/sevenzip/SevenZipIngestModule.java @@ -1,751 +1,750 @@ /* * Autopsy Forensic Browser * * Copyright 2013 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.sevenzip; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.logging.Level; import javax.swing.JPanel; import net.sf.sevenzipjbinding.ISequentialOutStream; import net.sf.sevenzipjbinding.ISevenZipInArchive; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.ingest.IngestModuleAbstractFile; import org.sleuthkit.autopsy.ingest.IngestModuleInit; import org.sleuthkit.autopsy.ingest.IngestServices; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.SleuthkitCase; import net.sf.sevenzipjbinding.SevenZip; import net.sf.sevenzipjbinding.SevenZipException; import net.sf.sevenzipjbinding.SevenZipNativeInitializationException; import net.sf.sevenzipjbinding.simple.ISimpleInArchive; import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.progress.ProgressHandleFactory; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.services.FileManager; import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil; import org.sleuthkit.autopsy.ingest.IngestMessage; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE; import org.sleuthkit.datamodel.BlackboardAttribute; import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE; import org.sleuthkit.datamodel.DerivedFile; import org.sleuthkit.datamodel.ReadContentInputStream; import org.sleuthkit.datamodel.TskCoreException; /** * 7Zip ingest module Extracts supported archives, adds extracted DerivedFiles, * reschedules extracted DerivedFiles for ingest. * * Updates datamodel / directory tree with new files. */ public final class SevenZipIngestModule implements IngestModuleAbstractFile { private static final Logger logger = Logger.getLogger(SevenZipIngestModule.class.getName()); public static final String MODULE_NAME = "7Zip"; public static final String MODULE_DESCRIPTION = "Extracts archive files, add new files, reschedules them to current ingest and populates directory tree with new files."; final public static String MODULE_VERSION = "1.0"; private String args; private IngestServices services; private volatile int messageID = 0; private int processedFiles = 0; private SleuthkitCase caseHandle = null; private boolean initialized = false; private static SevenZipIngestModule instance = null; //TODO use content type detection instead of extensions static final String[] SUPPORTED_EXTENSIONS = {"zip", "rar", "arj", "7z", "7zip", "gzip", "gz", "bzip2", "tar", }; // "iso"}; private String unpackDir; //relative to the case, to store in db private String unpackDirPath; //absolute, to extract to private FileManager fileManager; //encryption type strings private static final String ENCRYPTION_FILE_LEVEL = "File-level Encryption"; private static final String ENCRYPTION_FULL = "Full Encryption"; //private constructor to ensure singleton instance private SevenZipIngestModule() { } /** * Returns singleton instance of the module, creates one if needed * * @return instance of the module */ public static synchronized SevenZipIngestModule getDefault() { if (instance == null) { instance = new SevenZipIngestModule(); } return instance; } @Override public void init(IngestModuleInit initContext) { logger.log(Level.INFO, "init()"); services = IngestServices.getDefault(); initialized = false; final Case currentCase = Case.getCurrentCase(); unpackDir = Case.getModulesOutputDirRelPath() + File.separator + MODULE_NAME; unpackDirPath = currentCase.getModulesOutputDirAbsPath() + File.separator + MODULE_NAME; fileManager = currentCase.getServices().getFileManager(); File unpackDirPathFile = new File(unpackDirPath); if (!unpackDirPathFile.exists()) { try { unpackDirPathFile.mkdirs(); } catch (SecurityException e) { logger.log(Level.SEVERE, "Error initializing output dir: " + unpackDirPath, e); MessageNotifyUtil.Notify.error("Error initializing " + MODULE_NAME, "Error initializing output dir: " + unpackDirPath + ": " + e.getMessage()); return; } } try { SevenZip.initSevenZipFromPlatformJAR(); String platform = SevenZip.getUsedPlatform(); logger.log(Level.INFO, "7-Zip-JBinding library was initialized on supported platform: " + platform); } catch (SevenZipNativeInitializationException e) { logger.log(Level.SEVERE, "Error initializing 7-Zip-JBinding library", e); MessageNotifyUtil.Notify.error("Error initializing " + MODULE_NAME, "Could not initialize 7-ZIP library"); return; } initialized = true; } @Override public ProcessResult process(AbstractFile abstractFile) { if (initialized == false) { //error initializing the module logger.log(Level.WARNING, "Skipping processing, module not initialized, file: " + abstractFile.getName()); return ProcessResult.OK; } if (abstractFile.isFile() == false || !isSupported(abstractFile)) { //do not process dirs and files that are not supported return ProcessResult.OK; } //check if already has derived files, skip try { if (abstractFile.hasChildren()) { logger.log(Level.INFO, "File already has been processed as it has children, skipping: " + abstractFile.getName()); return ProcessResult.OK; } } catch (TskCoreException e) { logger.log(Level.INFO, "Error checking if file already has been processed, skipping: " + abstractFile.getName()); return ProcessResult.OK; } logger.log(Level.INFO, "Processing with 7ZIP: " + abstractFile.getName()); ++processedFiles; List<AbstractFile> unpackedFiles = unpack(abstractFile); if (!unpackedFiles.isEmpty()) { sendNewFilesEvent(unpackedFiles); rescheduleNewFiles(unpackedFiles); } //process, return error if occurred return ProcessResult.OK; } private void sendNewFilesEvent(List<AbstractFile> unpackedFiles) { } private void rescheduleNewFiles (List<AbstractFile> unpackedFiles) { } /** * Unpack the file to local folder and return a list of derived files * * @param archiveFile file to unpack * @return list of unpacked derived files */ private List<AbstractFile> unpack(AbstractFile archiveFile) { List<AbstractFile> unpackedFiles = Collections.<AbstractFile>emptyList(); boolean hasEncrypted = false; boolean fullEncryption = true; ISevenZipInArchive inArchive = null; SevenZipContentReadStream stream = null; final ProgressHandle progress = ProgressHandleFactory.createHandle(MODULE_NAME + " Extracting Archive"); int processedItems = 0; String compressMethod = null; try { stream = new SevenZipContentReadStream(new ReadContentInputStream(archiveFile)); inArchive = SevenZip.openInArchive(null, // autodetect archive type stream); int numItems = inArchive.getNumberOfItems(); logger.log(Level.INFO, "Count of items in archive: " + archiveFile.getName() + ": " + numItems); progress.start(numItems); final ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface(); //setup the archive local root folder String localRootPath = archiveFile.getName() + "_" + archiveFile.getId(); String localRootAbsPath = unpackDirPath + File.separator + localRootPath; File localRoot = new File(localRootAbsPath); if (!localRoot.exists()) { try { localRoot.mkdirs(); } catch (SecurityException e) { logger.log(Level.SEVERE, "Error setting up output path for archive root: " + localRootAbsPath); //bail return unpackedFiles; } } //initialize tree hierarchy to keep track of unpacked file structure UnpackedTree uTree = new UnpackedTree(unpackDir + "/" + localRootPath, archiveFile, fileManager); //unpack and process every item in archive for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) { final String extractedPath = item.getPath(); logger.log(Level.INFO, "Extracted item path: " + extractedPath); //find this node in the hierarchy, create if needed UnpackedTree.Data uNode = uTree.find(extractedPath); String fileName = uNode.getFileName(); //update progress bar progress.progress(archiveFile.getName() + ": " + fileName, processedItems); if (compressMethod == null) { compressMethod = item.getMethod(); } final boolean isDir = item.isFolder(); final boolean isEncrypted = item.isEncrypted(); if (isEncrypted) { logger.log(Level.WARNING, "Skipping encrypted file in archive: " + extractedPath); hasEncrypted = true; continue; } else { fullEncryption = false; } //TODO get file mac times and add to db final String localFileRelPath = localRootPath + File.separator + extractedPath; //final String localRelPath = unpackDir + File.separator + localFileRelPath; final String localAbsPath = unpackDirPath + File.separator + localFileRelPath; //create local dirs and empty files before extracted File localFile = new java.io.File(localAbsPath); //cannot rely on files in top-bottom order if (!localFile.exists()) { //TODO check, might give file locking issues, since 7zip is writing to these dirs try { if (isDir) { localFile.mkdirs(); } else { localFile.getParentFile().mkdirs(); try { localFile.createNewFile(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error creating extracted file: " + localFile.getAbsolutePath(), ex); } } } catch (SecurityException e) { logger.log(Level.SEVERE, "Error setting up output path for unpacked file: " + extractedPath); //TODO consider bail out / msg to the user } } final long size = item.getSize(); final Date createTime = item.getCreationTime(); final Date accessTime = item.getLastAccessTime(); final Date writeTime = item.getLastWriteTime(); - final long createtime = createTime==null? 0L : createTime.getTime(); - final long modtime = writeTime==null? 0L : writeTime.getTime(); - final long accesstime = accessTime==null? 0L : accessTime.getTime(); - //TODO convert relative to timezone + final long createtime = createTime==null? 0L : createTime.getTime() / 1000; + final long modtime = writeTime==null? 0L : writeTime.getTime() / 1000; + final long accesstime = accessTime==null? 0L : accessTime.getTime() / 1000; //record derived data in unode, to be traversed later after unpacking the archive uNode.addDerivedInfo(size, !isDir, modtime, createtime, accesstime, modtime); //unpack locally if a file if (!isDir) { UnpackStream unpackStream = null; try { unpackStream = new UnpackStream(localAbsPath); item.extractSlow(unpackStream); } finally { if (unpackStream != null) { unpackStream.close(); } } } //update units for progress bar ++processedItems; } //for every item in archive try { uTree.createDerivedFiles(); unpackedFiles = uTree.getAllFileObjects(); } catch (TskCoreException e) { logger.log(Level.SEVERE, "Error populating complete derived file hierarchy from the unpacked dir structure"); //TODO decide if should cleanup, for now bailing } } catch (SevenZipException ex) { logger.log(Level.SEVERE, "Error unpacking file: " + archiveFile, ex); //inbox message String msg = "Error unpacking file: " + archiveFile.getName(); String details = msg + ". " + ex.getMessage(); services.postMessage(IngestMessage.createErrorMessage(++messageID, instance, msg, details)); } finally { if (inArchive != null) { try { inArchive.close(); } catch (SevenZipException e) { logger.log(Level.SEVERE, "Error closing archive: " + archiveFile, e); } } if (stream != null) { try { stream.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error closing stream after unpacking archive: " + archiveFile, ex); } } //close progress bar progress.finish(); } //create artifact and send user message if (hasEncrypted) { String encryptionType = fullEncryption ? ENCRYPTION_FULL : ENCRYPTION_FILE_LEVEL; try { BlackboardArtifact generalInfo = archiveFile.newArtifact(ARTIFACT_TYPE.TSK_GEN_INFO); generalInfo.addAttribute(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ENCRYPTION_DETECTED.getTypeID(), MODULE_NAME, encryptionType)); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error creating blackboard artifact for encryption detected for file: " + archiveFile, ex); } String msg = "Encrypted files in archive detected. "; String details = "Some files in archive: " + archiveFile.getName() + " are encrypted. " + MODULE_NAME + " extractor was unable to extract all files from this archive."; MessageNotifyUtil.Notify.info(msg, details); services.postMessage(IngestMessage.createMessage(++messageID, IngestMessage.MessageType.INFO, instance, msg, details)); } return unpackedFiles; } @Override public void complete() { logger.log(Level.INFO, "complete()"); if (initialized == false) { return; } //cleanup if any } @Override public void stop() { logger.log(Level.INFO, "stop()"); //cleanup if any } @Override public String getName() { return MODULE_NAME; } @Override public String getDescription() { return MODULE_DESCRIPTION; } @Override public String getVersion() { return MODULE_VERSION; } @Override public String getArguments() { return args; } @Override public void setArguments(String args) { this.args = args; } @Override public ModuleType getType() { return ModuleType.AbstractFile; } @Override public boolean hasBackgroundJobsRunning() { return false; } @Override public boolean hasSimpleConfiguration() { return false; } @Override public boolean hasAdvancedConfiguration() { return false; } @Override public void saveSimpleConfiguration() { } @Override public void saveAdvancedConfiguration() { } @Override public JPanel getSimpleConfiguration() { return null; } @Override public JPanel getAdvancedConfiguration() { return null; } public boolean isSupported(AbstractFile file) { String fileNameLower = file.getName().toLowerCase(); int dotI = fileNameLower.lastIndexOf("."); if (dotI == -1 || dotI == fileNameLower.length() - 1) { return false; //no extension } final String extension = fileNameLower.substring(dotI + 1); for (int i = 0; i < SUPPORTED_EXTENSIONS.length; ++i) { if (extension.equals(SUPPORTED_EXTENSIONS[i])) { return true; } } return false; } /** * Stream used to unpack the archive to local file */ private static class UnpackStream implements ISequentialOutStream { private OutputStream output; private String localAbsPath; UnpackStream(String localAbsPath) { try { output = new BufferedOutputStream(new FileOutputStream(localAbsPath)); } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, "Error writing extracted file: " + localAbsPath, ex); } } @Override public int write(byte[] bytes) throws SevenZipException { try { output.write(bytes); } catch (IOException ex) { throw new SevenZipException("Error writing unpacked file to: " + localAbsPath, ex); } return bytes.length; } public void close() { if (output != null) { try { output.flush(); output.close(); } catch (IOException e) { logger.log(Level.SEVERE, "Error closing unpack stream for file: " + localAbsPath); } } } } /** * Representation of local directory tree of unpacked archive. Used to track * of local tree file hierarchy and files created to easily and reliably get * parent AbstractFile for unpacked file. So that we don't have to depend on * type of traversal of unpacked files handed to us by 7zip unpacker. */ private static class UnpackedTree { final String localPathRoot; final Data root; //dummy root to hold children final FileManager fileManager; UnpackedTree(String localPathRoot, AbstractFile archiveRoot, FileManager fileManager) { this.localPathRoot = localPathRoot; this.fileManager = fileManager; this.root = new Data(); this.root.setFile(archiveRoot); this.root.setFileName(archiveRoot.getName()); this.root.localRelPath = localPathRoot; } /** * Tokenizes filePath passed in and traverses the dir structure, * creating data nodes on the path way as needed * * @param filePath file path with 1 or more tokens separated by / * @return child node for the last file token in the filePath */ Data find(String filePath) { String[] toks = filePath.split("[\\/\\\\]"); List<String> tokens = new ArrayList<String>(); for (int i = 0; i < toks.length; ++i) { if (!toks[i].isEmpty()) { tokens.add(toks[i]); } } return find(root, tokens); } /** * recursive method that traverses the path * * @param tokenPath * @return */ private Data find(Data parent, List<String> tokenPath) { //base case if (tokenPath.isEmpty()) { return parent; } String childName = tokenPath.remove(0); //step towards base case Data child = parent.getChild(childName); if (child == null) { child = new Data(childName, parent); } return find(child, tokenPath); } /** * Get the root file objects (after createDerivedFiles() ) of this tree, * so that they can be rescheduled. * * @return root objects of this unpacked tree */ List<AbstractFile> getRootFileObjects() { List<AbstractFile> ret = new ArrayList<AbstractFile>(); for (Data child : root.children) { ret.add(child.getFile()); } return ret; } /** * Get the all file objects (after createDerivedFiles() ) of this tree, * so that they can be rescheduled. * * @return all file objects of this unpacked tree */ List<AbstractFile> getAllFileObjects() { List<AbstractFile> ret = new ArrayList<AbstractFile>(); for (Data child : root.children) { getAllFileObjectsRec(ret, child); } return ret; } private void getAllFileObjectsRec(List<AbstractFile> list, Data parent) { list.add(parent.getFile()); for (Data child : parent.children) { getAllFileObjectsRec(list, child); } } /** * Traverse the tree top-down after unzipping is done and create derived * files for the entire hierarchy */ void createDerivedFiles() throws TskCoreException { for (Data child : root.children) { createDerivedFilesRec(child); } } private void createDerivedFilesRec(Data node) throws TskCoreException { final String fileName = node.getFileName(); final String localRelPath = node.getLocalRelPath(); final long size = node.getSize(); final boolean isFile = node.isIsFile(); final AbstractFile parent = node.getParent().getFile(); try { DerivedFile df = fileManager.addDerivedFile(fileName, localRelPath, size, node.getCtime(), node.getCrtime(), node.getAtime(), node.getMtime(), isFile, parent, "", MODULE_NAME, "", ""); node.setFile(df); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error adding a derived file to db:" + fileName, ex); throw new TskCoreException("Error adding a derived file to db:" + fileName, ex); } //recurse for (Data child : node.children) { createDerivedFilesRec(child); } } private static class Data { private String fileName; private AbstractFile file; private List<Data> children = new ArrayList<Data>(); private String localRelPath; private long size; private long ctime, crtime, atime, mtime; private boolean isFile; private Data parent; //root constructor Data() { } //child node constructor Data(String fileName, Data parent) { this.fileName = fileName; this.parent = parent; this.localRelPath = parent.localRelPath + "/" + fileName; //new child derived file will be set by unpack() method parent.children.add(this); } public long getCtime() { return ctime; } public long getCrtime() { return crtime; } public long getAtime() { return atime; } public long getMtime() { return mtime; } public void setFileName(String fileName) { this.fileName = fileName; } Data getParent() { return parent; } void addDerivedInfo(long size, boolean isFile, long ctime, long crtime, long atime, long mtime) { this.size = size; this.isFile = isFile; this.ctime = ctime; this.crtime = crtime; this.atime = atime; this.mtime = mtime; } void setFile(AbstractFile file) { this.file = file; } /** * get child by name or null if it doesn't exist * * @param childFileName * @return */ Data getChild(String childFileName) { Data ret = null; for (Data child : children) { if (child.fileName.equals(childFileName)) { ret = child; break; } } return ret; } public String getFileName() { return fileName; } public AbstractFile getFile() { return file; } public String getLocalRelPath() { return localRelPath; } public long getSize() { return size; } public boolean isIsFile() { return isFile; } } } }
true
true
private List<AbstractFile> unpack(AbstractFile archiveFile) { List<AbstractFile> unpackedFiles = Collections.<AbstractFile>emptyList(); boolean hasEncrypted = false; boolean fullEncryption = true; ISevenZipInArchive inArchive = null; SevenZipContentReadStream stream = null; final ProgressHandle progress = ProgressHandleFactory.createHandle(MODULE_NAME + " Extracting Archive"); int processedItems = 0; String compressMethod = null; try { stream = new SevenZipContentReadStream(new ReadContentInputStream(archiveFile)); inArchive = SevenZip.openInArchive(null, // autodetect archive type stream); int numItems = inArchive.getNumberOfItems(); logger.log(Level.INFO, "Count of items in archive: " + archiveFile.getName() + ": " + numItems); progress.start(numItems); final ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface(); //setup the archive local root folder String localRootPath = archiveFile.getName() + "_" + archiveFile.getId(); String localRootAbsPath = unpackDirPath + File.separator + localRootPath; File localRoot = new File(localRootAbsPath); if (!localRoot.exists()) { try { localRoot.mkdirs(); } catch (SecurityException e) { logger.log(Level.SEVERE, "Error setting up output path for archive root: " + localRootAbsPath); //bail return unpackedFiles; } } //initialize tree hierarchy to keep track of unpacked file structure UnpackedTree uTree = new UnpackedTree(unpackDir + "/" + localRootPath, archiveFile, fileManager); //unpack and process every item in archive for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) { final String extractedPath = item.getPath(); logger.log(Level.INFO, "Extracted item path: " + extractedPath); //find this node in the hierarchy, create if needed UnpackedTree.Data uNode = uTree.find(extractedPath); String fileName = uNode.getFileName(); //update progress bar progress.progress(archiveFile.getName() + ": " + fileName, processedItems); if (compressMethod == null) { compressMethod = item.getMethod(); } final boolean isDir = item.isFolder(); final boolean isEncrypted = item.isEncrypted(); if (isEncrypted) { logger.log(Level.WARNING, "Skipping encrypted file in archive: " + extractedPath); hasEncrypted = true; continue; } else { fullEncryption = false; } //TODO get file mac times and add to db final String localFileRelPath = localRootPath + File.separator + extractedPath; //final String localRelPath = unpackDir + File.separator + localFileRelPath; final String localAbsPath = unpackDirPath + File.separator + localFileRelPath; //create local dirs and empty files before extracted File localFile = new java.io.File(localAbsPath); //cannot rely on files in top-bottom order if (!localFile.exists()) { //TODO check, might give file locking issues, since 7zip is writing to these dirs try { if (isDir) { localFile.mkdirs(); } else { localFile.getParentFile().mkdirs(); try { localFile.createNewFile(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error creating extracted file: " + localFile.getAbsolutePath(), ex); } } } catch (SecurityException e) { logger.log(Level.SEVERE, "Error setting up output path for unpacked file: " + extractedPath); //TODO consider bail out / msg to the user } } final long size = item.getSize(); final Date createTime = item.getCreationTime(); final Date accessTime = item.getLastAccessTime(); final Date writeTime = item.getLastWriteTime(); final long createtime = createTime==null? 0L : createTime.getTime(); final long modtime = writeTime==null? 0L : writeTime.getTime(); final long accesstime = accessTime==null? 0L : accessTime.getTime(); //TODO convert relative to timezone //record derived data in unode, to be traversed later after unpacking the archive uNode.addDerivedInfo(size, !isDir, modtime, createtime, accesstime, modtime); //unpack locally if a file if (!isDir) { UnpackStream unpackStream = null; try { unpackStream = new UnpackStream(localAbsPath); item.extractSlow(unpackStream); } finally { if (unpackStream != null) { unpackStream.close(); } } } //update units for progress bar ++processedItems; } //for every item in archive try { uTree.createDerivedFiles(); unpackedFiles = uTree.getAllFileObjects(); } catch (TskCoreException e) { logger.log(Level.SEVERE, "Error populating complete derived file hierarchy from the unpacked dir structure"); //TODO decide if should cleanup, for now bailing } } catch (SevenZipException ex) { logger.log(Level.SEVERE, "Error unpacking file: " + archiveFile, ex); //inbox message String msg = "Error unpacking file: " + archiveFile.getName(); String details = msg + ". " + ex.getMessage(); services.postMessage(IngestMessage.createErrorMessage(++messageID, instance, msg, details)); } finally { if (inArchive != null) { try { inArchive.close(); } catch (SevenZipException e) { logger.log(Level.SEVERE, "Error closing archive: " + archiveFile, e); } } if (stream != null) { try { stream.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error closing stream after unpacking archive: " + archiveFile, ex); } } //close progress bar progress.finish(); } //create artifact and send user message if (hasEncrypted) { String encryptionType = fullEncryption ? ENCRYPTION_FULL : ENCRYPTION_FILE_LEVEL; try { BlackboardArtifact generalInfo = archiveFile.newArtifact(ARTIFACT_TYPE.TSK_GEN_INFO); generalInfo.addAttribute(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ENCRYPTION_DETECTED.getTypeID(), MODULE_NAME, encryptionType)); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error creating blackboard artifact for encryption detected for file: " + archiveFile, ex); } String msg = "Encrypted files in archive detected. "; String details = "Some files in archive: " + archiveFile.getName() + " are encrypted. " + MODULE_NAME + " extractor was unable to extract all files from this archive."; MessageNotifyUtil.Notify.info(msg, details); services.postMessage(IngestMessage.createMessage(++messageID, IngestMessage.MessageType.INFO, instance, msg, details)); } return unpackedFiles; }
private List<AbstractFile> unpack(AbstractFile archiveFile) { List<AbstractFile> unpackedFiles = Collections.<AbstractFile>emptyList(); boolean hasEncrypted = false; boolean fullEncryption = true; ISevenZipInArchive inArchive = null; SevenZipContentReadStream stream = null; final ProgressHandle progress = ProgressHandleFactory.createHandle(MODULE_NAME + " Extracting Archive"); int processedItems = 0; String compressMethod = null; try { stream = new SevenZipContentReadStream(new ReadContentInputStream(archiveFile)); inArchive = SevenZip.openInArchive(null, // autodetect archive type stream); int numItems = inArchive.getNumberOfItems(); logger.log(Level.INFO, "Count of items in archive: " + archiveFile.getName() + ": " + numItems); progress.start(numItems); final ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface(); //setup the archive local root folder String localRootPath = archiveFile.getName() + "_" + archiveFile.getId(); String localRootAbsPath = unpackDirPath + File.separator + localRootPath; File localRoot = new File(localRootAbsPath); if (!localRoot.exists()) { try { localRoot.mkdirs(); } catch (SecurityException e) { logger.log(Level.SEVERE, "Error setting up output path for archive root: " + localRootAbsPath); //bail return unpackedFiles; } } //initialize tree hierarchy to keep track of unpacked file structure UnpackedTree uTree = new UnpackedTree(unpackDir + "/" + localRootPath, archiveFile, fileManager); //unpack and process every item in archive for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) { final String extractedPath = item.getPath(); logger.log(Level.INFO, "Extracted item path: " + extractedPath); //find this node in the hierarchy, create if needed UnpackedTree.Data uNode = uTree.find(extractedPath); String fileName = uNode.getFileName(); //update progress bar progress.progress(archiveFile.getName() + ": " + fileName, processedItems); if (compressMethod == null) { compressMethod = item.getMethod(); } final boolean isDir = item.isFolder(); final boolean isEncrypted = item.isEncrypted(); if (isEncrypted) { logger.log(Level.WARNING, "Skipping encrypted file in archive: " + extractedPath); hasEncrypted = true; continue; } else { fullEncryption = false; } //TODO get file mac times and add to db final String localFileRelPath = localRootPath + File.separator + extractedPath; //final String localRelPath = unpackDir + File.separator + localFileRelPath; final String localAbsPath = unpackDirPath + File.separator + localFileRelPath; //create local dirs and empty files before extracted File localFile = new java.io.File(localAbsPath); //cannot rely on files in top-bottom order if (!localFile.exists()) { //TODO check, might give file locking issues, since 7zip is writing to these dirs try { if (isDir) { localFile.mkdirs(); } else { localFile.getParentFile().mkdirs(); try { localFile.createNewFile(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error creating extracted file: " + localFile.getAbsolutePath(), ex); } } } catch (SecurityException e) { logger.log(Level.SEVERE, "Error setting up output path for unpacked file: " + extractedPath); //TODO consider bail out / msg to the user } } final long size = item.getSize(); final Date createTime = item.getCreationTime(); final Date accessTime = item.getLastAccessTime(); final Date writeTime = item.getLastWriteTime(); final long createtime = createTime==null? 0L : createTime.getTime() / 1000; final long modtime = writeTime==null? 0L : writeTime.getTime() / 1000; final long accesstime = accessTime==null? 0L : accessTime.getTime() / 1000; //record derived data in unode, to be traversed later after unpacking the archive uNode.addDerivedInfo(size, !isDir, modtime, createtime, accesstime, modtime); //unpack locally if a file if (!isDir) { UnpackStream unpackStream = null; try { unpackStream = new UnpackStream(localAbsPath); item.extractSlow(unpackStream); } finally { if (unpackStream != null) { unpackStream.close(); } } } //update units for progress bar ++processedItems; } //for every item in archive try { uTree.createDerivedFiles(); unpackedFiles = uTree.getAllFileObjects(); } catch (TskCoreException e) { logger.log(Level.SEVERE, "Error populating complete derived file hierarchy from the unpacked dir structure"); //TODO decide if should cleanup, for now bailing } } catch (SevenZipException ex) { logger.log(Level.SEVERE, "Error unpacking file: " + archiveFile, ex); //inbox message String msg = "Error unpacking file: " + archiveFile.getName(); String details = msg + ". " + ex.getMessage(); services.postMessage(IngestMessage.createErrorMessage(++messageID, instance, msg, details)); } finally { if (inArchive != null) { try { inArchive.close(); } catch (SevenZipException e) { logger.log(Level.SEVERE, "Error closing archive: " + archiveFile, e); } } if (stream != null) { try { stream.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error closing stream after unpacking archive: " + archiveFile, ex); } } //close progress bar progress.finish(); } //create artifact and send user message if (hasEncrypted) { String encryptionType = fullEncryption ? ENCRYPTION_FULL : ENCRYPTION_FILE_LEVEL; try { BlackboardArtifact generalInfo = archiveFile.newArtifact(ARTIFACT_TYPE.TSK_GEN_INFO); generalInfo.addAttribute(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ENCRYPTION_DETECTED.getTypeID(), MODULE_NAME, encryptionType)); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error creating blackboard artifact for encryption detected for file: " + archiveFile, ex); } String msg = "Encrypted files in archive detected. "; String details = "Some files in archive: " + archiveFile.getName() + " are encrypted. " + MODULE_NAME + " extractor was unable to extract all files from this archive."; MessageNotifyUtil.Notify.info(msg, details); services.postMessage(IngestMessage.createMessage(++messageID, IngestMessage.MessageType.INFO, instance, msg, details)); } return unpackedFiles; }
diff --git a/src/com/dunksoftware/seminoletix/ListActivity.java b/src/com/dunksoftware/seminoletix/ListActivity.java index f4e4744..5ea85f3 100644 --- a/src/com/dunksoftware/seminoletix/ListActivity.java +++ b/src/com/dunksoftware/seminoletix/ListActivity.java @@ -1,417 +1,417 @@ package com.dunksoftware.seminoletix; import java.io.IOException; import java.text.DateFormat; import java.util.Date; import java.util.concurrent.ExecutionException; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.text.Html; import android.text.Html.ImageGetter; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; @SuppressLint("DefaultLocale") public class ListActivity extends Activity { private JSONObject[] GameObjects = null; private JSONArray gamesArray = null; private AdditionDetailsListener mDetailsListener = null; private GetGames games; private GetCurrentUser getCurrentUser; private String response = "ERROR!"; private String homeTeam, awayTeam, sportType, date; CharSequence finalDetailString; private int remainingSeats = 0; private TableLayout mainTable; private final int MESSAGE = 200, DETAILS_POPUP = 250; @SuppressLint("DefaultLocale") @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); TextView welcomeMsg = (TextView)findViewById(R.id.UI_GreetingText); homeTeam = awayTeam = sportType = date = ""; // general initialization mainTable = (TableLayout)findViewById(R.id.UI_MainTableLayout); mDetailsListener = new AdditionDetailsListener(); getCurrentUser = new GetCurrentUser(); getCurrentUser.execute(); try { JSONObject userInfoObject = new JSONObject(getCurrentUser.get()); String constructHeader = "Welcome, " + userInfoObject.getJSONObject("name").getString("first") + " " + userInfoObject.getJSONObject("name").getString("last"); welcomeMsg.setText(constructHeader); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ExecutionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } games = new GetGames(); try { games.execute(); response=games.get(); // Show the pop-up box (for display testing) showDialog(MESSAGE); gamesArray = new JSONArray(response); // Allocate space for all JSON objects embedded in the JSON array GameObjects = new JSONObject[gamesArray.length()]; // Transfer each object in this JSONArray into its own object for(int i=0;i<gamesArray.length();i++) GameObjects[i] = gamesArray.getJSONObject(i); /* * give every game a button for displaying additional * details about that game. (This button will also be * used to register for games */ Button[] detailsButtons = new Button[ gamesArray.length()]; for(int i = 0; i < gamesArray.length(); i++) { TableRow gameTableRow = new TableRow(this); LinearLayout list = new LinearLayout(this); // Initialize each button and give it a reference id (i) detailsButtons[i] = new Button(this); detailsButtons[i].setText("More Details"); detailsButtons[i].setId(i); detailsButtons[i].setOnClickListener(mDetailsListener); TextView[] info = new TextView[4]; // set the list to a top down look list.setOrientation(LinearLayout.VERTICAL); info[0] = new TextView(this); info[0].setText("\tSport:\t\t" + GameObjects[i].getString("sport")); list.addView(info[0]); info[1] = new TextView(this); //Format the date so that it is appropriate - String dateTime = GameObjects[i].getString("availableDate"); + String dateTime = GameObjects[i].getString("date"); String date = FormatDate(dateTime); info[1].setText("\tGame Date:\t\t" + date); list.addView(info[1]); info[2] = new TextView(this); info[2].setText("\tHome Team:\t\t" + GameObjects[i].getJSONObject("teams") .getString("home").toUpperCase()); list.addView(info[2]); info[3] = new TextView(this); info[3].setText("\tAgainst:\t\t" + GameObjects[i].getJSONObject("teams") .getString("away").toUpperCase()); list.addView(info[3]); // add the button to display details for each game // might have to add tag to button list.addView(detailsButtons[i]); list.setPadding(0, 5, 0, 20); gameTableRow.addView(list); gameTableRow.setBackgroundResource(R.drawable.img_gloss_background); mainTable.addView(gameTableRow); } } catch(InterruptedException ex) { Log.w("List Activity - mGetTable.execute()", ex.getMessage()); } catch(ExecutionException ex) { Log.w("List Activity - mGetTable.execute()", ex.getMessage()); } catch (JSONException e) { e.printStackTrace(); } } @SuppressWarnings("deprecation") String FormatDate(String Date) { String[] splits = Date.split("T"); splits = splits[0].split("-"); Date d = new Date(Integer.parseInt(splits[0]) - 1900, Integer.parseInt(splits[1]), Integer.parseInt(splits[2])); DateFormat newDate = DateFormat.getDateInstance(DateFormat.LONG); newDate.format(d); return newDate.getDateInstance(DateFormat.LONG).format(d); //return splits[0].trim(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_list, menu); return true; } @SuppressWarnings("deprecation") @Override protected Dialog onCreateDialog(int id) { AlertDialog.Builder builder = null; switch( id ) { case MESSAGE: { builder = new AlertDialog. Builder(this); builder.setCancelable(false).setTitle("Page Result"). setMessage(response).setNeutralButton("Close", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /* onclick closes the dialog by default, unless code is * added here */ } }); break; } case DETAILS_POPUP: builder = new AlertDialog. Builder(this); // set up the URL for the map (map uses browser) TextView mapURL = new TextView(this); mapURL.setText(Html.fromHtml("<a href=http://tinyurl.com/bwvhpsv>" + "<i>View a Map of the Stadium</i></a><br /><br />")); mapURL.setTextSize(20); // make URL active mapURL.setMovementMethod(LinkMovementMethod.getInstance()); builder.setCancelable(false).setTitle( Html.fromHtml("<b>Intramural Review Page</b>")). setMessage(finalDetailString).setNeutralButton("Close", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /* onclick closes the dialog by default, unless code is * added here */ } }).setView(mapURL); // add link at the bottom break; } if( builder != null) { // now show the dialog box once it's completed builder.create().show(); } return super.onCreateDialog(id); } /** * This function will set the data for the necessary variables * needed to correctly display a details dialog box for the chosen * game. * @param gameIndex - Signifies which game (index) was chosen */ public void showDetails(int gameIndex) { // get the corresponding object for the desired game JSONObject selectedGame = GameObjects[gameIndex]; //set up the information variables try { homeTeam = selectedGame.getJSONObject("teams") .getString("home"); awayTeam = selectedGame.getJSONObject("teams") .getString("away"); sportType = selectedGame.getString("sport"); date = selectedGame.getString("date"); // format the date date = FormatDate(date); remainingSeats = selectedGame.getInt("seatsLeft"); } catch (JSONException e) { e.printStackTrace(); } // format the resulting info string //finalDetailString = Html.fromHtml(source, imageGetter, tagHandler); finalDetailString = Html.fromHtml( "<img src=img_" + homeTeam + ">\t\t" + "<b>V.S</b>\t\t" + "<img src=img_" + awayTeam + "> " + "<br />" + "<br />" + "<b>Sport: </b>" + sportType + "<br />" + "<br />" + "<b>Seats Remaining: </b>" + remainingSeats + "<br />" + "<br />" + "<b>Event Date: </b>" + date ,new ImageGetter() { @Override public Drawable getDrawable(String source) { Drawable drawFromPath; int path = ListActivity.this.getResources().getIdentifier(source, "drawable", "com.dunksoftware.seminoletix"); drawFromPath = (Drawable) ListActivity.this.getResources().getDrawable(path); drawFromPath.setBounds(0, 0, drawFromPath.getIntrinsicWidth(), drawFromPath.getIntrinsicHeight()); return drawFromPath; } }, null);// link to map of stadium showDialog(DETAILS_POPUP); // then call showdialog } /** * After determining what game was inquired about, this class * will draw up a Dialog box that will give a full list of info * concerning that game. After reviewing the terms of the game, users * can either return to the list of games or reserve a ticket to the * current game being viewed */ class AdditionDetailsListener implements View.OnClickListener { @Override public void onClick(View v) { Button btn_viewGame = (Button)v; showDetails( btn_viewGame.getId()); } } class GetCurrentUser extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { // Create a new HttpClient and Post Header MyHttpClient client=new MyHttpClient(null); //sets cookie client.setCookieStore(UserControl.mCookie); // Prepare a request object HttpGet httpget = new HttpGet(Constants.CurrentUserAddress); // Execute the request HttpResponse response=null; // return string String returnString = null; try { // Open the web page. response = client.execute(httpget); returnString = EntityUtils.toString(response.getEntity()); } catch (IOException ex) { // Connection was not established returnString = "Connection failed; " + ex.getMessage(); } return returnString; } } class GetGames extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { // Create a new HttpClient and Post Header MyHttpClient client=new MyHttpClient(null); //sets cookie client.setCookieStore(UserControl.mCookie); // Prepare a request object HttpGet httpget = new HttpGet(Constants.GamesAddress); // Execute the request HttpResponse response=null; // return string String returnString = null; try { // Open the web page. response = client.execute(httpget); returnString = EntityUtils.toString(response.getEntity()); } catch (IOException ex) { // Connection was not established returnString = "Connection failed; " + ex.getMessage(); } return returnString; } } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); TextView welcomeMsg = (TextView)findViewById(R.id.UI_GreetingText); homeTeam = awayTeam = sportType = date = ""; // general initialization mainTable = (TableLayout)findViewById(R.id.UI_MainTableLayout); mDetailsListener = new AdditionDetailsListener(); getCurrentUser = new GetCurrentUser(); getCurrentUser.execute(); try { JSONObject userInfoObject = new JSONObject(getCurrentUser.get()); String constructHeader = "Welcome, " + userInfoObject.getJSONObject("name").getString("first") + " " + userInfoObject.getJSONObject("name").getString("last"); welcomeMsg.setText(constructHeader); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ExecutionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } games = new GetGames(); try { games.execute(); response=games.get(); // Show the pop-up box (for display testing) showDialog(MESSAGE); gamesArray = new JSONArray(response); // Allocate space for all JSON objects embedded in the JSON array GameObjects = new JSONObject[gamesArray.length()]; // Transfer each object in this JSONArray into its own object for(int i=0;i<gamesArray.length();i++) GameObjects[i] = gamesArray.getJSONObject(i); /* * give every game a button for displaying additional * details about that game. (This button will also be * used to register for games */ Button[] detailsButtons = new Button[ gamesArray.length()]; for(int i = 0; i < gamesArray.length(); i++) { TableRow gameTableRow = new TableRow(this); LinearLayout list = new LinearLayout(this); // Initialize each button and give it a reference id (i) detailsButtons[i] = new Button(this); detailsButtons[i].setText("More Details"); detailsButtons[i].setId(i); detailsButtons[i].setOnClickListener(mDetailsListener); TextView[] info = new TextView[4]; // set the list to a top down look list.setOrientation(LinearLayout.VERTICAL); info[0] = new TextView(this); info[0].setText("\tSport:\t\t" + GameObjects[i].getString("sport")); list.addView(info[0]); info[1] = new TextView(this); //Format the date so that it is appropriate String dateTime = GameObjects[i].getString("availableDate"); String date = FormatDate(dateTime); info[1].setText("\tGame Date:\t\t" + date); list.addView(info[1]); info[2] = new TextView(this); info[2].setText("\tHome Team:\t\t" + GameObjects[i].getJSONObject("teams") .getString("home").toUpperCase()); list.addView(info[2]); info[3] = new TextView(this); info[3].setText("\tAgainst:\t\t" + GameObjects[i].getJSONObject("teams") .getString("away").toUpperCase()); list.addView(info[3]); // add the button to display details for each game // might have to add tag to button list.addView(detailsButtons[i]); list.setPadding(0, 5, 0, 20); gameTableRow.addView(list); gameTableRow.setBackgroundResource(R.drawable.img_gloss_background); mainTable.addView(gameTableRow); } } catch(InterruptedException ex) { Log.w("List Activity - mGetTable.execute()", ex.getMessage()); } catch(ExecutionException ex) { Log.w("List Activity - mGetTable.execute()", ex.getMessage()); } catch (JSONException e) { e.printStackTrace(); } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); TextView welcomeMsg = (TextView)findViewById(R.id.UI_GreetingText); homeTeam = awayTeam = sportType = date = ""; // general initialization mainTable = (TableLayout)findViewById(R.id.UI_MainTableLayout); mDetailsListener = new AdditionDetailsListener(); getCurrentUser = new GetCurrentUser(); getCurrentUser.execute(); try { JSONObject userInfoObject = new JSONObject(getCurrentUser.get()); String constructHeader = "Welcome, " + userInfoObject.getJSONObject("name").getString("first") + " " + userInfoObject.getJSONObject("name").getString("last"); welcomeMsg.setText(constructHeader); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ExecutionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } games = new GetGames(); try { games.execute(); response=games.get(); // Show the pop-up box (for display testing) showDialog(MESSAGE); gamesArray = new JSONArray(response); // Allocate space for all JSON objects embedded in the JSON array GameObjects = new JSONObject[gamesArray.length()]; // Transfer each object in this JSONArray into its own object for(int i=0;i<gamesArray.length();i++) GameObjects[i] = gamesArray.getJSONObject(i); /* * give every game a button for displaying additional * details about that game. (This button will also be * used to register for games */ Button[] detailsButtons = new Button[ gamesArray.length()]; for(int i = 0; i < gamesArray.length(); i++) { TableRow gameTableRow = new TableRow(this); LinearLayout list = new LinearLayout(this); // Initialize each button and give it a reference id (i) detailsButtons[i] = new Button(this); detailsButtons[i].setText("More Details"); detailsButtons[i].setId(i); detailsButtons[i].setOnClickListener(mDetailsListener); TextView[] info = new TextView[4]; // set the list to a top down look list.setOrientation(LinearLayout.VERTICAL); info[0] = new TextView(this); info[0].setText("\tSport:\t\t" + GameObjects[i].getString("sport")); list.addView(info[0]); info[1] = new TextView(this); //Format the date so that it is appropriate String dateTime = GameObjects[i].getString("date"); String date = FormatDate(dateTime); info[1].setText("\tGame Date:\t\t" + date); list.addView(info[1]); info[2] = new TextView(this); info[2].setText("\tHome Team:\t\t" + GameObjects[i].getJSONObject("teams") .getString("home").toUpperCase()); list.addView(info[2]); info[3] = new TextView(this); info[3].setText("\tAgainst:\t\t" + GameObjects[i].getJSONObject("teams") .getString("away").toUpperCase()); list.addView(info[3]); // add the button to display details for each game // might have to add tag to button list.addView(detailsButtons[i]); list.setPadding(0, 5, 0, 20); gameTableRow.addView(list); gameTableRow.setBackgroundResource(R.drawable.img_gloss_background); mainTable.addView(gameTableRow); } } catch(InterruptedException ex) { Log.w("List Activity - mGetTable.execute()", ex.getMessage()); } catch(ExecutionException ex) { Log.w("List Activity - mGetTable.execute()", ex.getMessage()); } catch (JSONException e) { e.printStackTrace(); } }
diff --git a/src/sjsu/cs157a/dbpro/servlet/filter/LoginCheckFilter.java b/src/sjsu/cs157a/dbpro/servlet/filter/LoginCheckFilter.java index 64ee08d..abd8416 100644 --- a/src/sjsu/cs157a/dbpro/servlet/filter/LoginCheckFilter.java +++ b/src/sjsu/cs157a/dbpro/servlet/filter/LoginCheckFilter.java @@ -1,55 +1,54 @@ package sjsu.cs157a.dbpro.servlet.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; public class LoginCheckFilter implements Filter { private static final Logger logger = Logger .getLogger(LoginCheckFilter.class); private static final String SIGN_IN_PATH = "/signin"; private static final String REGISTER_PATH = "/register"; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String path = req.getServletPath(); // place your code here logger.info("before chain.doFilter(): " + path); if (!path.equals(SIGN_IN_PATH) && !path.equals(REGISTER_PATH) && path.indexOf('.') == -1) { if (req.getSession().getAttribute("username") == null) { logger.warn("unexpected access to path: " + path); - resp.sendRedirect(req.getServletContext().getContextPath() - + SIGN_IN_PATH); + resp.sendRedirect(req.getContextPath() + SIGN_IN_PATH); return; } } // pass the request along the filter chain chain.doFilter(request, response); logger.info("after chain.doFilter(): " + path); } public void init(FilterConfig fConfig) throws ServletException { logger.info("filter init..."); } @Override public void destroy() { logger.info("filter destroy..."); } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String path = req.getServletPath(); // place your code here logger.info("before chain.doFilter(): " + path); if (!path.equals(SIGN_IN_PATH) && !path.equals(REGISTER_PATH) && path.indexOf('.') == -1) { if (req.getSession().getAttribute("username") == null) { logger.warn("unexpected access to path: " + path); resp.sendRedirect(req.getServletContext().getContextPath() + SIGN_IN_PATH); return; } } // pass the request along the filter chain chain.doFilter(request, response); logger.info("after chain.doFilter(): " + path); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String path = req.getServletPath(); // place your code here logger.info("before chain.doFilter(): " + path); if (!path.equals(SIGN_IN_PATH) && !path.equals(REGISTER_PATH) && path.indexOf('.') == -1) { if (req.getSession().getAttribute("username") == null) { logger.warn("unexpected access to path: " + path); resp.sendRedirect(req.getContextPath() + SIGN_IN_PATH); return; } } // pass the request along the filter chain chain.doFilter(request, response); logger.info("after chain.doFilter(): " + path); }
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java index cafeb4499..05b1df41d 100644 --- a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java +++ b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java @@ -1,1497 +1,1497 @@ package net.aufdemrand.denizen.objects; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.aufdemrand.denizen.flags.FlagManager; import net.aufdemrand.denizen.objects.properties.Property; import net.aufdemrand.denizen.objects.properties.PropertyParser; import net.aufdemrand.denizen.scripts.commands.core.FailCommand; import net.aufdemrand.denizen.scripts.commands.core.FinishCommand; import net.aufdemrand.denizen.tags.Attribute; import net.aufdemrand.denizen.tags.core.PlayerTags; import net.aufdemrand.denizen.utilities.DenizenAPI; import net.aufdemrand.denizen.utilities.debugging.dB; import net.aufdemrand.denizen.utilities.depends.Depends; import net.aufdemrand.denizen.utilities.packets.BossHealthBar; import net.citizensnpcs.api.CitizensAPI; import org.bukkit.Achievement; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.WeatherType; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.util.BlockIterator; public class dPlayer implements dObject, Adjustable { ///////////////////// // STATIC METHODS ///////////////// static Map<String, dPlayer> players = new HashMap<String, dPlayer>(); public static dPlayer mirrorBukkitPlayer(OfflinePlayer player) { if (player == null) return null; if (players.containsKey(player.getName())) return players.get(player.getName()); else return new dPlayer(player); } ///////////////////// // OBJECT FETCHER ///////////////// // <--[language] // @name p@ // @group Object Fetcher System // @description // p@ refers to the 'object identifier' of a dPlayer. The 'p@' is notation for Denizen's Object // Fetcher. The only valid constructor for a dPlayer is the name of the player the object should be // associated with. For example, to reference the player named 'mythan', use p@mythan. Player names // are case insensitive. // --> @Fetchable("p") public static dPlayer valueOf(String string) { if (string == null) return null; string = string.replace("p@", ""); //////// // Match player name OfflinePlayer returnable = null; for (OfflinePlayer player : Bukkit.getOfflinePlayers()) if (player.getName().equalsIgnoreCase(string)) { returnable = player; break; } if (returnable != null) { if (players.containsKey(returnable.getName())) return players.get(returnable.getName()); else return new dPlayer(returnable); } else dB.echoError("Invalid Player! '" + string + "' could not be found. Has the player logged off?"); return null; } public static boolean matches(String arg) { // If passed null, of course it doesn't match! if (arg == null) return false; // If passed a identified object that starts with 'p@', return true // even if the player doesn't technically exist. if (arg.toLowerCase().startsWith("p@")) return true; // No identifier supplied? Let's check offlinePlayers. Return true if // a match is found. OfflinePlayer returnable = null; for (OfflinePlayer player : Bukkit.getOfflinePlayers()) if (player.getName().equalsIgnoreCase(arg)) { returnable = player; break; } return returnable != null; } ///////////////////// // CONSTRUCTORS ///////////////// public dPlayer(OfflinePlayer player) { if (player == null) return; this.player_name = player.getName(); // Keep in a map to avoid multiple instances of a dPlayer per player. players.put(this.player_name, this); } ///////////////////// // INSTANCE FIELDS/METHODS ///////////////// String player_name = null; public boolean isValid() { return getPlayerEntity() != null || getOfflinePlayer() != null; } public Player getPlayerEntity() { if (player_name == null) return null; return Bukkit.getPlayer(player_name); } public OfflinePlayer getOfflinePlayer() { if (player_name == null) return null; return Bukkit.getOfflinePlayer(player_name); } public dEntity getDenizenEntity() { return new dEntity(getPlayerEntity()); } public dNPC getSelectedNPC() { if (getPlayerEntity().hasMetadata("selected")) return dNPC.valueOf(getPlayerEntity().getMetadata("selected").get(0).asString()); else return null; } public String getName() { return player_name; } public dLocation getLocation() { if (isOnline()) return new dLocation(getPlayerEntity().getLocation()); else return null; } public dLocation getEyeLocation() { if (isOnline()) return new dLocation(getPlayerEntity().getEyeLocation()); else return null; } public World getWorld() { if (isOnline()) return getPlayerEntity().getWorld(); else return null; } public boolean isOnline() { return getPlayerEntity() != null; } ///////////////////// // dObject Methods ///////////////// private String prefix = "Player"; @Override public String getPrefix() { return prefix; } @Override public dPlayer setPrefix(String prefix) { this.prefix = prefix; return this; } @Override public String debug() { return (prefix + "='<A>" + identify() + "<G>' "); } @Override public boolean isUnique() { return true; } @Override public String getObjectType() { return "Player"; } @Override public String identify() { return "p@" + player_name; } @Override public String identifySimple() { return identify(); } @Override public String toString() { return identify(); } @Override public String getAttribute(Attribute attribute) { if (attribute == null) return "null"; if (player_name == null) return Element.NULL.getAttribute(attribute); ///////////////////// // OFFLINE ATTRIBUTES ///////////////// ///////////////////// // DEBUG ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Boolean) // @description // Debugs the player in the log and returns true. // --> if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the player's debug with no color. // --> if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the player's debug. // --> if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the dObject's prefix. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); ///////////////////// // DENIZEN ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_history_list> // @returns dList // @description // Returns a list of the last 10 things the player has said, less // if the player hasn't said all that much. // --> if (attribute.startsWith("chat_history_list")) return new dList(PlayerTags.playerChatHistory.get(player_name)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_history[#]> // @returns Element // @description // returns the last thing the player said. // If a number is specified, returns an earlier thing the player said. // --> if (attribute.startsWith("chat_history")) { int x = 1; if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1))) x = attribute.getIntContext(1); // No playerchathistory? Return null. if (!PlayerTags.playerChatHistory.containsKey(player_name)) return Element.NULL.getAttribute(attribute.fulfill(1)); else return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<flag_name>]> // @returns Flag dList // @description // returns the specified flag from the player. // --> if (attribute.startsWith("flag")) { String flag_name; if (attribute.hasContext(1)) flag_name = attribute.getContext(1); else return Element.NULL.getAttribute(attribute.fulfill(1)); attribute.fulfill(1); if (attribute.startsWith("is_expired") || attribute.startsWith("isexpired")) return new Element(!FlagManager.playerHasFlag(this, flag_name)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("size") && !FlagManager.playerHasFlag(this, flag_name)) return new Element(0).getAttribute(attribute.fulfill(1)); if (FlagManager.playerHasFlag(this, flag_name)) return new dList(DenizenAPI.getCurrentInstance().flagManager() .getPlayerFlag(getName(), flag_name)) .getAttribute(attribute); else return Element.NULL.getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_flag[<flag_name>]> // @returns Element(Boolean) // @description // returns true if the Player has the specified flag, otherwise returns false. // --> if (attribute.startsWith("has_flag")) { String flag_name; if (attribute.hasContext(1)) flag_name = attribute.getContext(1); else return Element.NULL.getAttribute(attribute.fulfill(1)); return new Element(FlagManager.playerHasFlag(this, flag_name)).getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("current_step")) { String outcome = "null"; if (attribute.hasContext(1)) { try { outcome = DenizenAPI.getCurrentInstance().getSaves().getString("Players." + getName() + ".Scripts." + dScript.valueOf(attribute.getContext(1)).getName() + ".Current Step"); } catch (Exception e) { outcome = "null"; } } return new Element(outcome).getAttribute(attribute.fulfill(1)); } ///////////////////// // ECONOMY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the amount of money the player has with the registered Economy system. // --> if (attribute.startsWith("money")) { if(Depends.economy != null) { // <--[tag] // @attribute <[email protected]_singular> // @returns Element // @description // returns the name of a single piece of currency - EG: Dollar // (Only if supported by the registered Economy system.) // --> if (attribute.startsWith("money.currency_singular")) return new Element(Depends.economy.currencyNameSingular()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of multiple pieces of currency - EG: Dollars // (Only if supported by the registered Economy system.) // --> if (attribute.startsWith("money.currency")) return new Element(Depends.economy.currencyNamePlural()) .getAttribute(attribute.fulfill(2)); return new Element(Depends.economy.getBalance(player_name)) .getAttribute(attribute.fulfill(1)); } else { dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?"); return Element.NULL.getAttribute(attribute.fulfill(1)); } } ///////////////////// // ENTITY LIST ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected][(<entity>|...)]> // @returns dEntity // @description // Returns the entity that the player is looking at, within a maximum range of 50 blocks, // or null if the player is not looking at an entity. // Optionally, specify a list of entities, entity types, or 'npc' to only count those targets. // --> if (attribute.startsWith("target")) { int range = 50; int attribs = 1; // <--[tag] // @attribute <[email protected][(<entity>|...)].within[(<#>)]> // @returns dEntity // @description // Returns the entity that the player is looking at within the specified range limit, // or null if the player is not looking at an entity. // Optionally, specify a list of entities, entity types, or 'npc' to only count those targets. if (attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2) && aH.matchesInteger(attribute.getContext(2))) { attribs = 2; range = attribute.getIntContext(2); } List<Entity> entities = getPlayerEntity().getNearbyEntities(range, range, range); ArrayList<LivingEntity> possibleTargets = new ArrayList<LivingEntity>(); for (Entity entity : entities) { if (entity instanceof LivingEntity) { // if we have a context for entity types, check the entity if (attribute.hasContext(1)) { String context = attribute.getContext(1); if (context.toLowerCase().startsWith("li@")) context = context.substring(3); for (String ent: context.split("\\|")) { boolean valid = false; if (ent.equalsIgnoreCase("npc") && CitizensAPI.getNPCRegistry().isNPC(entity)) { valid = true; } else if (dEntity.matches(ent)) { // only accept generic entities that are not NPCs if (dEntity.valueOf(ent).isGeneric()) { if (!CitizensAPI.getNPCRegistry().isNPC(entity)) { valid = true; } } else { valid = true; } } if (valid) possibleTargets.add((LivingEntity) entity); } } else { // no entity type specified possibleTargets.add((LivingEntity) entity); entity.getType(); } } } // Find the valid target BlockIterator bi; try { bi = new BlockIterator(getPlayerEntity(), range); } catch (IllegalStateException e) { return Element.NULL.getAttribute(attribute.fulfill(attribs)); } Block b; Location l; int bx, by, bz; double ex, ey, ez; // Loop through player's line of sight while (bi.hasNext()) { b = bi.next(); bx = b.getX(); by = b.getY(); bz = b.getZ(); if (b.getType() != Material.AIR) { // Line of sight is broken break; } else { // Check for entities near this block in the line of sight for (LivingEntity possibleTarget : possibleTargets) { l = possibleTarget.getLocation(); ex = l.getX(); ey = l.getY(); ez = l.getZ(); if ((bx - .50 <= ex && ex <= bx + 1.50) && (bz - .50 <= ez && ez <= bz + 1.50) && (by - 1 <= ey && ey <= by + 2.5)) { // Entity is close enough, so return it return new dEntity(possibleTarget).getAttribute(attribute.fulfill(attribs)); } } } } return Element.NULL.getAttribute(attribute.fulfill(attribs)); } // <--[tag] // @attribute <[email protected]> // @returns dList(dPlayer) // @description // Returns all players that have ever played on the server, online or not. // ** NOTE: This tag is old. Please instead use <server.list_players> ** // --> if (attribute.startsWith("list")) { List<String> players = new ArrayList<String>(); // <--[tag] // @attribute <[email protected]> // @returns dList(dPlayer) // @description // Returns all online players. // **NOTE: This will only work if there is a player attached to the current script. // If you need it anywhere else, use <server.list_online_players>** // --> if (attribute.startsWith("list.online")) { for(Player player : Bukkit.getOnlinePlayers()) players.add(player.getName()); return new dList(players).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns dList(dPlayer) // @description // Returns all players that have ever played on the server, but are not currently online. // ** NOTE: This tag is old. Please instead use <server.list_offline_players> ** // --> else if (attribute.startsWith("list.offline")) { for(OfflinePlayer player : Bukkit.getOfflinePlayers()) { if (!Bukkit.getOnlinePlayers().toString().contains(player.getName())) players.add(player.getName()); } return new dList(players).getAttribute(attribute.fulfill(2)); } else { for(OfflinePlayer player : Bukkit.getOfflinePlayers()) players.add(player.getName()); return new dList(players).getAttribute(attribute.fulfill(1)); } } ///////////////////// // IDENTIFICATION ATTRIBUTES ///////////////// if (attribute.startsWith("name") && !isOnline()) // This can be parsed later with more detail if the player is online, so only check for offline. return new Element(player_name).getAttribute(attribute.fulfill(1)); ///////////////////// // LOCATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_spawn> // @returns dLocation // @description // Returns the location of the player's bed spawn location, 'null' if // it doesn't exist. // --> if (attribute.startsWith("bed_spawn")) return new dLocation(getOfflinePlayer().getBedSpawnLocation()) .getAttribute(attribute.fulfill(2)); ///////////////////// // STATE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_played> // @returns Duration // @description // returns the millisecond time of when the player first logged on to this server. // --> if (attribute.startsWith("first_played")) { attribute = attribute.fulfill(1); if (attribute.startsWith("milliseconds") || attribute.startsWith("in_milliseconds")) return new Element(getOfflinePlayer().getFirstPlayed()) .getAttribute(attribute.fulfill(1)); else return new Duration(getOfflinePlayer().getFirstPlayed() / 50) .getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_played_before> // @returns Element(Boolean) // @description // returns whether the player has played before. // --> if (attribute.startsWith("has_played_before")) return new Element(true) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_scaled> // @returns Element(Boolean) // @description // returns whether the player's health bar is currently being scaled. // --> if (attribute.startsWith("health.is_scaled")) return new Element(getPlayerEntity().isHealthScaled()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the current scale for the player's health bar // --> if (attribute.startsWith("health.scale")) return new Element(getPlayerEntity().getHealthScale()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_banned> // @returns Element(Boolean) // @description // returns whether the player is banned. // --> if (attribute.startsWith("is_banned")) return new Element(getOfflinePlayer().isBanned()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_online> // @returns Element(Boolean) // @description // returns whether the player is currently online. // --> if (attribute.startsWith("is_online")) return new Element(isOnline()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_op> // @returns Element(Boolean) // @description // returns whether the player is a full server operator. // --> if (attribute.startsWith("is_op")) return new Element(getOfflinePlayer().isOp()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_whitelisted> // @returns Element(Boolean) // @description // returns whether the player is whitelisted. // --> if (attribute.startsWith("is_whitelisted")) return new Element(getOfflinePlayer().isWhitelisted()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_played> // @returns Duration // @description // returns the millisecond time of when the player // was last seen. // --> if (attribute.startsWith("last_played")) { attribute = attribute.fulfill(1); if (attribute.startsWith("milliseconds") || attribute.startsWith("in_milliseconds")) return new Element(getOfflinePlayer().getLastPlayed()) .getAttribute(attribute.fulfill(1)); else return new Duration(getOfflinePlayer().getLastPlayed() / 50) .getAttribute(attribute); } ///////////////////// // ONLINE ATTRIBUTES ///////////////// // Player is required to be online after this point... if (!isOnline()) return new Element(identify()).getAttribute(attribute); ///////////////////// // CITIZENS ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_npc> // @returns dNPC // @description // returns the dNPC that the player currently has selected with // '/npc select', null if no player selected. // --> if (attribute.startsWith("selected_npc")) { if (getPlayerEntity().hasMetadata("selected")) return getSelectedNPC() .getAttribute(attribute.fulfill(1)); else return Element.NULL.getAttribute(attribute.fulfill(1)); } ///////////////////// // CONVERSION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dEntity // @description // returns the dEntity object of the player. // (Note: This should never actually be needed. <p@player> is considered a valid dEntity by script commands.) // --> if (attribute.startsWith("entity") && !attribute.startsWith("entity_")) return new dEntity(getPlayerEntity()) .getAttribute(attribute.fulfill(1)); ///////////////////// // IDENTIFICATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the player's IP address. // --> if (attribute.startsWith("ip") || attribute.startsWith("host_name")) return new Element(getPlayerEntity().getAddress().getHostName()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the display name of the player, which may contain // prefixes and suffixes, colors, etc. // --> if (attribute.startsWith("name.display")) return new Element(getPlayerEntity().getDisplayName()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of the player as shown in the player list. // --> if (attribute.startsWith("name.list")) return new Element(getPlayerEntity().getPlayerListName()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of the player. // --> if (attribute.startsWith("name")) return new Element(player_name).getAttribute(attribute.fulfill(1)); ///////////////////// // INVENTORY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dInventory // @description // returns a dInventory of the player's current inventory. // --> if (attribute.startsWith("inventory")) return new dInventory(getPlayerEntity().getInventory()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_on_cursor> // @returns dItem // @description // returns a dItem that the player's cursor is on, if any. This includes // chest interfaces, inventories, and hotbars, etc. // --> if (attribute.startsWith("item_on_cursor")) return new dItem(getPlayerEntity().getItemOnCursor()) .getAttribute(attribute.fulfill(1)); ///////////////////// // PERMISSION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_permission[permission.node]> // @returns Element(Boolean) // @description // returns whether the player has the specified node. // --> if (attribute.startsWith("permission") || attribute.startsWith("has_permission")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return null; } String permission = attribute.getContext(1); // <--[tag] // @attribute <[email protected]_permission[permission.node].global> // @returns Element(Boolean) // @description // returns whether the player has the specified node, regardless of world. // (Note: this may or may not be functional with your permissions system.) // --> // Non-world specific permission if (attribute.getAttribute(2).startsWith("global")) return new Element(Depends.permissions.has((World) null, player_name, permission)) .getAttribute(attribute.fulfill(2)); // Permission in certain world else if (attribute.getAttribute(2).startsWith("world")) return new Element(Depends.permissions.has(attribute.getContext(2), player_name, permission)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_permission[permission.node].world> // @returns Element(Boolean) // @description // returns whether the player has the specified node in regards to the // player's current world. // (Note: This may or may not be functional with your permissions system.) // --> // Permission in current world return new Element(Depends.permissions.has(getPlayerEntity(), permission)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_group[<group_name>]> // @returns Element(Boolean) // @description // returns whether the player is in the specified group. // --> if (attribute.startsWith("group") || attribute.startsWith("in_group")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return Element.NULL.getAttribute(attribute.fulfill(1)); } String group = attribute.getContext(1); // <--[tag] // @attribute <[email protected]_group[<group_name>].global> // @returns Element(Boolean) // @description // returns whether the player has the group with no regard to the // player's current world. // (Note: This may or may not be functional with your permissions system.) // --> // Non-world specific permission if (attribute.getAttribute(2).startsWith("global")) return new Element(Depends.permissions.playerInGroup((World) null, player_name, group)) .getAttribute(attribute.fulfill(2)); // Permission in certain world else if (attribute.getAttribute(2).startsWith("world")) return new Element(Depends.permissions.playerInGroup(attribute.getContext(2), player_name, group)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_group[<group_name>].world> // @returns Element(Boolean) // @description // returns whether the player has the group in regards to the // player's current world. // (Note: This may or may not be functional with your permissions system.) // --> // Permission in current world return new Element(Depends.permissions.playerInGroup(getPlayerEntity(), group)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_finished[<script>]> // @returns dLocation // @description // returns the if the Player has finished the specified script. // --> if (attribute.startsWith("has_finished")) { dScript script = dScript.valueOf(attribute.getContext(1)); if (script == null) return Element.FALSE.getAttribute(attribute.fulfill(1)); return new Element(FinishCommand.getScriptCompletes(getName(), script.getName()) > 0) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_failed[<script>]> // @returns dLocation // @description - // returns the if the Player has finished the specified script. + // returns the if the Player has failed the specified script. // --> if (attribute.startsWith("has_failed")) { dScript script = dScript.valueOf(attribute.getContext(1)); if (script == null) return Element.FALSE.getAttribute(attribute.fulfill(1)); return new Element(FailCommand.getScriptFails(getName(), script.getName()) > 0) .getAttribute(attribute.fulfill(1)); } ///////////////////// // LOCATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // returns the location of the player's compass target. // --> if (attribute.startsWith("compass_target")) return new dLocation(getPlayerEntity().getCompassTarget()) .getAttribute(attribute.fulfill(2)); ///////////////////// // STATE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_flight> // @returns Element(Boolean) // @description // returns whether the player is allowed to fly. // --> if (attribute.startsWith("allowed_flight")) return new Element(getPlayerEntity().getAllowFlight()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_speed> // @returns Element(Decimal) // @description // returns the speed the player can fly at. // --> if (attribute.startsWith("fly_speed")) return new Element(getPlayerEntity().getFlySpeed()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_level.formatted> // @returns Element // @description // returns a 'formatted' value of the player's current food level. // May be 'starving', 'famished', 'parched, 'hungry' or 'healthy'. // --> if (attribute.startsWith("food_level.formatted")) { double maxHunger = getPlayerEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHunger = attribute.getIntContext(2); if (getPlayerEntity().getFoodLevel() / maxHunger < .10) return new Element("starving").getAttribute(attribute.fulfill(2)); else if (getPlayerEntity().getFoodLevel() / maxHunger < .40) return new Element("famished").getAttribute(attribute.fulfill(2)); else if (getPlayerEntity().getFoodLevel() / maxHunger < .75) return new Element("parched").getAttribute(attribute.fulfill(2)); else if (getPlayerEntity().getFoodLevel() / maxHunger < 1) return new Element("hungry").getAttribute(attribute.fulfill(2)); else return new Element("healthy").getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the current saturation of the player. // --> if (attribute.startsWith("saturation")) return new Element(getPlayerEntity().getSaturation()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_level> // @returns Element(Number) // @description // returns the current food level of the player. // --> if (attribute.startsWith("food_level")) return new Element(getPlayerEntity().getFoodLevel()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns how much air the player can have. // --> if (attribute.startsWith("oxygen.max")) return new Element(getPlayerEntity().getMaximumAir()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns how much air the player has. // --> if (attribute.startsWith("oxygen")) return new Element(getPlayerEntity().getRemainingAir()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns the gamemode ID of the player. 0 = survival, 1 = creative, 2 = adventure // --> if (attribute.startsWith("gamemode.id")) return new Element(getPlayerEntity().getGameMode().getValue()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of the gamemode the player is currently set to. // --> if (attribute.startsWith("gamemode")) return new Element(getPlayerEntity().getGameMode().name()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_blocking> // @returns Element(Boolean) // @description // returns whether the player is currently blocking. // --> if (attribute.startsWith("is_blocking")) return new Element(getPlayerEntity().isBlocking()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_flying> // @returns Element(Boolean) // @description // returns whether the player is currently flying. // --> if (attribute.startsWith("is_flying")) return new Element(getPlayerEntity().isFlying()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_sleeping> // @returns Element(Boolean) // @description // returns whether the player is currently sleeping. // --> if (attribute.startsWith("is_sleeping")) return new Element(getPlayerEntity().isSleeping()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_sneaking> // @returns Element(Boolean) // @description // returns whether the player is currently sneaking. // --> if (attribute.startsWith("is_sneaking")) return new Element(getPlayerEntity().isSneaking()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_sprinting> // @returns Element(Boolean) // @description // returns whether the player is currently sprinting. // --> if (attribute.startsWith("is_sprinting")) return new Element(getPlayerEntity().isSprinting()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_asleep> // @returns Duration // @description // returns the time the player has been asleep. // --> if (attribute.startsWith("time_asleep")) return new Duration(getPlayerEntity().getSleepTicks() / 20) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Duration // @description // returns the time the player is currently experiencing. This time could differ from // the time that the rest of the world is currently experiencing if a 'time' or 'freeze_time' // mechanism is being used on the player. // --> if (attribute.startsWith("time")) return new Element(getPlayerEntity().getPlayerTime()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_speed> // @returns Element(Decimal) // @description // returns the speed the player can walk at. // --> if (attribute.startsWith("walk_speed")) return new Element(getPlayerEntity().getWalkSpeed()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the type of weather the player is experiencing. This can be different // from the weather currently in the world that the player is residing in if // the weather is currently being forced onto the player. // --> if (attribute.startsWith("weather")) return new Element(getPlayerEntity().getPlayerWeather().name()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns the number of XP levels the player has. // --> if (attribute.startsWith("xp.level")) return new Element(getPlayerEntity().getLevel()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_next_level> // @returns Element(Number) // @description // returns the amount of XP needed to get to the next level. // --> if (attribute.startsWith("xp.to_next_level")) return new Element(getPlayerEntity().getExpToLevel()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns the total amount of experience points. // --> if (attribute.startsWith("xp.total")) return new Element(getPlayerEntity().getTotalExperience()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the percentage of experience points to the next level. // --> if (attribute.startsWith("xp")) return new Element(getPlayerEntity().getExp() * 100) .getAttribute(attribute.fulfill(1)); // Iterate through this object's properties' attributes for (Property property : PropertyParser.getProperties(this)) { String returned = property.getAttribute(attribute); if (returned != null) return returned; } return new dEntity(getPlayerEntity()).getAttribute(attribute); } @Override public void adjust(Mechanism mechanism) { Element value = mechanism.getValue(); // <--[mechanism] // @object dPlayer // @name level // @input Element(Number) // @description // Sets the level on the player. Does not affect the current progression // of experience towards next level. // @tags // <player.xp.level> // --> if (mechanism.matches("level") && mechanism.requireInteger()) { getPlayerEntity().setLevel(value.asInt()); } // <--[mechanism] // @object dPlayer // @name award_achievement // @input Element // @description // Awards an achievement to the player. Valid achievements: // OPEN_INVENTORY, MINE_WOOD, BUILD_WORKBENCH, BUILD_PICKAXE, BUILD_FURNACE, ACQUIRE_IRON, // BUILD_HOE, MAKE_BREAD, BAKE_CAKE, BUILD_BETTER_PICKAXE, COOK_FISH, ON_A_RAIL, BUILD_SWORD, // KILL_ENEMY, KILL_COW, FLY_PIG, SNIPE_SKELETON, GET_DIAMONDS, NETHER_PORTAL, GHAST_RETURN, // GET_BLAZE_ROD, BREW_POTION, END_PORTAL, THE_END, ENCHANTMENTS, OVERKILL, BOOKCASE // @tags // None // --> if (mechanism.matches("award_achievement")&& mechanism.requireEnum(false, Achievement.values())) { getPlayerEntity().awardAchievement(Achievement.valueOf(value.asString().toUpperCase())); } // <--[mechanism] // @object dPlayer // @name health_scale // @input Element(Decimal) // @description // Sets the 'health scale' on the Player. Each heart equals '2'. The standard health scale is // 20, so for example, indicating a value of 40 will display double the amount of hearts // standard. // Player relogging will reset this mechanism. // @tags // <player.health.scale> // --> if (mechanism.matches("health_scale") && mechanism.requireDouble()) { getPlayerEntity().setHealthScale(value.asDouble()); } // <--[mechanism] // @object dPlayer // @name scale_health // @input Element(Boolean) // @description // Enables or disables the health scale value. Disabling will result in the standard // amount of hearts being shown. // @tags // <player.health.is_scaled> // --> if (mechanism.matches("scale_health") && mechanism.requireBoolean()) { getPlayerEntity().setHealthScaled(value.asBoolean()); } // <--[mechanism] // @object dPlayer // @name resource_pack // @input Element // @description // Sets the current resource pack by specifying a valid URL to a resource pack. // @tags // None // --> if (mechanism.matches("resource_pack") || mechanism.matches("texture_pack")) { getPlayerEntity().setResourcePack(value.asString()); } // <--[mechanism] // @object dPlayer // @name saturation // @input Element(Decimal) // @description // Sets the current food saturation level of a player. // @tags // <player.saturation> // --> if (mechanism.matches("saturation") && mechanism.requireFloat()) { getPlayerEntity().setSaturation(value.asFloat()); } // <--[mechanism] // @object dPlayer // @name food_level // @input Element(Number) // @description // Sets the current food level of a player. Typically, '20' is full. // @tags // <player.food_level> // --> if (mechanism.matches("food_level") && mechanism.requireInteger()) { getPlayerEntity().setFoodLevel(value.asInt()); } // <--[mechanism] // @object dPlayer // @name bed_spawn_location // @input dLocation // @description // Sets the bed location that the player respawns at. // @tags // <player.bed_spawn> // --> if (mechanism.matches("bed_spawn_location") && mechanism.requireObject(dLocation.class)) { getPlayerEntity().setBedSpawnLocation(dLocation.valueOf(value.asString())); } // <--[mechanism] // @object dPlayer // @name fly_speed // @input Element(Decimal) // @description // Sets the fly speed of the player. Valid range is 0.0 to 1.0 // @tags // <player.fly_speed> // --> if (mechanism.matches("fly_speed") && mechanism.requireFloat()) { getPlayerEntity().setFlySpeed(value.asFloat()); } // <--[mechanism] // @object dPlayer // @name weather // @input Element // @description // Sets the weather condition for the player. This does NOT affect the weather // in the world, and will block any world weather changes until the 'reset_weather' // mechanism is used. Valid weather: CLEAR, DOWNFALL // @tags // <player.weather> // --> if (mechanism.matches("weather") && mechanism.requireEnum(false, WeatherType.values())) { getPlayerEntity().setPlayerWeather(WeatherType.valueOf(value.asString().toUpperCase())); } // <--[mechanism] // @object dPlayer // @name reset_weather // @input None // @description // Resets the weather on the Player to the conditions currently taking place in the Player's // current world. // @tags // <player.weather> // --> if (mechanism.matches("reset_weather")) { getPlayerEntity().resetPlayerWeather(); } // <--[mechanism] // @object dPlayer // @name player_list_name // @input Element // @description // Sets the entry that is shown in the 'player list' that is shown when pressing tab. // @tags // <player.name.list> // --> if (mechanism.matches("player_list_name")) { getPlayerEntity().setPlayerListName(value.asString()); } // <--[mechanism] // @object dPlayer // @name display_name // @input Element // @description // Sets the name displayed for the player when chatting. // @tags // <player.name.display> // --> if (mechanism.matches("display_name")) { getPlayerEntity().setDisplayName(value.asString()); return; } // <--[mechanism] // @object dPlayer // @name time // @input Element(Number) // @description // Sets the time of day the Player is currently experiencing. Setting this will cause the // player to have a different time than other Players in the world are experiencing though // time will continue to progress. Using the 'reset_time' mechanism, or relogging your player // will reset this mechanism to match the world's current time. Valid range is 0-28000 // @tags // <player.time> // --> if (mechanism.matches("time") && mechanism.requireInteger()) { getPlayerEntity().setPlayerTime(value.asInt(), true); } // <--[mechanism] // @object dPlayer // @name freeze_time // @input Element(Number) // @description // Sets the time of day the Player is currently experiencing and freezes it there. Note: // there is a small 'twitch effect' when looking at the sky when time is frozen. // Setting this will cause the player to have a different time than other Players in // the world are experiencing. Using the 'reset_time' mechanism, or relogging your player // will reset this mechanism to match the world's current time. Valid range is 0-28000 // @tags // <player.time> // --> if (mechanism.matches("freeze_time")) { if (mechanism.requireInteger("Invalid integer specified. Assuming current world time.")) getPlayerEntity().setPlayerTime(value.asInt(), false); else getPlayerEntity().setPlayerTime(getPlayerEntity().getWorld().getTime(), false); } // <--[mechanism] // @object dPlayer // @name reset_time // @input None // @description // Resets any altered time that has been applied to this player. Using this will make // the Player's time match the world's current time. // @tags // <player.time> // --> if (mechanism.matches("reset_time")) { getPlayerEntity().resetPlayerTime(); } // <--[mechanism] // @object dPlayer // @name walk_speed // @input Element(Decimal) // @description // Sets the walk speed of the player. The standard value is '0.2'. Valid range is 0.0 to 1.0 // @tags // <player.walk_speed> // --> if (mechanism.matches("walk_speed") && mechanism.requireFloat()) { getPlayerEntity().setWalkSpeed(value.asFloat()); } // <--[mechanism] // @object dPlayer // @name show_boss_bar // @input Element // @description // Shows the player a boss health bar with the specified text as a name. // Use with no input value to remove the bar. // @tags // None // --> // TODO: Possibly rework into a full command? if (mechanism.matches("show_boss_bar")) { if (value.asString().length() > 0) BossHealthBar.displayTextBar(value.asString(), getPlayerEntity()); else BossHealthBar.removeTextBar(getPlayerEntity()); } // Pass along to dEntity mechanism handler if not already handled. if (!mechanism.fulfilled()) { Adjustable entity = new dEntity(getPlayerEntity()); entity.adjust(mechanism); } } }
true
true
public String getAttribute(Attribute attribute) { if (attribute == null) return "null"; if (player_name == null) return Element.NULL.getAttribute(attribute); ///////////////////// // OFFLINE ATTRIBUTES ///////////////// ///////////////////// // DEBUG ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Boolean) // @description // Debugs the player in the log and returns true. // --> if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the player's debug with no color. // --> if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the player's debug. // --> if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the dObject's prefix. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); ///////////////////// // DENIZEN ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_history_list> // @returns dList // @description // Returns a list of the last 10 things the player has said, less // if the player hasn't said all that much. // --> if (attribute.startsWith("chat_history_list")) return new dList(PlayerTags.playerChatHistory.get(player_name)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_history[#]> // @returns Element // @description // returns the last thing the player said. // If a number is specified, returns an earlier thing the player said. // --> if (attribute.startsWith("chat_history")) { int x = 1; if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1))) x = attribute.getIntContext(1); // No playerchathistory? Return null. if (!PlayerTags.playerChatHistory.containsKey(player_name)) return Element.NULL.getAttribute(attribute.fulfill(1)); else return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<flag_name>]> // @returns Flag dList // @description // returns the specified flag from the player. // --> if (attribute.startsWith("flag")) { String flag_name; if (attribute.hasContext(1)) flag_name = attribute.getContext(1); else return Element.NULL.getAttribute(attribute.fulfill(1)); attribute.fulfill(1); if (attribute.startsWith("is_expired") || attribute.startsWith("isexpired")) return new Element(!FlagManager.playerHasFlag(this, flag_name)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("size") && !FlagManager.playerHasFlag(this, flag_name)) return new Element(0).getAttribute(attribute.fulfill(1)); if (FlagManager.playerHasFlag(this, flag_name)) return new dList(DenizenAPI.getCurrentInstance().flagManager() .getPlayerFlag(getName(), flag_name)) .getAttribute(attribute); else return Element.NULL.getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_flag[<flag_name>]> // @returns Element(Boolean) // @description // returns true if the Player has the specified flag, otherwise returns false. // --> if (attribute.startsWith("has_flag")) { String flag_name; if (attribute.hasContext(1)) flag_name = attribute.getContext(1); else return Element.NULL.getAttribute(attribute.fulfill(1)); return new Element(FlagManager.playerHasFlag(this, flag_name)).getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("current_step")) { String outcome = "null"; if (attribute.hasContext(1)) { try { outcome = DenizenAPI.getCurrentInstance().getSaves().getString("Players." + getName() + ".Scripts." + dScript.valueOf(attribute.getContext(1)).getName() + ".Current Step"); } catch (Exception e) { outcome = "null"; } } return new Element(outcome).getAttribute(attribute.fulfill(1)); } ///////////////////// // ECONOMY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the amount of money the player has with the registered Economy system. // --> if (attribute.startsWith("money")) { if(Depends.economy != null) { // <--[tag] // @attribute <[email protected]_singular> // @returns Element // @description // returns the name of a single piece of currency - EG: Dollar // (Only if supported by the registered Economy system.) // --> if (attribute.startsWith("money.currency_singular")) return new Element(Depends.economy.currencyNameSingular()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of multiple pieces of currency - EG: Dollars // (Only if supported by the registered Economy system.) // --> if (attribute.startsWith("money.currency")) return new Element(Depends.economy.currencyNamePlural()) .getAttribute(attribute.fulfill(2)); return new Element(Depends.economy.getBalance(player_name)) .getAttribute(attribute.fulfill(1)); } else { dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?"); return Element.NULL.getAttribute(attribute.fulfill(1)); } } ///////////////////// // ENTITY LIST ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected][(<entity>|...)]> // @returns dEntity // @description // Returns the entity that the player is looking at, within a maximum range of 50 blocks, // or null if the player is not looking at an entity. // Optionally, specify a list of entities, entity types, or 'npc' to only count those targets. // --> if (attribute.startsWith("target")) { int range = 50; int attribs = 1; // <--[tag] // @attribute <[email protected][(<entity>|...)].within[(<#>)]> // @returns dEntity // @description // Returns the entity that the player is looking at within the specified range limit, // or null if the player is not looking at an entity. // Optionally, specify a list of entities, entity types, or 'npc' to only count those targets. if (attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2) && aH.matchesInteger(attribute.getContext(2))) { attribs = 2; range = attribute.getIntContext(2); } List<Entity> entities = getPlayerEntity().getNearbyEntities(range, range, range); ArrayList<LivingEntity> possibleTargets = new ArrayList<LivingEntity>(); for (Entity entity : entities) { if (entity instanceof LivingEntity) { // if we have a context for entity types, check the entity if (attribute.hasContext(1)) { String context = attribute.getContext(1); if (context.toLowerCase().startsWith("li@")) context = context.substring(3); for (String ent: context.split("\\|")) { boolean valid = false; if (ent.equalsIgnoreCase("npc") && CitizensAPI.getNPCRegistry().isNPC(entity)) { valid = true; } else if (dEntity.matches(ent)) { // only accept generic entities that are not NPCs if (dEntity.valueOf(ent).isGeneric()) { if (!CitizensAPI.getNPCRegistry().isNPC(entity)) { valid = true; } } else { valid = true; } } if (valid) possibleTargets.add((LivingEntity) entity); } } else { // no entity type specified possibleTargets.add((LivingEntity) entity); entity.getType(); } } } // Find the valid target BlockIterator bi; try { bi = new BlockIterator(getPlayerEntity(), range); } catch (IllegalStateException e) { return Element.NULL.getAttribute(attribute.fulfill(attribs)); } Block b; Location l; int bx, by, bz; double ex, ey, ez; // Loop through player's line of sight while (bi.hasNext()) { b = bi.next(); bx = b.getX(); by = b.getY(); bz = b.getZ(); if (b.getType() != Material.AIR) { // Line of sight is broken break; } else { // Check for entities near this block in the line of sight for (LivingEntity possibleTarget : possibleTargets) { l = possibleTarget.getLocation(); ex = l.getX(); ey = l.getY(); ez = l.getZ(); if ((bx - .50 <= ex && ex <= bx + 1.50) && (bz - .50 <= ez && ez <= bz + 1.50) && (by - 1 <= ey && ey <= by + 2.5)) { // Entity is close enough, so return it return new dEntity(possibleTarget).getAttribute(attribute.fulfill(attribs)); } } } } return Element.NULL.getAttribute(attribute.fulfill(attribs)); } // <--[tag] // @attribute <[email protected]> // @returns dList(dPlayer) // @description // Returns all players that have ever played on the server, online or not. // ** NOTE: This tag is old. Please instead use <server.list_players> ** // --> if (attribute.startsWith("list")) { List<String> players = new ArrayList<String>(); // <--[tag] // @attribute <[email protected]> // @returns dList(dPlayer) // @description // Returns all online players. // **NOTE: This will only work if there is a player attached to the current script. // If you need it anywhere else, use <server.list_online_players>** // --> if (attribute.startsWith("list.online")) { for(Player player : Bukkit.getOnlinePlayers()) players.add(player.getName()); return new dList(players).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns dList(dPlayer) // @description // Returns all players that have ever played on the server, but are not currently online. // ** NOTE: This tag is old. Please instead use <server.list_offline_players> ** // --> else if (attribute.startsWith("list.offline")) { for(OfflinePlayer player : Bukkit.getOfflinePlayers()) { if (!Bukkit.getOnlinePlayers().toString().contains(player.getName())) players.add(player.getName()); } return new dList(players).getAttribute(attribute.fulfill(2)); } else { for(OfflinePlayer player : Bukkit.getOfflinePlayers()) players.add(player.getName()); return new dList(players).getAttribute(attribute.fulfill(1)); } } ///////////////////// // IDENTIFICATION ATTRIBUTES ///////////////// if (attribute.startsWith("name") && !isOnline()) // This can be parsed later with more detail if the player is online, so only check for offline. return new Element(player_name).getAttribute(attribute.fulfill(1)); ///////////////////// // LOCATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_spawn> // @returns dLocation // @description // Returns the location of the player's bed spawn location, 'null' if // it doesn't exist. // --> if (attribute.startsWith("bed_spawn")) return new dLocation(getOfflinePlayer().getBedSpawnLocation()) .getAttribute(attribute.fulfill(2)); ///////////////////// // STATE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_played> // @returns Duration // @description // returns the millisecond time of when the player first logged on to this server. // --> if (attribute.startsWith("first_played")) { attribute = attribute.fulfill(1); if (attribute.startsWith("milliseconds") || attribute.startsWith("in_milliseconds")) return new Element(getOfflinePlayer().getFirstPlayed()) .getAttribute(attribute.fulfill(1)); else return new Duration(getOfflinePlayer().getFirstPlayed() / 50) .getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_played_before> // @returns Element(Boolean) // @description // returns whether the player has played before. // --> if (attribute.startsWith("has_played_before")) return new Element(true) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_scaled> // @returns Element(Boolean) // @description // returns whether the player's health bar is currently being scaled. // --> if (attribute.startsWith("health.is_scaled")) return new Element(getPlayerEntity().isHealthScaled()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the current scale for the player's health bar // --> if (attribute.startsWith("health.scale")) return new Element(getPlayerEntity().getHealthScale()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_banned> // @returns Element(Boolean) // @description // returns whether the player is banned. // --> if (attribute.startsWith("is_banned")) return new Element(getOfflinePlayer().isBanned()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_online> // @returns Element(Boolean) // @description // returns whether the player is currently online. // --> if (attribute.startsWith("is_online")) return new Element(isOnline()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_op> // @returns Element(Boolean) // @description // returns whether the player is a full server operator. // --> if (attribute.startsWith("is_op")) return new Element(getOfflinePlayer().isOp()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_whitelisted> // @returns Element(Boolean) // @description // returns whether the player is whitelisted. // --> if (attribute.startsWith("is_whitelisted")) return new Element(getOfflinePlayer().isWhitelisted()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_played> // @returns Duration // @description // returns the millisecond time of when the player // was last seen. // --> if (attribute.startsWith("last_played")) { attribute = attribute.fulfill(1); if (attribute.startsWith("milliseconds") || attribute.startsWith("in_milliseconds")) return new Element(getOfflinePlayer().getLastPlayed()) .getAttribute(attribute.fulfill(1)); else return new Duration(getOfflinePlayer().getLastPlayed() / 50) .getAttribute(attribute); } ///////////////////// // ONLINE ATTRIBUTES ///////////////// // Player is required to be online after this point... if (!isOnline()) return new Element(identify()).getAttribute(attribute); ///////////////////// // CITIZENS ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_npc> // @returns dNPC // @description // returns the dNPC that the player currently has selected with // '/npc select', null if no player selected. // --> if (attribute.startsWith("selected_npc")) { if (getPlayerEntity().hasMetadata("selected")) return getSelectedNPC() .getAttribute(attribute.fulfill(1)); else return Element.NULL.getAttribute(attribute.fulfill(1)); } ///////////////////// // CONVERSION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dEntity // @description // returns the dEntity object of the player. // (Note: This should never actually be needed. <p@player> is considered a valid dEntity by script commands.) // --> if (attribute.startsWith("entity") && !attribute.startsWith("entity_")) return new dEntity(getPlayerEntity()) .getAttribute(attribute.fulfill(1)); ///////////////////// // IDENTIFICATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the player's IP address. // --> if (attribute.startsWith("ip") || attribute.startsWith("host_name")) return new Element(getPlayerEntity().getAddress().getHostName()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the display name of the player, which may contain // prefixes and suffixes, colors, etc. // --> if (attribute.startsWith("name.display")) return new Element(getPlayerEntity().getDisplayName()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of the player as shown in the player list. // --> if (attribute.startsWith("name.list")) return new Element(getPlayerEntity().getPlayerListName()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of the player. // --> if (attribute.startsWith("name")) return new Element(player_name).getAttribute(attribute.fulfill(1)); ///////////////////// // INVENTORY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dInventory // @description // returns a dInventory of the player's current inventory. // --> if (attribute.startsWith("inventory")) return new dInventory(getPlayerEntity().getInventory()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_on_cursor> // @returns dItem // @description // returns a dItem that the player's cursor is on, if any. This includes // chest interfaces, inventories, and hotbars, etc. // --> if (attribute.startsWith("item_on_cursor")) return new dItem(getPlayerEntity().getItemOnCursor()) .getAttribute(attribute.fulfill(1)); ///////////////////// // PERMISSION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_permission[permission.node]> // @returns Element(Boolean) // @description // returns whether the player has the specified node. // --> if (attribute.startsWith("permission") || attribute.startsWith("has_permission")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return null; } String permission = attribute.getContext(1); // <--[tag] // @attribute <[email protected]_permission[permission.node].global> // @returns Element(Boolean) // @description // returns whether the player has the specified node, regardless of world. // (Note: this may or may not be functional with your permissions system.) // --> // Non-world specific permission if (attribute.getAttribute(2).startsWith("global")) return new Element(Depends.permissions.has((World) null, player_name, permission)) .getAttribute(attribute.fulfill(2)); // Permission in certain world else if (attribute.getAttribute(2).startsWith("world")) return new Element(Depends.permissions.has(attribute.getContext(2), player_name, permission)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_permission[permission.node].world> // @returns Element(Boolean) // @description // returns whether the player has the specified node in regards to the // player's current world. // (Note: This may or may not be functional with your permissions system.) // --> // Permission in current world return new Element(Depends.permissions.has(getPlayerEntity(), permission)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_group[<group_name>]> // @returns Element(Boolean) // @description // returns whether the player is in the specified group. // --> if (attribute.startsWith("group") || attribute.startsWith("in_group")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return Element.NULL.getAttribute(attribute.fulfill(1)); } String group = attribute.getContext(1); // <--[tag] // @attribute <[email protected]_group[<group_name>].global> // @returns Element(Boolean) // @description // returns whether the player has the group with no regard to the // player's current world. // (Note: This may or may not be functional with your permissions system.) // --> // Non-world specific permission if (attribute.getAttribute(2).startsWith("global")) return new Element(Depends.permissions.playerInGroup((World) null, player_name, group)) .getAttribute(attribute.fulfill(2)); // Permission in certain world else if (attribute.getAttribute(2).startsWith("world")) return new Element(Depends.permissions.playerInGroup(attribute.getContext(2), player_name, group)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_group[<group_name>].world> // @returns Element(Boolean) // @description // returns whether the player has the group in regards to the // player's current world. // (Note: This may or may not be functional with your permissions system.) // --> // Permission in current world return new Element(Depends.permissions.playerInGroup(getPlayerEntity(), group)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_finished[<script>]> // @returns dLocation // @description // returns the if the Player has finished the specified script. // --> if (attribute.startsWith("has_finished")) { dScript script = dScript.valueOf(attribute.getContext(1)); if (script == null) return Element.FALSE.getAttribute(attribute.fulfill(1)); return new Element(FinishCommand.getScriptCompletes(getName(), script.getName()) > 0) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_failed[<script>]> // @returns dLocation // @description // returns the if the Player has finished the specified script. // --> if (attribute.startsWith("has_failed")) { dScript script = dScript.valueOf(attribute.getContext(1)); if (script == null) return Element.FALSE.getAttribute(attribute.fulfill(1)); return new Element(FailCommand.getScriptFails(getName(), script.getName()) > 0) .getAttribute(attribute.fulfill(1)); } ///////////////////// // LOCATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // returns the location of the player's compass target. // --> if (attribute.startsWith("compass_target")) return new dLocation(getPlayerEntity().getCompassTarget()) .getAttribute(attribute.fulfill(2)); ///////////////////// // STATE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_flight> // @returns Element(Boolean) // @description // returns whether the player is allowed to fly. // --> if (attribute.startsWith("allowed_flight")) return new Element(getPlayerEntity().getAllowFlight()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_speed> // @returns Element(Decimal) // @description // returns the speed the player can fly at. // --> if (attribute.startsWith("fly_speed")) return new Element(getPlayerEntity().getFlySpeed()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_level.formatted> // @returns Element // @description // returns a 'formatted' value of the player's current food level. // May be 'starving', 'famished', 'parched, 'hungry' or 'healthy'. // --> if (attribute.startsWith("food_level.formatted")) { double maxHunger = getPlayerEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHunger = attribute.getIntContext(2); if (getPlayerEntity().getFoodLevel() / maxHunger < .10) return new Element("starving").getAttribute(attribute.fulfill(2)); else if (getPlayerEntity().getFoodLevel() / maxHunger < .40) return new Element("famished").getAttribute(attribute.fulfill(2)); else if (getPlayerEntity().getFoodLevel() / maxHunger < .75) return new Element("parched").getAttribute(attribute.fulfill(2)); else if (getPlayerEntity().getFoodLevel() / maxHunger < 1) return new Element("hungry").getAttribute(attribute.fulfill(2)); else return new Element("healthy").getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the current saturation of the player. // --> if (attribute.startsWith("saturation")) return new Element(getPlayerEntity().getSaturation()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_level> // @returns Element(Number) // @description // returns the current food level of the player. // --> if (attribute.startsWith("food_level")) return new Element(getPlayerEntity().getFoodLevel()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns how much air the player can have. // --> if (attribute.startsWith("oxygen.max")) return new Element(getPlayerEntity().getMaximumAir()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns how much air the player has. // --> if (attribute.startsWith("oxygen")) return new Element(getPlayerEntity().getRemainingAir()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns the gamemode ID of the player. 0 = survival, 1 = creative, 2 = adventure // --> if (attribute.startsWith("gamemode.id")) return new Element(getPlayerEntity().getGameMode().getValue()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of the gamemode the player is currently set to. // --> if (attribute.startsWith("gamemode")) return new Element(getPlayerEntity().getGameMode().name()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_blocking> // @returns Element(Boolean) // @description // returns whether the player is currently blocking. // --> if (attribute.startsWith("is_blocking")) return new Element(getPlayerEntity().isBlocking()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_flying> // @returns Element(Boolean) // @description // returns whether the player is currently flying. // --> if (attribute.startsWith("is_flying")) return new Element(getPlayerEntity().isFlying()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_sleeping> // @returns Element(Boolean) // @description // returns whether the player is currently sleeping. // --> if (attribute.startsWith("is_sleeping")) return new Element(getPlayerEntity().isSleeping()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_sneaking> // @returns Element(Boolean) // @description // returns whether the player is currently sneaking. // --> if (attribute.startsWith("is_sneaking")) return new Element(getPlayerEntity().isSneaking()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_sprinting> // @returns Element(Boolean) // @description // returns whether the player is currently sprinting. // --> if (attribute.startsWith("is_sprinting")) return new Element(getPlayerEntity().isSprinting()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_asleep> // @returns Duration // @description // returns the time the player has been asleep. // --> if (attribute.startsWith("time_asleep")) return new Duration(getPlayerEntity().getSleepTicks() / 20) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Duration // @description // returns the time the player is currently experiencing. This time could differ from // the time that the rest of the world is currently experiencing if a 'time' or 'freeze_time' // mechanism is being used on the player. // --> if (attribute.startsWith("time")) return new Element(getPlayerEntity().getPlayerTime()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_speed> // @returns Element(Decimal) // @description // returns the speed the player can walk at. // --> if (attribute.startsWith("walk_speed")) return new Element(getPlayerEntity().getWalkSpeed()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the type of weather the player is experiencing. This can be different // from the weather currently in the world that the player is residing in if // the weather is currently being forced onto the player. // --> if (attribute.startsWith("weather")) return new Element(getPlayerEntity().getPlayerWeather().name()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns the number of XP levels the player has. // --> if (attribute.startsWith("xp.level")) return new Element(getPlayerEntity().getLevel()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_next_level> // @returns Element(Number) // @description // returns the amount of XP needed to get to the next level. // --> if (attribute.startsWith("xp.to_next_level")) return new Element(getPlayerEntity().getExpToLevel()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns the total amount of experience points. // --> if (attribute.startsWith("xp.total")) return new Element(getPlayerEntity().getTotalExperience()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the percentage of experience points to the next level. // --> if (attribute.startsWith("xp")) return new Element(getPlayerEntity().getExp() * 100) .getAttribute(attribute.fulfill(1)); // Iterate through this object's properties' attributes for (Property property : PropertyParser.getProperties(this)) { String returned = property.getAttribute(attribute); if (returned != null) return returned; } return new dEntity(getPlayerEntity()).getAttribute(attribute); }
public String getAttribute(Attribute attribute) { if (attribute == null) return "null"; if (player_name == null) return Element.NULL.getAttribute(attribute); ///////////////////// // OFFLINE ATTRIBUTES ///////////////// ///////////////////// // DEBUG ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Boolean) // @description // Debugs the player in the log and returns true. // --> if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the player's debug with no color. // --> if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the player's debug. // --> if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the dObject's prefix. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); ///////////////////// // DENIZEN ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_history_list> // @returns dList // @description // Returns a list of the last 10 things the player has said, less // if the player hasn't said all that much. // --> if (attribute.startsWith("chat_history_list")) return new dList(PlayerTags.playerChatHistory.get(player_name)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_history[#]> // @returns Element // @description // returns the last thing the player said. // If a number is specified, returns an earlier thing the player said. // --> if (attribute.startsWith("chat_history")) { int x = 1; if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1))) x = attribute.getIntContext(1); // No playerchathistory? Return null. if (!PlayerTags.playerChatHistory.containsKey(player_name)) return Element.NULL.getAttribute(attribute.fulfill(1)); else return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<flag_name>]> // @returns Flag dList // @description // returns the specified flag from the player. // --> if (attribute.startsWith("flag")) { String flag_name; if (attribute.hasContext(1)) flag_name = attribute.getContext(1); else return Element.NULL.getAttribute(attribute.fulfill(1)); attribute.fulfill(1); if (attribute.startsWith("is_expired") || attribute.startsWith("isexpired")) return new Element(!FlagManager.playerHasFlag(this, flag_name)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("size") && !FlagManager.playerHasFlag(this, flag_name)) return new Element(0).getAttribute(attribute.fulfill(1)); if (FlagManager.playerHasFlag(this, flag_name)) return new dList(DenizenAPI.getCurrentInstance().flagManager() .getPlayerFlag(getName(), flag_name)) .getAttribute(attribute); else return Element.NULL.getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_flag[<flag_name>]> // @returns Element(Boolean) // @description // returns true if the Player has the specified flag, otherwise returns false. // --> if (attribute.startsWith("has_flag")) { String flag_name; if (attribute.hasContext(1)) flag_name = attribute.getContext(1); else return Element.NULL.getAttribute(attribute.fulfill(1)); return new Element(FlagManager.playerHasFlag(this, flag_name)).getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("current_step")) { String outcome = "null"; if (attribute.hasContext(1)) { try { outcome = DenizenAPI.getCurrentInstance().getSaves().getString("Players." + getName() + ".Scripts." + dScript.valueOf(attribute.getContext(1)).getName() + ".Current Step"); } catch (Exception e) { outcome = "null"; } } return new Element(outcome).getAttribute(attribute.fulfill(1)); } ///////////////////// // ECONOMY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the amount of money the player has with the registered Economy system. // --> if (attribute.startsWith("money")) { if(Depends.economy != null) { // <--[tag] // @attribute <[email protected]_singular> // @returns Element // @description // returns the name of a single piece of currency - EG: Dollar // (Only if supported by the registered Economy system.) // --> if (attribute.startsWith("money.currency_singular")) return new Element(Depends.economy.currencyNameSingular()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of multiple pieces of currency - EG: Dollars // (Only if supported by the registered Economy system.) // --> if (attribute.startsWith("money.currency")) return new Element(Depends.economy.currencyNamePlural()) .getAttribute(attribute.fulfill(2)); return new Element(Depends.economy.getBalance(player_name)) .getAttribute(attribute.fulfill(1)); } else { dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?"); return Element.NULL.getAttribute(attribute.fulfill(1)); } } ///////////////////// // ENTITY LIST ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected][(<entity>|...)]> // @returns dEntity // @description // Returns the entity that the player is looking at, within a maximum range of 50 blocks, // or null if the player is not looking at an entity. // Optionally, specify a list of entities, entity types, or 'npc' to only count those targets. // --> if (attribute.startsWith("target")) { int range = 50; int attribs = 1; // <--[tag] // @attribute <[email protected][(<entity>|...)].within[(<#>)]> // @returns dEntity // @description // Returns the entity that the player is looking at within the specified range limit, // or null if the player is not looking at an entity. // Optionally, specify a list of entities, entity types, or 'npc' to only count those targets. if (attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2) && aH.matchesInteger(attribute.getContext(2))) { attribs = 2; range = attribute.getIntContext(2); } List<Entity> entities = getPlayerEntity().getNearbyEntities(range, range, range); ArrayList<LivingEntity> possibleTargets = new ArrayList<LivingEntity>(); for (Entity entity : entities) { if (entity instanceof LivingEntity) { // if we have a context for entity types, check the entity if (attribute.hasContext(1)) { String context = attribute.getContext(1); if (context.toLowerCase().startsWith("li@")) context = context.substring(3); for (String ent: context.split("\\|")) { boolean valid = false; if (ent.equalsIgnoreCase("npc") && CitizensAPI.getNPCRegistry().isNPC(entity)) { valid = true; } else if (dEntity.matches(ent)) { // only accept generic entities that are not NPCs if (dEntity.valueOf(ent).isGeneric()) { if (!CitizensAPI.getNPCRegistry().isNPC(entity)) { valid = true; } } else { valid = true; } } if (valid) possibleTargets.add((LivingEntity) entity); } } else { // no entity type specified possibleTargets.add((LivingEntity) entity); entity.getType(); } } } // Find the valid target BlockIterator bi; try { bi = new BlockIterator(getPlayerEntity(), range); } catch (IllegalStateException e) { return Element.NULL.getAttribute(attribute.fulfill(attribs)); } Block b; Location l; int bx, by, bz; double ex, ey, ez; // Loop through player's line of sight while (bi.hasNext()) { b = bi.next(); bx = b.getX(); by = b.getY(); bz = b.getZ(); if (b.getType() != Material.AIR) { // Line of sight is broken break; } else { // Check for entities near this block in the line of sight for (LivingEntity possibleTarget : possibleTargets) { l = possibleTarget.getLocation(); ex = l.getX(); ey = l.getY(); ez = l.getZ(); if ((bx - .50 <= ex && ex <= bx + 1.50) && (bz - .50 <= ez && ez <= bz + 1.50) && (by - 1 <= ey && ey <= by + 2.5)) { // Entity is close enough, so return it return new dEntity(possibleTarget).getAttribute(attribute.fulfill(attribs)); } } } } return Element.NULL.getAttribute(attribute.fulfill(attribs)); } // <--[tag] // @attribute <[email protected]> // @returns dList(dPlayer) // @description // Returns all players that have ever played on the server, online or not. // ** NOTE: This tag is old. Please instead use <server.list_players> ** // --> if (attribute.startsWith("list")) { List<String> players = new ArrayList<String>(); // <--[tag] // @attribute <[email protected]> // @returns dList(dPlayer) // @description // Returns all online players. // **NOTE: This will only work if there is a player attached to the current script. // If you need it anywhere else, use <server.list_online_players>** // --> if (attribute.startsWith("list.online")) { for(Player player : Bukkit.getOnlinePlayers()) players.add(player.getName()); return new dList(players).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns dList(dPlayer) // @description // Returns all players that have ever played on the server, but are not currently online. // ** NOTE: This tag is old. Please instead use <server.list_offline_players> ** // --> else if (attribute.startsWith("list.offline")) { for(OfflinePlayer player : Bukkit.getOfflinePlayers()) { if (!Bukkit.getOnlinePlayers().toString().contains(player.getName())) players.add(player.getName()); } return new dList(players).getAttribute(attribute.fulfill(2)); } else { for(OfflinePlayer player : Bukkit.getOfflinePlayers()) players.add(player.getName()); return new dList(players).getAttribute(attribute.fulfill(1)); } } ///////////////////// // IDENTIFICATION ATTRIBUTES ///////////////// if (attribute.startsWith("name") && !isOnline()) // This can be parsed later with more detail if the player is online, so only check for offline. return new Element(player_name).getAttribute(attribute.fulfill(1)); ///////////////////// // LOCATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_spawn> // @returns dLocation // @description // Returns the location of the player's bed spawn location, 'null' if // it doesn't exist. // --> if (attribute.startsWith("bed_spawn")) return new dLocation(getOfflinePlayer().getBedSpawnLocation()) .getAttribute(attribute.fulfill(2)); ///////////////////// // STATE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_played> // @returns Duration // @description // returns the millisecond time of when the player first logged on to this server. // --> if (attribute.startsWith("first_played")) { attribute = attribute.fulfill(1); if (attribute.startsWith("milliseconds") || attribute.startsWith("in_milliseconds")) return new Element(getOfflinePlayer().getFirstPlayed()) .getAttribute(attribute.fulfill(1)); else return new Duration(getOfflinePlayer().getFirstPlayed() / 50) .getAttribute(attribute); } // <--[tag] // @attribute <[email protected]_played_before> // @returns Element(Boolean) // @description // returns whether the player has played before. // --> if (attribute.startsWith("has_played_before")) return new Element(true) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_scaled> // @returns Element(Boolean) // @description // returns whether the player's health bar is currently being scaled. // --> if (attribute.startsWith("health.is_scaled")) return new Element(getPlayerEntity().isHealthScaled()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the current scale for the player's health bar // --> if (attribute.startsWith("health.scale")) return new Element(getPlayerEntity().getHealthScale()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_banned> // @returns Element(Boolean) // @description // returns whether the player is banned. // --> if (attribute.startsWith("is_banned")) return new Element(getOfflinePlayer().isBanned()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_online> // @returns Element(Boolean) // @description // returns whether the player is currently online. // --> if (attribute.startsWith("is_online")) return new Element(isOnline()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_op> // @returns Element(Boolean) // @description // returns whether the player is a full server operator. // --> if (attribute.startsWith("is_op")) return new Element(getOfflinePlayer().isOp()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_whitelisted> // @returns Element(Boolean) // @description // returns whether the player is whitelisted. // --> if (attribute.startsWith("is_whitelisted")) return new Element(getOfflinePlayer().isWhitelisted()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_played> // @returns Duration // @description // returns the millisecond time of when the player // was last seen. // --> if (attribute.startsWith("last_played")) { attribute = attribute.fulfill(1); if (attribute.startsWith("milliseconds") || attribute.startsWith("in_milliseconds")) return new Element(getOfflinePlayer().getLastPlayed()) .getAttribute(attribute.fulfill(1)); else return new Duration(getOfflinePlayer().getLastPlayed() / 50) .getAttribute(attribute); } ///////////////////// // ONLINE ATTRIBUTES ///////////////// // Player is required to be online after this point... if (!isOnline()) return new Element(identify()).getAttribute(attribute); ///////////////////// // CITIZENS ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_npc> // @returns dNPC // @description // returns the dNPC that the player currently has selected with // '/npc select', null if no player selected. // --> if (attribute.startsWith("selected_npc")) { if (getPlayerEntity().hasMetadata("selected")) return getSelectedNPC() .getAttribute(attribute.fulfill(1)); else return Element.NULL.getAttribute(attribute.fulfill(1)); } ///////////////////// // CONVERSION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dEntity // @description // returns the dEntity object of the player. // (Note: This should never actually be needed. <p@player> is considered a valid dEntity by script commands.) // --> if (attribute.startsWith("entity") && !attribute.startsWith("entity_")) return new dEntity(getPlayerEntity()) .getAttribute(attribute.fulfill(1)); ///////////////////// // IDENTIFICATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the player's IP address. // --> if (attribute.startsWith("ip") || attribute.startsWith("host_name")) return new Element(getPlayerEntity().getAddress().getHostName()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the display name of the player, which may contain // prefixes and suffixes, colors, etc. // --> if (attribute.startsWith("name.display")) return new Element(getPlayerEntity().getDisplayName()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of the player as shown in the player list. // --> if (attribute.startsWith("name.list")) return new Element(getPlayerEntity().getPlayerListName()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of the player. // --> if (attribute.startsWith("name")) return new Element(player_name).getAttribute(attribute.fulfill(1)); ///////////////////// // INVENTORY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dInventory // @description // returns a dInventory of the player's current inventory. // --> if (attribute.startsWith("inventory")) return new dInventory(getPlayerEntity().getInventory()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_on_cursor> // @returns dItem // @description // returns a dItem that the player's cursor is on, if any. This includes // chest interfaces, inventories, and hotbars, etc. // --> if (attribute.startsWith("item_on_cursor")) return new dItem(getPlayerEntity().getItemOnCursor()) .getAttribute(attribute.fulfill(1)); ///////////////////// // PERMISSION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_permission[permission.node]> // @returns Element(Boolean) // @description // returns whether the player has the specified node. // --> if (attribute.startsWith("permission") || attribute.startsWith("has_permission")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return null; } String permission = attribute.getContext(1); // <--[tag] // @attribute <[email protected]_permission[permission.node].global> // @returns Element(Boolean) // @description // returns whether the player has the specified node, regardless of world. // (Note: this may or may not be functional with your permissions system.) // --> // Non-world specific permission if (attribute.getAttribute(2).startsWith("global")) return new Element(Depends.permissions.has((World) null, player_name, permission)) .getAttribute(attribute.fulfill(2)); // Permission in certain world else if (attribute.getAttribute(2).startsWith("world")) return new Element(Depends.permissions.has(attribute.getContext(2), player_name, permission)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_permission[permission.node].world> // @returns Element(Boolean) // @description // returns whether the player has the specified node in regards to the // player's current world. // (Note: This may or may not be functional with your permissions system.) // --> // Permission in current world return new Element(Depends.permissions.has(getPlayerEntity(), permission)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_group[<group_name>]> // @returns Element(Boolean) // @description // returns whether the player is in the specified group. // --> if (attribute.startsWith("group") || attribute.startsWith("in_group")) { if (Depends.permissions == null) { dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?"); return Element.NULL.getAttribute(attribute.fulfill(1)); } String group = attribute.getContext(1); // <--[tag] // @attribute <[email protected]_group[<group_name>].global> // @returns Element(Boolean) // @description // returns whether the player has the group with no regard to the // player's current world. // (Note: This may or may not be functional with your permissions system.) // --> // Non-world specific permission if (attribute.getAttribute(2).startsWith("global")) return new Element(Depends.permissions.playerInGroup((World) null, player_name, group)) .getAttribute(attribute.fulfill(2)); // Permission in certain world else if (attribute.getAttribute(2).startsWith("world")) return new Element(Depends.permissions.playerInGroup(attribute.getContext(2), player_name, group)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_group[<group_name>].world> // @returns Element(Boolean) // @description // returns whether the player has the group in regards to the // player's current world. // (Note: This may or may not be functional with your permissions system.) // --> // Permission in current world return new Element(Depends.permissions.playerInGroup(getPlayerEntity(), group)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_finished[<script>]> // @returns dLocation // @description // returns the if the Player has finished the specified script. // --> if (attribute.startsWith("has_finished")) { dScript script = dScript.valueOf(attribute.getContext(1)); if (script == null) return Element.FALSE.getAttribute(attribute.fulfill(1)); return new Element(FinishCommand.getScriptCompletes(getName(), script.getName()) > 0) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_failed[<script>]> // @returns dLocation // @description // returns the if the Player has failed the specified script. // --> if (attribute.startsWith("has_failed")) { dScript script = dScript.valueOf(attribute.getContext(1)); if (script == null) return Element.FALSE.getAttribute(attribute.fulfill(1)); return new Element(FailCommand.getScriptFails(getName(), script.getName()) > 0) .getAttribute(attribute.fulfill(1)); } ///////////////////// // LOCATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // returns the location of the player's compass target. // --> if (attribute.startsWith("compass_target")) return new dLocation(getPlayerEntity().getCompassTarget()) .getAttribute(attribute.fulfill(2)); ///////////////////// // STATE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_flight> // @returns Element(Boolean) // @description // returns whether the player is allowed to fly. // --> if (attribute.startsWith("allowed_flight")) return new Element(getPlayerEntity().getAllowFlight()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_speed> // @returns Element(Decimal) // @description // returns the speed the player can fly at. // --> if (attribute.startsWith("fly_speed")) return new Element(getPlayerEntity().getFlySpeed()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_level.formatted> // @returns Element // @description // returns a 'formatted' value of the player's current food level. // May be 'starving', 'famished', 'parched, 'hungry' or 'healthy'. // --> if (attribute.startsWith("food_level.formatted")) { double maxHunger = getPlayerEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHunger = attribute.getIntContext(2); if (getPlayerEntity().getFoodLevel() / maxHunger < .10) return new Element("starving").getAttribute(attribute.fulfill(2)); else if (getPlayerEntity().getFoodLevel() / maxHunger < .40) return new Element("famished").getAttribute(attribute.fulfill(2)); else if (getPlayerEntity().getFoodLevel() / maxHunger < .75) return new Element("parched").getAttribute(attribute.fulfill(2)); else if (getPlayerEntity().getFoodLevel() / maxHunger < 1) return new Element("hungry").getAttribute(attribute.fulfill(2)); else return new Element("healthy").getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the current saturation of the player. // --> if (attribute.startsWith("saturation")) return new Element(getPlayerEntity().getSaturation()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_level> // @returns Element(Number) // @description // returns the current food level of the player. // --> if (attribute.startsWith("food_level")) return new Element(getPlayerEntity().getFoodLevel()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns how much air the player can have. // --> if (attribute.startsWith("oxygen.max")) return new Element(getPlayerEntity().getMaximumAir()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns how much air the player has. // --> if (attribute.startsWith("oxygen")) return new Element(getPlayerEntity().getRemainingAir()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns the gamemode ID of the player. 0 = survival, 1 = creative, 2 = adventure // --> if (attribute.startsWith("gamemode.id")) return new Element(getPlayerEntity().getGameMode().getValue()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the name of the gamemode the player is currently set to. // --> if (attribute.startsWith("gamemode")) return new Element(getPlayerEntity().getGameMode().name()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_blocking> // @returns Element(Boolean) // @description // returns whether the player is currently blocking. // --> if (attribute.startsWith("is_blocking")) return new Element(getPlayerEntity().isBlocking()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_flying> // @returns Element(Boolean) // @description // returns whether the player is currently flying. // --> if (attribute.startsWith("is_flying")) return new Element(getPlayerEntity().isFlying()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_sleeping> // @returns Element(Boolean) // @description // returns whether the player is currently sleeping. // --> if (attribute.startsWith("is_sleeping")) return new Element(getPlayerEntity().isSleeping()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_sneaking> // @returns Element(Boolean) // @description // returns whether the player is currently sneaking. // --> if (attribute.startsWith("is_sneaking")) return new Element(getPlayerEntity().isSneaking()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_sprinting> // @returns Element(Boolean) // @description // returns whether the player is currently sprinting. // --> if (attribute.startsWith("is_sprinting")) return new Element(getPlayerEntity().isSprinting()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_asleep> // @returns Duration // @description // returns the time the player has been asleep. // --> if (attribute.startsWith("time_asleep")) return new Duration(getPlayerEntity().getSleepTicks() / 20) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Duration // @description // returns the time the player is currently experiencing. This time could differ from // the time that the rest of the world is currently experiencing if a 'time' or 'freeze_time' // mechanism is being used on the player. // --> if (attribute.startsWith("time")) return new Element(getPlayerEntity().getPlayerTime()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_speed> // @returns Element(Decimal) // @description // returns the speed the player can walk at. // --> if (attribute.startsWith("walk_speed")) return new Element(getPlayerEntity().getWalkSpeed()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns the type of weather the player is experiencing. This can be different // from the weather currently in the world that the player is residing in if // the weather is currently being forced onto the player. // --> if (attribute.startsWith("weather")) return new Element(getPlayerEntity().getPlayerWeather().name()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns the number of XP levels the player has. // --> if (attribute.startsWith("xp.level")) return new Element(getPlayerEntity().getLevel()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_next_level> // @returns Element(Number) // @description // returns the amount of XP needed to get to the next level. // --> if (attribute.startsWith("xp.to_next_level")) return new Element(getPlayerEntity().getExpToLevel()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // returns the total amount of experience points. // --> if (attribute.startsWith("xp.total")) return new Element(getPlayerEntity().getTotalExperience()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // returns the percentage of experience points to the next level. // --> if (attribute.startsWith("xp")) return new Element(getPlayerEntity().getExp() * 100) .getAttribute(attribute.fulfill(1)); // Iterate through this object's properties' attributes for (Property property : PropertyParser.getProperties(this)) { String returned = property.getAttribute(attribute); if (returned != null) return returned; } return new dEntity(getPlayerEntity()).getAttribute(attribute); }
diff --git a/src/org/geometerplus/zlibrary/ui/android/view/ZLAndroidWidget.java b/src/org/geometerplus/zlibrary/ui/android/view/ZLAndroidWidget.java index 48fc90bc..26255613 100644 --- a/src/org/geometerplus/zlibrary/ui/android/view/ZLAndroidWidget.java +++ b/src/org/geometerplus/zlibrary/ui/android/view/ZLAndroidWidget.java @@ -1,543 +1,543 @@ /* * Copyright (C) 2007-2010 Geometer Plus <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.zlibrary.ui.android.view; import android.content.Context; import android.graphics.*; import android.view.*; import android.util.AttributeSet; import org.geometerplus.zlibrary.core.view.ZLView; import org.geometerplus.zlibrary.core.application.ZLApplication; import org.geometerplus.zlibrary.ui.android.library.ZLAndroidActivity; import org.geometerplus.zlibrary.ui.android.util.ZLAndroidKeyUtil; public class ZLAndroidWidget extends View implements View.OnLongClickListener { private final Paint myPaint = new Paint(); private Bitmap myMainBitmap; private Bitmap mySecondaryBitmap; private boolean mySecondaryBitmapIsUpToDate; private Bitmap myFooterBitmap; private boolean myScrollingInProgress; private int myScrollingShift; private float myScrollingSpeed; private int myScrollingBound; public ZLAndroidWidget(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public ZLAndroidWidget(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ZLAndroidWidget(Context context) { super(context); init(); } private void init() { // next line prevent ignoring first onKeyDown DPad event // after any dialog was closed setFocusableInTouchMode(true); setDrawingCacheEnabled(false); setOnLongClickListener(this); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (myScreenIsTouched) { final ZLView view = ZLApplication.Instance().getCurrentView(); myScrollingInProgress = false; myScrollingShift = 0; myScreenIsTouched = false; view.onScrollingFinished(ZLView.PAGE_CENTRAL); setPageToScroll(ZLView.PAGE_CENTRAL); } } @Override protected void onDraw(final Canvas canvas) { final Context context = getContext(); if (context instanceof ZLAndroidActivity) { ((ZLAndroidActivity)context).createWakeLock(); } else { System.err.println("A surprise: view's context is not a ZLAndroidActivity"); } super.onDraw(canvas); final int w = getWidth(); final int h = getMainAreaHeight(); if ((myMainBitmap != null) && ((myMainBitmap.getWidth() != w) || (myMainBitmap.getHeight() != h))) { myMainBitmap = null; mySecondaryBitmap = null; System.gc(); System.gc(); System.gc(); } if (myMainBitmap == null) { myMainBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565); mySecondaryBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565); mySecondaryBitmapIsUpToDate = false; drawOnBitmap(myMainBitmap); } if (myScrollingInProgress || (myScrollingShift != 0)) { onDrawInScrolling(canvas); } else { onDrawStatic(canvas); ZLApplication.Instance().onRepaintFinished(); } } private void onDrawInScrolling(Canvas canvas) { final int w = getWidth(); final int h = getMainAreaHeight(); boolean stopScrolling = false; if (myScrollingInProgress) { myScrollingShift += (int)myScrollingSpeed; if (myScrollingSpeed > 0) { if (myScrollingShift >= myScrollingBound) { myScrollingShift = myScrollingBound; stopScrolling = true; } } else { if (myScrollingShift <= myScrollingBound) { myScrollingShift = myScrollingBound; stopScrolling = true; } } myScrollingSpeed *= 1.5; } final boolean horizontal = (myViewPageToScroll == ZLView.PAGE_RIGHT) || (myViewPageToScroll == ZLView.PAGE_LEFT); final int size = horizontal ? w : h; int shift = (myScrollingShift < 0) ? (myScrollingShift + size) : (myScrollingShift - size); /* canvas.drawBitmap( mySecondaryBitmap, horizontal ? shift : 0, horizontal ? 0 : shift, myPaint ); */ canvas.drawBitmap( mySecondaryBitmap, 0, 0, myPaint ); canvas.drawBitmap( myMainBitmap, horizontal ? myScrollingShift : 0, horizontal ? 0 : myScrollingShift, myPaint ); if (stopScrolling) { final ZLView view = ZLApplication.Instance().getCurrentView(); if (myScrollingBound != 0) { Bitmap swap = myMainBitmap; myMainBitmap = mySecondaryBitmap; mySecondaryBitmap = swap; mySecondaryBitmapIsUpToDate = false; view.onScrollingFinished(myViewPageToScroll); ZLApplication.Instance().onRepaintFinished(); } else { view.onScrollingFinished(ZLView.PAGE_CENTRAL); } setPageToScroll(ZLView.PAGE_CENTRAL); myScrollingInProgress = false; myScrollingShift = 0; } else { if (shift < 0) { shift += size; } // TODO: set color myPaint.setColor(Color.rgb(127, 127, 127)); if (horizontal) { canvas.drawLine(shift, 0, shift, h + 1, myPaint); } else { canvas.drawLine(0, shift, w + 1, shift, myPaint); } if (myScrollingInProgress) { postInvalidate(); } } drawFooter(canvas); } private int myViewPageToScroll = ZLView.PAGE_CENTRAL; private void setPageToScroll(int viewPage) { if (myViewPageToScroll != viewPage) { myViewPageToScroll = viewPage; mySecondaryBitmapIsUpToDate = false; } } void scrollToPage(int viewPage, int shift) { switch (viewPage) { case ZLView.PAGE_BOTTOM: case ZLView.PAGE_RIGHT: shift = -shift; break; } if (myMainBitmap == null) { return; } if (((shift > 0) && (myScrollingShift <= 0)) || ((shift < 0) && (myScrollingShift >= 0))) { mySecondaryBitmapIsUpToDate = false; } myScrollingShift = shift; setPageToScroll(viewPage); drawOnBitmap(mySecondaryBitmap); postInvalidate(); } void startAutoScrolling(int viewPage) { if (myMainBitmap == null) { return; } myScrollingInProgress = true; switch (viewPage) { case ZLView.PAGE_CENTRAL: switch (myViewPageToScroll) { case ZLView.PAGE_CENTRAL: myScrollingSpeed = 0; break; case ZLView.PAGE_LEFT: case ZLView.PAGE_TOP: myScrollingSpeed = -3; break; case ZLView.PAGE_RIGHT: case ZLView.PAGE_BOTTOM: myScrollingSpeed = 3; break; } myScrollingBound = 0; break; case ZLView.PAGE_LEFT: myScrollingSpeed = 3; myScrollingBound = getWidth(); break; case ZLView.PAGE_RIGHT: myScrollingSpeed = -3; myScrollingBound = -getWidth(); break; case ZLView.PAGE_TOP: myScrollingSpeed = 3; myScrollingBound = getMainAreaHeight(); break; case ZLView.PAGE_BOTTOM: myScrollingSpeed = -3; myScrollingBound = -getMainAreaHeight(); break; } if (viewPage != ZLView.PAGE_CENTRAL) { setPageToScroll(viewPage); } drawOnBitmap(mySecondaryBitmap); postInvalidate(); } private void drawOnBitmap(Bitmap bitmap) { final ZLView view = ZLApplication.Instance().getCurrentView(); if (view == null) { return; } if (bitmap == myMainBitmap) { mySecondaryBitmapIsUpToDate = false; } else if (mySecondaryBitmapIsUpToDate) { return; } else { mySecondaryBitmapIsUpToDate = true; } final ZLAndroidPaintContext context = new ZLAndroidPaintContext( new Canvas(bitmap), getWidth(), getMainAreaHeight(), view.isScrollbarShown() ? getVerticalScrollbarWidth() : 0 ); view.paint(context, (bitmap == myMainBitmap) ? ZLView.PAGE_CENTRAL : myViewPageToScroll); } private void drawFooter(Canvas canvas) { final ZLView view = ZLApplication.Instance().getCurrentView(); final ZLView.FooterArea footer = view.getFooterArea(); if (footer != null) { if (myFooterBitmap != null && (myFooterBitmap.getWidth() != getWidth() || myFooterBitmap.getHeight() != footer.getHeight())) { myFooterBitmap = null; } if (myFooterBitmap == null) { myFooterBitmap = Bitmap.createBitmap(getWidth(), footer.getHeight(), Bitmap.Config.RGB_565); } final ZLAndroidPaintContext context = new ZLAndroidPaintContext( new Canvas(myFooterBitmap), getWidth(), footer.getHeight(), view.isScrollbarShown() ? getVerticalScrollbarWidth() : 0 ); footer.paint(context); canvas.drawBitmap(myFooterBitmap, 0, getMainAreaHeight(), myPaint); } else { myFooterBitmap = null; } } private void onDrawStatic(Canvas canvas) { drawOnBitmap(myMainBitmap); canvas.drawBitmap(myMainBitmap, 0, 0, myPaint); drawFooter(canvas); } @Override public boolean onTrackballEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { onKeyDown(KeyEvent.KEYCODE_DPAD_CENTER, null); } else { ZLApplication.Instance().getCurrentView().onTrackballRotated((int)(10 * event.getX()), (int)(10 * event.getY())); } return true; } private class LongClickRunnable implements Runnable { public void run() { if (performLongClick()) { myLongClickPerformed = true; } } } private volatile LongClickRunnable myPendingLongClickRunnable; private volatile boolean myLongClickPerformed; private void postLongClickRunnable() { myLongClickPerformed = false; myPendingPress = false; if (myPendingLongClickRunnable == null) { myPendingLongClickRunnable = new LongClickRunnable(); } postDelayed(myPendingLongClickRunnable, 2 * ViewConfiguration.getLongPressTimeout()); } private class ShortClickRunnable implements Runnable { public void run() { final ZLView view = ZLApplication.Instance().getCurrentView(); view.onFingerSingleTap(myPressedX, myPressedY); myPendingPress = false; myPendingShortClickRunnable = null; } } private volatile ShortClickRunnable myPendingShortClickRunnable; private volatile boolean myPendingPress; private volatile boolean myPendingDoubleTap; private int myPressedX, myPressedY; private boolean myScreenIsTouched; @Override public boolean onTouchEvent(MotionEvent event) { int x = (int)event.getX(); int y = (int)event.getY(); final ZLView view = ZLApplication.Instance().getCurrentView(); switch (event.getAction()) { case MotionEvent.ACTION_UP: if (myPendingDoubleTap) { view.onFingerDoubleTap(); } if (myLongClickPerformed) { view.onFingerReleaseAfterLongPress(x, y); } else { if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); myPendingLongClickRunnable = null; } if (myPendingPress) { if (view.isDoubleTapSupported()) { if (myPendingShortClickRunnable == null) { myPendingShortClickRunnable = new ShortClickRunnable(); } postDelayed(myPendingShortClickRunnable, ViewConfiguration.getDoubleTapTimeout()); } else { view.onFingerSingleTap(x, y); } } else { view.onFingerRelease(x, y); } } myPendingDoubleTap = false; myPendingPress = false; myScreenIsTouched = false; break; case MotionEvent.ACTION_DOWN: if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; myPendingDoubleTap = true; } else { postLongClickRunnable(); + myPendingPress = true; } myScreenIsTouched = true; - myPendingPress = true; myPressedX = x; myPressedY = y; break; case MotionEvent.ACTION_MOVE: { final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); final boolean isAMove = Math.abs(myPressedX - x) > slop || Math.abs(myPressedY - y) > slop; if (isAMove) { myPendingDoubleTap = false; } if (myLongClickPerformed) { view.onFingerMoveAfterLongPress(x, y); } else { if (myPendingPress) { if (isAMove) { if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; } if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); } view.onFingerPress(myPressedX, myPressedY); myPendingPress = false; } } if (!myPendingPress) { view.onFingerMove(x, y); } } break; } } return true; } public boolean onLongClick(View v) { final ZLView view = ZLApplication.Instance().getCurrentView(); return view.onFingerLongPress(myPressedX, myPressedY); } public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: return ZLApplication.Instance().doActionByKey(ZLAndroidKeyUtil.getKeyNameByCode(keyCode)); case KeyEvent.KEYCODE_DPAD_LEFT: ZLApplication.Instance().getCurrentView().onTrackballRotated(-1, 0); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: ZLApplication.Instance().getCurrentView().onTrackballRotated(1, 0); return true; case KeyEvent.KEYCODE_DPAD_DOWN: ZLApplication.Instance().getCurrentView().onTrackballRotated(0, 1); return true; case KeyEvent.KEYCODE_DPAD_UP: ZLApplication.Instance().getCurrentView().onTrackballRotated(0, -1); return true; default: return false; } } public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: return true; default: return false; } } protected int computeVerticalScrollExtent() { final ZLView view = ZLApplication.Instance().getCurrentView(); if (!view.isScrollbarShown()) { return 0; } if (myScrollingInProgress || (myScrollingShift != 0)) { final int from = view.getScrollbarThumbLength(ZLView.PAGE_CENTRAL); final int to = view.getScrollbarThumbLength(myViewPageToScroll); final boolean horizontal = (myViewPageToScroll == ZLView.PAGE_RIGHT) || (myViewPageToScroll == ZLView.PAGE_LEFT); final int size = horizontal ? getWidth() : getMainAreaHeight(); final int shift = Math.abs(myScrollingShift); return (from * (size - shift) + to * shift) / size; } else { return view.getScrollbarThumbLength(ZLView.PAGE_CENTRAL); } } protected int computeVerticalScrollOffset() { final ZLView view = ZLApplication.Instance().getCurrentView(); if (!view.isScrollbarShown()) { return 0; } if (myScrollingInProgress || (myScrollingShift != 0)) { final int from = view.getScrollbarThumbPosition(ZLView.PAGE_CENTRAL); final int to = view.getScrollbarThumbPosition(myViewPageToScroll); final boolean horizontal = (myViewPageToScroll == ZLView.PAGE_RIGHT) || (myViewPageToScroll == ZLView.PAGE_LEFT); final int size = horizontal ? getWidth() : getMainAreaHeight(); final int shift = Math.abs(myScrollingShift); return (from * (size - shift) + to * shift) / size; } else { return view.getScrollbarThumbPosition(ZLView.PAGE_CENTRAL); } } protected int computeVerticalScrollRange() { final ZLView view = ZLApplication.Instance().getCurrentView(); if (!view.isScrollbarShown()) { return 0; } return view.getScrollbarFullSize(); } private int getMainAreaHeight() { final ZLView.FooterArea footer = ZLApplication.Instance().getCurrentView().getFooterArea(); return footer != null ? getHeight() - footer.getHeight() : getHeight(); } }
false
true
public boolean onTouchEvent(MotionEvent event) { int x = (int)event.getX(); int y = (int)event.getY(); final ZLView view = ZLApplication.Instance().getCurrentView(); switch (event.getAction()) { case MotionEvent.ACTION_UP: if (myPendingDoubleTap) { view.onFingerDoubleTap(); } if (myLongClickPerformed) { view.onFingerReleaseAfterLongPress(x, y); } else { if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); myPendingLongClickRunnable = null; } if (myPendingPress) { if (view.isDoubleTapSupported()) { if (myPendingShortClickRunnable == null) { myPendingShortClickRunnable = new ShortClickRunnable(); } postDelayed(myPendingShortClickRunnable, ViewConfiguration.getDoubleTapTimeout()); } else { view.onFingerSingleTap(x, y); } } else { view.onFingerRelease(x, y); } } myPendingDoubleTap = false; myPendingPress = false; myScreenIsTouched = false; break; case MotionEvent.ACTION_DOWN: if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; myPendingDoubleTap = true; } else { postLongClickRunnable(); } myScreenIsTouched = true; myPendingPress = true; myPressedX = x; myPressedY = y; break; case MotionEvent.ACTION_MOVE: { final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); final boolean isAMove = Math.abs(myPressedX - x) > slop || Math.abs(myPressedY - y) > slop; if (isAMove) { myPendingDoubleTap = false; } if (myLongClickPerformed) { view.onFingerMoveAfterLongPress(x, y); } else { if (myPendingPress) { if (isAMove) { if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; } if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); } view.onFingerPress(myPressedX, myPressedY); myPendingPress = false; } } if (!myPendingPress) { view.onFingerMove(x, y); } } break; } } return true; }
public boolean onTouchEvent(MotionEvent event) { int x = (int)event.getX(); int y = (int)event.getY(); final ZLView view = ZLApplication.Instance().getCurrentView(); switch (event.getAction()) { case MotionEvent.ACTION_UP: if (myPendingDoubleTap) { view.onFingerDoubleTap(); } if (myLongClickPerformed) { view.onFingerReleaseAfterLongPress(x, y); } else { if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); myPendingLongClickRunnable = null; } if (myPendingPress) { if (view.isDoubleTapSupported()) { if (myPendingShortClickRunnable == null) { myPendingShortClickRunnable = new ShortClickRunnable(); } postDelayed(myPendingShortClickRunnable, ViewConfiguration.getDoubleTapTimeout()); } else { view.onFingerSingleTap(x, y); } } else { view.onFingerRelease(x, y); } } myPendingDoubleTap = false; myPendingPress = false; myScreenIsTouched = false; break; case MotionEvent.ACTION_DOWN: if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; myPendingDoubleTap = true; } else { postLongClickRunnable(); myPendingPress = true; } myScreenIsTouched = true; myPressedX = x; myPressedY = y; break; case MotionEvent.ACTION_MOVE: { final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); final boolean isAMove = Math.abs(myPressedX - x) > slop || Math.abs(myPressedY - y) > slop; if (isAMove) { myPendingDoubleTap = false; } if (myLongClickPerformed) { view.onFingerMoveAfterLongPress(x, y); } else { if (myPendingPress) { if (isAMove) { if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; } if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); } view.onFingerPress(myPressedX, myPressedY); myPendingPress = false; } } if (!myPendingPress) { view.onFingerMove(x, y); } } break; } } return true; }
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java index 646dc711b..5b07c73bd 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java @@ -1,315 +1,315 @@ /** * Copyright 2010 JogAmp Community. 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. * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ package com.jogamp.opengl.test.junit.newt; import java.lang.reflect.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.AfterClass; import org.junit.Test; import java.awt.AWTException; import java.awt.Button; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Robot; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import java.util.ArrayList; import javax.media.opengl.*; import com.jogamp.opengl.util.Animator; import com.jogamp.newt.opengl.*; import com.jogamp.newt.awt.NewtCanvasAWT; import java.io.IOException; import com.jogamp.opengl.test.junit.util.*; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; /** * Testing focus traversal of an AWT component tree with {@link NewtCanvasAWT} attached. * <p> * {@link JFrame} . {@link JPanel}+ . {@link Container} . {@link NewtCanvasAWT} . {@link GLWindow} * </p> * <p> * <i>+ JPanel is set as JFrame's root content pane</i><br/> * </p> */ public class TestFocus02SwingAWTRobot extends UITestCase { static int width, height; static long durationPerTest = 10; static long awtWaitTimeout = 1000; static GLCapabilities glCaps; @BeforeClass public static void initClass() throws AWTException, InterruptedException, InvocationTargetException { width = 640; height = 480; final JFrame f = new JFrame(); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { f.setSize(100,100); f.setVisible(true); } } ); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { f.dispose(); } } ); glCaps = new GLCapabilities(null); } @AfterClass public static void release() { } private void testFocus01ProgrFocusImpl(Robot robot) throws AWTException, InterruptedException, InvocationTargetException { ArrayList<EventCountAdapter> eventCountAdapters = new ArrayList<EventCountAdapter>(); GLWindow glWindow1 = GLWindow.create(glCaps); glWindow1.setTitle("testWindowParenting01CreateVisibleDestroy"); GLEventListener demo1 = new GearsES2(); glWindow1.addGLEventListener(demo1); NEWTFocusAdapter glWindow1FA = new NEWTFocusAdapter("GLWindow1"); glWindow1.addWindowListener(glWindow1FA); NEWTKeyAdapter glWindow1KA = new NEWTKeyAdapter("GLWindow1"); glWindow1.addKeyListener(glWindow1KA); eventCountAdapters.add(glWindow1KA); NEWTMouseAdapter glWindow1MA = new NEWTMouseAdapter("GLWindow1"); glWindow1.addMouseListener(glWindow1MA); eventCountAdapters.add(glWindow1MA); NewtCanvasAWT newtCanvasAWT = new NewtCanvasAWT(glWindow1); AWTFocusAdapter newtCanvasAWTFA = new AWTFocusAdapter("NewtCanvasAWT"); newtCanvasAWT.addFocusListener(newtCanvasAWTFA); AWTKeyAdapter newtCanvasAWTKA = new AWTKeyAdapter("NewtCanvasAWT"); newtCanvasAWT.addKeyListener(newtCanvasAWTKA); eventCountAdapters.add(newtCanvasAWTKA); AWTMouseAdapter newtCanvasAWTMA = new AWTMouseAdapter("NewtCanvasAWT"); newtCanvasAWT.addMouseListener(newtCanvasAWTMA); eventCountAdapters.add(newtCanvasAWTMA); Button buttonNorthInner = new Button("north"); AWTFocusAdapter buttonNorthInnerFA = new AWTFocusAdapter("ButtonNorthInner"); buttonNorthInner.addFocusListener(buttonNorthInnerFA); AWTKeyAdapter buttonNorthInnerKA = new AWTKeyAdapter("ButtonNorthInner"); buttonNorthInner.addKeyListener(buttonNorthInnerKA); eventCountAdapters.add(buttonNorthInnerKA); AWTMouseAdapter buttonNorthInnerMA = new AWTMouseAdapter("ButtonNorthInner"); buttonNorthInner.addMouseListener(buttonNorthInnerMA); eventCountAdapters.add(buttonNorthInnerMA); final Container container1 = new Container(); container1.setLayout(new BorderLayout()); container1.add(buttonNorthInner, BorderLayout.NORTH); container1.add(new Button("south"), BorderLayout.SOUTH); container1.add(new Button("east"), BorderLayout.EAST); container1.add(new Button("west"), BorderLayout.WEST); container1.add(newtCanvasAWT, BorderLayout.CENTER); Button buttonNorthOuter = new Button("north"); AWTFocusAdapter buttonNorthOuterFA = new AWTFocusAdapter("ButtonNorthOuter"); buttonNorthOuter.addFocusListener(buttonNorthOuterFA); AWTKeyAdapter buttonNorthOuterKA = new AWTKeyAdapter("ButtonNorthOuter"); buttonNorthOuter.addKeyListener(buttonNorthOuterKA); eventCountAdapters.add(buttonNorthOuterKA); AWTMouseAdapter buttonNorthOuterMA = new AWTMouseAdapter("ButtonNorthOuter"); buttonNorthOuter.addMouseListener(buttonNorthOuterMA); eventCountAdapters.add(buttonNorthOuterMA); final JPanel jPanel1 = new JPanel(); jPanel1.setLayout(new BorderLayout()); jPanel1.add(buttonNorthOuter, BorderLayout.NORTH); jPanel1.add(new Button("south"), BorderLayout.SOUTH); jPanel1.add(new Button("east"), BorderLayout.EAST); jPanel1.add(new Button("west"), BorderLayout.WEST); jPanel1.add(container1, BorderLayout.CENTER); final JFrame jFrame1 = new JFrame("Swing Parent JFrame"); // jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // equivalent to Frame, use windowClosing event! jFrame1.setContentPane(jPanel1); jFrame1.setSize(width, height); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { jFrame1.setVisible(true); } } ); Assert.assertEquals(true, AWTRobotUtil.waitForVisible(jFrame1, true)); Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, true)); AWTRobotUtil.clearAWTFocus(robot); Assert.assertTrue(AWTRobotUtil.toFrontAndRequestFocus(robot, jFrame1)); int wait=0; while(wait<awtWaitTimeout/10 && glWindow1.getTotalFPSFrames()<1) { Thread.sleep(awtWaitTimeout/100); wait++; } System.err.println("Frames for initial setVisible(true): "+glWindow1.getTotalFPSFrames()); Assert.assertTrue(glWindow1.isVisible()); Assert.assertTrue(0 < glWindow1.getTotalFPSFrames()); // Continuous animation .. Animator animator1 = new Animator(glWindow1); animator1.start(); Thread.sleep(durationPerTest); // manual testing // Button Outer Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS AWT Button Outer request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthOuter, buttonNorthOuter, buttonNorthOuterFA, null); // OSX sporadically buttonNorthOuter did not gain - major UI failure Assert.assertEquals(false, glWindow1FA.focusGained()); Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); Assert.assertEquals(false, buttonNorthInnerFA.focusGained()); System.err.println("FOCUS AWT Button Outer sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthOuter, buttonNorthOuterKA); // OSX sporadically won't receive the keyboard input - major UI failure AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, buttonNorthOuter, buttonNorthOuterMA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, buttonNorthOuter, buttonNorthOuterMA); // NEWT Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS NEWT Canvas/GLWindow request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthOuterFA); // Manually tested on Java7/[Linux,Windows] (where this assertion failed), // Should be OK to have the AWT component assume it also has the focus. // Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA, // AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA)); if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) { System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA); } Assert.assertEquals(false, buttonNorthInnerFA.focusGained()); System.err.println("FOCUS NEWT Canvas/GLWindow sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA); Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount()); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, glWindow1, glWindow1MA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, glWindow1, glWindow1MA); Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount()); // Button Inner Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS AWT Button request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthInner, buttonNorthInner, buttonNorthInnerFA, glWindow1FA); + Assert.assertEquals(false, glWindow1FA.focusGained()); Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); Assert.assertEquals(false, buttonNorthOuterFA.focusGained()); System.err.println("FOCUS AWT Button sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthInner, buttonNorthInnerKA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, buttonNorthInner, buttonNorthInnerMA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, buttonNorthInner, buttonNorthInnerMA); // NEWT Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS NEWT Canvas/GLWindow request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthInnerFA); // Manually tested on Java7/[Linux,Windows] (where this assertion failed), // Should be OK to have the AWT component assume it also has the focus. // Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA, // AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA)); if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) { System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA); } - Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); Assert.assertEquals(false, buttonNorthOuterFA.focusGained()); System.err.println("FOCUS NEWT Canvas/GLWindow sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA); Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount()); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, glWindow1, glWindow1MA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, glWindow1, glWindow1MA); Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount()); animator1.stop(); Assert.assertEquals(false, animator1.isAnimating()); SwingUtilities.invokeAndWait(new Runnable() { public void run() { jFrame1.setVisible(false); jPanel1.remove(container1); jFrame1.dispose(); } }); glWindow1.destroy(); Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, false)); } @Test public void testFocus01ProgrFocus() throws AWTException, InterruptedException, InvocationTargetException { testFocus01ProgrFocusImpl(null); } @Test public void testFocus02RobotFocus() throws AWTException, InterruptedException, InvocationTargetException { Robot robot = new Robot(); robot.setAutoWaitForIdle(true); testFocus01ProgrFocusImpl(robot); } static int atoi(String a) { int i=0; try { i = Integer.parseInt(a); } catch (Exception ex) { ex.printStackTrace(); } return i; } @SuppressWarnings("unused") public static void main(String args[]) throws IOException, AWTException, InterruptedException, InvocationTargetException { for(int i=0; i<args.length; i++) { if(args[i].equals("-time")) { durationPerTest = atoi(args[++i]); } } if(true) { String tstname = TestFocus02SwingAWTRobot.class.getName(); org.junit.runner.JUnitCore.main(tstname); } else { TestFocus02SwingAWTRobot.initClass(); TestFocus02SwingAWTRobot test = new TestFocus02SwingAWTRobot(); test.testFocus01ProgrFocus(); test.testFocus02RobotFocus(); TestFocus02SwingAWTRobot.release(); } } }
false
true
private void testFocus01ProgrFocusImpl(Robot robot) throws AWTException, InterruptedException, InvocationTargetException { ArrayList<EventCountAdapter> eventCountAdapters = new ArrayList<EventCountAdapter>(); GLWindow glWindow1 = GLWindow.create(glCaps); glWindow1.setTitle("testWindowParenting01CreateVisibleDestroy"); GLEventListener demo1 = new GearsES2(); glWindow1.addGLEventListener(demo1); NEWTFocusAdapter glWindow1FA = new NEWTFocusAdapter("GLWindow1"); glWindow1.addWindowListener(glWindow1FA); NEWTKeyAdapter glWindow1KA = new NEWTKeyAdapter("GLWindow1"); glWindow1.addKeyListener(glWindow1KA); eventCountAdapters.add(glWindow1KA); NEWTMouseAdapter glWindow1MA = new NEWTMouseAdapter("GLWindow1"); glWindow1.addMouseListener(glWindow1MA); eventCountAdapters.add(glWindow1MA); NewtCanvasAWT newtCanvasAWT = new NewtCanvasAWT(glWindow1); AWTFocusAdapter newtCanvasAWTFA = new AWTFocusAdapter("NewtCanvasAWT"); newtCanvasAWT.addFocusListener(newtCanvasAWTFA); AWTKeyAdapter newtCanvasAWTKA = new AWTKeyAdapter("NewtCanvasAWT"); newtCanvasAWT.addKeyListener(newtCanvasAWTKA); eventCountAdapters.add(newtCanvasAWTKA); AWTMouseAdapter newtCanvasAWTMA = new AWTMouseAdapter("NewtCanvasAWT"); newtCanvasAWT.addMouseListener(newtCanvasAWTMA); eventCountAdapters.add(newtCanvasAWTMA); Button buttonNorthInner = new Button("north"); AWTFocusAdapter buttonNorthInnerFA = new AWTFocusAdapter("ButtonNorthInner"); buttonNorthInner.addFocusListener(buttonNorthInnerFA); AWTKeyAdapter buttonNorthInnerKA = new AWTKeyAdapter("ButtonNorthInner"); buttonNorthInner.addKeyListener(buttonNorthInnerKA); eventCountAdapters.add(buttonNorthInnerKA); AWTMouseAdapter buttonNorthInnerMA = new AWTMouseAdapter("ButtonNorthInner"); buttonNorthInner.addMouseListener(buttonNorthInnerMA); eventCountAdapters.add(buttonNorthInnerMA); final Container container1 = new Container(); container1.setLayout(new BorderLayout()); container1.add(buttonNorthInner, BorderLayout.NORTH); container1.add(new Button("south"), BorderLayout.SOUTH); container1.add(new Button("east"), BorderLayout.EAST); container1.add(new Button("west"), BorderLayout.WEST); container1.add(newtCanvasAWT, BorderLayout.CENTER); Button buttonNorthOuter = new Button("north"); AWTFocusAdapter buttonNorthOuterFA = new AWTFocusAdapter("ButtonNorthOuter"); buttonNorthOuter.addFocusListener(buttonNorthOuterFA); AWTKeyAdapter buttonNorthOuterKA = new AWTKeyAdapter("ButtonNorthOuter"); buttonNorthOuter.addKeyListener(buttonNorthOuterKA); eventCountAdapters.add(buttonNorthOuterKA); AWTMouseAdapter buttonNorthOuterMA = new AWTMouseAdapter("ButtonNorthOuter"); buttonNorthOuter.addMouseListener(buttonNorthOuterMA); eventCountAdapters.add(buttonNorthOuterMA); final JPanel jPanel1 = new JPanel(); jPanel1.setLayout(new BorderLayout()); jPanel1.add(buttonNorthOuter, BorderLayout.NORTH); jPanel1.add(new Button("south"), BorderLayout.SOUTH); jPanel1.add(new Button("east"), BorderLayout.EAST); jPanel1.add(new Button("west"), BorderLayout.WEST); jPanel1.add(container1, BorderLayout.CENTER); final JFrame jFrame1 = new JFrame("Swing Parent JFrame"); // jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // equivalent to Frame, use windowClosing event! jFrame1.setContentPane(jPanel1); jFrame1.setSize(width, height); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { jFrame1.setVisible(true); } } ); Assert.assertEquals(true, AWTRobotUtil.waitForVisible(jFrame1, true)); Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, true)); AWTRobotUtil.clearAWTFocus(robot); Assert.assertTrue(AWTRobotUtil.toFrontAndRequestFocus(robot, jFrame1)); int wait=0; while(wait<awtWaitTimeout/10 && glWindow1.getTotalFPSFrames()<1) { Thread.sleep(awtWaitTimeout/100); wait++; } System.err.println("Frames for initial setVisible(true): "+glWindow1.getTotalFPSFrames()); Assert.assertTrue(glWindow1.isVisible()); Assert.assertTrue(0 < glWindow1.getTotalFPSFrames()); // Continuous animation .. Animator animator1 = new Animator(glWindow1); animator1.start(); Thread.sleep(durationPerTest); // manual testing // Button Outer Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS AWT Button Outer request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthOuter, buttonNorthOuter, buttonNorthOuterFA, null); // OSX sporadically buttonNorthOuter did not gain - major UI failure Assert.assertEquals(false, glWindow1FA.focusGained()); Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); Assert.assertEquals(false, buttonNorthInnerFA.focusGained()); System.err.println("FOCUS AWT Button Outer sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthOuter, buttonNorthOuterKA); // OSX sporadically won't receive the keyboard input - major UI failure AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, buttonNorthOuter, buttonNorthOuterMA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, buttonNorthOuter, buttonNorthOuterMA); // NEWT Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS NEWT Canvas/GLWindow request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthOuterFA); // Manually tested on Java7/[Linux,Windows] (where this assertion failed), // Should be OK to have the AWT component assume it also has the focus. // Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA, // AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA)); if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) { System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA); } Assert.assertEquals(false, buttonNorthInnerFA.focusGained()); System.err.println("FOCUS NEWT Canvas/GLWindow sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA); Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount()); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, glWindow1, glWindow1MA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, glWindow1, glWindow1MA); Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount()); // Button Inner Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS AWT Button request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthInner, buttonNorthInner, buttonNorthInnerFA, glWindow1FA); Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); Assert.assertEquals(false, buttonNorthOuterFA.focusGained()); System.err.println("FOCUS AWT Button sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthInner, buttonNorthInnerKA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, buttonNorthInner, buttonNorthInnerMA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, buttonNorthInner, buttonNorthInnerMA); // NEWT Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS NEWT Canvas/GLWindow request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthInnerFA); // Manually tested on Java7/[Linux,Windows] (where this assertion failed), // Should be OK to have the AWT component assume it also has the focus. // Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA, // AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA)); if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) { System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA); } Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); Assert.assertEquals(false, buttonNorthOuterFA.focusGained()); System.err.println("FOCUS NEWT Canvas/GLWindow sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA); Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount()); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, glWindow1, glWindow1MA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, glWindow1, glWindow1MA); Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount()); animator1.stop(); Assert.assertEquals(false, animator1.isAnimating()); SwingUtilities.invokeAndWait(new Runnable() { public void run() { jFrame1.setVisible(false); jPanel1.remove(container1); jFrame1.dispose(); } }); glWindow1.destroy(); Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, false)); }
private void testFocus01ProgrFocusImpl(Robot robot) throws AWTException, InterruptedException, InvocationTargetException { ArrayList<EventCountAdapter> eventCountAdapters = new ArrayList<EventCountAdapter>(); GLWindow glWindow1 = GLWindow.create(glCaps); glWindow1.setTitle("testWindowParenting01CreateVisibleDestroy"); GLEventListener demo1 = new GearsES2(); glWindow1.addGLEventListener(demo1); NEWTFocusAdapter glWindow1FA = new NEWTFocusAdapter("GLWindow1"); glWindow1.addWindowListener(glWindow1FA); NEWTKeyAdapter glWindow1KA = new NEWTKeyAdapter("GLWindow1"); glWindow1.addKeyListener(glWindow1KA); eventCountAdapters.add(glWindow1KA); NEWTMouseAdapter glWindow1MA = new NEWTMouseAdapter("GLWindow1"); glWindow1.addMouseListener(glWindow1MA); eventCountAdapters.add(glWindow1MA); NewtCanvasAWT newtCanvasAWT = new NewtCanvasAWT(glWindow1); AWTFocusAdapter newtCanvasAWTFA = new AWTFocusAdapter("NewtCanvasAWT"); newtCanvasAWT.addFocusListener(newtCanvasAWTFA); AWTKeyAdapter newtCanvasAWTKA = new AWTKeyAdapter("NewtCanvasAWT"); newtCanvasAWT.addKeyListener(newtCanvasAWTKA); eventCountAdapters.add(newtCanvasAWTKA); AWTMouseAdapter newtCanvasAWTMA = new AWTMouseAdapter("NewtCanvasAWT"); newtCanvasAWT.addMouseListener(newtCanvasAWTMA); eventCountAdapters.add(newtCanvasAWTMA); Button buttonNorthInner = new Button("north"); AWTFocusAdapter buttonNorthInnerFA = new AWTFocusAdapter("ButtonNorthInner"); buttonNorthInner.addFocusListener(buttonNorthInnerFA); AWTKeyAdapter buttonNorthInnerKA = new AWTKeyAdapter("ButtonNorthInner"); buttonNorthInner.addKeyListener(buttonNorthInnerKA); eventCountAdapters.add(buttonNorthInnerKA); AWTMouseAdapter buttonNorthInnerMA = new AWTMouseAdapter("ButtonNorthInner"); buttonNorthInner.addMouseListener(buttonNorthInnerMA); eventCountAdapters.add(buttonNorthInnerMA); final Container container1 = new Container(); container1.setLayout(new BorderLayout()); container1.add(buttonNorthInner, BorderLayout.NORTH); container1.add(new Button("south"), BorderLayout.SOUTH); container1.add(new Button("east"), BorderLayout.EAST); container1.add(new Button("west"), BorderLayout.WEST); container1.add(newtCanvasAWT, BorderLayout.CENTER); Button buttonNorthOuter = new Button("north"); AWTFocusAdapter buttonNorthOuterFA = new AWTFocusAdapter("ButtonNorthOuter"); buttonNorthOuter.addFocusListener(buttonNorthOuterFA); AWTKeyAdapter buttonNorthOuterKA = new AWTKeyAdapter("ButtonNorthOuter"); buttonNorthOuter.addKeyListener(buttonNorthOuterKA); eventCountAdapters.add(buttonNorthOuterKA); AWTMouseAdapter buttonNorthOuterMA = new AWTMouseAdapter("ButtonNorthOuter"); buttonNorthOuter.addMouseListener(buttonNorthOuterMA); eventCountAdapters.add(buttonNorthOuterMA); final JPanel jPanel1 = new JPanel(); jPanel1.setLayout(new BorderLayout()); jPanel1.add(buttonNorthOuter, BorderLayout.NORTH); jPanel1.add(new Button("south"), BorderLayout.SOUTH); jPanel1.add(new Button("east"), BorderLayout.EAST); jPanel1.add(new Button("west"), BorderLayout.WEST); jPanel1.add(container1, BorderLayout.CENTER); final JFrame jFrame1 = new JFrame("Swing Parent JFrame"); // jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // equivalent to Frame, use windowClosing event! jFrame1.setContentPane(jPanel1); jFrame1.setSize(width, height); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { jFrame1.setVisible(true); } } ); Assert.assertEquals(true, AWTRobotUtil.waitForVisible(jFrame1, true)); Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, true)); AWTRobotUtil.clearAWTFocus(robot); Assert.assertTrue(AWTRobotUtil.toFrontAndRequestFocus(robot, jFrame1)); int wait=0; while(wait<awtWaitTimeout/10 && glWindow1.getTotalFPSFrames()<1) { Thread.sleep(awtWaitTimeout/100); wait++; } System.err.println("Frames for initial setVisible(true): "+glWindow1.getTotalFPSFrames()); Assert.assertTrue(glWindow1.isVisible()); Assert.assertTrue(0 < glWindow1.getTotalFPSFrames()); // Continuous animation .. Animator animator1 = new Animator(glWindow1); animator1.start(); Thread.sleep(durationPerTest); // manual testing // Button Outer Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS AWT Button Outer request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthOuter, buttonNorthOuter, buttonNorthOuterFA, null); // OSX sporadically buttonNorthOuter did not gain - major UI failure Assert.assertEquals(false, glWindow1FA.focusGained()); Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); Assert.assertEquals(false, buttonNorthInnerFA.focusGained()); System.err.println("FOCUS AWT Button Outer sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthOuter, buttonNorthOuterKA); // OSX sporadically won't receive the keyboard input - major UI failure AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, buttonNorthOuter, buttonNorthOuterMA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, buttonNorthOuter, buttonNorthOuterMA); // NEWT Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS NEWT Canvas/GLWindow request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthOuterFA); // Manually tested on Java7/[Linux,Windows] (where this assertion failed), // Should be OK to have the AWT component assume it also has the focus. // Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA, // AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA)); if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) { System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA); } Assert.assertEquals(false, buttonNorthInnerFA.focusGained()); System.err.println("FOCUS NEWT Canvas/GLWindow sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA); Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount()); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, glWindow1, glWindow1MA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, glWindow1, glWindow1MA); Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount()); // Button Inner Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS AWT Button request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthInner, buttonNorthInner, buttonNorthInnerFA, glWindow1FA); Assert.assertEquals(false, glWindow1FA.focusGained()); Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); Assert.assertEquals(false, buttonNorthOuterFA.focusGained()); System.err.println("FOCUS AWT Button sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthInner, buttonNorthInnerKA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, buttonNorthInner, buttonNorthInnerMA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, buttonNorthInner, buttonNorthInnerMA); // NEWT Focus Thread.sleep(100); // allow event sync System.err.println("FOCUS NEWT Canvas/GLWindow request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthInnerFA); // Manually tested on Java7/[Linux,Windows] (where this assertion failed), // Should be OK to have the AWT component assume it also has the focus. // Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA, // AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA)); if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) { System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA); } Assert.assertEquals(false, buttonNorthOuterFA.focusGained()); System.err.println("FOCUS NEWT Canvas/GLWindow sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA); Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount()); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, glWindow1, glWindow1MA); AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, glWindow1, glWindow1MA); Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount()); animator1.stop(); Assert.assertEquals(false, animator1.isAnimating()); SwingUtilities.invokeAndWait(new Runnable() { public void run() { jFrame1.setVisible(false); jPanel1.remove(container1); jFrame1.dispose(); } }); glWindow1.destroy(); Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, false)); }
diff --git a/src/main/java/hudson/maven/MavenModuleSetBuild.java b/src/main/java/hudson/maven/MavenModuleSetBuild.java index d60a9a3..a2838fc 100644 --- a/src/main/java/hudson/maven/MavenModuleSetBuild.java +++ b/src/main/java/hudson/maven/MavenModuleSetBuild.java @@ -1,1086 +1,1091 @@ /* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Red Hat, Inc., Victor Glushenkov, Alan Harder, Olivier Lamy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.maven; import static hudson.model.Result.FAILURE; import hudson.AbortException; import hudson.EnvVars; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.Launcher; import hudson.Util; import hudson.maven.MavenBuild.ProxyImpl2; import hudson.maven.reporters.MavenFingerprinter; import hudson.maven.reporters.MavenMailer; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.Cause.UpstreamCause; import hudson.model.Computer; import hudson.model.Environment; import hudson.model.Fingerprint; import hudson.model.Hudson; import hudson.model.ParametersAction; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogSet; import hudson.tasks.BuildWrapper; import hudson.tasks.MailSender; import hudson.tasks.Maven.MavenInstallation; import hudson.util.ArgumentListBuilder; import hudson.util.IOUtils; import hudson.util.MaskingClassLoader; import hudson.util.StreamTaskListener; import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.io.PrintStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.io.FilenameUtils; import org.apache.maven.BuildFailureException; import org.apache.maven.artifact.versioning.ComparableVersion; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ReactorManager; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.monitor.event.EventDispatcher; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; /** * {@link Build} for {@link MavenModuleSet}. * * <p> * A "build" of {@link MavenModuleSet} consists of: * * <ol> * <li>Update the workspace. * <li>Parse POMs * <li>Trigger module builds. * </ol> * * This object remembers the changelog and what {@link MavenBuild}s are done * on this. * * @author Kohsuke Kawaguchi */ public class MavenModuleSetBuild extends AbstractMavenBuild<MavenModuleSet,MavenModuleSetBuild> { /** * {@link MavenReporter}s that will contribute project actions. * Can be null if there's none. */ /*package*/ List<MavenReporter> projectActionReporters; public MavenModuleSetBuild(MavenModuleSet job) throws IOException { super(job); } public MavenModuleSetBuild(MavenModuleSet project, File buildDir) throws IOException { super(project, buildDir); } /** * Exposes {@code MAVEN_OPTS} to forked processes. * * When we fork Maven, we do so directly by executing Java, thus this environment variable * is pointless (we have to tweak JVM launch option correctly instead, which can be seen in * {@link MavenProcessFactory}), but setting the environment variable explicitly is still * useful in case this Maven forks other Maven processes via normal way. See HUDSON-3644. */ @Override public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException { EnvVars envs = super.getEnvironment(log); String opts = project.getMavenOpts(); if(opts!=null) envs.put("MAVEN_OPTS", opts); return envs; } /** * Displays the combined status of all modules. * <p> * More precisely, this picks up the status of this build itself, * plus all the latest builds of the modules that belongs to this build. */ @Override public Result getResult() { Result r = super.getResult(); for (MavenBuild b : getModuleLastBuilds().values()) { Result br = b.getResult(); if(r==null) r = br; else if(br==Result.NOT_BUILT) continue; // UGLY: when computing combined status, ignore the modules that were not built else if(br!=null) r = r.combine(br); } return r; } /** * Returns the filtered changeset entries that match the given module. */ /*package*/ List<ChangeLogSet.Entry> getChangeSetFor(final MavenModule mod) { return new ArrayList<ChangeLogSet.Entry>() { { // modules that are under 'mod'. lazily computed List<MavenModule> subsidiaries = null; for (ChangeLogSet.Entry e : getChangeSet()) { if(isDescendantOf(e, mod)) { if(subsidiaries==null) subsidiaries = mod.getSubsidiaries(); // make sure at least one change belongs to this module proper, // and not its subsidiary module if (notInSubsidiary(subsidiaries, e)) add(e); } } } private boolean notInSubsidiary(List<MavenModule> subsidiaries, ChangeLogSet.Entry e) { for (String path : e.getAffectedPaths()) if(!belongsToSubsidiary(subsidiaries, path)) return true; return false; } private boolean belongsToSubsidiary(List<MavenModule> subsidiaries, String path) { for (MavenModule sub : subsidiaries) if (FilenameUtils.separatorsToUnix(path).startsWith(FilenameUtils.normalize(sub.getRelativePath()))) return true; return false; } /** * Does this change happen somewhere in the given module or its descendants? */ private boolean isDescendantOf(ChangeLogSet.Entry e, MavenModule mod) { for (String path : e.getAffectedPaths()) { if (FilenameUtils.separatorsToUnix(path).startsWith(FilenameUtils.normalize(mod.getRelativePath()))) return true; } return false; } }; } /** * Computes the module builds that correspond to this build. * <p> * A module may be built multiple times (by the user action), * so the value is a list. */ public Map<MavenModule,List<MavenBuild>> getModuleBuilds() { Collection<MavenModule> mods = getParent().getModules(); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber() : Integer.MAX_VALUE; // preserve the order by using LinkedHashMap Map<MavenModule,List<MavenBuild>> r = new LinkedHashMap<MavenModule,List<MavenBuild>>(mods.size()); for (MavenModule m : mods) { List<MavenBuild> builds = new ArrayList<MavenBuild>(); MavenBuild b = m.getNearestBuild(number); while(b!=null && b.getNumber()<end) { builds.add(b); b = b.getNextBuild(); } r.put(m,builds); } return r; } /** * Returns the estimated duration for this builds. * Takes only the modules into account which are actually being build in * case of incremental builds. */ @Override public long getEstimatedDuration() { if (!project.isIncrementalBuild()) { return super.getEstimatedDuration(); } long result = 0; Map<MavenModule, List<MavenBuild>> moduleBuilds = getModuleBuilds(); for (List<MavenBuild> builds : moduleBuilds.values()) { if (!builds.isEmpty()) { MavenBuild build = builds.get(0); if (build.getResult() != Result.NOT_BUILT && build.getEstimatedDuration() != -1) { result += build.getEstimatedDuration(); } } } result += estimateModuleSetBuildDurationOverhead(3); return result != 0 ? result : -1; } /** * Estimates the duration overhead the {@link MavenModuleSetBuild} itself adds * to the sum of duration of the module builds. */ private long estimateModuleSetBuildDurationOverhead(int numberOfBuilds) { List<MavenModuleSetBuild> moduleSetBuilds = getPreviousBuildsOverThreshold(numberOfBuilds, Result.UNSTABLE); if (moduleSetBuilds.isEmpty()) { return 0; } long overhead = 0; for(MavenModuleSetBuild moduleSetBuild : moduleSetBuilds) { long sumOfModuleBuilds = 0; for (List<MavenBuild> builds : moduleSetBuild.getModuleBuilds().values()) { if (!builds.isEmpty()) { MavenBuild moduleBuild = builds.get(0); sumOfModuleBuilds += moduleBuild.getDuration(); } } overhead += Math.max(0, moduleSetBuild.getDuration() - sumOfModuleBuilds); } return Math.round((double)overhead / moduleSetBuilds.size()); } @Override public synchronized void delete() throws IOException { super.delete(); // Delete all contained module builds too for (List<MavenBuild> list : getModuleBuilds().values()) for (MavenBuild build : list) build.delete(); } @Override public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) { // map corresponding module build under this object if(token.indexOf('$')>0) { MavenModule m = getProject().getModule(token); if(m!=null) return m.getBuildByNumber(getNumber()); } return super.getDynamic(token,req,rsp); } /** * Computes the latest module builds that correspond to this build. * (when indivudual modules are built, a new ModuleSetBuild is not created, * but rather the new module build falls under the previous ModuleSetBuild) */ public Map<MavenModule,MavenBuild> getModuleLastBuilds() { Collection<MavenModule> mods = getParent().getModules(); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber() : Integer.MAX_VALUE; // preserve the order by using LinkedHashMap Map<MavenModule,MavenBuild> r = new LinkedHashMap<MavenModule,MavenBuild>(mods.size()); for (MavenModule m : mods) { MavenBuild b = m.getNearestOldBuild(end - 1); if(b!=null && b.getNumber()>=getNumber()) r.put(m,b); } return r; } public void registerAsProjectAction(MavenReporter reporter) { if(projectActionReporters==null) projectActionReporters = new ArrayList<MavenReporter>(); projectActionReporters.add(reporter); } /** * Finds {@link Action}s from all the module builds that belong to this * {@link MavenModuleSetBuild}. One action per one {@link MavenModule}, * and newer ones take precedence over older ones. */ public <T extends Action> List<T> findModuleBuildActions(Class<T> action) { Collection<MavenModule> mods = getParent().getModules(); List<T> r = new ArrayList<T>(mods.size()); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber()-1 : Integer.MAX_VALUE; for (MavenModule m : mods) { MavenBuild b = m.getNearestOldBuild(end); while(b!=null && b.getNumber()>=number) { T a = b.getAction(action); if(a!=null) { r.add(a); break; } b = b.getPreviousBuild(); } } return r; } public void run() { run(new RunnerImpl()); getProject().updateTransientActions(); } @Override public Fingerprint.RangeSet getDownstreamRelationship(AbstractProject that) { Fingerprint.RangeSet rs = super.getDownstreamRelationship(that); for(List<MavenBuild> builds : getModuleBuilds().values()) for (MavenBuild b : builds) rs.add(b.getDownstreamRelationship(that)); return rs; } /** * Called when a module build that corresponds to this module set build * has completed. */ /*package*/ void notifyModuleBuild(MavenBuild newBuild) { try { // update module set build number getParent().updateNextBuildNumber(); // update actions Map<MavenModule, List<MavenBuild>> moduleBuilds = getModuleBuilds(); // actions need to be replaced atomically especially // given that two builds might complete simultaneously. synchronized(this) { boolean modified = false; List<Action> actions = getActions(); Set<Class<? extends AggregatableAction>> individuals = new HashSet<Class<? extends AggregatableAction>>(); for (Action a : actions) { if(a instanceof MavenAggregatedReport) { MavenAggregatedReport mar = (MavenAggregatedReport) a; mar.update(moduleBuilds,newBuild); individuals.add(mar.getIndividualActionType()); modified = true; } } // see if the new build has any new aggregatable action that we haven't seen. for (AggregatableAction aa : newBuild.getActions(AggregatableAction.class)) { if(individuals.add(aa.getClass())) { // new AggregatableAction MavenAggregatedReport mar = aa.createAggregatedAction(this, moduleBuilds); mar.update(moduleBuilds,newBuild); actions.add(mar); modified = true; } } if(modified) { save(); getProject().updateTransientActions(); } } // symlink to this module build String moduleFsName = newBuild.getProject().getModuleName().toFileSystemName(); Util.createSymlink(getRootDir(), "../../modules/"+ moduleFsName +"/builds/"+newBuild.getId() /*ugly!*/, moduleFsName, StreamTaskListener.NULL); } catch (IOException e) { LOGGER.log(Level.WARNING,"Failed to update "+this,e); } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Failed to update "+this,e); } } /** * The sole job of the {@link MavenModuleSet} build is to update SCM * and triggers module builds. */ private class RunnerImpl extends AbstractRunner { private Map<ModuleName,MavenBuild.ProxyImpl2> proxies; protected Result doRun(final BuildListener listener) throws Exception { PrintStream logger = listener.getLogger(); Result r = null; try { EnvVars envVars = getEnvironment(listener); MavenInstallation mvn = project.getMaven(); if(mvn==null) throw new AbortException("A Maven installation needs to be available for this project to be built.\n"+ "Either your server has no Maven installations defined, or the requested Maven version does not exist."); mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener); String mavenVersion = getModuleRoot().act( new MavenVersionCallable( mvn.getHome() )); if(!project.isAggregatorStyleBuild()) { parsePoms(listener, logger, envVars, mvn); // start module builds logger.println("Triggering "+project.getRootModule().getModuleName()); project.getRootModule().scheduleBuild(new UpstreamCause((Run<?,?>)MavenModuleSetBuild.this)); } else { // do builds here try { List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>(); for (BuildWrapper w : project.getBuildWrappersList()) wrappers.add(w); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) parameters.createBuildWrappers(MavenModuleSetBuild.this,wrappers); for( BuildWrapper w : wrappers) { Environment e = w.setUp(MavenModuleSetBuild.this, launcher, listener); if(e==null) return (r = Result.FAILURE); buildEnvironments.add(e); e.buildEnvVars(envVars); // #3502: too late for getEnvironment to do this } if(!preBuild(listener, project.getPublishers())) return Result.FAILURE; parsePoms(listener, logger, envVars, mvn); // #5428 : do pre-build *before* parsing pom SplittableBuildListener slistener = new SplittableBuildListener(listener); proxies = new HashMap<ModuleName, ProxyImpl2>(); List<String> changedModules = new ArrayList<String>(); for (MavenModule m : project.sortedActiveModules) { MavenBuild mb = m.newBuild(); // Check if incrementalBuild is selected and that there are changes - // we act as if incrementalBuild is not set if there are no changes. if (!MavenModuleSetBuild.this.getChangeSet().isEmptySet() && project.isIncrementalBuild()) { //If there are changes for this module, add it. // Also add it if we've never seen this module before, // or if the previous build of this module failed or was unstable. if ((mb.getPreviousBuiltBuild() == null) || (!getChangeSetFor(m).isEmpty()) || (mb.getPreviousBuiltBuild().getResult().isWorseThan(Result.SUCCESS))) { changedModules.add(m.getModuleName().toString()); } } mb.setWorkspace(getModuleRoot().child(m.getRelativePath())); proxies.put(m.getModuleName(), mb.new ProxyImpl2(MavenModuleSetBuild.this,slistener)); } // run the complete build here // figure out the root POM location. // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) String rootPOM = project.getRootPOM(); FilePath pom = getModuleRoot().child(rootPOM); FilePath parentLoc = getWorkspace().child(rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; ProcessCache.MavenProcess process = null; boolean maven3orLater = new ComparableVersion (mavenVersion).compareTo( new ComparableVersion ("3.0") ) >= 0; - if (maven3orLater) + if ( maven3orLater ) { LOGGER.info( "using maven 3 " + mavenVersion ); - process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener, - new Maven3ProcessFactory(project,launcher,envVars,pom.getParent())); - } else + process = + MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, + new Maven3ProcessFactory( project, launcher, envVars, + pom.getParent() ) ); + } + else { - process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener, - new MavenProcessFactory(project,launcher,envVars,pom.getParent())); + process = + MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, + new MavenProcessFactory( project, launcher, envVars, + pom.getParent() ) ); } ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote()); if(project.usesPrivateRepository()) margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository")); // If incrementalBuild is set, and we're on Maven 2.1 or later, *and* there's at least one module // listed in changedModules, do the Maven incremental build commands - if there are no changed modules, // We're building everything anyway. if (project.isIncrementalBuild() && mvn.isMaven2_1(launcher) && !changedModules.isEmpty()) { margs.add("-amd"); margs.add("-pl", Util.join(changedModules, ",")); } if (project.getAlternateSettings() != null) { if (IOUtils.isAbsolute(project.getAlternateSettings())) { margs.add("-s").add(project.getAlternateSettings()); } else { FilePath mrSettings = getModuleRoot().child(project.getAlternateSettings()); FilePath wsSettings = getWorkspace().child(project.getAlternateSettings()); if (!wsSettings.exists() && mrSettings.exists()) wsSettings = mrSettings; margs.add("-s").add(wsSettings.getRemote()); } } margs.addTokenized(envVars.expand(project.getGoals())); if (maven3orLater) { Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName, List<MavenReporter>>(project.sortedActiveModules.size()); for (MavenModule mavenModule : project.sortedActiveModules) { reporters.put( mavenModule.getModuleName(), mavenModule.createReporters() ); } Maven3Builder maven3Builder = new Maven3Builder( slistener, proxies, reporters, margs.toList(), envVars ); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(maven3Builder); return r; } finally { maven3Builder.end(launcher); getActions().remove(mpa); process.discard(); } } else { Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(builder); return r; } finally { builder.end(launcher); getActions().remove(mpa); process.discard(); } } } finally { if (r != null) { setResult(r); } // tear down in reverse order boolean failed=false; for( int i=buildEnvironments.size()-1; i>=0; i-- ) { if (!buildEnvironments.get(i).tearDown(MavenModuleSetBuild.this,listener)) { failed=true; } } // WARNING The return in the finally clause will trump any return before if (failed) return Result.FAILURE; } } return r; } catch (AbortException e) { if(e.getMessage()!=null) listener.error(e.getMessage()); return Result.FAILURE; } catch (InterruptedIOException e) { e.printStackTrace(listener.error("Aborted Maven execution for InterruptedIOException")); return Result.ABORTED; } catch (IOException e) { e.printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); return Result.FAILURE; } catch (RunnerAbortedException e) { return Result.FAILURE; } catch (RuntimeException e) { // bug in the code. e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to [email protected]")); logger.println("project="+project); logger.println("project.getModules()="+project.getModules()); logger.println("project.getRootModule()="+project.getRootModule()); throw e; } } private void parsePoms(BuildListener listener, PrintStream logger, EnvVars envVars, MavenInstallation mvn) throws IOException, InterruptedException { logger.println("Parsing POMs"); List<PomInfo> poms; try { poms = getModuleRoot().act(new PomParser(listener, mvn, project)); } catch (IOException e) { if (e.getCause() instanceof AbortException) throw (AbortException) e.getCause(); throw e; } catch (MavenExecutionException e) { // Maven failed to parse POM e.getCause().printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); throw new AbortException(); } // update the module list Map<ModuleName,MavenModule> modules = project.modules; synchronized(modules) { Map<ModuleName,MavenModule> old = new HashMap<ModuleName, MavenModule>(modules); List<MavenModule> sortedModules = new ArrayList<MavenModule>(); modules.clear(); if(debug) logger.println("Root POM is "+poms.get(0).name); project.reconfigure(poms.get(0)); for (PomInfo pom : poms) { MavenModule mm = old.get(pom.name); if(mm!=null) {// found an existing matching module if(debug) logger.println("Reconfiguring "+mm); mm.reconfigure(pom); modules.put(pom.name,mm); } else {// this looks like a new module logger.println(Messages.MavenModuleSetBuild_DiscoveredModule(pom.name,pom.displayName)); mm = new MavenModule(project,pom,getNumber()); modules.put(mm.getModuleName(),mm); } sortedModules.add(mm); mm.save(); } // at this point the list contains all the live modules project.sortedActiveModules = sortedModules; // remaining modules are no longer active. old.keySet().removeAll(modules.keySet()); for (MavenModule om : old.values()) { if(debug) logger.println("Disabling "+om); om.makeDisabled(true); } modules.putAll(old); } // we might have added new modules Hudson.getInstance().rebuildDependencyGraph(); // module builds must start with this build's number for (MavenModule m : modules.values()) m.updateNextBuildNumber(getNumber()); } protected void post2(BuildListener listener) throws Exception { // asynchronous executions from the build might have left some unsaved state, // so just to be safe, save them all. for (MavenBuild b : getModuleLastBuilds().values()) b.save(); // at this point the result is all set, so ignore the return value if (!performAllBuildSteps(listener, project.getPublishers(), true)) setResult(FAILURE); if (!performAllBuildSteps(listener, project.getProperties(), true)) setResult(FAILURE); // aggregate all module fingerprints to us, // so that dependencies between module builds can be understood as // dependencies between module set builds. // TODO: we really want to implement this as a publisher, // but we don't want to ask for a user configuration, nor should it // show up in the persisted record. MavenFingerprinter.aggregate(MavenModuleSetBuild.this); } @Override public void cleanUp(BuildListener listener) throws Exception { MavenMailer mailer = project.getReporters().get(MavenMailer.class); if (mailer != null) { new MailSender(mailer.recipients, mailer.dontNotifyEveryUnstableBuild, mailer.sendToIndividuals).execute(MavenModuleSetBuild.this, listener); } // too late to set the build result at this point. so ignore failures. performAllBuildSteps(listener, project.getPublishers(), false); performAllBuildSteps(listener, project.getProperties(), false); super.cleanUp(listener); } } /** * Runs Maven and builds the project. * * This is only used for * {@link MavenModuleSet#isAggregatorStyleBuild() the aggregator style build}. */ private static final class Builder extends MavenBuilder { private final Map<ModuleName,MavenBuildProxy2> proxies; private final Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName,List<MavenReporter>>(); private final Map<ModuleName,List<ExecutedMojo>> executedMojos = new HashMap<ModuleName,List<ExecutedMojo>>(); private long mojoStartTime; private MavenBuildProxy2 lastProxy; /** * Kept so that we can finalize them in the end method. */ private final transient Map<ModuleName,ProxyImpl2> sourceProxies; public Builder(BuildListener listener,Map<ModuleName,ProxyImpl2> proxies, Collection<MavenModule> modules, List<String> goals, Map<String,String> systemProps) { super(listener,goals,systemProps); this.sourceProxies = proxies; this.proxies = new HashMap<ModuleName, MavenBuildProxy2>(proxies); for (Entry<ModuleName,MavenBuildProxy2> e : this.proxies.entrySet()) e.setValue(new FilterImpl(e.getValue())); for (MavenModule m : modules) reporters.put(m.getModuleName(),m.createReporters()); } private class FilterImpl extends MavenBuildProxy2.Filter<MavenBuildProxy2> implements Serializable { public FilterImpl(MavenBuildProxy2 core) { super(core); } @Override public void executeAsync(final BuildCallable<?,?> program) throws IOException { futures.add(Channel.current().callAsync(new AsyncInvoker(core,program))); } private static final long serialVersionUID = 1L; } /** * Invoked after the maven has finished running, and in the master, not in the maven process. */ void end(Launcher launcher) throws IOException, InterruptedException { for (Map.Entry<ModuleName,ProxyImpl2> e : sourceProxies.entrySet()) { ProxyImpl2 p = e.getValue(); for (MavenReporter r : reporters.get(e.getKey())) { // we'd love to do this when the module build ends, but doing so requires // we know how many task segments are in the current build. r.end(p.owner(),launcher,listener); p.appendLastLog(); } p.close(); } } @Override public Result call() throws IOException { try { System.out.println("Builder extends MavenBuilder in call " + Thread.currentThread().getContextClassLoader()); return super.call(); } finally { if(lastProxy!=null) lastProxy.appendLastLog(); } } @Override void preBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException { // set all modules which are not actually being build (in incremental builds) to NOT_BUILD @SuppressWarnings("unchecked") List<MavenProject> projects = rm.getSortedProjects(); Set<ModuleName> buildingProjects = new HashSet<ModuleName>(); for (MavenProject p : projects) { buildingProjects.add(new ModuleName(p)); } for (Entry<ModuleName,MavenBuildProxy2> e : this.proxies.entrySet()) { if (! buildingProjects.contains(e.getKey())) { MavenBuildProxy2 proxy = e.getValue(); proxy.start(); proxy.setResult(Result.NOT_BUILT); proxy.end(); } } } void postBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException { // TODO } void preModule(MavenProject project) throws InterruptedException, IOException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy2 proxy = proxies.get(name); listener.getLogger().flush(); // make sure the data until here are all written proxy.start(); for (MavenReporter r : reporters.get(name)) if(!r.preBuild(proxy,project,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); } void postModule(MavenProject project) throws InterruptedException, IOException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy2 proxy = proxies.get(name); List<MavenReporter> rs = reporters.get(name); if(rs==null) { // probe for issue #906 throw new AssertionError("reporters.get("+name+")==null. reporters="+reporters+" proxies="+proxies); } for (MavenReporter r : rs) if(!r.postBuild(proxy,project,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); proxy.setExecutedMojos(executedMojos.get(name)); listener.getLogger().flush(); // make sure the data until here are all written proxy.end(); lastProxy = proxy; } void preExecute(MavenProject project, MojoInfo mojoInfo) throws IOException, InterruptedException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy proxy = proxies.get(name); for (MavenReporter r : reporters.get(name)) if(!r.preExecute(proxy,project,mojoInfo,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); mojoStartTime = System.currentTimeMillis(); } void postExecute(MavenProject project, MojoInfo mojoInfo, Exception exception) throws IOException, InterruptedException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); List<ExecutedMojo> mojoList = executedMojos.get(name); if(mojoList==null) executedMojos.put(name,mojoList=new ArrayList<ExecutedMojo>()); mojoList.add(new ExecutedMojo(mojoInfo,System.currentTimeMillis()-mojoStartTime)); MavenBuildProxy2 proxy = proxies.get(name); for (MavenReporter r : reporters.get(name)) if(!r.postExecute(proxy,project,mojoInfo,listener,exception)) throw new hudson.maven.agent.AbortException(r+" failed"); if(exception!=null) proxy.setResult(Result.FAILURE); } void onReportGenerated(MavenProject project, MavenReportInfo report) throws IOException, InterruptedException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy proxy = proxies.get(name); for (MavenReporter r : reporters.get(name)) if(!r.reportGenerated(proxy,project,report,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); } private static final long serialVersionUID = 1L; @Override public ClassLoader getClassLoader() { return new MaskingClassLoader( super.getClassLoader() ); } } /** * Used to tunnel exception from Maven through remoting. */ private static final class MavenExecutionException extends RuntimeException { private MavenExecutionException(Exception cause) { super(cause); } @Override public Exception getCause() { return (Exception)super.getCause(); } private static final long serialVersionUID = 1L; } /** * Executed on the slave to parse POM and extract information into {@link PomInfo}, * which will be then brought back to the master. */ private static final class PomParser implements FileCallable<List<PomInfo>> { private final BuildListener listener; private final String rootPOM; /** * Capture the value of the static field so that the debug flag * takes an effect even when {@link PomParser} runs in a slave. */ private final boolean verbose = debug; private final MavenInstallation mavenHome; private final String profiles; private final Properties properties; private final String privateRepository; private final String alternateSettings; private final boolean nonRecursive; // We're called against the module root, not the workspace, which can cause a lot of confusion. private final String workspaceProper; public PomParser(BuildListener listener, MavenInstallation mavenHome, MavenModuleSet project) { // project cannot be shipped to the remote JVM, so all the relevant properties need to be captured now. this.listener = listener; this.mavenHome = mavenHome; this.rootPOM = project.getRootPOM(); this.profiles = project.getProfiles(); this.properties = project.getMavenProperties(); this.nonRecursive = project.isNonRecursive(); this.workspaceProper = project.getLastBuild().getWorkspace().getRemote(); if (project.usesPrivateRepository()) { this.privateRepository = project.getLastBuild().getWorkspace().child(".repository").getRemote(); } else { this.privateRepository = null; } this.alternateSettings = project.getAlternateSettings(); } /** * Computes the path of {@link #rootPOM}. * * Returns "abc" if rootPOM="abc/pom.xml" * If rootPOM="pom.xml", this method returns "". */ private String getRootPath(String prefix) { int idx = Math.max(rootPOM.lastIndexOf('/'), rootPOM.lastIndexOf('\\')); if(idx==-1) return ""; return prefix + rootPOM.substring(0,idx); } public List<PomInfo> invoke(File ws, VirtualChannel channel) throws IOException { File pom; String rootPOMRelPrefix; PrintStream logger = listener.getLogger(); if (IOUtils.isAbsolute(rootPOM)) { pom = new File(rootPOM); } else { // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) pom = new File(ws, rootPOM); File parentLoc = new File(ws.getParentFile(),rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; } if(!pom.exists()) throw new AbortException(Messages.MavenModuleSetBuild_NoSuchPOMFile(pom)); if (rootPOM.startsWith("../") || rootPOM.startsWith("..\\")) { File wsp = new File(workspaceProper); if (!ws.equals(wsp)) { rootPOMRelPrefix = ws.getCanonicalPath().substring(wsp.getCanonicalPath().length()+1)+"/"; } else { rootPOMRelPrefix = wsp.getName() + "/"; } } else { rootPOMRelPrefix = ""; } if(verbose) logger.println("Parsing " + (nonRecursive ? "non-recursively " : "recursively ") + pom); File settingsLoc; if (alternateSettings == null) { settingsLoc = null; } else if (IOUtils.isAbsolute(alternateSettings)) { settingsLoc = new File(alternateSettings); } else { // Check for settings.xml first in the workspace proper, and then in the current directory, // which is getModuleRoot(). // This is backwards from the order the root POM logic uses, but it's to be consistent with the Maven execution logic. settingsLoc = new File(workspaceProper, alternateSettings); File mrSettingsLoc = new File(workspaceProper, alternateSettings); if (!settingsLoc.exists() && mrSettingsLoc.exists()) settingsLoc = mrSettingsLoc; } if ((settingsLoc != null) && (!settingsLoc.exists())) { throw new AbortException(Messages.MavenModuleSetBuild_NoSuchAlternateSettings(settingsLoc.getAbsolutePath())); } try { MavenEmbedder embedder = MavenUtil. createEmbedder(listener, mavenHome.getHomeDir(), profiles, properties, privateRepository, settingsLoc); MavenProject mp = embedder.readProject(pom); Map<MavenProject,String> relPath = new HashMap<MavenProject,String>(); MavenUtil.resolveModules(embedder,mp,getRootPath(rootPOMRelPrefix),relPath,listener,nonRecursive); if(verbose) { for (Entry<MavenProject, String> e : relPath.entrySet()) logger.printf("Discovered %s at %s\n",e.getKey().getId(),e.getValue()); } List<PomInfo> infos = new ArrayList<PomInfo>(); toPomInfo(mp,null,relPath,infos); for (PomInfo pi : infos) pi.cutCycle(); return infos; } catch (MavenEmbedderException e) { throw new MavenExecutionException(e); } catch (ProjectBuildingException e) { throw new MavenExecutionException(e); } } private void toPomInfo(MavenProject mp, PomInfo parent, Map<MavenProject,String> relPath, List<PomInfo> infos) { PomInfo pi = new PomInfo(mp, parent, relPath.get(mp)); infos.add(pi); for (MavenProject child : (List<MavenProject>)mp.getCollectedProjects()) toPomInfo(child,pi,relPath,infos); } private static final long serialVersionUID = 1L; } private static final Logger LOGGER = Logger.getLogger(MavenModuleSetBuild.class.getName()); /** * Extra verbose debug switch. */ public static boolean debug = false; @Override public MavenModuleSet getParent() {// don't know why, but javac wants this return super.getParent(); } }
false
true
protected Result doRun(final BuildListener listener) throws Exception { PrintStream logger = listener.getLogger(); Result r = null; try { EnvVars envVars = getEnvironment(listener); MavenInstallation mvn = project.getMaven(); if(mvn==null) throw new AbortException("A Maven installation needs to be available for this project to be built.\n"+ "Either your server has no Maven installations defined, or the requested Maven version does not exist."); mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener); String mavenVersion = getModuleRoot().act( new MavenVersionCallable( mvn.getHome() )); if(!project.isAggregatorStyleBuild()) { parsePoms(listener, logger, envVars, mvn); // start module builds logger.println("Triggering "+project.getRootModule().getModuleName()); project.getRootModule().scheduleBuild(new UpstreamCause((Run<?,?>)MavenModuleSetBuild.this)); } else { // do builds here try { List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>(); for (BuildWrapper w : project.getBuildWrappersList()) wrappers.add(w); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) parameters.createBuildWrappers(MavenModuleSetBuild.this,wrappers); for( BuildWrapper w : wrappers) { Environment e = w.setUp(MavenModuleSetBuild.this, launcher, listener); if(e==null) return (r = Result.FAILURE); buildEnvironments.add(e); e.buildEnvVars(envVars); // #3502: too late for getEnvironment to do this } if(!preBuild(listener, project.getPublishers())) return Result.FAILURE; parsePoms(listener, logger, envVars, mvn); // #5428 : do pre-build *before* parsing pom SplittableBuildListener slistener = new SplittableBuildListener(listener); proxies = new HashMap<ModuleName, ProxyImpl2>(); List<String> changedModules = new ArrayList<String>(); for (MavenModule m : project.sortedActiveModules) { MavenBuild mb = m.newBuild(); // Check if incrementalBuild is selected and that there are changes - // we act as if incrementalBuild is not set if there are no changes. if (!MavenModuleSetBuild.this.getChangeSet().isEmptySet() && project.isIncrementalBuild()) { //If there are changes for this module, add it. // Also add it if we've never seen this module before, // or if the previous build of this module failed or was unstable. if ((mb.getPreviousBuiltBuild() == null) || (!getChangeSetFor(m).isEmpty()) || (mb.getPreviousBuiltBuild().getResult().isWorseThan(Result.SUCCESS))) { changedModules.add(m.getModuleName().toString()); } } mb.setWorkspace(getModuleRoot().child(m.getRelativePath())); proxies.put(m.getModuleName(), mb.new ProxyImpl2(MavenModuleSetBuild.this,slistener)); } // run the complete build here // figure out the root POM location. // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) String rootPOM = project.getRootPOM(); FilePath pom = getModuleRoot().child(rootPOM); FilePath parentLoc = getWorkspace().child(rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; ProcessCache.MavenProcess process = null; boolean maven3orLater = new ComparableVersion (mavenVersion).compareTo( new ComparableVersion ("3.0") ) >= 0; if (maven3orLater) { LOGGER.info( "using maven 3 " + mavenVersion ); process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener, new Maven3ProcessFactory(project,launcher,envVars,pom.getParent())); } else { process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener, new MavenProcessFactory(project,launcher,envVars,pom.getParent())); } ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote()); if(project.usesPrivateRepository()) margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository")); // If incrementalBuild is set, and we're on Maven 2.1 or later, *and* there's at least one module // listed in changedModules, do the Maven incremental build commands - if there are no changed modules, // We're building everything anyway. if (project.isIncrementalBuild() && mvn.isMaven2_1(launcher) && !changedModules.isEmpty()) { margs.add("-amd"); margs.add("-pl", Util.join(changedModules, ",")); } if (project.getAlternateSettings() != null) { if (IOUtils.isAbsolute(project.getAlternateSettings())) { margs.add("-s").add(project.getAlternateSettings()); } else { FilePath mrSettings = getModuleRoot().child(project.getAlternateSettings()); FilePath wsSettings = getWorkspace().child(project.getAlternateSettings()); if (!wsSettings.exists() && mrSettings.exists()) wsSettings = mrSettings; margs.add("-s").add(wsSettings.getRemote()); } } margs.addTokenized(envVars.expand(project.getGoals())); if (maven3orLater) { Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName, List<MavenReporter>>(project.sortedActiveModules.size()); for (MavenModule mavenModule : project.sortedActiveModules) { reporters.put( mavenModule.getModuleName(), mavenModule.createReporters() ); } Maven3Builder maven3Builder = new Maven3Builder( slistener, proxies, reporters, margs.toList(), envVars ); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(maven3Builder); return r; } finally { maven3Builder.end(launcher); getActions().remove(mpa); process.discard(); } } else { Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(builder); return r; } finally { builder.end(launcher); getActions().remove(mpa); process.discard(); } } } finally { if (r != null) { setResult(r); } // tear down in reverse order boolean failed=false; for( int i=buildEnvironments.size()-1; i>=0; i-- ) { if (!buildEnvironments.get(i).tearDown(MavenModuleSetBuild.this,listener)) { failed=true; } } // WARNING The return in the finally clause will trump any return before if (failed) return Result.FAILURE; } } return r; } catch (AbortException e) { if(e.getMessage()!=null) listener.error(e.getMessage()); return Result.FAILURE; } catch (InterruptedIOException e) { e.printStackTrace(listener.error("Aborted Maven execution for InterruptedIOException")); return Result.ABORTED; } catch (IOException e) { e.printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); return Result.FAILURE; } catch (RunnerAbortedException e) { return Result.FAILURE; } catch (RuntimeException e) { // bug in the code. e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to [email protected]")); logger.println("project="+project); logger.println("project.getModules()="+project.getModules()); logger.println("project.getRootModule()="+project.getRootModule()); throw e; } }
protected Result doRun(final BuildListener listener) throws Exception { PrintStream logger = listener.getLogger(); Result r = null; try { EnvVars envVars = getEnvironment(listener); MavenInstallation mvn = project.getMaven(); if(mvn==null) throw new AbortException("A Maven installation needs to be available for this project to be built.\n"+ "Either your server has no Maven installations defined, or the requested Maven version does not exist."); mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener); String mavenVersion = getModuleRoot().act( new MavenVersionCallable( mvn.getHome() )); if(!project.isAggregatorStyleBuild()) { parsePoms(listener, logger, envVars, mvn); // start module builds logger.println("Triggering "+project.getRootModule().getModuleName()); project.getRootModule().scheduleBuild(new UpstreamCause((Run<?,?>)MavenModuleSetBuild.this)); } else { // do builds here try { List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>(); for (BuildWrapper w : project.getBuildWrappersList()) wrappers.add(w); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) parameters.createBuildWrappers(MavenModuleSetBuild.this,wrappers); for( BuildWrapper w : wrappers) { Environment e = w.setUp(MavenModuleSetBuild.this, launcher, listener); if(e==null) return (r = Result.FAILURE); buildEnvironments.add(e); e.buildEnvVars(envVars); // #3502: too late for getEnvironment to do this } if(!preBuild(listener, project.getPublishers())) return Result.FAILURE; parsePoms(listener, logger, envVars, mvn); // #5428 : do pre-build *before* parsing pom SplittableBuildListener slistener = new SplittableBuildListener(listener); proxies = new HashMap<ModuleName, ProxyImpl2>(); List<String> changedModules = new ArrayList<String>(); for (MavenModule m : project.sortedActiveModules) { MavenBuild mb = m.newBuild(); // Check if incrementalBuild is selected and that there are changes - // we act as if incrementalBuild is not set if there are no changes. if (!MavenModuleSetBuild.this.getChangeSet().isEmptySet() && project.isIncrementalBuild()) { //If there are changes for this module, add it. // Also add it if we've never seen this module before, // or if the previous build of this module failed or was unstable. if ((mb.getPreviousBuiltBuild() == null) || (!getChangeSetFor(m).isEmpty()) || (mb.getPreviousBuiltBuild().getResult().isWorseThan(Result.SUCCESS))) { changedModules.add(m.getModuleName().toString()); } } mb.setWorkspace(getModuleRoot().child(m.getRelativePath())); proxies.put(m.getModuleName(), mb.new ProxyImpl2(MavenModuleSetBuild.this,slistener)); } // run the complete build here // figure out the root POM location. // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) String rootPOM = project.getRootPOM(); FilePath pom = getModuleRoot().child(rootPOM); FilePath parentLoc = getWorkspace().child(rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; ProcessCache.MavenProcess process = null; boolean maven3orLater = new ComparableVersion (mavenVersion).compareTo( new ComparableVersion ("3.0") ) >= 0; if ( maven3orLater ) { LOGGER.info( "using maven 3 " + mavenVersion ); process = MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, new Maven3ProcessFactory( project, launcher, envVars, pom.getParent() ) ); } else { process = MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, new MavenProcessFactory( project, launcher, envVars, pom.getParent() ) ); } ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote()); if(project.usesPrivateRepository()) margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository")); // If incrementalBuild is set, and we're on Maven 2.1 or later, *and* there's at least one module // listed in changedModules, do the Maven incremental build commands - if there are no changed modules, // We're building everything anyway. if (project.isIncrementalBuild() && mvn.isMaven2_1(launcher) && !changedModules.isEmpty()) { margs.add("-amd"); margs.add("-pl", Util.join(changedModules, ",")); } if (project.getAlternateSettings() != null) { if (IOUtils.isAbsolute(project.getAlternateSettings())) { margs.add("-s").add(project.getAlternateSettings()); } else { FilePath mrSettings = getModuleRoot().child(project.getAlternateSettings()); FilePath wsSettings = getWorkspace().child(project.getAlternateSettings()); if (!wsSettings.exists() && mrSettings.exists()) wsSettings = mrSettings; margs.add("-s").add(wsSettings.getRemote()); } } margs.addTokenized(envVars.expand(project.getGoals())); if (maven3orLater) { Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName, List<MavenReporter>>(project.sortedActiveModules.size()); for (MavenModule mavenModule : project.sortedActiveModules) { reporters.put( mavenModule.getModuleName(), mavenModule.createReporters() ); } Maven3Builder maven3Builder = new Maven3Builder( slistener, proxies, reporters, margs.toList(), envVars ); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(maven3Builder); return r; } finally { maven3Builder.end(launcher); getActions().remove(mpa); process.discard(); } } else { Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(builder); return r; } finally { builder.end(launcher); getActions().remove(mpa); process.discard(); } } } finally { if (r != null) { setResult(r); } // tear down in reverse order boolean failed=false; for( int i=buildEnvironments.size()-1; i>=0; i-- ) { if (!buildEnvironments.get(i).tearDown(MavenModuleSetBuild.this,listener)) { failed=true; } } // WARNING The return in the finally clause will trump any return before if (failed) return Result.FAILURE; } } return r; } catch (AbortException e) { if(e.getMessage()!=null) listener.error(e.getMessage()); return Result.FAILURE; } catch (InterruptedIOException e) { e.printStackTrace(listener.error("Aborted Maven execution for InterruptedIOException")); return Result.ABORTED; } catch (IOException e) { e.printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); return Result.FAILURE; } catch (RunnerAbortedException e) { return Result.FAILURE; } catch (RuntimeException e) { // bug in the code. e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to [email protected]")); logger.println("project="+project); logger.println("project.getModules()="+project.getModules()); logger.println("project.getRootModule()="+project.getRootModule()); throw e; } }
diff --git a/java/de/dfki/lt/mary/MaryServer.java b/java/de/dfki/lt/mary/MaryServer.java index 0acf715b7..a695a3d69 100755 --- a/java/de/dfki/lt/mary/MaryServer.java +++ b/java/de/dfki/lt/mary/MaryServer.java @@ -1,858 +1,859 @@ /** * Copyright 2000-2006 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * Permission is hereby granted, free of charge, to use and distribute * this software and its documentation without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of this work, and to * permit persons to whom this work is furnished to do so, subject to * the following conditions: * * 1. The code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Any modifications must be clearly marked as such. * 3. Original authors' names are not deleted. * 4. The authors' names are not used to endorse or promote products * derived from this software without specific prior written * permission. * * DFKI GMBH AND THE CONTRIBUTORS TO THIS WORK DISCLAIM ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DFKI GMBH NOR THE * CONTRIBUTORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ package de.dfki.lt.mary; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.net.ServerSocket; import java.net.Socket; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import org.apache.log4j.Logger; import de.dfki.lt.mary.modules.synthesis.Voice; import de.dfki.lt.mary.unitselection.UnitSelectionVoice; import de.dfki.lt.mary.unitselection.interpolation.InterpolatingVoice; import de.dfki.lt.mary.util.MaryAudioUtils; import de.dfki.lt.signalproc.effects.BaseAudioEffect; import de.dfki.lt.signalproc.effects.EffectsApplier; /** * Listen for clients on socket port * <code>MaryProperties.socketPort()</code>. * For each new client, create a new RequestHandler thread. * <p> * Clients are expected to follow the following <b>protocol</b>: * <p> * A client opens two socket connections to the server. The first, * <code>infoSocket</code>, serves for passing meta-information, * such as the requested input and output types or warnings. * The second, <code>dataSocket</code>, serves for passing the actual * input and output data. * The server expects the communication as follows. * <ol> * <li> The client opens an <code>infoSocket</code>, * optionally sends one line "MARY VERSION" to obtain * three lines of version information, and then sends one line * "MARY IN=INPUTTYPE OUT=OUTPUTTYPE [AUDIO=AUDIOTYPE]", * where INPUTTYPE and OUTPUTTYPE can have a number of different values, * depending on the configuration with which the server was started. * For an English system, these values include: * <ul> * <li> TEXT_EN plain ASCII text, English (input only) </li> * <li> SABLE text annotated with SABLE markup (input only) </li> * <li> SSML text annotated with SSML markup (input only) </li> * <li> APML text annotated with APML markup (input only) </li> * <li> RAWMARYXML untokenised MaryXML </li> * <li> TOKENS_EN tokenized text </li> * <li> WORDS_EN numbers and abbreviations expanded </li> * <li> POS_EN parts of speech tags added </li> * <li> SEGMENTS_EN phoneme symbols </li> * <li> INTONATION_EN ToBI intonation symbols </li> * <li> POSTPROCESSED_EN post-lexical phonological rules </li> * <li> ACOUSTPARAMS acoustic parameters in MaryXML structure </li> * <li> MBROLA phone symbols, duration and frequency values </li> * <li> AUDIO audio data (output only) </li> * </ul> * INPUTTYPE must be earlier in this list than OUTPUTTYPE. * The list of input and output data types can be requested from the server by * sending it a line "MARY LIST DATATYPES". The server will reply with a list of lines * where each line represents one data type, e.g. "RAWMARYXML INPUT OUTPUT", "TEXT_DE LOCALE=de INPUT" or "AUDIO OUTPUT". * See the code in MaryClient.fillDataTypes(). * <p> * The optional AUDIO=AUDIOTYPE specifies the type of audio file * to be sent for audio output. Possible values are: * <ul> * <li> WAVE </li> * <li> AU </li> * <li> SND </li> * <li> AIFF </li> * <li> AIFC </li> * <li> MP3 </li> * <li> Vorbis </li> * <li> STREAMING_AU</li> * <li> STREAMING_MP3</li> * </ul> * <p> * The optional VOICE=VOICENAME specifies the default voice with which * the text is to be spoken. As for the data types, possible values * depend on the configuration of the server. The list can be retrieved * by sending the server a line "MARY LIST VOICES", which will reply with * lines such as "de7 de female", "kevin16 en male" or "us2 en male". * <p> * The optional EFFECTS=EFFECTSWITHPARAMETERS specifies the audio effects * to be applied as a post-processing step along with their parameters. * EFFECTSWITHPARAMETERS is a String of the form * "Effect1Name(Effect1Parameter1=Effect1Value1; Effect1Parameter2=Effect1Value2), Effect2Name(Effect2Parameter1=Effect2Value1)" * For example, "Robot(amount=100),Whisper(amount=50)" will convert the output into * a whispered robotic voice with the specified amounts. * <p> * Example: The line * <pre> * MARY IN=TEXT_EN OUT=AUDIO AUDIO=WAVE VOICE=kevin16 EFFECTS * </pre> * will process normal ASCII text, and send back a WAV audio file * synthesised with the voice "kevin16". * </li> * * <li> The server reads and parses this input line. If its format is correct, * a line containing a single integer is sent back to the client * on <code>infoSocket</code>. This * integer is a unique identification number for this request. * </li> * * <li> The client opens a second socket connection to the server, on the same * port, the <code>dataSocket</code>. As a first line on this * <code>dataSocket</code>, * it sends the single integer it had just received via the * <code>infoSocket</code>. * </li> * * <li> The server groups dataSocket and infoSocket together based on this * identification number, and starts reading data of the requested input * type from <code>dataSocket</code>. * </li> * * <li> If any errors or warning messages are issued during input parsing or * consecutive processing, these are printed to <code>infoSocket</code>. * </li> * * <li> The processing result is output to <code>dataSocket</code>. * </li> * </ol> * * @see RequestHandler * @author Marc Schr&ouml;der */ public class MaryServer { private ServerSocket server; private Logger logger; private int runningNumber = 1; private Map<Integer,Object[]> clientMap; public MaryServer() { logger = Logger.getLogger("server"); } public void run() throws IOException, NoSuchPropertyException { logger.info("Starting server."); clientMap = Collections.synchronizedMap(new HashMap<Integer,Object[]>()); server = new ServerSocket(MaryProperties.needInteger("socket.port")); while (true) { logger.info("Waiting for client to connect on port " + server.getLocalPort()); Socket client = server.accept(); logger.info( "Connection from " + client.getInetAddress().getHostName() + " (" + client.getInetAddress().getHostAddress() + ")."); new ClientHandler(client).start(); } } private int getID() { return runningNumber++; } public class ClientHandler extends Thread { Socket client; public ClientHandler(Socket client) { this.client = client; } public void run() { logger = Logger.getLogger("server"); try { handle(); } catch (Exception e) { logger.info("Error parsing request:", e); try { PrintWriter outputWriter = new PrintWriter(client.getOutputStream(), true); outputWriter.println("Error parsing request:"); outputWriter.println(e.getMessage()); outputWriter.close(); client.close(); } catch (IOException ioe) { logger.info("Cannot write to client."); } } } /** * Implement the protocol for communicating with a socket client. */ private void handle() throws Exception { // !!!! reject all clients that are not from authorized domains? // Read one line from client BufferedReader buffReader = null; PrintWriter outputWriter = null; String line = null; buffReader = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8")); outputWriter = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), "UTF-8"), true); line = buffReader.readLine(); logger.debug("read request: `"+line+"'"); if (line == null) { logger.info("Client seems to have disconnected - cannot read."); return; } // A: General information request, no synthesis. // This may consist of one or several lines of info requests and // may either stand alone or precede another request. while (handleInfoRequest(line, outputWriter)) { // In case this precedes another request, try to read another line: line = buffReader.readLine(); if (line == null) return; } // VARIANT B1: Synthesis request. if (handleSynthesisRequest(line, outputWriter)) { return; // VARIANT B2: Second connection of synthesis request. } else if (handleNumberRequest(line, buffReader)) { return; } else { // complain String nl = System.getProperty("line.separator"); throw new Exception( "Expected either a line" + nl + "MARY IN=<INPUTTYPE> OUT=<OUTPUTTYPE> [AUDIO=<AUDIOTYPE>]" + nl + "or a line containing only a number identifying a request."); } } private boolean handleInfoRequest(String inputLine, PrintWriter outputWriter) { // Optional version information: if (inputLine.startsWith("MARY VERSION")) { logger.debug("InfoRequest " + inputLine); // Write version information to client. outputWriter.println("Mary TTS server " + Version.specificationVersion() + " (impl. " + Version.implementationVersion() + ")"); // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY LIST DATATYPES")) { logger.debug("InfoRequest " + inputLine); // List all known datatypes Vector allTypes = MaryDataType.getDataTypes(); for (Iterator it = allTypes.iterator(); it.hasNext();) { MaryDataType t = (MaryDataType) it.next(); outputWriter.print(t.name()); if (t.getLocale() != null) outputWriter.print(" LOCALE=" + t.getLocale()); if (t.isInputType()) outputWriter.print(" INPUT"); if (t.isOutputType()) outputWriter.print(" OUTPUT"); outputWriter.println(); } // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY LIST VOICES")) { logger.debug("InfoRequest " + inputLine); // list all known voices Collection voices = Voice.getAvailableVoices(); for (Iterator it = voices.iterator(); it.hasNext();) { Voice v = (Voice) it.next(); if (v instanceof InterpolatingVoice) { // do not list interpolating voice } else if (v instanceof UnitSelectionVoice){ outputWriter.println(v.getName() + " " + v.getLocale() + " " + v.gender().toString() + " " +((UnitSelectionVoice)v).getDomain());} else { outputWriter.println(v.getName() + " " + v.getLocale()+ " " + v.gender().toString()); } } // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY LIST AUDIOFILEFORMATTYPES")) { logger.debug("InfoRequest " + inputLine); AudioFileFormat.Type[] audioTypes = AudioSystem.getAudioFileTypes(); for (int t=0; t<audioTypes.length; t++) { outputWriter.println(audioTypes[t].getExtension()+" "+audioTypes[t].toString()); } // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY EXAMPLETEXT")) { logger.debug("InfoRequest " + inputLine); // send an example text for a given data type StringTokenizer st = new StringTokenizer(inputLine); // discard two tokens (MARY and EXAMPLETEXT) st.nextToken(); st.nextToken(); if (st.hasMoreTokens()) { String typeName = st.nextToken(); - if (MaryDataType.exists(typeName)) { + try { MaryDataType type = MaryDataType.get(typeName); + // if we get here, the type exists assert type != null; String exampleText = type.exampleText(); if (exampleText != null) outputWriter.println(exampleText.trim()); - } + } catch (Error err) {} // type doesn't exist } // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE EXAMPLETEXT")) { //the request is about the example text of //a limited domain unit selection voice logger.debug("InfoRequest " + inputLine); // send an example text for a given data type StringTokenizer st = new StringTokenizer(inputLine); // discard three tokens (MARY, VOICE, and EXAMPLETEXT) st.nextToken(); st.nextToken(); st.nextToken(); if (st.hasMoreTokens()) { String voiceName = st.nextToken(); Voice v = Voice.getVoice(voiceName); if (v != null) { String text = ((de.dfki.lt.mary.unitselection.UnitSelectionVoice) v).getExampleText(); outputWriter.println(text); } } // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTS")) { //the request is about the available audio effects logger.debug("InfoRequest " + inputLine); // <EffectSeparator>charEffectSeparator</EffectSeparator> // <Effect> // <Name>effect´s name</Name> // <SampleParam>example parameters string</SampleParam> // <HelpText>help text string</HelpText> // </Effect> // <Effect> // <Name>effect´s name</effectName> // <SampleParam>example parameters string</SampleParam> // <HelpText>help text string</HelpText> // </Effect> // ... // <Effect> // <Name>effect´s name</effectName> // <SampleParam>example parameters string</SampleParam> // <HelpText>help text string</HelpText> // </Effect> String audioEffectClass = "<EffectSeparator>" + EffectsApplier.chEffectSeparator + "</EffectSeparator>"; for (int i=0; i<MaryProperties.effectClasses().size(); i++) { audioEffectClass += "<Effect>"; audioEffectClass += "<Name>" + MaryProperties.effectNames().elementAt(i) + "</Name>"; audioEffectClass += "<Param>" + MaryProperties.effectParams().elementAt(i) + "</Param>"; audioEffectClass += "<SampleParam>" + MaryProperties.effectSampleParams().elementAt(i) + "</SampleParam>"; audioEffectClass += "<HelpText>" + MaryProperties.effectHelpTexts().elementAt(i) + "</HelpText>"; audioEffectClass += "</Effect>"; } outputWriter.println(audioEffectClass); // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTHELPTEXTLINEBREAK")) { logger.debug("InfoRequest " + inputLine); outputWriter.println(BaseAudioEffect.strLineBreak); // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTPARAM ")) { for (int i=0; i<MaryProperties.effectNames().size(); i++) { int tmpInd = inputLine.indexOf("MARY VOICE GETAUDIOEFFECTPARAM "+MaryProperties.effectNames().elementAt(i)); if (tmpInd>-1) { //the request is about the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { String audioEffectParams = MaryProperties.effectParams().elementAt(i); outputWriter.println(audioEffectParams.trim()); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else if (inputLine.startsWith("MARY VOICE GETFULLAUDIOEFFECT ")) { for (int i=0; i<MaryProperties.effectNames().size(); i++) { int tmpInd = inputLine.indexOf("MARY VOICE GETFULLAUDIOEFFECT "+MaryProperties.effectNames().elementAt(i)); if (tmpInd>-1) { //the request is about the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { ae.setParams(MaryProperties.effectParams().elementAt(i)); String audioEffectFull = ae.getFullEffectAsString(); outputWriter.println(audioEffectFull.trim()); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else if (inputLine.startsWith("MARY VOICE SETAUDIOEFFECTPARAM ")) { String effectName; for (int i=0; i<MaryProperties.effectNames().size(); i++) { effectName = MaryProperties.effectNames().elementAt(i); int tmpInd = inputLine.indexOf("MARY VOICE SETAUDIOEFFECTPARAM " + effectName); if (tmpInd>-1) { //the request is about changing the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); int ind = inputLine.indexOf(effectName); String strTmp = inputLine.substring(ind, inputLine.length()); int ind2 = strTmp.indexOf('_'); String strParamNew = strTmp.substring(ind2+1, strTmp.length()); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { ae.setParams(strParamNew); String audioEffectParams = ae.getParamsAsString(false); MaryProperties.effectParams().set(i, audioEffectParams); outputWriter.println(audioEffectParams); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTHELPTEXT ")) { for (int i=0; i<MaryProperties.effectNames().size(); i++) { int tmpInd = inputLine.indexOf("MARY VOICE GETAUDIOEFFECTHELPTEXT " + MaryProperties.effectNames().elementAt(i)); if (tmpInd>-1) { //the request is about the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { String helpText = ae.getHelpText(); outputWriter.println(helpText.trim()); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else return false; } private boolean handleSynthesisRequest(String inputLine, PrintWriter outputWriter) throws Exception { int id = 0; // * if MARY ..., then if (inputLine.startsWith("MARY")) { StringTokenizer t = new StringTokenizer(inputLine); String helper = null; MaryDataType inputType = null; MaryDataType outputType = null; Voice voice = null; String style = ""; String effects = ""; AudioFileFormat.Type audioFileFormatType = null; boolean streamingAudio = false; if (t.hasMoreTokens()) t.nextToken(); // discard MARY head // IN= if (t.hasMoreTokens()) { String token = t.nextToken(); StringTokenizer tt = new StringTokenizer(token, "="); if (tt.countTokens() == 2 && tt.nextToken().equals("IN")) { // The value of IN= helper = tt.nextToken(); // the input type if (MaryDataType.exists(helper)) { inputType = MaryDataType.get(helper); } else { throw new Exception("Invalid input type: " + helper); } } else { throw new Exception("Expected IN=<INPUTTYPE>"); } } else { // IN is required throw new Exception("Expected IN=<INPUTTYPE>"); } // OUT= if (t.hasMoreTokens()) { String token = t.nextToken(); StringTokenizer tt = new StringTokenizer(token, "="); if (tt.countTokens() == 2 && tt.nextToken().equals("OUT")) { // The value of OUT= helper = tt.nextToken(); // the output type if (MaryDataType.exists(helper)) { outputType = MaryDataType.get(helper); } else { throw new Exception("Invalid output type: " + helper); } } else { throw new Exception("Expected OUT=<OUTPUTTYPE>"); } } else { // OUT is required throw new Exception("Expected OUT=<OUTPUTTYPE>"); } if (t.hasMoreTokens()) { String token = t.nextToken(); boolean tokenConsumed = false; StringTokenizer tt = new StringTokenizer(token, "="); // AUDIO (optional and ignored if output type != AUDIO) if (tt.countTokens() == 2 && tt.nextToken().equals("AUDIO")) { tokenConsumed = true; if (outputType == MaryDataType.get("AUDIO")) { // The value of AUDIO= String typeString = tt.nextToken(); if (typeString.startsWith("STREAMING_")) { streamingAudio = true; audioFileFormatType = MaryAudioUtils.getAudioFileFormatType(typeString.substring(10)); } else { audioFileFormatType = MaryAudioUtils.getAudioFileFormatType(typeString); } } } else { // no AUDIO field if (outputType == MaryDataType.get("AUDIO")) { throw new Exception("Expected AUDIO=<AUDIOTYPE>"); } } if (tokenConsumed && t.hasMoreTokens()) { token = t.nextToken(); tokenConsumed = false; } // Optional VOICE field if (!tokenConsumed) { tt = new StringTokenizer(token, "="); if (tt.countTokens() == 2 && tt.nextToken().equals("VOICE")) { tokenConsumed = true; // the values of VOICE= String voiceName = tt.nextToken(); if ((voiceName.equals("male") || voiceName.equals("female")) && (inputType.getLocale() != null || outputType.getLocale() != null)) { // Locale-specific interpretation of gender Locale locale = inputType.getLocale(); if (locale == null) locale = outputType.getLocale(); voice = Voice.getVoice(locale, new Voice.Gender(voiceName)); } else { // Plain old voice name voice = Voice.getVoice(voiceName); } if (voice == null) { throw new Exception( "No voice matches `" + voiceName + "'. Use a different voice name or remove VOICE= tag from request."); } } } if (voice == null) { // no voice tag -- use locale default Locale locale = inputType.getLocale(); if (locale == null) locale = outputType.getLocale(); if (locale == null) locale = Locale.GERMAN; voice = Voice.getDefaultVoice(locale); logger.debug("No voice requested -- using default " + voice); } if (tokenConsumed && t.hasMoreTokens()) { token = t.nextToken(); tokenConsumed = false; } //Optional STYLE field style = ""; if (!tokenConsumed) { tt = new StringTokenizer(token, "="); if (tt.countTokens()==2 && tt.nextToken().equals("STYLE")) { tokenConsumed = true; // the values of STYLE= style = tt.nextToken(); } } if (style == "") logger.debug("No style requested"); else logger.debug("Style requested: " + style); if (tokenConsumed && t.hasMoreTokens()) { token = t.nextToken(); tokenConsumed = false; } // //Optional EFFECTS field effects = ""; if (!tokenConsumed) { tt = new StringTokenizer(token, "="); if (tt.countTokens()==2 && tt.nextToken().equals("EFFECTS")) { tokenConsumed = true; // the values of EFFECTS= effects = tt.nextToken(); } } if (effects == "") logger.debug("No audio effects requested"); else logger.debug("Audio effects requested: " + effects); if (tokenConsumed && t.hasMoreTokens()) { token = t.nextToken(); tokenConsumed = false; } // // Optional LOG field // If present, the rest of the line counts as the value of LOG= if (!tokenConsumed) { tt = new StringTokenizer(token, "="); if (tt.countTokens() >= 2 && tt.nextToken().equals("LOG")) { tokenConsumed = true; // the values of LOG= helper = tt.nextToken(); // Rest of line: while (t.hasMoreTokens()) helper = helper + " " + t.nextToken(); logger.info("Connection info: " + helper); } } } // Now, the parse is complete. // this request's id: id = getID(); // Construct audio file format -- even when output is not AUDIO, // in case we need to pass via audio to get our output type. AudioFileFormat audioFileFormat = null; if (audioFileFormatType == null) { audioFileFormatType = AudioFileFormat.Type.WAVE; } AudioFormat audioFormat = voice.dbAudioFormat(); if (audioFileFormatType.toString().equals("MP3")) { if (!MaryAudioUtils.canCreateMP3()) throw new UnsupportedAudioFileException("Conversion to MP3 not supported."); audioFormat = MaryAudioUtils.getMP3AudioFormat(); } else if (audioFileFormatType.toString().equals("Vorbis")) { if (!MaryAudioUtils.canCreateOgg()) throw new UnsupportedAudioFileException("Conversion to OGG Vorbis format not supported."); audioFormat = MaryAudioUtils.getOggAudioFormat(); } audioFileFormat = new AudioFileFormat(audioFileFormatType, audioFormat, AudioSystem.NOT_SPECIFIED); Request request = new Request(inputType, outputType, voice, effects, style, id, audioFileFormat, streamingAudio); outputWriter.println(id); // -- create new clientMap entry Object[] value = new Object[2]; value[0] = client; value[1] = request; clientMap.put(id, value); return true; } return false; } private boolean handleNumberRequest(String inputLine, Reader reader) throws Exception { // * if number int id = 0; try { id = Integer.parseInt(inputLine); } catch (NumberFormatException e) { return false; } // -- find corresponding infoSocket and request in clientMap Socket infoSocket = null; Request request = null; // Wait up to TIMEOUT milliseconds for the first ClientHandler // to write its clientMap entry: long TIMEOUT = 1000; long startTime = System.currentTimeMillis(); Object[] value = null; do { Thread.yield(); value = (Object[]) clientMap.get(id); } while (value == null && System.currentTimeMillis() - startTime < TIMEOUT); if (value != null) { infoSocket = (Socket) value[0]; request = (Request) value[1]; } // Verify that the request is non-null and that the // corresponding socket comes from the same IP address: if (request == null || infoSocket == null || !infoSocket.getInetAddress().equals(client.getInetAddress())) { throw new Exception("Invalid identification number."); // Don't be more specific, because in general it is none of // their business whether in principle someone else has // this id. } // -- delete clientMap entry try { clientMap.remove(id); } catch (UnsupportedOperationException e) { logger.info("Cannot remove clientMap entry", e); } // -- send off to new request RequestHandler rh = new RequestHandler(request, infoSocket, client, reader); rh.start(); return true; } } }
false
true
private boolean handleInfoRequest(String inputLine, PrintWriter outputWriter) { // Optional version information: if (inputLine.startsWith("MARY VERSION")) { logger.debug("InfoRequest " + inputLine); // Write version information to client. outputWriter.println("Mary TTS server " + Version.specificationVersion() + " (impl. " + Version.implementationVersion() + ")"); // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY LIST DATATYPES")) { logger.debug("InfoRequest " + inputLine); // List all known datatypes Vector allTypes = MaryDataType.getDataTypes(); for (Iterator it = allTypes.iterator(); it.hasNext();) { MaryDataType t = (MaryDataType) it.next(); outputWriter.print(t.name()); if (t.getLocale() != null) outputWriter.print(" LOCALE=" + t.getLocale()); if (t.isInputType()) outputWriter.print(" INPUT"); if (t.isOutputType()) outputWriter.print(" OUTPUT"); outputWriter.println(); } // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY LIST VOICES")) { logger.debug("InfoRequest " + inputLine); // list all known voices Collection voices = Voice.getAvailableVoices(); for (Iterator it = voices.iterator(); it.hasNext();) { Voice v = (Voice) it.next(); if (v instanceof InterpolatingVoice) { // do not list interpolating voice } else if (v instanceof UnitSelectionVoice){ outputWriter.println(v.getName() + " " + v.getLocale() + " " + v.gender().toString() + " " +((UnitSelectionVoice)v).getDomain());} else { outputWriter.println(v.getName() + " " + v.getLocale()+ " " + v.gender().toString()); } } // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY LIST AUDIOFILEFORMATTYPES")) { logger.debug("InfoRequest " + inputLine); AudioFileFormat.Type[] audioTypes = AudioSystem.getAudioFileTypes(); for (int t=0; t<audioTypes.length; t++) { outputWriter.println(audioTypes[t].getExtension()+" "+audioTypes[t].toString()); } // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY EXAMPLETEXT")) { logger.debug("InfoRequest " + inputLine); // send an example text for a given data type StringTokenizer st = new StringTokenizer(inputLine); // discard two tokens (MARY and EXAMPLETEXT) st.nextToken(); st.nextToken(); if (st.hasMoreTokens()) { String typeName = st.nextToken(); if (MaryDataType.exists(typeName)) { MaryDataType type = MaryDataType.get(typeName); assert type != null; String exampleText = type.exampleText(); if (exampleText != null) outputWriter.println(exampleText.trim()); } } // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE EXAMPLETEXT")) { //the request is about the example text of //a limited domain unit selection voice logger.debug("InfoRequest " + inputLine); // send an example text for a given data type StringTokenizer st = new StringTokenizer(inputLine); // discard three tokens (MARY, VOICE, and EXAMPLETEXT) st.nextToken(); st.nextToken(); st.nextToken(); if (st.hasMoreTokens()) { String voiceName = st.nextToken(); Voice v = Voice.getVoice(voiceName); if (v != null) { String text = ((de.dfki.lt.mary.unitselection.UnitSelectionVoice) v).getExampleText(); outputWriter.println(text); } } // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTS")) { //the request is about the available audio effects logger.debug("InfoRequest " + inputLine); // <EffectSeparator>charEffectSeparator</EffectSeparator> // <Effect> // <Name>effect´s name</Name> // <SampleParam>example parameters string</SampleParam> // <HelpText>help text string</HelpText> // </Effect> // <Effect> // <Name>effect´s name</effectName> // <SampleParam>example parameters string</SampleParam> // <HelpText>help text string</HelpText> // </Effect> // ... // <Effect> // <Name>effect´s name</effectName> // <SampleParam>example parameters string</SampleParam> // <HelpText>help text string</HelpText> // </Effect> String audioEffectClass = "<EffectSeparator>" + EffectsApplier.chEffectSeparator + "</EffectSeparator>"; for (int i=0; i<MaryProperties.effectClasses().size(); i++) { audioEffectClass += "<Effect>"; audioEffectClass += "<Name>" + MaryProperties.effectNames().elementAt(i) + "</Name>"; audioEffectClass += "<Param>" + MaryProperties.effectParams().elementAt(i) + "</Param>"; audioEffectClass += "<SampleParam>" + MaryProperties.effectSampleParams().elementAt(i) + "</SampleParam>"; audioEffectClass += "<HelpText>" + MaryProperties.effectHelpTexts().elementAt(i) + "</HelpText>"; audioEffectClass += "</Effect>"; } outputWriter.println(audioEffectClass); // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTHELPTEXTLINEBREAK")) { logger.debug("InfoRequest " + inputLine); outputWriter.println(BaseAudioEffect.strLineBreak); // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTPARAM ")) { for (int i=0; i<MaryProperties.effectNames().size(); i++) { int tmpInd = inputLine.indexOf("MARY VOICE GETAUDIOEFFECTPARAM "+MaryProperties.effectNames().elementAt(i)); if (tmpInd>-1) { //the request is about the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { String audioEffectParams = MaryProperties.effectParams().elementAt(i); outputWriter.println(audioEffectParams.trim()); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else if (inputLine.startsWith("MARY VOICE GETFULLAUDIOEFFECT ")) { for (int i=0; i<MaryProperties.effectNames().size(); i++) { int tmpInd = inputLine.indexOf("MARY VOICE GETFULLAUDIOEFFECT "+MaryProperties.effectNames().elementAt(i)); if (tmpInd>-1) { //the request is about the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { ae.setParams(MaryProperties.effectParams().elementAt(i)); String audioEffectFull = ae.getFullEffectAsString(); outputWriter.println(audioEffectFull.trim()); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else if (inputLine.startsWith("MARY VOICE SETAUDIOEFFECTPARAM ")) { String effectName; for (int i=0; i<MaryProperties.effectNames().size(); i++) { effectName = MaryProperties.effectNames().elementAt(i); int tmpInd = inputLine.indexOf("MARY VOICE SETAUDIOEFFECTPARAM " + effectName); if (tmpInd>-1) { //the request is about changing the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); int ind = inputLine.indexOf(effectName); String strTmp = inputLine.substring(ind, inputLine.length()); int ind2 = strTmp.indexOf('_'); String strParamNew = strTmp.substring(ind2+1, strTmp.length()); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { ae.setParams(strParamNew); String audioEffectParams = ae.getParamsAsString(false); MaryProperties.effectParams().set(i, audioEffectParams); outputWriter.println(audioEffectParams); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTHELPTEXT ")) { for (int i=0; i<MaryProperties.effectNames().size(); i++) { int tmpInd = inputLine.indexOf("MARY VOICE GETAUDIOEFFECTHELPTEXT " + MaryProperties.effectNames().elementAt(i)); if (tmpInd>-1) { //the request is about the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { String helpText = ae.getHelpText(); outputWriter.println(helpText.trim()); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else return false; }
private boolean handleInfoRequest(String inputLine, PrintWriter outputWriter) { // Optional version information: if (inputLine.startsWith("MARY VERSION")) { logger.debug("InfoRequest " + inputLine); // Write version information to client. outputWriter.println("Mary TTS server " + Version.specificationVersion() + " (impl. " + Version.implementationVersion() + ")"); // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY LIST DATATYPES")) { logger.debug("InfoRequest " + inputLine); // List all known datatypes Vector allTypes = MaryDataType.getDataTypes(); for (Iterator it = allTypes.iterator(); it.hasNext();) { MaryDataType t = (MaryDataType) it.next(); outputWriter.print(t.name()); if (t.getLocale() != null) outputWriter.print(" LOCALE=" + t.getLocale()); if (t.isInputType()) outputWriter.print(" INPUT"); if (t.isOutputType()) outputWriter.print(" OUTPUT"); outputWriter.println(); } // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY LIST VOICES")) { logger.debug("InfoRequest " + inputLine); // list all known voices Collection voices = Voice.getAvailableVoices(); for (Iterator it = voices.iterator(); it.hasNext();) { Voice v = (Voice) it.next(); if (v instanceof InterpolatingVoice) { // do not list interpolating voice } else if (v instanceof UnitSelectionVoice){ outputWriter.println(v.getName() + " " + v.getLocale() + " " + v.gender().toString() + " " +((UnitSelectionVoice)v).getDomain());} else { outputWriter.println(v.getName() + " " + v.getLocale()+ " " + v.gender().toString()); } } // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY LIST AUDIOFILEFORMATTYPES")) { logger.debug("InfoRequest " + inputLine); AudioFileFormat.Type[] audioTypes = AudioSystem.getAudioFileTypes(); for (int t=0; t<audioTypes.length; t++) { outputWriter.println(audioTypes[t].getExtension()+" "+audioTypes[t].toString()); } // Empty line marks end of info: outputWriter.println(); return true; } else if (inputLine.startsWith("MARY EXAMPLETEXT")) { logger.debug("InfoRequest " + inputLine); // send an example text for a given data type StringTokenizer st = new StringTokenizer(inputLine); // discard two tokens (MARY and EXAMPLETEXT) st.nextToken(); st.nextToken(); if (st.hasMoreTokens()) { String typeName = st.nextToken(); try { MaryDataType type = MaryDataType.get(typeName); // if we get here, the type exists assert type != null; String exampleText = type.exampleText(); if (exampleText != null) outputWriter.println(exampleText.trim()); } catch (Error err) {} // type doesn't exist } // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE EXAMPLETEXT")) { //the request is about the example text of //a limited domain unit selection voice logger.debug("InfoRequest " + inputLine); // send an example text for a given data type StringTokenizer st = new StringTokenizer(inputLine); // discard three tokens (MARY, VOICE, and EXAMPLETEXT) st.nextToken(); st.nextToken(); st.nextToken(); if (st.hasMoreTokens()) { String voiceName = st.nextToken(); Voice v = Voice.getVoice(voiceName); if (v != null) { String text = ((de.dfki.lt.mary.unitselection.UnitSelectionVoice) v).getExampleText(); outputWriter.println(text); } } // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTS")) { //the request is about the available audio effects logger.debug("InfoRequest " + inputLine); // <EffectSeparator>charEffectSeparator</EffectSeparator> // <Effect> // <Name>effect´s name</Name> // <SampleParam>example parameters string</SampleParam> // <HelpText>help text string</HelpText> // </Effect> // <Effect> // <Name>effect´s name</effectName> // <SampleParam>example parameters string</SampleParam> // <HelpText>help text string</HelpText> // </Effect> // ... // <Effect> // <Name>effect´s name</effectName> // <SampleParam>example parameters string</SampleParam> // <HelpText>help text string</HelpText> // </Effect> String audioEffectClass = "<EffectSeparator>" + EffectsApplier.chEffectSeparator + "</EffectSeparator>"; for (int i=0; i<MaryProperties.effectClasses().size(); i++) { audioEffectClass += "<Effect>"; audioEffectClass += "<Name>" + MaryProperties.effectNames().elementAt(i) + "</Name>"; audioEffectClass += "<Param>" + MaryProperties.effectParams().elementAt(i) + "</Param>"; audioEffectClass += "<SampleParam>" + MaryProperties.effectSampleParams().elementAt(i) + "</SampleParam>"; audioEffectClass += "<HelpText>" + MaryProperties.effectHelpTexts().elementAt(i) + "</HelpText>"; audioEffectClass += "</Effect>"; } outputWriter.println(audioEffectClass); // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTHELPTEXTLINEBREAK")) { logger.debug("InfoRequest " + inputLine); outputWriter.println(BaseAudioEffect.strLineBreak); // upon failure, simply return nothing outputWriter.println(); return true; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTPARAM ")) { for (int i=0; i<MaryProperties.effectNames().size(); i++) { int tmpInd = inputLine.indexOf("MARY VOICE GETAUDIOEFFECTPARAM "+MaryProperties.effectNames().elementAt(i)); if (tmpInd>-1) { //the request is about the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { String audioEffectParams = MaryProperties.effectParams().elementAt(i); outputWriter.println(audioEffectParams.trim()); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else if (inputLine.startsWith("MARY VOICE GETFULLAUDIOEFFECT ")) { for (int i=0; i<MaryProperties.effectNames().size(); i++) { int tmpInd = inputLine.indexOf("MARY VOICE GETFULLAUDIOEFFECT "+MaryProperties.effectNames().elementAt(i)); if (tmpInd>-1) { //the request is about the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { ae.setParams(MaryProperties.effectParams().elementAt(i)); String audioEffectFull = ae.getFullEffectAsString(); outputWriter.println(audioEffectFull.trim()); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else if (inputLine.startsWith("MARY VOICE SETAUDIOEFFECTPARAM ")) { String effectName; for (int i=0; i<MaryProperties.effectNames().size(); i++) { effectName = MaryProperties.effectNames().elementAt(i); int tmpInd = inputLine.indexOf("MARY VOICE SETAUDIOEFFECTPARAM " + effectName); if (tmpInd>-1) { //the request is about changing the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); int ind = inputLine.indexOf(effectName); String strTmp = inputLine.substring(ind, inputLine.length()); int ind2 = strTmp.indexOf('_'); String strParamNew = strTmp.substring(ind2+1, strTmp.length()); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { ae.setParams(strParamNew); String audioEffectParams = ae.getParamsAsString(false); MaryProperties.effectParams().set(i, audioEffectParams); outputWriter.println(audioEffectParams); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else if (inputLine.startsWith("MARY VOICE GETAUDIOEFFECTHELPTEXT ")) { for (int i=0; i<MaryProperties.effectNames().size(); i++) { int tmpInd = inputLine.indexOf("MARY VOICE GETAUDIOEFFECTHELPTEXT " + MaryProperties.effectNames().elementAt(i)); if (tmpInd>-1) { //the request is about the parameters of a specific audio effect logger.debug("InfoRequest " + inputLine); BaseAudioEffect ae = null; try { ae = (BaseAudioEffect)Class.forName(MaryProperties.effectClasses().elementAt(i)).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ae!=null) { String helpText = ae.getHelpText(); outputWriter.println(helpText.trim()); } // upon failure, simply return nothing outputWriter.println(); return true; } } return false; } else return false; }
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsController.java b/grails/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsController.java index b0b4b84dd..d5f85be3c 100644 --- a/grails/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsController.java +++ b/grails/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsController.java @@ -1,150 +1,149 @@ /* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.servlet.mvc; import groovy.lang.Closure; import groovy.lang.GroovyObject; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.WordUtils; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.GrailsControllerClass; import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletRequest; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.IncompatibleParameterCountException; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.NoClosurePropertyForURIException; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.NoViewNameDefinedException; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.UnknownControllerException; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.UnsupportedReturnValueException; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.util.UrlPathHelper; /** * <p>Base class for Grails controllers. * * @author Steven Devijver * @since Jul 2, 2005 */ public class SimpleGrailsController implements Controller, ApplicationContextAware { private static final String SLASH = "/"; private UrlPathHelper urlPathHelper = new UrlPathHelper(); private GrailsApplication application = null; private ApplicationContext applicationContext = null; public SimpleGrailsController() { super(); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void setGrailsApplication(GrailsApplication application) { this.application = application; } /** * <p>This method wraps regular request and response objects into Grails request and response objects. * * <p>It can handle maps as model types next to ModelAndView instances. * * @param request HTTP request * @param response HTTP response * @return the model */ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { - // Step 1: determine the name of the controller. - // This maps to a slash + the name of the controller. - String uri = this.urlPathHelper.getRequestUri(request); + // Step 1: determine the correct URI of the request. + String uri = this.urlPathHelper.getLookupPathForRequest(request); if (uri.indexOf("?") > -1) { uri = uri.substring(0, uri.indexOf("?")); } // Step 2: lookup the controller in the application. GrailsControllerClass controllerClass = this.application.getControllerByURI(uri); if (controllerClass == null) { throw new UnknownControllerException("No controller found for URI [" + uri + "]!"); } String controllerName = WordUtils.uncapitalize(controllerClass.getName()); // Step 3: load controller from application context. GroovyObject controller = (GroovyObject)this.applicationContext.getBean(controllerClass.getFullName()); // Step 4: get closure property name for URI. String closurePropertyName = controllerClass.getClosurePropertyName(uri); if (closurePropertyName == null) { throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!"); } // Step 5: get the view name for this URI. String viewName = controllerClass.getViewName(uri); boolean viewNameBlank = (viewName == null || viewName.length() == 0); // Step 6: get closure from closure property Closure closure = (Closure)controller.getProperty(closurePropertyName); // Step 7: determine argument count and execute. Object returnValue = null; if (closure.getParameterTypes().length == 1) { // closure may have zero or one parameter, we cannot be sure. returnValue = closure.call(new Object[] { new GrailsHttpServletRequest(request) }); } else if (closure.getParameterTypes().length == 2) { returnValue = closure.call(new Object[] { new GrailsHttpServletRequest(request), response }); } else { throw new IncompatibleParameterCountException("Closure on property [" + closurePropertyName + "] in [" + controllerClass.getFullName() + "] has an incompatible parameter count [" + closure.getParameterTypes().length + "]! Supported values are 0 and 2."); } // Step 8: determine return value type and handle accordingly if (returnValue == null) { if (viewNameBlank) { return null; } else { return new ModelAndView(viewName); } } else if (returnValue instanceof Map) { if (viewNameBlank) { throw new NoViewNameDefinedException("Map instance returned by and no view name specified for closure on property [" + closurePropertyName + "] in controller [" + controllerClass.getFullName() + "]!"); } else { return new ModelAndView(viewName, (Map)returnValue); } } else if (returnValue instanceof ModelAndView) { ModelAndView modelAndView = (ModelAndView)returnValue; if (modelAndView.getView() == null && modelAndView.getViewName() == null) { if (viewNameBlank) { throw new NoViewNameDefinedException("ModelAndView instance returned by and no view name defined by nor for closure on property [" + closurePropertyName + "] in controller [" + controllerClass.getFullName() + "]!"); } else { modelAndView.setViewName(viewName); } } return modelAndView; } throw new UnsupportedReturnValueException("Return value [" + returnValue + "] is not supported for closure property [" + closurePropertyName + "] in controller [" + controllerClass.getFullName() + "]!"); } }
true
true
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { // Step 1: determine the name of the controller. // This maps to a slash + the name of the controller. String uri = this.urlPathHelper.getRequestUri(request); if (uri.indexOf("?") > -1) { uri = uri.substring(0, uri.indexOf("?")); } // Step 2: lookup the controller in the application. GrailsControllerClass controllerClass = this.application.getControllerByURI(uri); if (controllerClass == null) { throw new UnknownControllerException("No controller found for URI [" + uri + "]!"); } String controllerName = WordUtils.uncapitalize(controllerClass.getName()); // Step 3: load controller from application context. GroovyObject controller = (GroovyObject)this.applicationContext.getBean(controllerClass.getFullName()); // Step 4: get closure property name for URI. String closurePropertyName = controllerClass.getClosurePropertyName(uri); if (closurePropertyName == null) { throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!"); } // Step 5: get the view name for this URI. String viewName = controllerClass.getViewName(uri); boolean viewNameBlank = (viewName == null || viewName.length() == 0); // Step 6: get closure from closure property Closure closure = (Closure)controller.getProperty(closurePropertyName); // Step 7: determine argument count and execute. Object returnValue = null; if (closure.getParameterTypes().length == 1) { // closure may have zero or one parameter, we cannot be sure. returnValue = closure.call(new Object[] { new GrailsHttpServletRequest(request) }); } else if (closure.getParameterTypes().length == 2) { returnValue = closure.call(new Object[] { new GrailsHttpServletRequest(request), response }); } else { throw new IncompatibleParameterCountException("Closure on property [" + closurePropertyName + "] in [" + controllerClass.getFullName() + "] has an incompatible parameter count [" + closure.getParameterTypes().length + "]! Supported values are 0 and 2."); } // Step 8: determine return value type and handle accordingly if (returnValue == null) { if (viewNameBlank) { return null; } else { return new ModelAndView(viewName); } } else if (returnValue instanceof Map) { if (viewNameBlank) { throw new NoViewNameDefinedException("Map instance returned by and no view name specified for closure on property [" + closurePropertyName + "] in controller [" + controllerClass.getFullName() + "]!"); } else { return new ModelAndView(viewName, (Map)returnValue); } } else if (returnValue instanceof ModelAndView) { ModelAndView modelAndView = (ModelAndView)returnValue; if (modelAndView.getView() == null && modelAndView.getViewName() == null) { if (viewNameBlank) { throw new NoViewNameDefinedException("ModelAndView instance returned by and no view name defined by nor for closure on property [" + closurePropertyName + "] in controller [" + controllerClass.getFullName() + "]!"); } else { modelAndView.setViewName(viewName); } } return modelAndView; } throw new UnsupportedReturnValueException("Return value [" + returnValue + "] is not supported for closure property [" + closurePropertyName + "] in controller [" + controllerClass.getFullName() + "]!"); }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { // Step 1: determine the correct URI of the request. String uri = this.urlPathHelper.getLookupPathForRequest(request); if (uri.indexOf("?") > -1) { uri = uri.substring(0, uri.indexOf("?")); } // Step 2: lookup the controller in the application. GrailsControllerClass controllerClass = this.application.getControllerByURI(uri); if (controllerClass == null) { throw new UnknownControllerException("No controller found for URI [" + uri + "]!"); } String controllerName = WordUtils.uncapitalize(controllerClass.getName()); // Step 3: load controller from application context. GroovyObject controller = (GroovyObject)this.applicationContext.getBean(controllerClass.getFullName()); // Step 4: get closure property name for URI. String closurePropertyName = controllerClass.getClosurePropertyName(uri); if (closurePropertyName == null) { throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!"); } // Step 5: get the view name for this URI. String viewName = controllerClass.getViewName(uri); boolean viewNameBlank = (viewName == null || viewName.length() == 0); // Step 6: get closure from closure property Closure closure = (Closure)controller.getProperty(closurePropertyName); // Step 7: determine argument count and execute. Object returnValue = null; if (closure.getParameterTypes().length == 1) { // closure may have zero or one parameter, we cannot be sure. returnValue = closure.call(new Object[] { new GrailsHttpServletRequest(request) }); } else if (closure.getParameterTypes().length == 2) { returnValue = closure.call(new Object[] { new GrailsHttpServletRequest(request), response }); } else { throw new IncompatibleParameterCountException("Closure on property [" + closurePropertyName + "] in [" + controllerClass.getFullName() + "] has an incompatible parameter count [" + closure.getParameterTypes().length + "]! Supported values are 0 and 2."); } // Step 8: determine return value type and handle accordingly if (returnValue == null) { if (viewNameBlank) { return null; } else { return new ModelAndView(viewName); } } else if (returnValue instanceof Map) { if (viewNameBlank) { throw new NoViewNameDefinedException("Map instance returned by and no view name specified for closure on property [" + closurePropertyName + "] in controller [" + controllerClass.getFullName() + "]!"); } else { return new ModelAndView(viewName, (Map)returnValue); } } else if (returnValue instanceof ModelAndView) { ModelAndView modelAndView = (ModelAndView)returnValue; if (modelAndView.getView() == null && modelAndView.getViewName() == null) { if (viewNameBlank) { throw new NoViewNameDefinedException("ModelAndView instance returned by and no view name defined by nor for closure on property [" + closurePropertyName + "] in controller [" + controllerClass.getFullName() + "]!"); } else { modelAndView.setViewName(viewName); } } return modelAndView; } throw new UnsupportedReturnValueException("Return value [" + returnValue + "] is not supported for closure property [" + closurePropertyName + "] in controller [" + controllerClass.getFullName() + "]!"); }
diff --git a/src/main/java/org/agoncal/application/petstore/security/LoginContextProducer.java b/src/main/java/org/agoncal/application/petstore/security/LoginContextProducer.java index f4c84fb..7decb7f 100644 --- a/src/main/java/org/agoncal/application/petstore/security/LoginContextProducer.java +++ b/src/main/java/org/agoncal/application/petstore/security/LoginContextProducer.java @@ -1,37 +1,37 @@ package org.agoncal.application.petstore.security; import org.agoncal.application.petstore.util.ConfigProperty; import javax.enterprise.inject.Produces; import javax.inject.Inject; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; /** * @author blep * Date: 16/02/12 * Time: 07:28 */ public class LoginContextProducer { // ====================================== // = Attributes = // ====================================== @Inject private SimpleCallbackHandler callbackHandler; // ====================================== // = Business methods = // ====================================== @Produces public LoginContext produceLoginContext(@ConfigProperty("loginConfigFile") String loginConfigFileName, @ConfigProperty("loginModuleName") String loginModuleName) throws LoginException { - System.setProperty("java.security.auth.login.config", LoginContextProducer.class.getResource(loginConfigFileName).getFile()); + System.setProperty("java.security.auth.login.config", new File(LoginContextProducer.class.getResource(loginConfigFileName).toURI()).getPath()); return new LoginContext(loginModuleName, callbackHandler); } }
true
true
public LoginContext produceLoginContext(@ConfigProperty("loginConfigFile") String loginConfigFileName, @ConfigProperty("loginModuleName") String loginModuleName) throws LoginException { System.setProperty("java.security.auth.login.config", LoginContextProducer.class.getResource(loginConfigFileName).getFile()); return new LoginContext(loginModuleName, callbackHandler); }
public LoginContext produceLoginContext(@ConfigProperty("loginConfigFile") String loginConfigFileName, @ConfigProperty("loginModuleName") String loginModuleName) throws LoginException { System.setProperty("java.security.auth.login.config", new File(LoginContextProducer.class.getResource(loginConfigFileName).toURI()).getPath()); return new LoginContext(loginModuleName, callbackHandler); }
diff --git a/auiplugin-tests/src/test/java/it/com/atlassian/aui/javascript/integrationTests/AUISeleniumQUnitTest.java b/auiplugin-tests/src/test/java/it/com/atlassian/aui/javascript/integrationTests/AUISeleniumQUnitTest.java index ac7cbed..3ce7352 100644 --- a/auiplugin-tests/src/test/java/it/com/atlassian/aui/javascript/integrationTests/AUISeleniumQUnitTest.java +++ b/auiplugin-tests/src/test/java/it/com/atlassian/aui/javascript/integrationTests/AUISeleniumQUnitTest.java @@ -1,121 +1,130 @@ package it.com.atlassian.aui.javascript.integrationTests; public class AUISeleniumQUnitTest extends AbstractAUISeleniumTestCase { public void testWhenITypeUnitTests() { openQunitTestPage("whenitype"); runQunitTests("WhenIType"); } public void testDialogUnitTests() { openQunitTestPage("dialog"); runQunitTests("Dialog"); } public void testDropdownUnitTests() { openQunitTestPage("dropdown"); runQunitTests("Dropdown"); } public void testFormatUnitTests() { openQunitTestPage("format"); runQunitTests("Format"); } public void testFormsUnitTests() { openQunitTestPage("forms"); runQunitTests("Forms"); } public void testInlineDialogUnitTests() { openQunitTestPage("inline-dialog"); runQunitTests("Inline-Dialog"); } public void testMessagesUnitTests() { openQunitTestPage("messages"); runQunitTests("Messages"); } public void testStalkerUnitTests() { openQunitTestPage("stalker"); runQunitTests("Stalker"); } public void testTablesUnitTests() { openQunitTestPage("tables"); runQunitTests("Tables"); } public void testTabsUnitTests() { openQunitTestPage("tabs"); runQunitTests("Tabs"); } public void testToolbarUnitTests() { openQunitTestPage("toolbar"); runQunitTests("Toolbar"); } public void testEventsUnitTests() { openQunitTestPage("events"); runQunitTests("Events"); } //HELPER FUNCTIONS //runs qunit tests on the page, component argument for reporting purposes only private void runQunitTests(String component) { client.waitForCondition("selenium.isElementPresent('qunit-testresult')"); + try + { + client.wait(3000); + client.wait(); + } + catch (InterruptedException e) + { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } int numberOfFailedTests = Integer.valueOf(client.getEval("window.AJS.$('li.fail li.fail').size()")); if (numberOfFailedTests != 0) { String failedTests[] = getFailedAssertionsText(); String failedTestListString = ""; for (int i = 0; i < failedTests.length; i++) { failedTestListString = failedTestListString + "FAILED! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> " + failedTests[i] + "\n"; } fail("There are " + (numberOfFailedTests) + " failed unit tests for" + component + " \n\n" + failedTestListString); } } //Function to retrive all the failed assertions and place them in an array to be used for reporting private String[] getFailedAssertionsText() { String result = client.getEval("var string = \"\";function getText(){window.AJS.$('li.fail li.fail').each( function(){string = string + window.AJS.$(this).text() + \"|\";});return string;} getText();"); String resultSplit[]; resultSplit = result.split("\\|"); return resultSplit; } //Opens a qunit test page for the specified component (assumes correct test file structure) private void openQunitTestPage(String component) { openTestPage("unit-tests/tests/" + component + "-unit-tests/" + component + "-unit-tests.html"); } }
true
true
private void runQunitTests(String component) { client.waitForCondition("selenium.isElementPresent('qunit-testresult')"); int numberOfFailedTests = Integer.valueOf(client.getEval("window.AJS.$('li.fail li.fail').size()")); if (numberOfFailedTests != 0) { String failedTests[] = getFailedAssertionsText(); String failedTestListString = ""; for (int i = 0; i < failedTests.length; i++) { failedTestListString = failedTestListString + "FAILED! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> " + failedTests[i] + "\n"; } fail("There are " + (numberOfFailedTests) + " failed unit tests for" + component + " \n\n" + failedTestListString); } }
private void runQunitTests(String component) { client.waitForCondition("selenium.isElementPresent('qunit-testresult')"); try { client.wait(3000); client.wait(); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } int numberOfFailedTests = Integer.valueOf(client.getEval("window.AJS.$('li.fail li.fail').size()")); if (numberOfFailedTests != 0) { String failedTests[] = getFailedAssertionsText(); String failedTestListString = ""; for (int i = 0; i < failedTests.length; i++) { failedTestListString = failedTestListString + "FAILED! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> " + failedTests[i] + "\n"; } fail("There are " + (numberOfFailedTests) + " failed unit tests for" + component + " \n\n" + failedTestListString); } }
diff --git a/src/gov/nih/nci/eagle/service/handlers/EpidemiologicalQueryHandler.java b/src/gov/nih/nci/eagle/service/handlers/EpidemiologicalQueryHandler.java index fa41a92..dac69d3 100755 --- a/src/gov/nih/nci/eagle/service/handlers/EpidemiologicalQueryHandler.java +++ b/src/gov/nih/nci/eagle/service/handlers/EpidemiologicalQueryHandler.java @@ -1,262 +1,262 @@ package gov.nih.nci.eagle.service.handlers; import gov.nih.nci.caintegrator.domain.study.bean.StudyParticipant; import gov.nih.nci.caintegrator.dto.query.QueryDTO; import gov.nih.nci.caintegrator.studyQueryService.QueryHandler; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.BehavioralCriterion; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.EPIQueryDTO; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.EducationLevel; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.EnvironmentalTobaccoSmokeCriterion; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.FamilyHistoryCriterion; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.Gender; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.MaritalStatus; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.PatientCharacteristicsCriterion; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.Relative; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.Religion; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.SmokingExposure; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.SmokingStatus; import gov.nih.nci.caintegrator.studyQueryService.dto.epi.TobaccoConsumptionCriterion; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Conjunction; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.Expression; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; public class EpidemiologicalQueryHandler implements QueryHandler { private SessionFactory sessionFactory; // private static final String TARGET_FINDING_ALIAS = " finding"; public Integer getResultCount(QueryDTO query) { throw new UnsupportedOperationException(); } public List getResults(QueryDTO dto, Integer page) { throw new UnsupportedOperationException(); } public List getResults(QueryDTO queryDTO) { EPIQueryDTO epiQueryDTO = (EPIQueryDTO) queryDTO; Session session = sessionFactory.getCurrentSession(); Criteria targetCrit = session.createCriteria(StudyParticipant.class); targetCrit.createAlias("epidemiologicalFinding", "finding"); targetCrit.createAlias("finding.tobaccoConsumptionCollection", "tc", CriteriaSpecification.LEFT_JOIN); targetCrit.createAlias("finding.behavioralAssessment", "ba"); targetCrit.createAlias("finding.lifestyle", "ls"); - targetCrit.createAlias("finding.relativeCollection", "relatives", CriteriaSpecification.LEFT_JOIN); + targetCrit.createAlias("finding.relativeCollection", "relatives"); targetCrit.createAlias("finding.environmentalFactorCollection", "factors", CriteriaSpecification.LEFT_JOIN); /* 1. Handle PatientCharacteristics Criterion */ PatientCharacteristicsCriterion patCharacterCrit = epiQueryDTO .getPatientCharacteristicsCriterion(); if (patCharacterCrit != null) populatePatientCharacteristicsCriterion(patCharacterCrit, targetCrit); /* 2. Handle Tobacco Dependency Criterion */ BehavioralCriterion behaviorCrit = epiQueryDTO.getBehavioralCriterion(); if (behaviorCrit != null) populateBehaviorCriterion(behaviorCrit, targetCrit); /* Handle Tobacco Consumption Criterion */ TobaccoConsumptionCriterion tobaccoCrit = epiQueryDTO .getTobaccoConsumptionCriterion(); if (tobaccoCrit != null) populateTobaccoConsumptionCrit(tobaccoCrit, targetCrit); FamilyHistoryCriterion familyHistcrit = epiQueryDTO .getFamilyHistoryCriterion(); if (familyHistcrit != null) populateFamilyHistoryCrit(familyHistcrit, targetCrit); EnvironmentalTobaccoSmokeCriterion envCrit = epiQueryDTO .getEnvironmentalTobaccoSmokeCriterion(); if (envCrit != null && envCrit .getSmokingExposureCollection() != null) { Collection<SmokingExposure> exposure = envCrit .getSmokingExposureCollection(); List<String> exposures = new ArrayList<String>(); for (SmokingExposure ex : exposure) { exposures.add(ex.toString()); } targetCrit.add(Restrictions.in("factors.exposureType", exposures)); } // Handle patient ID criteria if (epiQueryDTO.getPatientIds() != null && epiQueryDTO.getPatientIds().size() > 0) { targetCrit.add(Restrictions.in("studySubjectIdentifier", epiQueryDTO.getPatientIds())); } targetCrit.addOrder(Order.asc("id")); List<StudyParticipant> l = targetCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); return l; } private void populateFamilyHistoryCrit( FamilyHistoryCriterion familyHistcrit, Criteria targetCrit) { Integer lungCancerrelativeCrit = familyHistcrit .getFamilyLungCancer(); if (lungCancerrelativeCrit != null) { targetCrit.add(Restrictions.eq("finding.relativeWithLungCancer", lungCancerrelativeCrit.toString())); } Collection<Relative> smokingRelativeCrit = familyHistcrit .getSmokingRelativeCollection(); if (smokingRelativeCrit != null) { Disjunction dis = Restrictions.disjunction(); for(Relative r : smokingRelativeCrit) { Conjunction con = Restrictions.conjunction(); con.add(Restrictions.eq("relatives.relationshipType", r.getName().toUpperCase())); con.add(Restrictions.eq("relatives.smokingStatus", "1")); dis.add(con); } targetCrit.add(dis); } } private void populateTobaccoConsumptionCrit( TobaccoConsumptionCriterion tobaccoCrit, Criteria targetCrit) { if (tobaccoCrit != null) { Double lowerIntensity = tobaccoCrit.getIntensityLower(); Double upperIntensity = tobaccoCrit.getIntensityUpper(); if (lowerIntensity != null && upperIntensity != null) { assert (upperIntensity.compareTo(lowerIntensity) > 0); targetCrit.add(Restrictions.between("tc.intensity", lowerIntensity, upperIntensity)); } Integer durationLower = tobaccoCrit.getDurationLower(); Integer durationUpper = tobaccoCrit.getDurationUpper(); if (durationLower != null && durationUpper != null) { assert (durationUpper.compareTo(durationUpper) > 0); targetCrit.add(Restrictions.between("tc.duration", durationLower, durationUpper)); } Integer ageLower = tobaccoCrit.getAgeAtInitiationLower(); Integer ageUpper = tobaccoCrit.getAgeAtInitiationUpper(); if (ageLower != null && ageUpper != null) { assert (ageUpper.compareTo(ageLower) > 0); targetCrit.add(Restrictions.between("tc.ageAtInitiation", ageLower, ageUpper)); } SmokingStatus smokeStatus = tobaccoCrit.getSmokingStatus(); if (smokeStatus != null) targetCrit.add(Expression.eq("tc.smokingStatus", new Integer( smokeStatus.getValue()).toString())); } } private void populateBehaviorCriterion(BehavioralCriterion behaviorCrit, Criteria targetCrit) { Integer fScore = behaviorCrit.getFagerstromScore(); if (fScore != null) targetCrit.add(Expression.eq("ba.fagerstromScore", fScore)); Integer dScore = behaviorCrit.getDepressionScore(); if (dScore != null) targetCrit.add(Expression.eq("ba.depressionScore", dScore)); Integer aScore = behaviorCrit.getAnxietyScore(); if (aScore != null) targetCrit.add(Expression.eq("ba.anxietyScore", aScore)); } private void populatePatientCharacteristicsCriterion( PatientCharacteristicsCriterion patCharacterCrit, Criteria targetCrit) { assert (patCharacterCrit != null); pupulatePatientAttributesCriterion(patCharacterCrit, targetCrit); populateLifeStyleCriterion(targetCrit, patCharacterCrit); } private void pupulatePatientAttributesCriterion( PatientCharacteristicsCriterion patCharacterCrit, Criteria targetCrit) { Double lowerAgeLimit = patCharacterCrit.getAgeLowerLimit(); Double upperAgeLimit = patCharacterCrit.getAgeUpperLimit(); if ((lowerAgeLimit != null && lowerAgeLimit != 0) && (upperAgeLimit != null && upperAgeLimit != 0)) targetCrit.add(Restrictions.between("ageAtDiagnosis.absoluteValue", lowerAgeLimit, upperAgeLimit)); Gender gender = patCharacterCrit.getSelfReportedgender(); if (gender != null) targetCrit.add(Restrictions.eq("administrativeGenderCode", gender .getName().toUpperCase())); Double lowerWtLimit = patCharacterCrit.getWeightLowerLimit(); Double upperWtLimit = patCharacterCrit.getWeightUpperLimit(); if ((lowerWtLimit != null && lowerWtLimit != 0) && (upperWtLimit != null && upperWtLimit != 0)) targetCrit.add(Restrictions.between("weight", lowerWtLimit, upperWtLimit)); Double lowerHtLimit = patCharacterCrit.getHeightLowerLimit(); Double upperHtLimit = patCharacterCrit.getHeightUpperLimit(); if ((lowerHtLimit != null && lowerHtLimit != 0) && (upperHtLimit != null && upperHtLimit != 0)) targetCrit.add(Restrictions.between("height", lowerHtLimit, upperHtLimit)); Double lowerWaistLimit = patCharacterCrit.getWaistLowerLimit(); Double upperWaistLimit = patCharacterCrit.getWaisUpperLimit(); if ((lowerWaistLimit != null && lowerWaistLimit != 0) && (upperWaistLimit != null && upperWaistLimit != 0)) targetCrit.add(Restrictions.between("waistCircumference", lowerWaistLimit, upperWaistLimit)); } private void populateLifeStyleCriterion(Criteria targetCrit, PatientCharacteristicsCriterion patCharacterCrit) { MaritalStatus mStatus = patCharacterCrit.getMaritalStatus(); if (mStatus != null) targetCrit.add(Expression.eq("ls.maritalStatus", new Integer( mStatus.getValue()).toString())); Religion religion = patCharacterCrit.getReligion(); if (religion != null) targetCrit.add(Expression.eq("ls.religion", new Integer(religion .getValue()).toString())); String ra = patCharacterCrit.getResidentialArea(); if (ra != null) targetCrit.add(Expression.eq("ls.residentialArea", ra)); EducationLevel el = patCharacterCrit.getEducationLevel(); if (el != null) targetCrit.add(Expression.eq("ls.educationLevel", new Integer(el .getValue()).toString())); } public boolean canHandle(QueryDTO query) { return (query instanceof EPIQueryDTO); } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFacotry) { this.sessionFactory = sessionFacotry; } }
true
true
public List getResults(QueryDTO queryDTO) { EPIQueryDTO epiQueryDTO = (EPIQueryDTO) queryDTO; Session session = sessionFactory.getCurrentSession(); Criteria targetCrit = session.createCriteria(StudyParticipant.class); targetCrit.createAlias("epidemiologicalFinding", "finding"); targetCrit.createAlias("finding.tobaccoConsumptionCollection", "tc", CriteriaSpecification.LEFT_JOIN); targetCrit.createAlias("finding.behavioralAssessment", "ba"); targetCrit.createAlias("finding.lifestyle", "ls"); targetCrit.createAlias("finding.relativeCollection", "relatives", CriteriaSpecification.LEFT_JOIN); targetCrit.createAlias("finding.environmentalFactorCollection", "factors", CriteriaSpecification.LEFT_JOIN); /* 1. Handle PatientCharacteristics Criterion */ PatientCharacteristicsCriterion patCharacterCrit = epiQueryDTO .getPatientCharacteristicsCriterion(); if (patCharacterCrit != null) populatePatientCharacteristicsCriterion(patCharacterCrit, targetCrit); /* 2. Handle Tobacco Dependency Criterion */ BehavioralCriterion behaviorCrit = epiQueryDTO.getBehavioralCriterion(); if (behaviorCrit != null) populateBehaviorCriterion(behaviorCrit, targetCrit); /* Handle Tobacco Consumption Criterion */ TobaccoConsumptionCriterion tobaccoCrit = epiQueryDTO .getTobaccoConsumptionCriterion(); if (tobaccoCrit != null) populateTobaccoConsumptionCrit(tobaccoCrit, targetCrit); FamilyHistoryCriterion familyHistcrit = epiQueryDTO .getFamilyHistoryCriterion(); if (familyHistcrit != null) populateFamilyHistoryCrit(familyHistcrit, targetCrit); EnvironmentalTobaccoSmokeCriterion envCrit = epiQueryDTO .getEnvironmentalTobaccoSmokeCriterion(); if (envCrit != null && envCrit .getSmokingExposureCollection() != null) { Collection<SmokingExposure> exposure = envCrit .getSmokingExposureCollection(); List<String> exposures = new ArrayList<String>(); for (SmokingExposure ex : exposure) { exposures.add(ex.toString()); } targetCrit.add(Restrictions.in("factors.exposureType", exposures)); } // Handle patient ID criteria if (epiQueryDTO.getPatientIds() != null && epiQueryDTO.getPatientIds().size() > 0) { targetCrit.add(Restrictions.in("studySubjectIdentifier", epiQueryDTO.getPatientIds())); } targetCrit.addOrder(Order.asc("id")); List<StudyParticipant> l = targetCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); return l; }
public List getResults(QueryDTO queryDTO) { EPIQueryDTO epiQueryDTO = (EPIQueryDTO) queryDTO; Session session = sessionFactory.getCurrentSession(); Criteria targetCrit = session.createCriteria(StudyParticipant.class); targetCrit.createAlias("epidemiologicalFinding", "finding"); targetCrit.createAlias("finding.tobaccoConsumptionCollection", "tc", CriteriaSpecification.LEFT_JOIN); targetCrit.createAlias("finding.behavioralAssessment", "ba"); targetCrit.createAlias("finding.lifestyle", "ls"); targetCrit.createAlias("finding.relativeCollection", "relatives"); targetCrit.createAlias("finding.environmentalFactorCollection", "factors", CriteriaSpecification.LEFT_JOIN); /* 1. Handle PatientCharacteristics Criterion */ PatientCharacteristicsCriterion patCharacterCrit = epiQueryDTO .getPatientCharacteristicsCriterion(); if (patCharacterCrit != null) populatePatientCharacteristicsCriterion(patCharacterCrit, targetCrit); /* 2. Handle Tobacco Dependency Criterion */ BehavioralCriterion behaviorCrit = epiQueryDTO.getBehavioralCriterion(); if (behaviorCrit != null) populateBehaviorCriterion(behaviorCrit, targetCrit); /* Handle Tobacco Consumption Criterion */ TobaccoConsumptionCriterion tobaccoCrit = epiQueryDTO .getTobaccoConsumptionCriterion(); if (tobaccoCrit != null) populateTobaccoConsumptionCrit(tobaccoCrit, targetCrit); FamilyHistoryCriterion familyHistcrit = epiQueryDTO .getFamilyHistoryCriterion(); if (familyHistcrit != null) populateFamilyHistoryCrit(familyHistcrit, targetCrit); EnvironmentalTobaccoSmokeCriterion envCrit = epiQueryDTO .getEnvironmentalTobaccoSmokeCriterion(); if (envCrit != null && envCrit .getSmokingExposureCollection() != null) { Collection<SmokingExposure> exposure = envCrit .getSmokingExposureCollection(); List<String> exposures = new ArrayList<String>(); for (SmokingExposure ex : exposure) { exposures.add(ex.toString()); } targetCrit.add(Restrictions.in("factors.exposureType", exposures)); } // Handle patient ID criteria if (epiQueryDTO.getPatientIds() != null && epiQueryDTO.getPatientIds().size() > 0) { targetCrit.add(Restrictions.in("studySubjectIdentifier", epiQueryDTO.getPatientIds())); } targetCrit.addOrder(Order.asc("id")); List<StudyParticipant> l = targetCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); return l; }
diff --git a/src/java/fedora/utilities/install/InstallOptions.java b/src/java/fedora/utilities/install/InstallOptions.java index b3c699dff..016011385 100644 --- a/src/java/fedora/utilities/install/InstallOptions.java +++ b/src/java/fedora/utilities/install/InstallOptions.java @@ -1,420 +1,420 @@ package fedora.utilities.install; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import fedora.utilities.DriverShim; import fedora.utilities.FileUtils; public class InstallOptions { public static final String INSTALL_TYPE = "install.type"; public static final String FEDORA_HOME = "fedora.home"; public static final String FEDORA_SERVERHOST = "fedora.serverHost"; public static final String APIA_AUTH_REQUIRED = "apia.auth.required"; public static final String SSL_AVAILABLE = "ssl.available"; public static final String APIA_SSL_REQUIRED = "apia.ssl.required"; public static final String APIM_SSL_REQUIRED = "apim.ssl.required"; public static final String SERVLET_ENGINE = "servlet.engine"; public static final String TOMCAT_HOME = "tomcat.home"; public static final String FEDORA_ADMIN_PASS = "fedora.admin.pass"; public static final String TOMCAT_SHUTDOWN_PORT = "tomcat.shutdown.port"; public static final String TOMCAT_HTTP_PORT = "tomcat.http.port"; public static final String TOMCAT_SSL_PORT = "tomcat.ssl.port"; public static final String KEYSTORE_FILE = "keystore.file"; public static final String DATABASE = "database"; public static final String DATABASE_DRIVER = "database.driver"; public static final String DATABASE_JDBCURL = "database.jdbcURL"; public static final String DATABASE_DRIVERCLASS = "database.jdbcDriverClass"; public static final String DATABASE_USERNAME = "database.username"; public static final String DATABASE_PASSWORD = "database.password"; public static final String XACML_ENABLED = "xacml.enabled"; public static final String DEPLOY_LOCAL_SERVICES = "deploy.local.services"; public static final String UNATTENDED = "unattended"; public static final String DATABASE_UPDATE = "database.update"; public static final String INSTALL_QUICK = "quick"; public static final String INCLUDED = "included"; public static final String MCKOI = "mckoi"; public static final String MYSQL = "mysql"; public static final String ORACLE = "oracle"; public static final String POSTGRESQL = "postgresql"; public static final String OTHER = "other"; public static final String EXISTING_TOMCAT = "existingTomcat"; private Map<Object, Object> _map; private Distribution _dist; /** * Initialize options from the given map of String values, keyed by * option id. */ public InstallOptions(Distribution dist, Map<Object, Object> map) throws OptionValidationException { _dist = dist; _map = map; applyDefaults(); validateAll(); } /** * Initialize options interactively, via input from the console. */ public InstallOptions(Distribution dist) throws InstallationCancelledException { _dist = dist; _map = new HashMap<Object, Object>(); System.out.println(); System.out.println("**********************"); System.out.println(" Fedora Installation "); System.out.println("**********************"); System.out.println(); System.out.println("Please answer the following questions to install Fedora."); System.out.println("You can enter CANCEL at any time to abort installation."); System.out.println(); inputOption(INSTALL_TYPE); inputOption(FEDORA_HOME); inputOption(FEDORA_ADMIN_PASS); String fedoraHome = new File(getValue(InstallOptions.FEDORA_HOME)).getAbsolutePath(); String includedJDBCURL = "jdbc:mckoi:local://" + fedoraHome + "/" + Distribution.MCKOI_BASENAME +"/db.conf?create_or_boot=true"; if (getValue(INSTALL_TYPE).equals(INSTALL_QUICK)) { // See the defaultValues defined in OptionDefinition.properties // for the null values below _map.put(FEDORA_SERVERHOST, null); // localhost _map.put(APIA_AUTH_REQUIRED, null); // false _map.put(SSL_AVAILABLE, Boolean.toString(false)); _map.put(APIM_SSL_REQUIRED, Boolean.toString(false)); _map.put(SERVLET_ENGINE, null); // included _map.put(TOMCAT_HOME, fedoraHome + File.separator + "tomcat"); _map.put(TOMCAT_HTTP_PORT, null); // 8080 _map.put(TOMCAT_SHUTDOWN_PORT, null); // 8005 //_map.put(TOMCAT_SSL_PORT, null); // 8443 //_map.put(KEYSTORE_FILE, null); // included _map.put(XACML_ENABLED, Boolean.toString(false)); _map.put(DATABASE, INCLUDED); // included _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver"); _map.put(DEPLOY_LOCAL_SERVICES, null); // true applyDefaults(); return; } inputOption(FEDORA_SERVERHOST); inputOption(APIA_AUTH_REQUIRED); inputOption(SSL_AVAILABLE); boolean sslAvailable = getBooleanValue(SSL_AVAILABLE, true); if (sslAvailable) { inputOption(APIA_SSL_REQUIRED); inputOption(APIM_SSL_REQUIRED); } inputOption(SERVLET_ENGINE); if (!getValue(SERVLET_ENGINE).equals(OTHER)) { inputOption(TOMCAT_HOME); inputOption(TOMCAT_HTTP_PORT); inputOption(TOMCAT_SHUTDOWN_PORT); if (sslAvailable) { inputOption(TOMCAT_SSL_PORT); if (getValue(SERVLET_ENGINE).equals(INCLUDED) || getValue(SERVLET_ENGINE).equals(EXISTING_TOMCAT)) { inputOption(KEYSTORE_FILE); } } } inputOption(XACML_ENABLED); // Database selection // Ultimately we want to provide the following properties: // database, database.username, database.password, // database.driver, database.jdbcURL, database.jdbcDriverClass inputOption(DATABASE); String db = DATABASE + "." + getValue(DATABASE); // The following lets us use the database-specific OptionDefinition.properties // for the user prompts and defaults String driver = db + ".driver"; String jdbcURL = db + ".jdbcURL"; String jdbcDriverClass = db + ".jdbcDriverClass"; if ( getValue(DATABASE).equals(INCLUDED) ) { _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_JDBCURL, includedJDBCURL); - _map.put(DATABASE_DRIVERCLASS, OptionDefinition.get(DATABASE_DRIVERCLASS).getDefaultValue()); + _map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver"); } else { boolean dbValidated = false; while (!dbValidated) { inputOption(driver); _map.put(DATABASE_DRIVER, getValue(driver)); inputOption(DATABASE_USERNAME); inputOption(DATABASE_PASSWORD); inputOption(jdbcURL); _map.put(DATABASE_JDBCURL, getValue(jdbcURL)); inputOption(jdbcDriverClass); _map.put(DATABASE_DRIVERCLASS, getValue(jdbcDriverClass)); dbValidated = validateDatabaseConnection(); } } inputOption(DEPLOY_LOCAL_SERVICES); } private String dashes(int len) { StringBuffer out = new StringBuffer(); for (int i = 0; i < len; i++) { out.append('-'); } return out.toString(); } /** * Get the indicated option from the console. * * Continue prompting until the value is valid, or the user has * indicated they want to cancel the installation. */ private void inputOption(String optionId) throws InstallationCancelledException { OptionDefinition opt = OptionDefinition.get(optionId); if (opt.getLabel() == null || opt.getLabel().length() == 0) { throw new InstallationCancelledException(optionId + " is missing label (check OptionDefinition.properties?)"); } System.out.println(opt.getLabel()); System.out.println(dashes(opt.getLabel().length())); System.out.println(opt.getDescription()); System.out.println(); String[] valids = opt.getValidValues(); if (valids != null) { System.out.print("Options : "); for (int i = 0; i < valids.length; i++) { if (i > 0) System.out.print(", "); System.out.print(valids[i]); } System.out.println(); } String defaultVal = opt.getDefaultValue(); if (valids != null || defaultVal != null) { System.out.println(); } boolean gotValidValue = false; while (!gotValidValue) { System.out.print("Enter a value "); if (defaultVal != null) { System.out.print("[default is " + defaultVal + "] "); } System.out.print("==> "); String value = readLine().trim(); if (value.length() == 0 && defaultVal != null) { value = defaultVal; } System.out.println(); if (value.equalsIgnoreCase("cancel")) { throw new InstallationCancelledException("Cancelled by user."); } try { opt.validateValue(value); gotValidValue = true; _map.put(optionId, value); System.out.println(); } catch (OptionValidationException e) { System.out.println("Error: " + e.getMessage()); } } } private String readLine() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); return reader.readLine(); } catch (Exception e) { throw new RuntimeException("Error: Unable to read from STDIN"); } } /** * Dump all options (including any defaults that were applied) * to the given stream, in java properties file format. * * The output stream remains open after this method returns. */ public void dump(OutputStream out) throws IOException { Properties props = new Properties(); Iterator iter = _map.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); props.setProperty(key, getValue(key)); } props.store(out, "Install Options"); } /** * Get the value of the given option, or <code>null</code> if it doesn't exist. */ public String getValue(String name) { return (String) _map.get(name); } /** * Get the value of the given option as an integer, or the given default value * if unspecified. * * @throws NumberFormatException if the value is specified, but cannot be parsed * as an integer. */ public int getIntValue(String name, int defaultValue) throws NumberFormatException { String value = getValue(name); if (value == null) { return defaultValue; } else { return Integer.parseInt(value); } } /** * Get the value of the given option as a boolean, or the given default value * if unspecified. * * If specified, the value is assumed to be <code>true</code> if given as "true", * regardless of case. All other values are assumed to be <code>false</code>. */ public boolean getBooleanValue(String name, boolean defaultValue) { String value = getValue(name); if (value == null) { return defaultValue; } else { return value.equals("true"); } } /** * Get an iterator of the names of all specified options. */ public Iterator getOptionNames() { return _map.keySet().iterator(); } /** * Apply defaults to the options, where possible. */ private void applyDefaults() { Iterator names = getOptionNames(); while (names.hasNext()) { String name = (String) names.next(); String val = (String) _map.get(name); if (val == null || val.length() == 0) { OptionDefinition opt = OptionDefinition.get(name); _map.put(name, opt.getDefaultValue()); } } } /** * Validate the options, assuming defaults have already been applied. * * Validation for a given option might entail more than a syntax check. * It might check whether a given directory exists, for example. */ private void validateAll() throws OptionValidationException { boolean unattended = getBooleanValue(UNATTENDED, false); Iterator keys = getOptionNames(); while (keys.hasNext()) { String optionId = (String) keys.next(); OptionDefinition opt = OptionDefinition.get(optionId); opt.validateValue(getValue(optionId), unattended); } } private boolean validateDatabaseConnection() { String database = getValue(DATABASE); if (database.equals(InstallOptions.INCLUDED)) { return true; } File driver = null; if (getValue(DATABASE_DRIVER).equals(InstallOptions.INCLUDED)) { InputStream is; boolean success = false; try { if (database.equals(InstallOptions.MCKOI)) { is = _dist.get(Distribution.JDBC_MCKOI); driver = new File(System.getProperty("java.io.tmpdir"), Distribution.JDBC_MCKOI); success = FileUtils.copy(is, new FileOutputStream(driver)); } else if (database.equals(InstallOptions.MYSQL)) { is = _dist.get(Distribution.JDBC_MYSQL); driver = new File(System.getProperty("java.io.tmpdir"), Distribution.JDBC_MYSQL); success = FileUtils.copy(is, new FileOutputStream(driver)); } if (!success) { System.err.println("Extraction of included JDBC driver failed."); return false; } } catch(IOException e) { e.printStackTrace(); return false; } } else { driver = new File(getValue(DATABASE_DRIVER)); } try { DriverShim.loadAndRegister(driver, getValue(DATABASE_DRIVERCLASS)); Connection conn = DriverManager.getConnection(getValue(DATABASE_JDBCURL), getValue(DATABASE_USERNAME), getValue(DATABASE_PASSWORD)); DatabaseMetaData dmd = conn.getMetaData(); System.out.println("Successfully connected to " + dmd.getDatabaseProductName()); // check if we need to update old table ResultSet rs = dmd.getTables(null, null, "%", null); while (rs.next()) { if (rs.getString("TABLE_NAME").equals("do")) { inputOption(DATABASE_UPDATE); break; } } conn.close(); return true; } catch(Exception e) { e.printStackTrace(); return false; } } }
true
true
public InstallOptions(Distribution dist) throws InstallationCancelledException { _dist = dist; _map = new HashMap<Object, Object>(); System.out.println(); System.out.println("**********************"); System.out.println(" Fedora Installation "); System.out.println("**********************"); System.out.println(); System.out.println("Please answer the following questions to install Fedora."); System.out.println("You can enter CANCEL at any time to abort installation."); System.out.println(); inputOption(INSTALL_TYPE); inputOption(FEDORA_HOME); inputOption(FEDORA_ADMIN_PASS); String fedoraHome = new File(getValue(InstallOptions.FEDORA_HOME)).getAbsolutePath(); String includedJDBCURL = "jdbc:mckoi:local://" + fedoraHome + "/" + Distribution.MCKOI_BASENAME +"/db.conf?create_or_boot=true"; if (getValue(INSTALL_TYPE).equals(INSTALL_QUICK)) { // See the defaultValues defined in OptionDefinition.properties // for the null values below _map.put(FEDORA_SERVERHOST, null); // localhost _map.put(APIA_AUTH_REQUIRED, null); // false _map.put(SSL_AVAILABLE, Boolean.toString(false)); _map.put(APIM_SSL_REQUIRED, Boolean.toString(false)); _map.put(SERVLET_ENGINE, null); // included _map.put(TOMCAT_HOME, fedoraHome + File.separator + "tomcat"); _map.put(TOMCAT_HTTP_PORT, null); // 8080 _map.put(TOMCAT_SHUTDOWN_PORT, null); // 8005 //_map.put(TOMCAT_SSL_PORT, null); // 8443 //_map.put(KEYSTORE_FILE, null); // included _map.put(XACML_ENABLED, Boolean.toString(false)); _map.put(DATABASE, INCLUDED); // included _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver"); _map.put(DEPLOY_LOCAL_SERVICES, null); // true applyDefaults(); return; } inputOption(FEDORA_SERVERHOST); inputOption(APIA_AUTH_REQUIRED); inputOption(SSL_AVAILABLE); boolean sslAvailable = getBooleanValue(SSL_AVAILABLE, true); if (sslAvailable) { inputOption(APIA_SSL_REQUIRED); inputOption(APIM_SSL_REQUIRED); } inputOption(SERVLET_ENGINE); if (!getValue(SERVLET_ENGINE).equals(OTHER)) { inputOption(TOMCAT_HOME); inputOption(TOMCAT_HTTP_PORT); inputOption(TOMCAT_SHUTDOWN_PORT); if (sslAvailable) { inputOption(TOMCAT_SSL_PORT); if (getValue(SERVLET_ENGINE).equals(INCLUDED) || getValue(SERVLET_ENGINE).equals(EXISTING_TOMCAT)) { inputOption(KEYSTORE_FILE); } } } inputOption(XACML_ENABLED); // Database selection // Ultimately we want to provide the following properties: // database, database.username, database.password, // database.driver, database.jdbcURL, database.jdbcDriverClass inputOption(DATABASE); String db = DATABASE + "." + getValue(DATABASE); // The following lets us use the database-specific OptionDefinition.properties // for the user prompts and defaults String driver = db + ".driver"; String jdbcURL = db + ".jdbcURL"; String jdbcDriverClass = db + ".jdbcDriverClass"; if ( getValue(DATABASE).equals(INCLUDED) ) { _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, OptionDefinition.get(DATABASE_DRIVERCLASS).getDefaultValue()); } else { boolean dbValidated = false; while (!dbValidated) { inputOption(driver); _map.put(DATABASE_DRIVER, getValue(driver)); inputOption(DATABASE_USERNAME); inputOption(DATABASE_PASSWORD); inputOption(jdbcURL); _map.put(DATABASE_JDBCURL, getValue(jdbcURL)); inputOption(jdbcDriverClass); _map.put(DATABASE_DRIVERCLASS, getValue(jdbcDriverClass)); dbValidated = validateDatabaseConnection(); } } inputOption(DEPLOY_LOCAL_SERVICES); }
public InstallOptions(Distribution dist) throws InstallationCancelledException { _dist = dist; _map = new HashMap<Object, Object>(); System.out.println(); System.out.println("**********************"); System.out.println(" Fedora Installation "); System.out.println("**********************"); System.out.println(); System.out.println("Please answer the following questions to install Fedora."); System.out.println("You can enter CANCEL at any time to abort installation."); System.out.println(); inputOption(INSTALL_TYPE); inputOption(FEDORA_HOME); inputOption(FEDORA_ADMIN_PASS); String fedoraHome = new File(getValue(InstallOptions.FEDORA_HOME)).getAbsolutePath(); String includedJDBCURL = "jdbc:mckoi:local://" + fedoraHome + "/" + Distribution.MCKOI_BASENAME +"/db.conf?create_or_boot=true"; if (getValue(INSTALL_TYPE).equals(INSTALL_QUICK)) { // See the defaultValues defined in OptionDefinition.properties // for the null values below _map.put(FEDORA_SERVERHOST, null); // localhost _map.put(APIA_AUTH_REQUIRED, null); // false _map.put(SSL_AVAILABLE, Boolean.toString(false)); _map.put(APIM_SSL_REQUIRED, Boolean.toString(false)); _map.put(SERVLET_ENGINE, null); // included _map.put(TOMCAT_HOME, fedoraHome + File.separator + "tomcat"); _map.put(TOMCAT_HTTP_PORT, null); // 8080 _map.put(TOMCAT_SHUTDOWN_PORT, null); // 8005 //_map.put(TOMCAT_SSL_PORT, null); // 8443 //_map.put(KEYSTORE_FILE, null); // included _map.put(XACML_ENABLED, Boolean.toString(false)); _map.put(DATABASE, INCLUDED); // included _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver"); _map.put(DEPLOY_LOCAL_SERVICES, null); // true applyDefaults(); return; } inputOption(FEDORA_SERVERHOST); inputOption(APIA_AUTH_REQUIRED); inputOption(SSL_AVAILABLE); boolean sslAvailable = getBooleanValue(SSL_AVAILABLE, true); if (sslAvailable) { inputOption(APIA_SSL_REQUIRED); inputOption(APIM_SSL_REQUIRED); } inputOption(SERVLET_ENGINE); if (!getValue(SERVLET_ENGINE).equals(OTHER)) { inputOption(TOMCAT_HOME); inputOption(TOMCAT_HTTP_PORT); inputOption(TOMCAT_SHUTDOWN_PORT); if (sslAvailable) { inputOption(TOMCAT_SSL_PORT); if (getValue(SERVLET_ENGINE).equals(INCLUDED) || getValue(SERVLET_ENGINE).equals(EXISTING_TOMCAT)) { inputOption(KEYSTORE_FILE); } } } inputOption(XACML_ENABLED); // Database selection // Ultimately we want to provide the following properties: // database, database.username, database.password, // database.driver, database.jdbcURL, database.jdbcDriverClass inputOption(DATABASE); String db = DATABASE + "." + getValue(DATABASE); // The following lets us use the database-specific OptionDefinition.properties // for the user prompts and defaults String driver = db + ".driver"; String jdbcURL = db + ".jdbcURL"; String jdbcDriverClass = db + ".jdbcDriverClass"; if ( getValue(DATABASE).equals(INCLUDED) ) { _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver"); } else { boolean dbValidated = false; while (!dbValidated) { inputOption(driver); _map.put(DATABASE_DRIVER, getValue(driver)); inputOption(DATABASE_USERNAME); inputOption(DATABASE_PASSWORD); inputOption(jdbcURL); _map.put(DATABASE_JDBCURL, getValue(jdbcURL)); inputOption(jdbcDriverClass); _map.put(DATABASE_DRIVERCLASS, getValue(jdbcDriverClass)); dbValidated = validateDatabaseConnection(); } } inputOption(DEPLOY_LOCAL_SERVICES); }
diff --git a/src/net/loadingchunks/plugins/GuardWolf/GWSQL.java b/src/net/loadingchunks/plugins/GuardWolf/GWSQL.java index 2acee61..ef7e4af 100644 --- a/src/net/loadingchunks/plugins/GuardWolf/GWSQL.java +++ b/src/net/loadingchunks/plugins/GuardWolf/GWSQL.java @@ -1,122 +1,122 @@ package net.loadingchunks.plugins.GuardWolf; import java.sql.*; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; /** * Handler for the /gw sample command. * @author Cue */ public class GWSQL { public Connection con; public Statement stmt; public final GuardWolf plugin; public GWSQL(GuardWolf plugin) { this.plugin = plugin; } public void Connect() { try { Class.forName("com.mysql.jdbc.Driver"); this.con = DriverManager.getConnection(this.plugin.gwConfig.get("db_address"), this.plugin.gwConfig.get("db_user"), this.plugin.gwConfig.get("db_pass")); } catch ( SQLException e ) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public void Ban(String name, String banner, long time, String reason, int permanent) { Integer strike = 1; try { PreparedStatement stat = con.prepareStatement("INSERT INTO `" + this.plugin.gwConfig.get("db_table") + "`" + "(`user`,`country`,`banned_at`,`expires_at`,`reason`,`banned_by`,`strike`,`strike_expires`,`unbanned`,`permanent`)" + " VALUES ('" + name + "','?',NOW(),FROM_UNIXTIME(" + time + "),'" + reason + "','" + banner + "'," + strike + ",NOW(),0," + permanent + ")" ); stat.execute(); } catch ( SQLException e ) { e.printStackTrace(); } } public void UnBan(String name, String unbanner) { try { PreparedStatement stat = con.prepareStatement("UPDATE `" + this.plugin.gwConfig.get("db_table") + "` SET `unbanned` = 0 WHERE `user` = '" + name + "' LIMIT 1"); stat.execute(); } catch ( SQLException e ) { e.printStackTrace(); } } public void Stats() { try { Statement stat = con.createStatement(); ResultSet result = stat.executeQuery("SELECT COUNT(*) as counter FROM `" + this.plugin.gwConfig.get("db_table") + "`"); result.next(); System.out.println("Ban Records: " + result.getInt("counter")); } catch ( SQLException e ) { e.printStackTrace(); } } public String CheckBan(String user) { System.out.println("[GW] Checking ban status..."); try { PreparedStatement stat = con.prepareStatement("SELECT * FROM `mcusers_ban` WHERE (expires_at > NOW() OR `permanent` = 1) AND `user` = '" + user + "' AND `unbanned` = 0 ORDER BY id DESC"); ResultSet result = stat.executeQuery(); if(result.last()) { if(result.getInt("permanent") == 1) return result.getString("reason") + " (Permanent Ban)"; else return result.getString("reason") + " (Expires " + result.getString("expires_at") + ")"; } else return null; } catch ( SQLException e ) { e.printStackTrace(); } return null; } - public String ListBan(int page, String user, CommandSender sender) + public void ListBan(int page, String user, CommandSender sender) { String tempString = ""; if(user.isEmpty()) { try { PreparedStatement stat = con.prepareStatement("SELECT *,COUNT(*) as c FROM `mcusers_ban` GROUP BY `user` ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) - return ChatColor.RED + "No bans found."; + sender.sendMessage(ChatColor.RED + "No bans found."); else { result.first(); do { sender.sendMessage("- " + ChatColor.WHITE + result.getString("user") + " (" + result.getInt("c") + " bans found)"); } while(result.next()); } } catch ( SQLException e ) { e.printStackTrace(); } } else { try { PreparedStatement stat = con.prepareStatement("SELECT * FROM `mcusers_ban` WHERE `user` = '" + user + "' ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) - return ChatColor.RED + "No bans found for this user."; + sender.sendMessage(ChatColor.RED + "No bans found for this user."); else { result.first(); do { tempString = "- " + ChatColor.WHITE + result.getString("reason"); if(result.getInt("permanent") == 1) tempString = tempString + " (Permanent)"; else tempString = tempString + " (Expires: " + result.getString("expires_at") + ")"; sender.sendMessage(tempString); } while (result.next()); } } catch ( SQLException e ) { e.printStackTrace(); } } - return "Error getting Ban List!"; + sender.sendMessage(ChatColor.RED + "Error getting Ban List!"); } }
false
true
public String ListBan(int page, String user, CommandSender sender) { String tempString = ""; if(user.isEmpty()) { try { PreparedStatement stat = con.prepareStatement("SELECT *,COUNT(*) as c FROM `mcusers_ban` GROUP BY `user` ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) return ChatColor.RED + "No bans found."; else { result.first(); do { sender.sendMessage("- " + ChatColor.WHITE + result.getString("user") + " (" + result.getInt("c") + " bans found)"); } while(result.next()); } } catch ( SQLException e ) { e.printStackTrace(); } } else { try { PreparedStatement stat = con.prepareStatement("SELECT * FROM `mcusers_ban` WHERE `user` = '" + user + "' ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) return ChatColor.RED + "No bans found for this user."; else { result.first(); do { tempString = "- " + ChatColor.WHITE + result.getString("reason"); if(result.getInt("permanent") == 1) tempString = tempString + " (Permanent)"; else tempString = tempString + " (Expires: " + result.getString("expires_at") + ")"; sender.sendMessage(tempString); } while (result.next()); } } catch ( SQLException e ) { e.printStackTrace(); } } return "Error getting Ban List!"; }
public void ListBan(int page, String user, CommandSender sender) { String tempString = ""; if(user.isEmpty()) { try { PreparedStatement stat = con.prepareStatement("SELECT *,COUNT(*) as c FROM `mcusers_ban` GROUP BY `user` ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) sender.sendMessage(ChatColor.RED + "No bans found."); else { result.first(); do { sender.sendMessage("- " + ChatColor.WHITE + result.getString("user") + " (" + result.getInt("c") + " bans found)"); } while(result.next()); } } catch ( SQLException e ) { e.printStackTrace(); } } else { try { PreparedStatement stat = con.prepareStatement("SELECT * FROM `mcusers_ban` WHERE `user` = '" + user + "' ORDER BY `permanent`,`expires_at` DESC LIMIT " + ((page - 1)*(Integer.parseInt(this.plugin.gwConfig.get("per_page")))) + "," + (Integer.parseInt(this.plugin.gwConfig.get("per_page")))); ResultSet result = stat.executeQuery(); if(!result.last()) sender.sendMessage(ChatColor.RED + "No bans found for this user."); else { result.first(); do { tempString = "- " + ChatColor.WHITE + result.getString("reason"); if(result.getInt("permanent") == 1) tempString = tempString + " (Permanent)"; else tempString = tempString + " (Expires: " + result.getString("expires_at") + ")"; sender.sendMessage(tempString); } while (result.next()); } } catch ( SQLException e ) { e.printStackTrace(); } } sender.sendMessage(ChatColor.RED + "Error getting Ban List!"); }
diff --git a/libs/lint_checks/src/main/java/com/android/tools/lint/checks/ToastDetector.java b/libs/lint_checks/src/main/java/com/android/tools/lint/checks/ToastDetector.java index e245fe8..9bc7af5 100644 --- a/libs/lint_checks/src/main/java/com/android/tools/lint/checks/ToastDetector.java +++ b/libs/lint_checks/src/main/java/com/android/tools/lint/checks/ToastDetector.java @@ -1,156 +1,156 @@ /* * Copyright (C) 2012 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.tools.lint.checks; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.tools.lint.detector.api.Category; import com.android.tools.lint.detector.api.Context; import com.android.tools.lint.detector.api.Detector; import com.android.tools.lint.detector.api.Issue; import com.android.tools.lint.detector.api.JavaContext; import com.android.tools.lint.detector.api.Scope; import com.android.tools.lint.detector.api.Severity; import java.io.File; import java.util.Collections; import java.util.List; import lombok.ast.AstVisitor; import lombok.ast.Expression; import lombok.ast.ForwardingAstVisitor; import lombok.ast.IntegralLiteral; import lombok.ast.MethodInvocation; import lombok.ast.Node; import lombok.ast.Return; import lombok.ast.StrictListAccessor; /** Detector looking for Toast.makeText() without a corresponding show() call */ public class ToastDetector extends Detector implements Detector.JavaScanner { /** The main issue discovered by this detector */ public static final Issue ISSUE = Issue.create( "ShowToast", //$NON-NLS-1$ "Looks for code creating a Toast but forgetting to call show() on it", "`Toast.makeText()` creates a `Toast` but does *not* show it. You must call " + "`show()` on the resulting object to actually make the `Toast` appear.", Category.CORRECTNESS, 6, Severity.WARNING, ToastDetector.class, Scope.JAVA_FILE_SCOPE); /** Constructs a new {@link ToastDetector} check */ public ToastDetector() { } @Override public boolean appliesTo(@NonNull Context context, @NonNull File file) { return true; } // ---- Implements JavaScanner ---- @Override public List<String> getApplicableMethodNames() { return Collections.singletonList("makeText"); //$NON-NLS-1$ } @Override public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull MethodInvocation node) { assert node.astName().astValue().equals("makeText"); if (node.astOperand() == null) { // "makeText()" in the code with no operand return; } String operand = node.astOperand().toString(); if (!(operand.equals("Toast") || operand.endsWith(".Toast"))) { return; } // Make sure you pass the right kind of duration: it's not a delay, it's // LENGTH_SHORT or LENGTH_LONG // (see http://code.google.com/p/android/issues/detail?id=3655) StrictListAccessor<Expression, MethodInvocation> args = node.astArguments(); if (args.size() == 3) { Expression duration = args.last(); if (duration instanceof IntegralLiteral) { context.report(ISSUE, duration, context.getLocation(duration), "Expected duration Toast.LENGTH_SHORT or Toast.LENGTH_LONG, a custom " + "duration value is not supported", null); } } Node method = JavaContext.findSurroundingMethod(node.getParent()); if (method == null) { return; } ShowFinder finder = new ShowFinder(node); method.accept(finder); if (!finder.isShowCalled()) { - context.report(ISSUE, method, context.getLocation(node), + context.report(ISSUE, node, context.getLocation(node), "Toast created but not shown: did you forget to call show() ?", null); } } private static class ShowFinder extends ForwardingAstVisitor { /** The target makeText call */ private final MethodInvocation mTarget; /** Whether we've found the show method */ private boolean mFound; /** Whether we've seen the target makeText node yet */ private boolean mSeenTarget; private ShowFinder(MethodInvocation target) { mTarget = target; } @Override public boolean visitMethodInvocation(MethodInvocation node) { if (node == mTarget) { mSeenTarget = true; } else if ((mSeenTarget || node.astOperand() == mTarget) && "show".equals(node.astName().astValue())) { //$NON-NLS-1$ // TODO: Do more flow analysis to see whether we're really calling show // on the right type of object? mFound = true; } return true; } @Override public boolean visitReturn(Return node) { if (node.astValue() == mTarget) { // If you just do "return Toast.makeText(...) don't warn mFound = true; } return super.visitReturn(node); } boolean isShowCalled() { return mFound; } } }
true
true
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull MethodInvocation node) { assert node.astName().astValue().equals("makeText"); if (node.astOperand() == null) { // "makeText()" in the code with no operand return; } String operand = node.astOperand().toString(); if (!(operand.equals("Toast") || operand.endsWith(".Toast"))) { return; } // Make sure you pass the right kind of duration: it's not a delay, it's // LENGTH_SHORT or LENGTH_LONG // (see http://code.google.com/p/android/issues/detail?id=3655) StrictListAccessor<Expression, MethodInvocation> args = node.astArguments(); if (args.size() == 3) { Expression duration = args.last(); if (duration instanceof IntegralLiteral) { context.report(ISSUE, duration, context.getLocation(duration), "Expected duration Toast.LENGTH_SHORT or Toast.LENGTH_LONG, a custom " + "duration value is not supported", null); } } Node method = JavaContext.findSurroundingMethod(node.getParent()); if (method == null) { return; } ShowFinder finder = new ShowFinder(node); method.accept(finder); if (!finder.isShowCalled()) { context.report(ISSUE, method, context.getLocation(node), "Toast created but not shown: did you forget to call show() ?", null); } }
public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull MethodInvocation node) { assert node.astName().astValue().equals("makeText"); if (node.astOperand() == null) { // "makeText()" in the code with no operand return; } String operand = node.astOperand().toString(); if (!(operand.equals("Toast") || operand.endsWith(".Toast"))) { return; } // Make sure you pass the right kind of duration: it's not a delay, it's // LENGTH_SHORT or LENGTH_LONG // (see http://code.google.com/p/android/issues/detail?id=3655) StrictListAccessor<Expression, MethodInvocation> args = node.astArguments(); if (args.size() == 3) { Expression duration = args.last(); if (duration instanceof IntegralLiteral) { context.report(ISSUE, duration, context.getLocation(duration), "Expected duration Toast.LENGTH_SHORT or Toast.LENGTH_LONG, a custom " + "duration value is not supported", null); } } Node method = JavaContext.findSurroundingMethod(node.getParent()); if (method == null) { return; } ShowFinder finder = new ShowFinder(node); method.accept(finder); if (!finder.isShowCalled()) { context.report(ISSUE, node, context.getLocation(node), "Toast created but not shown: did you forget to call show() ?", null); } }
diff --git a/plugins/org.eclipse.jst.j2ee.web/web/org/eclipse/jst/j2ee/internal/web/operations/CreateServletTemplateModel.java b/plugins/org.eclipse.jst.j2ee.web/web/org/eclipse/jst/j2ee/internal/web/operations/CreateServletTemplateModel.java index 2dd2372d0..75156c012 100644 --- a/plugins/org.eclipse.jst.j2ee.web/web/org/eclipse/jst/j2ee/internal/web/operations/CreateServletTemplateModel.java +++ b/plugins/org.eclipse.jst.j2ee.web/web/org/eclipse/jst/j2ee/internal/web/operations/CreateServletTemplateModel.java @@ -1,172 +1,173 @@ /******************************************************************************* * Copyright (c) 2003, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ /* * Created on Aug 6, 2004 */ package org.eclipse.jst.j2ee.internal.web.operations; import java.util.List; import org.eclipse.jst.j2ee.internal.common.operations.INewJavaClassDataModelProperties; import org.eclipse.wst.common.frameworks.datamodel.IDataModel; /** * @author jlanuti */ public class CreateServletTemplateModel { IDataModel dataModel = null; public static final String INIT = "init"; //$NON-NLS-1$ public static final String TO_STRING = "toString"; //$NON-NLS-1$ public static final String GET_SERVLET_INFO = "getServletInfo"; //$NON-NLS-1$ public static final String DO_POST = "doPost"; //$NON-NLS-1$ public static final String DO_PUT = "doPut"; //$NON-NLS-1$ public static final String DO_DELETE = "doDelete"; //$NON-NLS-1$ public static final String DESTROY = "destroy"; //$NON-NLS-1$ public static final String DO_GET = "doGet"; //$NON-NLS-1$ public static final int NAME = 0; public static final int VALUE = 1; public static final int DESCRIPTION = 2; /** * Constructor */ public CreateServletTemplateModel(IDataModel dataModel) { super(); this.dataModel = dataModel; } public String getServletClassName() { return getProperty(INewJavaClassDataModelProperties.CLASS_NAME); } public String getJavaPackageName() { return getProperty(INewJavaClassDataModelProperties.JAVA_PACKAGE); } public String getQualifiedJavaClassName() { return getJavaPackageName() + "." + getServletClassName(); //$NON-NLS-1$ } public String getSuperclassName() { return getProperty(INewJavaClassDataModelProperties.SUPERCLASS); } public String getServletName() { return getProperty(INewJavaClassDataModelProperties.CLASS_NAME); } public boolean isPublic() { return dataModel.getBooleanProperty(INewJavaClassDataModelProperties.MODIFIER_PUBLIC); } public boolean isFinal() { return dataModel.getBooleanProperty(INewJavaClassDataModelProperties.MODIFIER_FINAL); } public boolean isAbstract() { return dataModel.getBooleanProperty(INewJavaClassDataModelProperties.MODIFIER_ABSTRACT); } protected String getProperty(String propertyName) { return dataModel.getStringProperty(propertyName); } public boolean shouldGenInit() { return implementImplementedMethod(INIT); } public boolean shouldGenToString() { return implementImplementedMethod(TO_STRING); } public boolean shouldGenGetServletInfo() { return implementImplementedMethod(GET_SERVLET_INFO); } public boolean shouldGenDoPost() { return implementImplementedMethod(DO_POST); } public boolean shouldGenDoPut() { return implementImplementedMethod(DO_PUT); } public boolean shouldGenDoDelete() { return implementImplementedMethod(DO_DELETE); } public boolean shouldGenDestroy() { return implementImplementedMethod(DESTROY); } public boolean shouldGenDoGet() { return implementImplementedMethod(DO_GET); } public List getInitParams() { return (List) dataModel.getProperty(INewServletClassDataModelProperties.INIT_PARAM); } public String getInitParam(int index, int type) { List params = getInitParams(); if (index < params.size()) { String[] stringArray = (String[]) params.get(index); return stringArray[type]; } return null; } public List getServletMappings() { return (List) dataModel.getProperty(INewServletClassDataModelProperties.URL_MAPPINGS); } public String getServletMapping(int index) { List mappings = getServletMappings(); if (index < mappings.size()) { String[] map = (String[]) mappings.get(index); return map[0]; } return null; } public String getServletDescription() { return dataModel.getStringProperty(INewServletClassDataModelProperties.DESCRIPTION); } public List getInterfaces() { return (List) this.dataModel.getProperty(INewJavaClassDataModelProperties.INTERFACES); } protected boolean implementImplementedMethod(String methodName) { - if (methodName.equals(INIT)) - return dataModel.getBooleanProperty(INewServletClassDataModelProperties.INIT); - else if (methodName.equals(TO_STRING)) - return dataModel.getBooleanProperty(INewServletClassDataModelProperties.TO_STRING); - else if (methodName.equals(GET_SERVLET_INFO)) - return dataModel.getBooleanProperty(INewServletClassDataModelProperties.GET_SERVLET_INFO); - else if (methodName.equals(DO_POST)) - return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_POST); - else if (methodName.equals(DO_PUT)) - return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_PUT); - else if (methodName.equals(DO_DELETE)) - return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_DELETE); - else if (methodName.equals(DESTROY)) - return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DESTROY); - else if (methodName.equals(DO_GET)) - return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_GET); - else - return false; + if (dataModel.getBooleanProperty(INewJavaClassDataModelProperties.ABSTRACT_METHODS)) { + if (methodName.equals(INIT)) + return dataModel.getBooleanProperty(INewServletClassDataModelProperties.INIT); + else if (methodName.equals(TO_STRING)) + return dataModel.getBooleanProperty(INewServletClassDataModelProperties.TO_STRING); + else if (methodName.equals(GET_SERVLET_INFO)) + return dataModel.getBooleanProperty(INewServletClassDataModelProperties.GET_SERVLET_INFO); + else if (methodName.equals(DO_POST)) + return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_POST); + else if (methodName.equals(DO_PUT)) + return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_PUT); + else if (methodName.equals(DO_DELETE)) + return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_DELETE); + else if (methodName.equals(DESTROY)) + return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DESTROY); + else if (methodName.equals(DO_GET)) + return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_GET); + } + return false; } }
true
true
protected boolean implementImplementedMethod(String methodName) { if (methodName.equals(INIT)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.INIT); else if (methodName.equals(TO_STRING)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.TO_STRING); else if (methodName.equals(GET_SERVLET_INFO)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.GET_SERVLET_INFO); else if (methodName.equals(DO_POST)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_POST); else if (methodName.equals(DO_PUT)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_PUT); else if (methodName.equals(DO_DELETE)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_DELETE); else if (methodName.equals(DESTROY)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DESTROY); else if (methodName.equals(DO_GET)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_GET); else return false; }
protected boolean implementImplementedMethod(String methodName) { if (dataModel.getBooleanProperty(INewJavaClassDataModelProperties.ABSTRACT_METHODS)) { if (methodName.equals(INIT)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.INIT); else if (methodName.equals(TO_STRING)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.TO_STRING); else if (methodName.equals(GET_SERVLET_INFO)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.GET_SERVLET_INFO); else if (methodName.equals(DO_POST)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_POST); else if (methodName.equals(DO_PUT)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_PUT); else if (methodName.equals(DO_DELETE)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_DELETE); else if (methodName.equals(DESTROY)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DESTROY); else if (methodName.equals(DO_GET)) return dataModel.getBooleanProperty(INewServletClassDataModelProperties.DO_GET); } return false; }
diff --git a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/JsfAllTests.java b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/JsfAllTests.java index 28ebf7628..c951b3957 100755 --- a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/JsfAllTests.java +++ b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/JsfAllTests.java @@ -1,231 +1,232 @@ /******************************************************************************* * Copyright (c) 2007 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.jsf.vpe.jsf.test; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.jst.jsp.core.internal.java.search.JSPIndexManager; import org.jboss.tools.jsf.vpe.jsf.test.jbide.ChangeMessageBundleTest_JBIDE5818; import org.jboss.tools.jsf.vpe.jsf.test.jbide.ContextMenuDoubleInsertionTest_JBIDE3888; import org.jboss.tools.jsf.vpe.jsf.test.jbide.EditFontFamilyTest_JBIDE5872; import org.jboss.tools.jsf.vpe.jsf.test.jbide.ExceptionInVPEComments_JBIDE5143; import org.jboss.tools.jsf.vpe.jsf.test.jbide.FacetProcessingTest; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE1105Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE1460Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE1479Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE1494Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE1615Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE1720Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE1744Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE1805Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2010Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2119Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2219Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2297Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2354Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2434Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2505Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2526Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2550Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2582Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2584Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2594Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2624Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2774Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2828Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE2979Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3030Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3127Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3144Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3163Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3197Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3247Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3376Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3396Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3441Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3473Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3482Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3519Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3617Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3632Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3650Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3734Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE3969Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE4037Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE4179Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE4337Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE4373Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE4509Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE4510Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE4534Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE5920Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE675Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE788Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JBIDE924Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JSF2ValidatorTest; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JsfJbide1467Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JsfJbide1501Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JsfJbide1568Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JsfJbide1718Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JsfJbide2170Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.JsfJbide2362Test; import org.jboss.tools.jsf.vpe.jsf.test.jbide.MessageResolutionInPreviewTabTest; import org.jboss.tools.jsf.vpe.jsf.test.jbide.MozDirtyTest_JBIDE5105; import org.jboss.tools.jsf.vpe.jsf.test.jbide.NullPointerWithStyleProperty_JBIDE5193; import org.jboss.tools.jsf.vpe.jsf.test.jbide.OpenOnCssClassTest_JBIDE4775; import org.jboss.tools.jsf.vpe.jsf.test.jbide.OpenOnInJarPackageFragment_JBIDE5682; import org.jboss.tools.jsf.vpe.jsf.test.jbide.OpenOnInsideJspRoot_JBIDE4852; import org.jboss.tools.jsf.vpe.jsf.test.jbide.OpenOnJsf20Test_JBIDE5382; import org.jboss.tools.jsf.vpe.jsf.test.jbide.OpenOnTLDPackedInJar_JBIDE5693; import org.jboss.tools.jsf.vpe.jsf.test.jbide.PreferencesForEditors_JBIDE5692; import org.jboss.tools.jsf.vpe.jsf.test.jbide.RefreshBundles_JBIDE5460; import org.jboss.tools.jsf.vpe.jsf.test.jbide.RenderFacetAndInsertChildrenTest; import org.jboss.tools.jsf.vpe.jsf.test.jbide.SelectAllAndCut_JBIDE4853; import org.jboss.tools.jsf.vpe.jsf.test.jbide.SelectWholeElement_JBIDE4713; import org.jboss.tools.jsf.vpe.jsf.test.jbide.SourceDomUtilTest; import org.jboss.tools.jsf.vpe.jsf.test.jbide.TestContextPathResolution; import org.jboss.tools.jsf.vpe.jsf.test.jbide.TestFViewLocaleAttribute_JBIDE5218; import org.jboss.tools.jsf.vpe.jsf.test.jbide.UnclosedELExpressionTest; import org.jboss.tools.jsf.vpe.jsf.test.jbide.TestForUsingComponentsLibrariesWithDefaultNamespace; import org.jboss.tools.jsf.vpe.jsf.test.jbide.TestOpenOnForXhtmlFiles_JBIDE5577; import org.jboss.tools.jsf.vpe.jsf.test.jbide.VPERefreshTest; import org.jboss.tools.jsf.vpe.jsf.test.jbide.VisualRefreshComment_JBIDE6067; import org.jboss.tools.jsf.vpe.jsf.test.jbide.VpeI18nTest_JBIDE4887; import org.jboss.tools.jsf.vpe.jsf.test.jbide.XulRunnerVpeUtilsTest; import org.jboss.tools.vpe.base.test.VpeTestSetup; /** * Class for testing all RichFaces components * * @author sdzmitrovich * */ public class JsfAllTests { public static final String IMPORT_PROJECT_NAME = "jsfTest"; //$NON-NLS-1$ public static final String IMPORT_JSF_20_PROJECT_NAME = "jsf2test"; //$NON-NLS-1$ public static final String IMPORT_CUSTOM_FACELETS_PROJECT = "customFaceletsTestProject";//$NON-NLS-1$ public static final String IMPORT_JBIDE3247_PROJECT_NAME = "JBIDE3247"; //$NON-NLS-1$ public static final String IMPORT_I18N_PROJECT_NAME = "i18nTest"; //$NON-NLS-1$ public static final String IMPORT_NATURES_CHECKER_PROJECT = "naturesCheckTest"; //$NON-NLS-1$ public static final String IMPORT_JSF_LOCALES_PROJECT_NAME = "jsfLocales"; //$NON-NLS-1$ public static final String IMPORT_JBIDE5460_PROJECT_NAME = "JBIDE5460TestProject"; //$NON-NLS-1$ public static final String IMPORT_TEST_WITH_2_URL_PATTERNS_PROJECT_NAME = "TestWith2URLPatterns"; //$NON-NLS-1$ public static Test suite() { +// FIXME https://issues.jboss.org/browse/JBIDE-8488 // JSPIndexManager.getInstance().shutdown(); TestSuite suite = new TestSuite("Tests for Vpe Jsf components"); //$NON-NLS-1$ // $JUnit-BEGIN$ /* * Content tests */ suite.addTestSuite(JsfComponentContentTest.class) ; suite.addTestSuite(Jsf20ComponentContentTest.class); /* * Other tests */ suite.addTestSuite(SourceDomUtilTest.class); suite.addTestSuite(XulRunnerVpeUtilsTest.class); suite.addTestSuite(JSF2ValidatorTest.class); suite.addTestSuite(UnclosedELExpressionTest.class); suite.addTestSuite(TestContextPathResolution.class); suite.addTestSuite(JBIDE5920Test.class); suite.addTestSuite(RenderFacetAndInsertChildrenTest.class); suite.addTestSuite(EditFontFamilyTest_JBIDE5872.class); suite.addTestSuite(ChangeMessageBundleTest_JBIDE5818.class); suite.addTestSuite(TestForUsingComponentsLibrariesWithDefaultNamespace.class); // suite.addTestSuite(EditingSPecialSymbolsVPE_JBIDE3810.class); suite.addTestSuite(OpenOnJsf20Test_JBIDE5382.class); suite.addTestSuite(MozDirtyTest_JBIDE5105.class); suite.addTestSuite(VpeI18nTest_JBIDE4887.class); suite.addTestSuite(JsfComponentTest.class); suite.addTestSuite(JBIDE3519Test.class); suite.addTestSuite(ContextMenuDoubleInsertionTest_JBIDE3888.class); suite.addTestSuite(SelectAllAndCut_JBIDE4853.class); suite.addTestSuite(SelectWholeElement_JBIDE4713.class); suite.addTestSuite(JBIDE4037Test.class); suite.addTestSuite(JBIDE3734Test.class); suite.addTestSuite(JBIDE3617Test.class); suite.addTestSuite(JBIDE3473Test.class); suite.addTestSuite(JBIDE3441Test.class); suite.addTestSuite(JsfJbide1467Test.class); suite.addTestSuite(JsfJbide1501Test.class); suite.addTestSuite(JsfJbide1568Test.class); suite.addTestSuite(JBIDE1615Test.class); suite.addTestSuite(JBIDE1479Test.class); suite.addTestSuite(JBIDE788Test.class); suite.addTestSuite(JBIDE1105Test.class); suite.addTestSuite(JBIDE1744Test.class); suite.addTestSuite(JBIDE1460Test.class); suite.addTestSuite(JBIDE1720Test.class); suite.addTestSuite(JsfJbide1718Test.class); suite.addTestSuite(JBIDE1494Test.class); suite.addTestSuite(JBIDE2297Test.class); suite.addTestSuite(JsfJbide2170Test.class); suite.addTestSuite(JBIDE2434Test.class); suite.addTestSuite(JsfJbide2362Test.class); suite.addTestSuite(JBIDE2119Test.class); suite.addTestSuite(JBIDE2219Test.class); suite.addTestSuite(JBIDE2505Test.class); suite.addTestSuite(JBIDE2584Test.class); suite.addTestSuite(ElPreferencesTestCase.class); suite.addTestSuite(JBIDE2010Test.class); suite.addTestSuite(JBIDE2582Test.class); suite.addTestSuite(JBIDE2594Test.class); suite.addTestSuite(JBIDE924Test.class); suite.addTestSuite(JBIDE2526Test.class); suite.addTestSuite(JBIDE2624Test.class); suite.addTestSuite(JBIDE1805Test.class); suite.addTestSuite(JBIDE2774Test.class); suite.addTestSuite(JBIDE2828Test.class); suite.addTestSuite(JBIDE3030Test.class); suite.addTestSuite(JBIDE2979Test.class); suite.addTestSuite(JBIDE3127Test.class); suite.addTestSuite(JBIDE3144Test.class); suite.addTestSuite(JBIDE2354Test.class); suite.addTestSuite(JBIDE3163Test.class); suite.addTestSuite(JBIDE3376Test.class); suite.addTestSuite(JBIDE3396Test.class); suite.addTestSuite(JBIDE3482Test.class); suite.addTestSuite(JBIDE3632Test.class); suite.addTestSuite(JBIDE3650Test.class); suite.addTestSuite(JBIDE3197Test.class); suite.addTestSuite(JBIDE4373Test.class); suite.addTestSuite(JBIDE675Test.class); suite.addTestSuite(JBIDE3969Test.class); suite.addTestSuite(JBIDE4337Test.class); suite.addTestSuite(JBIDE4179Test.class); suite.addTestSuite(JBIDE4509Test.class); suite.addTestSuite(JBIDE4510Test.class); suite.addTestSuite(JBIDE4534Test.class); suite.addTestSuite(JBIDE3247Test.class); suite.addTestSuite(JBIDE2550Test.class); suite.addTestSuite(OpenOnCssClassTest_JBIDE4775.class); suite.addTestSuite(VPERefreshTest.class); suite.addTestSuite(OpenOnInsideJspRoot_JBIDE4852.class); suite.addTestSuite(NullPointerWithStyleProperty_JBIDE5193.class); suite.addTestSuite(TestFViewLocaleAttribute_JBIDE5218.class); suite.addTestSuite(TestOpenOnForXhtmlFiles_JBIDE5577.class); suite.addTestSuite(OpenOnInJarPackageFragment_JBIDE5682.class); suite.addTestSuite(MessageResolutionInPreviewTabTest.class); suite.addTestSuite(OpenOnTLDPackedInJar_JBIDE5693.class); suite.addTestSuite(PreferencesForEditors_JBIDE5692.class); suite.addTestSuite(FacetProcessingTest.class); suite.addTestSuite(RefreshBundles_JBIDE5460.class); suite.addTestSuite(ExceptionInVPEComments_JBIDE5143.class); suite.addTestSuite(VisualRefreshComment_JBIDE6067.class); // $JUnit-END$ return new VpeTestSetup(suite); } }
true
true
public static Test suite() { // JSPIndexManager.getInstance().shutdown(); TestSuite suite = new TestSuite("Tests for Vpe Jsf components"); //$NON-NLS-1$ // $JUnit-BEGIN$ /* * Content tests */ suite.addTestSuite(JsfComponentContentTest.class) ; suite.addTestSuite(Jsf20ComponentContentTest.class); /* * Other tests */ suite.addTestSuite(SourceDomUtilTest.class); suite.addTestSuite(XulRunnerVpeUtilsTest.class); suite.addTestSuite(JSF2ValidatorTest.class); suite.addTestSuite(UnclosedELExpressionTest.class); suite.addTestSuite(TestContextPathResolution.class); suite.addTestSuite(JBIDE5920Test.class); suite.addTestSuite(RenderFacetAndInsertChildrenTest.class); suite.addTestSuite(EditFontFamilyTest_JBIDE5872.class); suite.addTestSuite(ChangeMessageBundleTest_JBIDE5818.class); suite.addTestSuite(TestForUsingComponentsLibrariesWithDefaultNamespace.class); // suite.addTestSuite(EditingSPecialSymbolsVPE_JBIDE3810.class); suite.addTestSuite(OpenOnJsf20Test_JBIDE5382.class); suite.addTestSuite(MozDirtyTest_JBIDE5105.class); suite.addTestSuite(VpeI18nTest_JBIDE4887.class); suite.addTestSuite(JsfComponentTest.class); suite.addTestSuite(JBIDE3519Test.class); suite.addTestSuite(ContextMenuDoubleInsertionTest_JBIDE3888.class); suite.addTestSuite(SelectAllAndCut_JBIDE4853.class); suite.addTestSuite(SelectWholeElement_JBIDE4713.class); suite.addTestSuite(JBIDE4037Test.class); suite.addTestSuite(JBIDE3734Test.class); suite.addTestSuite(JBIDE3617Test.class); suite.addTestSuite(JBIDE3473Test.class); suite.addTestSuite(JBIDE3441Test.class); suite.addTestSuite(JsfJbide1467Test.class); suite.addTestSuite(JsfJbide1501Test.class); suite.addTestSuite(JsfJbide1568Test.class); suite.addTestSuite(JBIDE1615Test.class); suite.addTestSuite(JBIDE1479Test.class); suite.addTestSuite(JBIDE788Test.class); suite.addTestSuite(JBIDE1105Test.class); suite.addTestSuite(JBIDE1744Test.class); suite.addTestSuite(JBIDE1460Test.class); suite.addTestSuite(JBIDE1720Test.class); suite.addTestSuite(JsfJbide1718Test.class); suite.addTestSuite(JBIDE1494Test.class); suite.addTestSuite(JBIDE2297Test.class); suite.addTestSuite(JsfJbide2170Test.class); suite.addTestSuite(JBIDE2434Test.class); suite.addTestSuite(JsfJbide2362Test.class); suite.addTestSuite(JBIDE2119Test.class); suite.addTestSuite(JBIDE2219Test.class); suite.addTestSuite(JBIDE2505Test.class); suite.addTestSuite(JBIDE2584Test.class); suite.addTestSuite(ElPreferencesTestCase.class); suite.addTestSuite(JBIDE2010Test.class); suite.addTestSuite(JBIDE2582Test.class); suite.addTestSuite(JBIDE2594Test.class); suite.addTestSuite(JBIDE924Test.class); suite.addTestSuite(JBIDE2526Test.class); suite.addTestSuite(JBIDE2624Test.class); suite.addTestSuite(JBIDE1805Test.class); suite.addTestSuite(JBIDE2774Test.class); suite.addTestSuite(JBIDE2828Test.class); suite.addTestSuite(JBIDE3030Test.class); suite.addTestSuite(JBIDE2979Test.class); suite.addTestSuite(JBIDE3127Test.class); suite.addTestSuite(JBIDE3144Test.class); suite.addTestSuite(JBIDE2354Test.class); suite.addTestSuite(JBIDE3163Test.class); suite.addTestSuite(JBIDE3376Test.class); suite.addTestSuite(JBIDE3396Test.class); suite.addTestSuite(JBIDE3482Test.class); suite.addTestSuite(JBIDE3632Test.class); suite.addTestSuite(JBIDE3650Test.class); suite.addTestSuite(JBIDE3197Test.class); suite.addTestSuite(JBIDE4373Test.class); suite.addTestSuite(JBIDE675Test.class); suite.addTestSuite(JBIDE3969Test.class); suite.addTestSuite(JBIDE4337Test.class); suite.addTestSuite(JBIDE4179Test.class); suite.addTestSuite(JBIDE4509Test.class); suite.addTestSuite(JBIDE4510Test.class); suite.addTestSuite(JBIDE4534Test.class); suite.addTestSuite(JBIDE3247Test.class); suite.addTestSuite(JBIDE2550Test.class); suite.addTestSuite(OpenOnCssClassTest_JBIDE4775.class); suite.addTestSuite(VPERefreshTest.class); suite.addTestSuite(OpenOnInsideJspRoot_JBIDE4852.class); suite.addTestSuite(NullPointerWithStyleProperty_JBIDE5193.class); suite.addTestSuite(TestFViewLocaleAttribute_JBIDE5218.class); suite.addTestSuite(TestOpenOnForXhtmlFiles_JBIDE5577.class); suite.addTestSuite(OpenOnInJarPackageFragment_JBIDE5682.class); suite.addTestSuite(MessageResolutionInPreviewTabTest.class); suite.addTestSuite(OpenOnTLDPackedInJar_JBIDE5693.class); suite.addTestSuite(PreferencesForEditors_JBIDE5692.class); suite.addTestSuite(FacetProcessingTest.class); suite.addTestSuite(RefreshBundles_JBIDE5460.class); suite.addTestSuite(ExceptionInVPEComments_JBIDE5143.class); suite.addTestSuite(VisualRefreshComment_JBIDE6067.class); // $JUnit-END$ return new VpeTestSetup(suite); }
public static Test suite() { // FIXME https://issues.jboss.org/browse/JBIDE-8488 // JSPIndexManager.getInstance().shutdown(); TestSuite suite = new TestSuite("Tests for Vpe Jsf components"); //$NON-NLS-1$ // $JUnit-BEGIN$ /* * Content tests */ suite.addTestSuite(JsfComponentContentTest.class) ; suite.addTestSuite(Jsf20ComponentContentTest.class); /* * Other tests */ suite.addTestSuite(SourceDomUtilTest.class); suite.addTestSuite(XulRunnerVpeUtilsTest.class); suite.addTestSuite(JSF2ValidatorTest.class); suite.addTestSuite(UnclosedELExpressionTest.class); suite.addTestSuite(TestContextPathResolution.class); suite.addTestSuite(JBIDE5920Test.class); suite.addTestSuite(RenderFacetAndInsertChildrenTest.class); suite.addTestSuite(EditFontFamilyTest_JBIDE5872.class); suite.addTestSuite(ChangeMessageBundleTest_JBIDE5818.class); suite.addTestSuite(TestForUsingComponentsLibrariesWithDefaultNamespace.class); // suite.addTestSuite(EditingSPecialSymbolsVPE_JBIDE3810.class); suite.addTestSuite(OpenOnJsf20Test_JBIDE5382.class); suite.addTestSuite(MozDirtyTest_JBIDE5105.class); suite.addTestSuite(VpeI18nTest_JBIDE4887.class); suite.addTestSuite(JsfComponentTest.class); suite.addTestSuite(JBIDE3519Test.class); suite.addTestSuite(ContextMenuDoubleInsertionTest_JBIDE3888.class); suite.addTestSuite(SelectAllAndCut_JBIDE4853.class); suite.addTestSuite(SelectWholeElement_JBIDE4713.class); suite.addTestSuite(JBIDE4037Test.class); suite.addTestSuite(JBIDE3734Test.class); suite.addTestSuite(JBIDE3617Test.class); suite.addTestSuite(JBIDE3473Test.class); suite.addTestSuite(JBIDE3441Test.class); suite.addTestSuite(JsfJbide1467Test.class); suite.addTestSuite(JsfJbide1501Test.class); suite.addTestSuite(JsfJbide1568Test.class); suite.addTestSuite(JBIDE1615Test.class); suite.addTestSuite(JBIDE1479Test.class); suite.addTestSuite(JBIDE788Test.class); suite.addTestSuite(JBIDE1105Test.class); suite.addTestSuite(JBIDE1744Test.class); suite.addTestSuite(JBIDE1460Test.class); suite.addTestSuite(JBIDE1720Test.class); suite.addTestSuite(JsfJbide1718Test.class); suite.addTestSuite(JBIDE1494Test.class); suite.addTestSuite(JBIDE2297Test.class); suite.addTestSuite(JsfJbide2170Test.class); suite.addTestSuite(JBIDE2434Test.class); suite.addTestSuite(JsfJbide2362Test.class); suite.addTestSuite(JBIDE2119Test.class); suite.addTestSuite(JBIDE2219Test.class); suite.addTestSuite(JBIDE2505Test.class); suite.addTestSuite(JBIDE2584Test.class); suite.addTestSuite(ElPreferencesTestCase.class); suite.addTestSuite(JBIDE2010Test.class); suite.addTestSuite(JBIDE2582Test.class); suite.addTestSuite(JBIDE2594Test.class); suite.addTestSuite(JBIDE924Test.class); suite.addTestSuite(JBIDE2526Test.class); suite.addTestSuite(JBIDE2624Test.class); suite.addTestSuite(JBIDE1805Test.class); suite.addTestSuite(JBIDE2774Test.class); suite.addTestSuite(JBIDE2828Test.class); suite.addTestSuite(JBIDE3030Test.class); suite.addTestSuite(JBIDE2979Test.class); suite.addTestSuite(JBIDE3127Test.class); suite.addTestSuite(JBIDE3144Test.class); suite.addTestSuite(JBIDE2354Test.class); suite.addTestSuite(JBIDE3163Test.class); suite.addTestSuite(JBIDE3376Test.class); suite.addTestSuite(JBIDE3396Test.class); suite.addTestSuite(JBIDE3482Test.class); suite.addTestSuite(JBIDE3632Test.class); suite.addTestSuite(JBIDE3650Test.class); suite.addTestSuite(JBIDE3197Test.class); suite.addTestSuite(JBIDE4373Test.class); suite.addTestSuite(JBIDE675Test.class); suite.addTestSuite(JBIDE3969Test.class); suite.addTestSuite(JBIDE4337Test.class); suite.addTestSuite(JBIDE4179Test.class); suite.addTestSuite(JBIDE4509Test.class); suite.addTestSuite(JBIDE4510Test.class); suite.addTestSuite(JBIDE4534Test.class); suite.addTestSuite(JBIDE3247Test.class); suite.addTestSuite(JBIDE2550Test.class); suite.addTestSuite(OpenOnCssClassTest_JBIDE4775.class); suite.addTestSuite(VPERefreshTest.class); suite.addTestSuite(OpenOnInsideJspRoot_JBIDE4852.class); suite.addTestSuite(NullPointerWithStyleProperty_JBIDE5193.class); suite.addTestSuite(TestFViewLocaleAttribute_JBIDE5218.class); suite.addTestSuite(TestOpenOnForXhtmlFiles_JBIDE5577.class); suite.addTestSuite(OpenOnInJarPackageFragment_JBIDE5682.class); suite.addTestSuite(MessageResolutionInPreviewTabTest.class); suite.addTestSuite(OpenOnTLDPackedInJar_JBIDE5693.class); suite.addTestSuite(PreferencesForEditors_JBIDE5692.class); suite.addTestSuite(FacetProcessingTest.class); suite.addTestSuite(RefreshBundles_JBIDE5460.class); suite.addTestSuite(ExceptionInVPEComments_JBIDE5143.class); suite.addTestSuite(VisualRefreshComment_JBIDE6067.class); // $JUnit-END$ return new VpeTestSetup(suite); }